Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3870052fb4 | ||
|
|
b019b00e82 | ||
|
|
50aa9b3595 | ||
|
|
af8d5ab06b | ||
|
|
adf0744f75 | ||
|
|
652bafd75a | ||
|
|
5440cbc37e | ||
|
|
a434da9e85 | ||
|
|
2c565fbd8d | ||
|
|
0d30ee628e | ||
|
|
0f7aa5a600 | ||
|
|
1b07005d91 | ||
|
|
aaed36aa19 | ||
|
|
c3a8a9b6b6 | ||
|
|
868f4a5798 | ||
|
|
93850ec11c | ||
|
|
40c51bcd02 | ||
|
|
bed48bbe46 | ||
|
|
34cc6be8df | ||
|
|
c55042aff4 | ||
|
|
3726913c1f |
40
.github/logo.svg
vendored
40
.github/logo.svg
vendored
@@ -1,40 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120" width="100%" height="100%" style="background-color: transparent;">
|
||||
<defs>
|
||||
<style>
|
||||
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@800&display=swap');
|
||||
|
||||
.title-font {
|
||||
font-family: 'Plus Jakarta Sans', sans-serif;
|
||||
font-size: 48px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
text-anchor: middle;
|
||||
}
|
||||
|
||||
.star-fx {
|
||||
animation: floatAnimation 4s ease-in-out infinite;
|
||||
}
|
||||
.star-top { transform-origin: 265px 25px; fill: #cec1e6; }
|
||||
.star-bottom { transform-origin: 45px 95px; animation-delay: 0.5s; fill: #fad6e6; }
|
||||
|
||||
@keyframes floatAnimation {
|
||||
0% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
50% { transform: translateY(-8px) rotate(10deg); opacity: 1; }
|
||||
100% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
}
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<g transform="translate(160, 75)">
|
||||
<text class="title-font" dx="2" dy="2">
|
||||
<tspan fill="#f9d5e7">Snow</tspan><tspan fill="#a5c9ff">Luma</tspan>
|
||||
</text>
|
||||
|
||||
<text class="title-font" dx="0" dy="0">
|
||||
<tspan fill="#a5c9ff">Snow</tspan><tspan fill="#cec1e6">Luma</tspan>
|
||||
</text>
|
||||
</g>
|
||||
|
||||
<path class="star-fx star-top" d="M265,13 L267.8,21.1 L276,24 L267.8,26.9 L265,35 L262.2,26.9 L254,24 L262.2,21.1 Z"/>
|
||||
<path class="star-fx star-bottom" d="M45,84 L47.1,90.2 L53.5,92.2 L47.1,94.2 L45,100 L42.9,94.2 L36.5,92.2 L42.9,90.2 Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
43
.github/workflows/ci.yml
vendored
43
.github/workflows/ci.yml
vendored
@@ -1,43 +0,0 @@
|
||||
# Run the full workspace test suite on every pull request.
|
||||
#
|
||||
# The repo previously had no PR test gate, so broken tests could land on `dev`
|
||||
# unnoticed — and did (protocol's oidb-service rejection path, plus an external
|
||||
# contributor PR). This gates every PR on the whole suite.
|
||||
#
|
||||
# `pnpm -r --no-bail --if-present test` runs each package's `test` script
|
||||
# (skipping packages without one); --no-bail means one failing package still
|
||||
# reports the rest, and the run as a whole still fails if any package fails.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Cancel an in-flight run when the PR gets new commits.
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run all package tests
|
||||
run: pnpm -r --no-bail --if-present test
|
||||
109
.github/workflows/mcp-npm-publish.yml
vendored
109
.github/workflows/mcp-npm-publish.yml
vendored
@@ -1,109 +0,0 @@
|
||||
name: Publish MCP to npm
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/mcp/**'
|
||||
# The action catalog is generated from @snowluma/onebot's specs, so an
|
||||
# action change must republish the MCP snapshot.
|
||||
- 'packages/onebot/**'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'tsconfig.base.json'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: mcp-npm-publish-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Build, test, and publish MCP
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Type check MCP
|
||||
run: pnpm --filter @snowluma/mcp typecheck
|
||||
|
||||
- name: Test MCP (regenerates + validates the action catalog)
|
||||
run: pnpm --filter @snowluma/mcp test
|
||||
|
||||
- name: Build MCP
|
||||
run: pnpm --filter @snowluma/mcp build
|
||||
|
||||
- name: Check npm package version
|
||||
id: npm
|
||||
working-directory: packages/mcp
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
|
||||
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
|
||||
|
||||
{
|
||||
echo "package_name=${package_name}"
|
||||
echo "package_version=${package_version}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
|
||||
echo "already_published=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
|
||||
else
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Publish MCP to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/mcp
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
shell: bash
|
||||
run: |
|
||||
{
|
||||
echo "## MCP npm publish"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
117
README.md
117
README.md
@@ -1,6 +1,4 @@
|
||||
<h1 align="center">
|
||||
<img src=".github/logo.svg" width="100%" alt="SnowLuma" />
|
||||
</h1>
|
||||
<h1 align="center">❄️ SnowLuma</h1>
|
||||
|
||||
<p align="center">
|
||||
<i>Next Remote Protocol Framework.</i>
|
||||
@@ -9,7 +7,8 @@
|
||||
<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="NPM" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&color=cb3837"></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>
|
||||
|
||||
@@ -22,29 +21,111 @@
|
||||
|
||||
---
|
||||
|
||||
SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。
|
||||
## 简介
|
||||
|
||||
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 等消息格式。
|
||||
- **高性能架构**:TypeScript 全栈,基于 pnpm monorepo 管理,核心逻辑分离。
|
||||
- **现代化管理**:内置 WebUI 面板,支持实时日志、密码热更、多账号管理。
|
||||
- **多适配器支持**:WebSocket (Server/Client)、HTTP (Server/Post)。
|
||||
- **数据持久化**:使用 SQLite 存储好友、群组等关系数据。
|
||||
- **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,跨重启可用。
|
||||
|
||||
## 快速开始
|
||||
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。
|
||||
2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。
|
||||
3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。
|
||||
下载预构建发布包:
|
||||
|
||||
```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) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
|
||||
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
|
||||
|
||||
---
|
||||
## 贡献者
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" /></a>
|
||||
</p>
|
||||
感谢每一位为 SnowLuma 提交过代码的伙伴。
|
||||
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
|
||||
</a>
|
||||
|
||||
## Star 趋势
|
||||
|
||||
<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)
|
||||
|
||||
500
RoadMap.md
500
RoadMap.md
@@ -1,9 +1,491 @@
|
||||
# V2.0.0 前计划
|
||||
- [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
|
||||
- [x] 优化Debug体验,实现免打包Debug,同时数据目录正确。(Proton兜底思路改成ts+map提取类型,用于tsx和nodejs,vite正常打包的时候剥离)
|
||||
- [x] 拆分core,架构为Common(公共能力) OneBot(外层封装 协议转换),Core(Api raw能力,基础能力等功能),Bridge(封装和关键解析能力和Event message/sent group/member_add ...)
|
||||
- [x] 剥离ProtocolBuffer定义到单独package。
|
||||
- [x] 整理发送和解析消息链路,提高性能。`packages/{bridge,onebot}/bench/*.bench.ts` 拿到了基线数字。最大瓶颈不在 protobuf 解析(已经 sub-μs),而在两处 SQLite 反复 `db.prepare(sql)` 重 parse —— 把 `node:sqlite`(实验性)换成 `better-sqlite3`(稳定)+ 缓存 prepared statements 后:`group_member_join` 全链路 17.5μs → 4.7μs(**3.7x**),`storeMeta` 17μs → 11μs,`storeEvent` 23μs → 18μs,`findMeta` 5.4μs → 1.3μs(**4x**)。送侧组合 hot path(storeMeta + storeEvent)单条消息 40μs → 29μs。另外干掉 `Buffer.from(pkt.body)` 的冗余 alloc(pkt.body 本来就是 Uint8Array)。`elementsToJson` 同步快路径 / WAL checkpoint 调参 / JSON 序列化替换 等次要优化点保留,待真有 throughput 压力再做。
|
||||
- [x] 对齐NapCat设计采用Api层,挂到ctx,Core与Onebot都这么设计。
|
||||
- [x] Core 侧:13 个 Api 类(message/contacts/groupAdmin/groupFile/groupAlbum/interaction/friend/profile/forward/misc/extras/web)已挂到 `bridge.apis.<area>.method()`,`BridgeInterface` + `actions/*` 全部删除。
|
||||
- [x] OneBot 侧:`ApiActionContext` 砍掉 ~40 个纯转发字段(groupAdmin / groupFile / groupAlbum / friend / interaction / message / profile / web 八区),actions 直接 `ctx.bridge.apis.<area>.method(...)` 调用 Core 的 Api 层。保留的 ~30 个字段全是真组合 helper(module-level send/forward、message store reads、meta-lookup composers)。完全 NapCat 化(class-per-action / TypeBox schema / actionName 枚举 / auto-register decorator)暂未做——profile 文档/工具链需求出现后再做。
|
||||
# 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`)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.9.10",
|
||||
"version": "1.9.2",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -8,8 +8,7 @@
|
||||
"build": "pnpm --filter @snowluma/core build",
|
||||
"build:sdk": "pnpm --filter @snowluma/sdk build",
|
||||
"build:webui": "pnpm --filter webui build",
|
||||
"build:mcp": "pnpm --filter @snowluma/mcp build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter webui build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
export {
|
||||
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
|
||||
type HookProcessStatus, type QqPortLoginInfo
|
||||
} from './hook-manager';
|
||||
|
||||
@@ -1,282 +0,0 @@
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import https from 'https';
|
||||
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;
|
||||
// QQ's Ptlogin quick-login ports plus its main process mean a single
|
||||
// logged-in client surfaces roughly this many processes. When no usable
|
||||
// probe port is found, a count BELOW this implies the target PID is still at
|
||||
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
|
||||
// unrelated `qq` processes), so we fall through to deep-link probing rather
|
||||
// than guess "logged out".
|
||||
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
|
||||
* probe reads are modelled; QQ sends more but they're irrelevant here. */
|
||||
interface PtloginUin {
|
||||
uin?: string | number;
|
||||
account?: string | number;
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
async function fetchPtlogin(port: number): Promise<PtloginUin[]> {
|
||||
return new Promise((resolve) => {
|
||||
const url = `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
|
||||
|
||||
const req = https.get(
|
||||
url,
|
||||
{
|
||||
headers: {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
},
|
||||
rejectUnauthorized: false, // 忽略本地自签证书报错
|
||||
timeout: CONNECTION_TIMEOUT_MS,
|
||||
},
|
||||
(res) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => { text += chunk.toString(); });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
// 100% 复刻 Python 切片逻辑:获取两个方括号中间的字符串,再包装成数组
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
|
||||
resolve(data);
|
||||
} catch {
|
||||
resolve([]);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
req.on('error', () => resolve([]));
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve([]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
|
||||
// 抽象的 QQNT
|
||||
const res1 = await fetchPtlogin(port);
|
||||
const res2 = await fetchPtlogin(port);
|
||||
|
||||
const target = res1.length < res2.length ? res1 : res2;
|
||||
|
||||
if (target.length === 1) {
|
||||
const account = target[0];
|
||||
return {
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
loggedIn: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Any non-1 result — the 2+0 alternation, both-2, both-empty, etc. — is
|
||||
// inconclusive; hand off to the deep-link / process-count fallback.
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
|
||||
async function getQqProcessCount(): Promise<number> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync('tasklist /fi "imagename eq QQ.exe" /nh');
|
||||
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
|
||||
} else {
|
||||
const { stdout } = await execAsync('pgrep -c qq');
|
||||
return parseInt(stdout.trim(), 10) || 0;
|
||||
}
|
||||
} catch {
|
||||
// On failure report the ambiguous threshold so we never falsely
|
||||
// conclude "logged out".
|
||||
return LOGGED_OUT_PROCESS_COUNT_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
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) {
|
||||
ports.add(Number(match[1]));
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return { port: 0, uin: '', loggedIn: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const matchedPtPorts = ports.filter(p => PT_PORTS.includes(p));
|
||||
|
||||
if (matchedPtPorts.length > 0) {
|
||||
for (const port of matchedPtPorts) {
|
||||
const ptResult = await tryPtloginMethod(port);
|
||||
if (ptResult !== 'fallback') {
|
||||
return ptResult;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return {
|
||||
port: ports[0] || 0,
|
||||
uin: '',
|
||||
loggedIn: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const deepLinkPorts = ports.filter(p => p >= PORT_RANGE_START && p <= PORT_RANGE_END);
|
||||
for (const port of deepLinkPorts) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import net from 'net';
|
||||
import { mkdtemp, rm, writeFile } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listLiveLinuxPipePids, QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
|
||||
async function makeRuntimeDir(): Promise<string> {
|
||||
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-'));
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (!tmpDir) return;
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
tmpDir = null;
|
||||
});
|
||||
|
||||
describe('listLiveLinuxPipePids', () => {
|
||||
it('ignores stale-looking control socket names when the probe rejects them', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), '');
|
||||
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, async () => false);
|
||||
|
||||
expect([...pids]).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns only connectable control sockets', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.recv.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.not-a-pid.control.sock'), '');
|
||||
|
||||
const probe = vi.fn(async (socketPath: string) => socketPath.endsWith('mojo.56.control.sock'));
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, probe);
|
||||
|
||||
expect([...pids]).toEqual([56]);
|
||||
expect(probe).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('QqHookClient — pipe close mid-send', () => {
|
||||
// Regression: when the control pipe closes while a send() is awaiting its
|
||||
// ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The
|
||||
// reply is only `await`ed after the ack, so if the ack rejects first the
|
||||
// reply promise is rejected with NO awaiter — an UNHANDLED rejection that
|
||||
// crashes the Node process (Docker: supervisor restarts it ~1s later; on
|
||||
// Windows it just dies → "connection pipe closed", bot down). The .catch()
|
||||
// guard on each deferred prevents it; without the guard this test trips the
|
||||
// unhandledRejection assertion below.
|
||||
it('does not raise an unhandled rejection', async () => {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-pipe-'));
|
||||
const prevRuntimeDir = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
|
||||
process.env.SNOWLUMA_HOOK_RUNTIME_DIR = dir;
|
||||
|
||||
const PID = 778899;
|
||||
const helloFrame = (): Buffer => {
|
||||
const h = Buffer.alloc(40);
|
||||
h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC
|
||||
h.writeUInt16LE(1, 4); // PIPE_VERSION
|
||||
h.writeUInt16LE(1, 6); // PipeOp.hello
|
||||
h.writeBigUInt64LE(BigInt(PID), 32); // value0 = pid
|
||||
return h;
|
||||
};
|
||||
|
||||
let controlConn: net.Socket | null = null;
|
||||
const controlServer = net.createServer((sock) => { controlConn = sock; sock.write(helloFrame()); });
|
||||
const recvServer = net.createServer((sock) => { sock.write(helloFrame()); });
|
||||
await new Promise<void>((r) => controlServer.listen(path.join(dir, `mojo.${PID}.control.sock`), () => r()));
|
||||
await new Promise<void>((r) => recvServer.listen(path.join(dir, `mojo.${PID}.recv.sock`), () => r()));
|
||||
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (reason: unknown): void => { unhandled.push(reason); };
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
|
||||
const client = new QqHookClient(PID);
|
||||
client.on('error', () => { /* socket reset on destroy — ignore */ });
|
||||
try {
|
||||
await client.connectAll({ recv: true });
|
||||
|
||||
// Start a reply-expecting send, let it reach the in-flight (awaiting-ack)
|
||||
// state, then have the "hook" drop the pipe before it answers.
|
||||
const sent = client.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 })
|
||||
.then(() => 'resolved' as const, (e: unknown) => e);
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
controlConn?.destroy();
|
||||
|
||||
const outcome = await sent;
|
||||
await new Promise((r) => setTimeout(r, 50)); // let Node surface any unhandled rejection
|
||||
|
||||
expect(outcome).toBeInstanceOf(Error);
|
||||
expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
client.close();
|
||||
await new Promise<void>((r) => controlServer.close(() => r()));
|
||||
await new Promise<void>((r) => recvServer.close(() => r()));
|
||||
if (prevRuntimeDir === undefined) delete process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
|
||||
else process.env.SNOWLUMA_HOOK_RUNTIME_DIR = prevRuntimeDir;
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.10",
|
||||
"name": "@snowluma/channel-hook",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
"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": {
|
||||
@@ -11,6 +11,14 @@
|
||||
"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"
|
||||
@@ -49,6 +57,7 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/channel": "workspace:*",
|
||||
"@snowluma/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
174
packages/channel-hook/src/hook-adapter.ts
Normal file
174
packages/channel-hook/src/hook-adapter.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
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;
|
||||
}
|
||||
82
packages/channel-hook/src/hook-channel.ts
Normal file
82
packages/channel-hook/src/hook-channel.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -18,22 +18,23 @@ import type { HookProcessInfo } from './types';
|
||||
|
||||
/**
|
||||
* Sink that the hook layer calls back into when it observes a new login,
|
||||
* a parsed packet, or a PID disconnect. The concrete implementation lives
|
||||
* in @snowluma/core (`BridgeManager`), which is wired in by the top-level
|
||||
* app entry. Declaring it here keeps @snowluma/bridge free of any
|
||||
* dependency on @snowluma/core — the hook package is self-contained.
|
||||
* a parsed packet, or a PID disconnect. The concrete implementation is
|
||||
* `HookAdapter`, which sits between this hook runtime and the `Hub` in
|
||||
* `@snowluma/core`. Declaring it here keeps `@snowluma/channel` (and
|
||||
* future `@snowluma/channel-hook`) free of any dependency on
|
||||
* `@snowluma/core` — the hook package is self-contained.
|
||||
*/
|
||||
export interface BridgeManagerSink {
|
||||
export interface HookSink {
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
|
||||
onPacket(pkt: PacketInfo): void;
|
||||
onPidDisconnected(pid: number): void;
|
||||
}
|
||||
|
||||
export type HookManagerDeps = {
|
||||
bridgeManager: BridgeManagerSink;
|
||||
sink: HookSink;
|
||||
/** Sink for parsed packets from any live HookSession. Defaults to
|
||||
* `bridgeManager.onPacket` — every packet flows straight into the
|
||||
* per-UIN bridge dispatcher with no intermediate event emitter. */
|
||||
* `sink.onPacket` — every packet flows straight into the per-UIN
|
||||
* channel dispatcher with no intermediate event emitter. */
|
||||
onPacket?: PacketSink;
|
||||
/** Native injector entrypoints. Defaults to the real native addon. */
|
||||
injector?: HookSessionDeps['injector'];
|
||||
@@ -59,7 +60,7 @@ export type HookManagerDeps = {
|
||||
* Responsibilities:
|
||||
* - Route user commands (load/unload/refresh) to the matching session.
|
||||
* - Route watcher diff events to the matching session.
|
||||
* - Forward session events ('login' / 'disconnected') to BridgeManager.
|
||||
* - Forward session events ('login' / 'disconnected') to the `HookSink`.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
*
|
||||
@@ -68,7 +69,7 @@ export type HookManagerDeps = {
|
||||
* real QQ.exe or a native addon.
|
||||
*/
|
||||
export class HookManager {
|
||||
private readonly bridgeManager: BridgeManagerSink;
|
||||
private readonly sink: HookSink;
|
||||
private readonly onPacket: PacketSink;
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
@@ -83,8 +84,8 @@ export class HookManager {
|
||||
private disposed = false;
|
||||
|
||||
constructor(deps: HookManagerDeps) {
|
||||
this.bridgeManager = deps.bridgeManager;
|
||||
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
|
||||
this.sink = deps.sink;
|
||||
this.onPacket = deps.onPacket ?? ((pkt) => deps.sink.onPacket(pkt));
|
||||
this.log = deps.log ?? createLogger('Hook');
|
||||
|
||||
this.injector = deps.injector ?? {
|
||||
@@ -248,10 +249,10 @@ export class HookManager {
|
||||
session.attachProcessInfo({ name: defaultProcessName() });
|
||||
|
||||
session.on('login', (uin: string, sender) => {
|
||||
this.bridgeManager.onHookLogin(pid, uin, sender);
|
||||
this.sink.onHookLogin(pid, uin, sender);
|
||||
});
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
if (wasLoggedIn) this.sink.onPidDisconnected(pid);
|
||||
});
|
||||
session.on('disposed', () => {
|
||||
this.sessions.delete(pid);
|
||||
@@ -312,3 +313,4 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
|
||||
export type { HookProcessBaseInfo } from './injector';
|
||||
export type { QqPortLoginInfo } from './qq-port-probe';
|
||||
export type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
|
||||
@@ -20,8 +20,8 @@ export type HookSessionDeps = {
|
||||
isPipeLive: (pid: number) => boolean;
|
||||
tickNow?: () => Promise<void>;
|
||||
};
|
||||
/** Sink for parsed packets. Called with the BridgeManager-shaped
|
||||
* PacketInfo for every packet received while logged in. If omitted,
|
||||
/** Sink for parsed packets. Called with the canonical PacketInfo
|
||||
* shape for every packet received while logged in. If omitted,
|
||||
* packets are dropped (useful in unit tests that don't care). */
|
||||
onPacket?: PacketSink;
|
||||
log?: Logger;
|
||||
@@ -35,7 +35,7 @@ export type HookSessionDeps = {
|
||||
* promise chain so user clicks (load/unload/refresh) and watcher-driven
|
||||
* events (onPipeUp/onPipeDown) never interleave.
|
||||
*
|
||||
* Communication: emits high-level events instead of calling BridgeManager
|
||||
* Communication: emits high-level events instead of calling the sink
|
||||
* directly, so HookManager forwards them and tests can attach spies.
|
||||
*
|
||||
* Emitted events:
|
||||
@@ -406,7 +406,7 @@ export class HookSession extends EventEmitter {
|
||||
const uin = packet.uin || this._uin;
|
||||
if (!isRealUin(uin)) return;
|
||||
if (!this.onPacket) return;
|
||||
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
|
||||
// Re-shape the hook-client wire packet into the canonical PacketInfo
|
||||
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
|
||||
// renaming was that module's entire purpose, so it lives at the source
|
||||
// now (no need for a single-listener event-emitter in between).
|
||||
15
packages/channel-hook/src/index.ts
Normal file
15
packages/channel-hook/src/index.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
// `@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';
|
||||
@@ -55,9 +55,9 @@ function defaultProcessName(): string {
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
|
||||
// 2. Dev via tsx (packages/channel/src/injector.ts): __dirname=<root>/packages/channel/src
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
// Same offset works for `packages/bridge/dist/index.mjs` after build.
|
||||
// Same offset works for `packages/channel/dist/index.mjs` after build.
|
||||
// 3. cwd-based fallback when neither __dirname-relative path resolves.
|
||||
return [
|
||||
path.resolve(__dirname, 'native'),
|
||||
@@ -465,12 +465,6 @@ export class QqHookClient extends EventEmitter {
|
||||
});
|
||||
|
||||
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
|
||||
// Always attach a handler so a rejection can never become "unhandled" (which
|
||||
// crashes Node). When the pipe closes, rejectControlPending() rejects every
|
||||
// pending deferred — but the reply is only `await`ed AFTER the ack, so if the
|
||||
// ack fails first the reply promise is rejected with NO awaiter. The real
|
||||
// `await` below still observes the value/rejection (a separate continuation).
|
||||
ackDeferred.promise.catch(() => { /* observed by the await, or harmless */ });
|
||||
this.pendingAcks.set(requestId, {
|
||||
resolve: ackDeferred.resolve,
|
||||
reject: ackDeferred.reject,
|
||||
@@ -480,7 +474,6 @@ export class QqHookClient extends EventEmitter {
|
||||
let replyDeferred: Deferred<QqHookSendReply> | null = null;
|
||||
if (wantReply) {
|
||||
replyDeferred = createDeferred<QqHookSendReply>();
|
||||
replyDeferred.promise.catch(() => { /* see note above — prevents unhandled rejection */ });
|
||||
this.pendingReplies.set(requestId, replyDeferred);
|
||||
}
|
||||
|
||||
168
packages/channel-hook/src/qq-port-probe.ts
Normal file
168
packages/channel-hook/src/qq-port-probe.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
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;
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import path from 'path';
|
||||
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { HookSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
@@ -37,13 +37,13 @@ function makeManager(opts: {
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
const sink = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
} as unknown as HookSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
sink,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
@@ -9,7 +9,7 @@ import { EventEmitter } from 'events';
|
||||
import { HookManager } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { HookSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
@@ -41,14 +41,14 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
const sink = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
} as unknown as HookSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
sink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
@@ -82,9 +82,9 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
|
||||
// The "QQ never logs in" hypothesis: BridgeManager should never have
|
||||
// been told about a login or a disconnect.
|
||||
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
expect(sink.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(sink.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(sink.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
44
packages/channel-hook/tests/qq-hook-client.test.ts
Normal file
44
packages/channel-hook/tests/qq-hook-client.test.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { mkdtemp, rm, writeFile } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listLiveLinuxPipePids } from '../src/qq-hook-client';
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
|
||||
async function makeRuntimeDir(): Promise<string> {
|
||||
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-'));
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (!tmpDir) return;
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
tmpDir = null;
|
||||
});
|
||||
|
||||
describe('listLiveLinuxPipePids', () => {
|
||||
it('ignores stale-looking control socket names when the probe rejects them', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), '');
|
||||
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, async () => false);
|
||||
|
||||
expect([...pids]).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns only connectable control sockets', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.recv.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.not-a-pid.control.sock'), '');
|
||||
|
||||
const probe = vi.fn(async (socketPath: string) => socketPath.endsWith('mojo.56.control.sock'));
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, probe);
|
||||
|
||||
expect([...pids]).toEqual([56]);
|
||||
expect(probe).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
16
packages/channel-hook/tsconfig.json
Normal file
16
packages/channel-hook/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*",
|
||||
"tests"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
34
packages/channel-socket/package.json
Normal file
34
packages/channel-socket/package.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"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:"
|
||||
}
|
||||
}
|
||||
8
packages/channel-socket/src/index.ts
Normal file
8
packages/channel-socket/src/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// `@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';
|
||||
30
packages/channel-socket/src/socket-adapter.ts
Normal file
30
packages/channel-socket/src/socket-adapter.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
41
packages/channel-socket/src/socket-channel.ts
Normal file
41
packages/channel-socket/src/socket-channel.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
44
packages/channel/package.json
Normal file
44
packages/channel/package.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
15
packages/channel/src/adapter.ts
Normal file
15
packages/channel/src/adapter.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
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;
|
||||
}
|
||||
26
packages/channel/src/channel-ctx.ts
Normal file
26
packages/channel/src/channel-ctx.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
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(),
|
||||
};
|
||||
}
|
||||
73
packages/channel/src/channel-interface.ts
Normal file
73
packages/channel/src/channel-interface.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
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;
|
||||
}
|
||||
34
packages/channel/src/channel.ts
Normal file
34
packages/channel/src/channel.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
0
packages/channel/src/hub-events.ts
Normal file
0
packages/channel/src/hub-events.ts
Normal file
5
packages/channel/src/index.ts
Normal file
5
packages/channel/src/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
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';
|
||||
|
||||
16
packages/channel/tsconfig.json
Normal file
16
packages/channel/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*",
|
||||
"tests"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
8
packages/channel/vitest.config.ts
Normal file
8
packages/channel/vitest.config.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.10",
|
||||
"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).",
|
||||
|
||||
@@ -49,70 +49,3 @@ export function summarizeParams(params: unknown): string {
|
||||
}
|
||||
return out.join(' ');
|
||||
}
|
||||
|
||||
const VERBOSE_STRING_MAX = 200;
|
||||
const VERBOSE_TOTAL_MAX = 1500;
|
||||
// Keys whose values must never be rendered — tokens, passwords, secrets.
|
||||
const REDACT_KEY = /^(.*[-_])?(token|password|passwd|secret|access[-_]?token)([-_].*)?$/i;
|
||||
|
||||
/**
|
||||
* Deep, debug-grade render of a params object for the `trace` level: shows the
|
||||
* full nested structure (message segments, nested objects) so a reproduction
|
||||
* is legible — unlike {@link summarizeParams}, which collapses nested values.
|
||||
*
|
||||
* Three guards keep it safe and bounded:
|
||||
* - per-string cap (long values like base64 image data become `"…<N B>"`),
|
||||
* - total output budget (so a giant payload can't flood the buffer),
|
||||
* - key-based redaction (token / password / secret → `"***"`).
|
||||
*/
|
||||
export function renderParamsVerbose(params: unknown): string {
|
||||
const seen = new WeakSet<object>();
|
||||
let budget = VERBOSE_TOTAL_MAX;
|
||||
|
||||
const walk = (value: unknown, key?: string): string => {
|
||||
if (budget <= 0) return '…';
|
||||
if (key !== undefined && REDACT_KEY.test(key)) return '"***"';
|
||||
if (value === null) return 'null';
|
||||
if (value === undefined) return 'undefined';
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string': {
|
||||
const truncated =
|
||||
value.length > VERBOSE_STRING_MAX
|
||||
? `${value.slice(0, VERBOSE_STRING_MAX)}…<${value.length}B>`
|
||||
: value;
|
||||
const out = JSON.stringify(truncated);
|
||||
budget -= out.length;
|
||||
return out;
|
||||
}
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint': {
|
||||
const out = String(value);
|
||||
budget -= out.length;
|
||||
return out;
|
||||
}
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) return '"[circular]"';
|
||||
seen.add(value as object);
|
||||
const parts: string[] = [];
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
if (budget <= 0) { parts.push('…'); break; }
|
||||
parts.push(walk(item));
|
||||
}
|
||||
return `[${parts.join(',')}]`;
|
||||
}
|
||||
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (budget <= 0) { parts.push('…'); break; }
|
||||
parts.push(`${k}:${walk(v, k)}`);
|
||||
}
|
||||
return `{${parts.join(',')}}`;
|
||||
}
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
|
||||
return walk(params);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
import { currentRequestId } from './request-context';
|
||||
|
||||
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
@@ -11,8 +10,6 @@ export interface LogEntry {
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
|
||||
req?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
@@ -29,7 +26,6 @@ interface LogOptions {
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
@@ -38,7 +34,6 @@ const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
@@ -47,7 +42,6 @@ const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
@@ -59,55 +53,13 @@ const COLOR_SCOPE = 35;
|
||||
const COLOR_DIM = 2;
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const MAX_LOG_ENTRIES = 1000;
|
||||
|
||||
/** Trace ring cap — env-tunable since trace is the high-volume stream. */
|
||||
function resolveTraceBufferMax(): number {
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
}
|
||||
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
|
||||
/**
|
||||
* Fixed-capacity circular buffer. O(1) push + eviction (no array `.shift()`),
|
||||
* so the high-throughput trace stream never pays an O(n) shift per overflow.
|
||||
*/
|
||||
class RingBuffer<T> {
|
||||
private readonly buf: (T | undefined)[];
|
||||
private start = 0;
|
||||
private count = 0;
|
||||
constructor(private readonly cap: number) {
|
||||
this.buf = new Array<T | undefined>(cap);
|
||||
}
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
if (this.count < this.cap) this.count += 1;
|
||||
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
const logRing = new RingBuffer<LogEntry>(MAX_LOG_ENTRIES);
|
||||
const traceRing = new RingBuffer<LogEntry>(TRACE_BUFFER_MAX);
|
||||
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 === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
@@ -123,7 +75,7 @@ function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
@@ -158,16 +110,15 @@ function currentTime(): string {
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: number): string {
|
||||
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);
|
||||
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
@@ -178,46 +129,28 @@ function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: n
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
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);
|
||||
|
||||
// `trace` never touches disk and is the high-volume full-chain stream. When
|
||||
// it won't reach the console/memory buffer either (level not dialed to
|
||||
// trace), bail BEFORE format/render AND before evaluating any lazy producer
|
||||
// — this is what keeps full-chain tracing ~free at the default level even
|
||||
// with hundreds of groups.
|
||||
if (level === 'trace' && !passesConsole) return;
|
||||
|
||||
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
|
||||
// (and its expensive deep render) only runs now that trace is confirmed live.
|
||||
let realArgs = args;
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const message = format(...realArgs);
|
||||
const line = render(level, options, realArgs, reqId);
|
||||
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 } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line,
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
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
|
||||
@@ -229,11 +162,10 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// File transport sees debug-and-up for post-mortem value; `trace` is
|
||||
// memory / WebUI only (omitted here to avoid huge on-disk volume). ANSI
|
||||
// stripping happens inside the transport. UIN routes the line to its
|
||||
// per-account sub-file in addition to the shared one.
|
||||
if (level !== 'trace') getFileTransport().write(line, options.uin);
|
||||
// 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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -247,14 +179,8 @@ export function closeLogger(): Promise<void> {
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
// Merge the normal + trace rings by id (ids are monotonic, so id order is
|
||||
// chronological). The trace ring is empty unless trace level is/was active,
|
||||
// so the common case is just the normal ring with no sort.
|
||||
const merged = traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
return merged.slice(-n);
|
||||
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 {
|
||||
@@ -265,13 +191,6 @@ export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
/**
|
||||
* High-volume, memory-only diagnostic level (never written to disk). Pass a
|
||||
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
|
||||
* arguments (and any costly rendering) are built only when trace is active.
|
||||
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
|
||||
*/
|
||||
trace: (...args: unknown[]) => void;
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
@@ -288,7 +207,6 @@ export interface Logger {
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
trace: (...args: unknown[]) => emit('trace', opts, args),
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
@@ -308,8 +226,3 @@ function makeLogger(opts: LogOptions): Logger {
|
||||
export function createLogger(scope: string): Logger {
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
|
||||
// Request-correlation helpers live alongside the logger since `[req#N]`
|
||||
// stamping is a logging concern. Re-exported here so callers import the
|
||||
// whole logging surface from one place.
|
||||
export { nextRequestId, runWithRequestId, currentRequestId } from './request-context';
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
interface RequestStore {
|
||||
id: number;
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<RequestStore>();
|
||||
let counter = 0;
|
||||
|
||||
/**
|
||||
* Allocate the next per-process request id (monotonic). Wraps via uint32 so
|
||||
* it never overflows to a non-integer; `0` is skipped so "no id" stays
|
||||
* unambiguous.
|
||||
*/
|
||||
export function nextRequestId(): number {
|
||||
counter = (counter + 1) >>> 0;
|
||||
if (counter === 0) counter = 1;
|
||||
return counter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` with `id` bound as the ambient request id for the entire async
|
||||
* chain it spawns. Any logger call anywhere in that chain — across packages,
|
||||
* across awaits — picks it up via {@link currentRequestId} with no signature
|
||||
* threading. Used by the OneBot action handler to correlate a request's whole
|
||||
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
|
||||
*/
|
||||
export function runWithRequestId<T>(id: number, fn: () => T): T {
|
||||
return storage.run({ id }, fn);
|
||||
}
|
||||
|
||||
/** The request id bound to the current async context, or undefined outside one. */
|
||||
export function currentRequestId(): number | undefined {
|
||||
return storage.getStore()?.id;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.9.10",
|
||||
"version": "1.9.2",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -10,25 +10,25 @@
|
||||
"types": "./src/index.ts",
|
||||
"default": "../../dist/index.mjs"
|
||||
},
|
||||
"./bridge": {
|
||||
"types": "./src/bridge/bridge.ts",
|
||||
"default": "./src/bridge/bridge.ts"
|
||||
"./core": {
|
||||
"types": "./src/core.ts",
|
||||
"default": "./src/core.ts"
|
||||
},
|
||||
"./bridge-interface": {
|
||||
"types": "./src/bridge/bridge-interface.ts",
|
||||
"default": "./src/bridge/bridge-interface.ts"
|
||||
"./core-context": {
|
||||
"types": "./src/core-context.ts",
|
||||
"default": "./src/core-context.ts"
|
||||
},
|
||||
"./bridge-context": {
|
||||
"types": "./src/bridge/bridge-context.ts",
|
||||
"default": "./src/bridge/bridge-context.ts"
|
||||
"./core-ctx": {
|
||||
"types": "./src/core-ctx.ts",
|
||||
"default": "./src/core-ctx.ts"
|
||||
},
|
||||
"./manager": {
|
||||
"types": "./src/bridge/manager.ts",
|
||||
"default": "./src/bridge/manager.ts"
|
||||
"./hub": {
|
||||
"types": "./src/hub.ts",
|
||||
"default": "./src/hub.ts"
|
||||
},
|
||||
"./apis": {
|
||||
"types": "./src/bridge/apis/index.ts",
|
||||
"default": "./src/bridge/apis/index.ts"
|
||||
"types": "./src/apis/index.ts",
|
||||
"default": "./src/apis/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
@@ -40,7 +40,9 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/bridge": "workspace:*",
|
||||
"@snowluma/channel": "workspace:*",
|
||||
"@snowluma/channel-hook": "workspace:*",
|
||||
"@snowluma/channel-socket": "workspace:*",
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/onebot": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
@@ -53,7 +55,7 @@
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "^24.12.2",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.21",
|
||||
"hono": "^4.12.18",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
@@ -12,8 +12,22 @@ import type {
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from '@snowluma/protocol/qq-info';
|
||||
import type { DownloadRKeyInfo } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
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) ───────────────────
|
||||
|
||||
@@ -63,7 +77,7 @@ export class ContactsApi {
|
||||
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const friends: FriendInfo[] = [];
|
||||
@@ -5,38 +5,9 @@ import {
|
||||
} 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 { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { CoreContext } from '../core-context';
|
||||
import type { MediaIndexNode } from './shared';
|
||||
|
||||
/** Inputs for a voice-to-text request, gathered from the received `record`
|
||||
* element + its message meta. `uuid`/`md5Hex` come from the cached record;
|
||||
* the uins + scene from the message meta. */
|
||||
export interface PttTransInput {
|
||||
isGroup: boolean;
|
||||
msgId: number;
|
||||
senderUin: number;
|
||||
/** Receiver uin (c2c) or group uin (group). */
|
||||
peerUin: number;
|
||||
uuid: string;
|
||||
md5Hex: string;
|
||||
duration: number;
|
||||
size: number;
|
||||
format: number;
|
||||
/** Group ptt numeric file id (group only; optional). */
|
||||
fileId?: number;
|
||||
}
|
||||
|
||||
function hexToBytes(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;
|
||||
}
|
||||
|
||||
// ─────────────── public types (re-exported from bridge.ts as before) ───
|
||||
|
||||
export type StrangerStatus = NamespaceStrangerStatus;
|
||||
@@ -56,7 +27,7 @@ export interface AiVoiceItem {
|
||||
}
|
||||
|
||||
export class ExtrasApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// ─────────────── Group todo (0xF90) ───────────────
|
||||
|
||||
@@ -117,44 +88,4 @@ export class ExtrasApi {
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
|
||||
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
|
||||
|
||||
/**
|
||||
* Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and
|
||||
* return the recognised text IF the response carries it inline (the
|
||||
* already-transcribed case). For a freshly-received voice the response is an
|
||||
* empty ack and the text is delivered later via the async Event 0x210
|
||||
* subType-61 push — callers should treat `''` as "pending" and wait for the
|
||||
* `ptt_trans_result` event (correlated by msgId). Live-verified end to end.
|
||||
*/
|
||||
async translatePttToText(input: PttTransInput): Promise<string> {
|
||||
const md5 = hexToBytes(input.md5Hex);
|
||||
const req: PttTransReq = input.isGroup
|
||||
? {
|
||||
type: 1,
|
||||
groupItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
|
||||
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
|
||||
format: input.format, uuid: input.uuid,
|
||||
},
|
||||
}
|
||||
: {
|
||||
type: 2,
|
||||
c2cItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
|
||||
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
|
||||
},
|
||||
};
|
||||
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
|
||||
|
||||
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'ptt translate request failed');
|
||||
}
|
||||
const resp = protobuf_decode<PttTransResp>(result.responseData);
|
||||
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
|
||||
if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
|
||||
}
|
||||
}
|
||||
@@ -7,18 +7,16 @@ import type {
|
||||
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 { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { CoreContext } from '../core-context';
|
||||
import { resolveSelfUid, toInt } from './shared';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
// 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.
|
||||
@@ -62,7 +60,7 @@ function hexToBytesLocal(hex: string): Uint8Array {
|
||||
}
|
||||
|
||||
async function buildForwardPushBody(
|
||||
bridge: Bridge,
|
||||
bridge: BridgeContext,
|
||||
node: ForwardNodePayload,
|
||||
groupId?: number,
|
||||
userUid?: string,
|
||||
@@ -203,7 +201,7 @@ function previewFromElements(elements: MessageElement[]): string {
|
||||
}
|
||||
|
||||
export class ForwardApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
|
||||
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
|
||||
@@ -233,7 +231,7 @@ export class ForwardApi {
|
||||
throw new Error('forward nodes are required');
|
||||
}
|
||||
|
||||
const bridge = asBridge(this.ctx);
|
||||
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,
|
||||
@@ -378,7 +376,7 @@ export class ForwardApi {
|
||||
}
|
||||
|
||||
async fetch(resId: string): Promise<ForwardNodePayload[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const cached = forwardResCache.get(resId);
|
||||
if (cached) {
|
||||
return cached.map(node => ({
|
||||
@@ -1,10 +1,10 @@
|
||||
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 { BridgeContext } from '../bridge-context';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class FriendApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
/**
|
||||
* Accept or reject an inbound friend request. `uidOrFlag` is either a
|
||||
@@ -12,10 +12,10 @@ import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set
|
||||
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 { BridgeContext } from '../bridge-context';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class GroupAdminApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
} 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 { BridgeContext } from '../bridge-context';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
|
||||
function convertBigIntToString(obj: unknown): JsonValue {
|
||||
@@ -31,7 +31,7 @@ function convertBigIntToString(obj: unknown): JsonValue {
|
||||
}
|
||||
|
||||
export class GroupAlbumApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
|
||||
async list(groupId: number): Promise<GroupAlbumList> {
|
||||
@@ -4,8 +4,7 @@ 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 { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
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';
|
||||
@@ -28,8 +27,6 @@ import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
|
||||
|
||||
const log = createLogger('GroupFile');
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
// ─────────────── public result types ───────────────
|
||||
|
||||
export interface GroupFileInfo {
|
||||
@@ -217,7 +214,7 @@ function buildPrivateFileUploadExt(
|
||||
}
|
||||
|
||||
export class GroupFileApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// ─────────────── publish (group file → chat) ───────────────
|
||||
|
||||
@@ -241,7 +238,7 @@ export class GroupFileApi {
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
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);
|
||||
@@ -341,7 +338,7 @@ export class GroupFileApi {
|
||||
name = '',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
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');
|
||||
|
||||
@@ -580,7 +577,7 @@ export class GroupFileApi {
|
||||
}
|
||||
|
||||
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
void userId;
|
||||
const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
|
||||
@@ -627,7 +624,7 @@ export class GroupFileApi {
|
||||
}
|
||||
|
||||
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
|
||||
}
|
||||
@@ -637,7 +634,7 @@ export class GroupFileApi {
|
||||
}
|
||||
|
||||
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { CoreContext } from '../core-context';
|
||||
import { ContactsApi } from './contacts';
|
||||
import { ExtrasApi } from './extras';
|
||||
import { ForwardApi } from './forward';
|
||||
@@ -47,7 +47,7 @@ export interface ApiHub {
|
||||
* runtime-mutated `apis.xxx` slots, neither of which is worth the
|
||||
* complexity for ~13 small classes.
|
||||
*/
|
||||
export function buildApiHub(ctx: BridgeContext): ApiHub {
|
||||
export function buildApiHub(ctx: CoreContext): ApiHub {
|
||||
return {
|
||||
message: new MessageApi(ctx),
|
||||
contacts: new ContactsApi(ctx),
|
||||
@@ -67,16 +67,21 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
|
||||
// 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 } from './contacts';
|
||||
export { ExtrasApi } from './extras';
|
||||
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 } from './message';
|
||||
export { MessageApi, type SendMessageReceipt } from './message';
|
||||
export { MiscApi } from './misc';
|
||||
export { ProfileApi } from './profile';
|
||||
export { WebApi } from './web';
|
||||
export { type MediaIndexNode } from './shared';
|
||||
export { WebApi, type ClientKeyInfo, type WebHonorInfo, type WebNoticeInfo } from './web';
|
||||
|
||||
@@ -12,10 +12,10 @@ import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-ess
|
||||
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 { BridgeContext } from '../bridge-context';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class InteractionApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
|
||||
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
|
||||
@@ -11,21 +11,26 @@ import type {
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
// `Bridge` is imported as a type only so we can narrow `ctx` back to
|
||||
// the concrete Bridge instance when passing it to `buildSendElems`
|
||||
// (which still takes `Bridge` because the highway upload helpers it
|
||||
// transitively calls each take `Bridge` — refactoring those is a
|
||||
// separate concern that doesn't need to land alongside the Api split).
|
||||
//
|
||||
// At runtime `ctx` IS the Bridge instance that constructed this
|
||||
// MessageApi — `buildApiHub(ctx)` passes the Bridge itself.
|
||||
import type { Bridge, SendMessageReceipt } from '../bridge';
|
||||
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: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
/**
|
||||
* Send a message to a QQ group.
|
||||
@@ -41,7 +46,7 @@ export class MessageApi {
|
||||
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 as unknown as Bridge, groupId });
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx, groupId });
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
@@ -97,7 +102,7 @@ export class MessageApi {
|
||||
userUid = await this.ctx.resolveUserUid(userUin);
|
||||
}
|
||||
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx, userUid });
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
@@ -4,15 +4,14 @@ import type {
|
||||
MiniAppShareResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
// 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 { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key';
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
translateEn2Zh(words: string[]): Promise<string[]> {
|
||||
return TranslateEnToZh.invoke(this.ctx, { words });
|
||||
@@ -76,15 +75,4 @@ export class MiscApi {
|
||||
sendGroupSign(groupId: number): Promise<void> {
|
||||
return SendGroupSign.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
async getDecryptKey(dbSalt: string): Promise<string> {
|
||||
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
|
||||
}
|
||||
if (!result.dbKey) {
|
||||
throw new Error('Decrypt key is empty');
|
||||
}
|
||||
return result.dbKey;
|
||||
}
|
||||
}
|
||||
@@ -13,13 +13,10 @@ import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-inp
|
||||
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 { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export class ProfileApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// ─────────────── status / profile setters ───────────────
|
||||
|
||||
@@ -82,7 +79,7 @@ export class ProfileApi {
|
||||
}
|
||||
|
||||
async setAvatar(source: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const loaded = await loadBinarySource(source, 'avatar');
|
||||
if (!loaded.bytes.length) throw new Error('avatar file is empty');
|
||||
|
||||
@@ -102,7 +99,7 @@ export class ProfileApi {
|
||||
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
|
||||
*/
|
||||
async setGroupAvatar(groupId: number, source: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const loaded = await loadBinarySource(source, 'group-avatar');
|
||||
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Bridge } from '../bridge';
|
||||
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
export function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
@@ -31,7 +32,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: Bridge): Promise<string> {
|
||||
export async function resolveSelfUid(bridge: BridgeContext): Promise<string> {
|
||||
let selfUid = bridge.identity.selfUid;
|
||||
if (selfUid) return selfUid;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
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';
|
||||
@@ -11,10 +11,7 @@ import {
|
||||
type SetNoticeRetSuccess,
|
||||
} from '@snowluma/protocol/web/group-notice';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
import type { CoreContext } from '../core-context';
|
||||
|
||||
export type ClientKeyInfo = NamespaceClientKeyInfo;
|
||||
|
||||
@@ -45,15 +42,15 @@ export interface WebNoticeInfo {
|
||||
|
||||
// ─────────────── private helpers (cookie acquisition) ───────────────
|
||||
|
||||
function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
|
||||
function forceFetchClientKeyInner(bridge: BridgeContext): Promise<ClientKeyInfo> {
|
||||
return ForceFetchClientKey.invoke(bridge);
|
||||
}
|
||||
|
||||
function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
|
||||
function getPSkey(bridge: BridgeContext, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
|
||||
return GetPskey.invoke(bridge, { domainList });
|
||||
}
|
||||
|
||||
async function getCookies(bridge: Bridge, domain: string): Promise<Record<string, string>> {
|
||||
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
|
||||
@@ -83,7 +80,7 @@ async function getCookies(bridge: Bridge, domain: string): Promise<Record<string
|
||||
return data;
|
||||
}
|
||||
|
||||
async function getSKey(bridge: Bridge): Promise<string> {
|
||||
async function getSKey(bridge: BridgeContext): Promise<string> {
|
||||
const ClientKeyData = await forceFetchClientKeyInner(bridge);
|
||||
|
||||
if (!ClientKeyData.clientKey) {
|
||||
@@ -120,23 +117,23 @@ function getBknFromSKey(skey: string): number {
|
||||
}
|
||||
|
||||
export class WebApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: CoreContext) { }
|
||||
|
||||
// ─────────────── cookie / token primitives ───────────────
|
||||
|
||||
async forceFetchClientKey(): Promise<ClientKeyInfo> {
|
||||
return forceFetchClientKeyInner(asBridge(this.ctx));
|
||||
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(asBridge(this.ctx), domain);
|
||||
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(asBridge(this.ctx), domain);
|
||||
const cookieObject = await getCookies(this.ctx, domain);
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
@@ -144,7 +141,7 @@ export class WebApi {
|
||||
|
||||
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
|
||||
async getCsrfToken(): Promise<number> {
|
||||
const skey = await getSKey(asBridge(this.ctx));
|
||||
const skey = await getSKey(this.ctx);
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
@@ -153,7 +150,7 @@ export class WebApi {
|
||||
|
||||
/** 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(asBridge(this.ctx), domain);
|
||||
const cookieObject = await getCookies(this.ctx, domain);
|
||||
const cookiesStr = Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
@@ -172,7 +169,7 @@ export class WebApi {
|
||||
|
||||
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
|
||||
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
|
||||
@@ -181,7 +178,7 @@ export class WebApi {
|
||||
|
||||
/** Walks every page and returns the concatenated result. */
|
||||
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await getGroupEssenceMsgAll(cookieObject, groupCode);
|
||||
@@ -190,7 +187,7 @@ export class WebApi {
|
||||
// ─────────────── group honor ───────────────
|
||||
|
||||
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
@@ -239,7 +236,7 @@ export class WebApi {
|
||||
confirm_required?: number;
|
||||
},
|
||||
): Promise<SetNoticeRetSuccess> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
@@ -248,11 +245,16 @@ export class WebApi {
|
||||
let imgHeight = 300;
|
||||
|
||||
if (options?.image) {
|
||||
// Route through loadBinarySource so the group-notice image download
|
||||
// gets the same browser-UA + Referer-retry hardening as every other
|
||||
// media fetch — and http/file/base64 source handling for free.
|
||||
const loaded = await loadBinarySource(options.image, 'group-notice image');
|
||||
const imageBuffer = Buffer.from(loaded.bytes);
|
||||
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) {
|
||||
@@ -284,7 +286,7 @@ export class WebApi {
|
||||
}
|
||||
|
||||
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
@@ -325,7 +327,7 @@ export class WebApi {
|
||||
}
|
||||
|
||||
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const bridge = this.ctx;
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
|
||||
@@ -1,8 +0,0 @@
|
||||
import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
import type { ApiHub } from './apis';
|
||||
|
||||
export interface BridgeContext extends BaseBridgeContext {
|
||||
readonly apis: ApiHub;
|
||||
}
|
||||
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import type { BridgeContext } from './bridge-context';
|
||||
|
||||
export interface BridgeInterface extends BridgeContext {
|
||||
readonly activePid: number | null;
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import {
|
||||
AiVoiceChatType,
|
||||
type AiVoiceCategory,
|
||||
type StrangerStatus,
|
||||
} from './apis/extras';
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
|
||||
export class Bridge implements BridgeInterface {
|
||||
readonly identity: IdentityService;
|
||||
private pids_ = new Set<number>();
|
||||
readonly events = new BridgeEventBus();
|
||||
readonly apis: ApiHub;
|
||||
private readonly pipeline: IncomingPacketPipeline;
|
||||
private packetClient_: PacketSender | null = null;
|
||||
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
|
||||
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||
|
||||
constructor(identity: IdentityService) {
|
||||
this.identity = identity;
|
||||
this.apis = buildApiHub(this);
|
||||
this.identity.setFetcher({
|
||||
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
|
||||
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
|
||||
});
|
||||
this.pipeline = new IncomingPacketPipeline({
|
||||
identity: this.identity,
|
||||
events: this.events,
|
||||
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
|
||||
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
|
||||
resolveStrangerProfile: async (uid) => {
|
||||
try {
|
||||
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
|
||||
if (p.uin <= 0) return null;
|
||||
return { uin: p.uin, nickname: p.nickname };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
resolveGroupJoinRequest: async (groupId, uid, subType) => {
|
||||
try {
|
||||
const requests = await this.apis.contacts.fetchGroupRequests();
|
||||
const match = requests.find(r => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
|
||||
});
|
||||
if (!match) return null;
|
||||
return { comment: match.comment, sequence: match.sequence };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
});
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
this.pipeline.process(pkt);
|
||||
}
|
||||
|
||||
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
|
||||
if (refreshGroupList) {
|
||||
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
|
||||
}
|
||||
if (!this.identity.findGroup(groupId)) return false;
|
||||
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
|
||||
return true;
|
||||
}
|
||||
rememberUploadedFile(meta: UploadedFileMeta): void {
|
||||
if (!meta.fileId) return;
|
||||
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
|
||||
// Map iteration order is insertion order — drop the oldest.
|
||||
const oldest = this.uploadedFileMeta_.keys().next().value;
|
||||
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
|
||||
}
|
||||
this.uploadedFileMeta_.set(meta.fileId, meta);
|
||||
}
|
||||
|
||||
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
|
||||
if (!fileId) return undefined;
|
||||
return this.uploadedFileMeta_.get(fileId);
|
||||
}
|
||||
|
||||
nextClientSequence(): number {
|
||||
return ++this.clientSeq_;
|
||||
}
|
||||
|
||||
nextMessageRandom(): number {
|
||||
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
|
||||
return this.msgRandom_ & 0x7FFFFFFF;
|
||||
}
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
|
||||
return {
|
||||
success: false, gotResponse: false, errorCode: -1,
|
||||
errorMessage: 'no packet sender attached', responseData: null,
|
||||
};
|
||||
}
|
||||
const startedAt = Date.now();
|
||||
const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
const elapsed = Date.now() - startedAt;
|
||||
const respLen = result.responseData ? result.responseData.length : 0;
|
||||
if (!result.success || result.errorCode !== 0) {
|
||||
// QQ-side rejection or transport failure — the usual root cause when an
|
||||
// action misbehaves. Warn (persisted) with cmd + code so a user's log
|
||||
// shows exactly where the chain broke.
|
||||
log.warn('packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
|
||||
serviceCmd, result.errorCode, result.gotResponse,
|
||||
result.errorMessage ?? '', this.identity.uin, body.length, elapsed);
|
||||
} else {
|
||||
// Happy path — memory-only trace so the full chain shows under the
|
||||
// request's [req#N] when debugging, without flooding disk.
|
||||
log.trace(() => [`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
}
|
||||
}
|
||||
export interface SendMessageReceipt {
|
||||
messageId: number;
|
||||
sequence: number;
|
||||
clientSequence: number;
|
||||
random: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface UploadedFileMeta {
|
||||
fileId: string;
|
||||
scope: 'group' | 'private';
|
||||
/** Group id if scope='group', else `undefined`. */
|
||||
groupId?: number;
|
||||
/** Friend uin if scope='private', else `undefined`. */
|
||||
userId?: number;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
fileMd5: Uint8Array;
|
||||
fileSha1: Uint8Array;
|
||||
/** Server-issued hash returned alongside the upload (private only). */
|
||||
fileHash?: string;
|
||||
/** Insert time — used to evict the oldest entry when the cache fills. */
|
||||
rememberedAt: number;
|
||||
}
|
||||
|
||||
export interface DownloadRKeyInfo {
|
||||
rkey: string;
|
||||
ttlSeconds: number;
|
||||
storeId: number;
|
||||
createTime: number;
|
||||
type: number;
|
||||
}
|
||||
|
||||
export interface ClientKeyInfo {
|
||||
clientKey: string;
|
||||
expireTime: string;
|
||||
keyIndex: string
|
||||
}
|
||||
export { AiVoiceChatType };
|
||||
export type { AiVoiceCategory, StrangerStatus };
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { Bridge } from './bridge';
|
||||
|
||||
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_;
|
||||
}
|
||||
}
|
||||
26
packages/core/src/core-context.ts
Normal file
26
packages/core/src/core-context.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { BridgeContext as ProtocolBridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
import type { ApiHub } from './apis';
|
||||
|
||||
/**
|
||||
* `CoreContext` — the internal context that Api wrappers (`apis/*`)
|
||||
* consume. Only used inside `@snowluma/core`; OneBot and other inbound
|
||||
* adapters consume the narrower `CoreCtx` projection instead.
|
||||
*
|
||||
* It extends the protocol-layer `BridgeContext` with one extra slot:
|
||||
* `apis: ApiHub`. The protocol layer can't mention `ApiHub` because
|
||||
* the apis live in @snowluma/core, so the shared surface is layered:
|
||||
*
|
||||
* - `@snowluma/protocol/bridge-context.BridgeContext` — identity,
|
||||
* events, raw packet I/O, sequences, file cache. Consumed by
|
||||
* `element-builder`, highway uploaders, msg-push decoders.
|
||||
* - `@snowluma/core/core-context.CoreContext` — adds `apis`.
|
||||
* Consumed by everything inside `apis/*` and by tests that
|
||||
* stub the surface for OneBot-side unit tests.
|
||||
*
|
||||
* The concrete `Core` class implements this extended interface.
|
||||
*/
|
||||
export interface CoreContext extends ProtocolBridgeContext {
|
||||
readonly apis: ApiHub;
|
||||
}
|
||||
|
||||
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
|
||||
34
packages/core/src/core-ctx.ts
Normal file
34
packages/core/src/core-ctx.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { ChannelKind } from '@snowluma/channel';
|
||||
import type { CoreContext } from './core-context';
|
||||
|
||||
/**
|
||||
* `CoreCtx` — the public surface every QQ account exposes to the rest
|
||||
* of the system (OneBot, future MCP clients, WebUI status panels). It
|
||||
* is the structural projection of a `Core` instance that consumers
|
||||
* receive via `Hub.events.on('core-online', ...)`.
|
||||
*
|
||||
* Reading this type is the right starting point when wiring a new
|
||||
* consumer:
|
||||
*
|
||||
* - `identity` / `events` / `apis` / sequence helpers / file cache
|
||||
* are inherited from `CoreContext`.
|
||||
* - `kind` / `id` / `uin` mirror the underlying channel's identity
|
||||
* so consumers can branch on transport kind when they really need
|
||||
* to (e.g. WebUI diagnostics) without `instanceof` checks.
|
||||
* - `dispose()` is the lifecycle hook; `Hub` calls it when the
|
||||
* underlying channel disappears.
|
||||
*
|
||||
* Day-to-day consumers should stay kind-agnostic — that's the entire
|
||||
* point of the abstraction.
|
||||
*/
|
||||
export interface CoreCtx extends CoreContext {
|
||||
/** Transport family backing this account. */
|
||||
readonly kind: ChannelKind;
|
||||
/** Stable, unique-per-account id (mirrors the channel's id). */
|
||||
readonly id: string;
|
||||
/** QQ number this account represents. Mirrors `identity.uin`. */
|
||||
readonly uin: string;
|
||||
/** Release identity DB handles, event subscribers, and any
|
||||
* account-level resources. Idempotent. */
|
||||
dispose(): void;
|
||||
}
|
||||
181
packages/core/src/core.ts
Normal file
181
packages/core/src/core.ts
Normal file
@@ -0,0 +1,181 @@
|
||||
import type { ChannelCtx, ChannelKind } from '@snowluma/channel';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import type { CoreCtx } from './core-ctx';
|
||||
|
||||
/**
|
||||
* `Core` — the QQ-account-level business object that sits on top of a
|
||||
* `Channel` transport (consumed indirectly via a `ChannelCtx`
|
||||
* capability POJO). Owns everything OneBot, the apis, and the msg-push
|
||||
* pipeline care about:
|
||||
*
|
||||
* - `identity` (per-uin SQLite-backed roster + uid↔uin index),
|
||||
* - the typed `BridgeEventBus` (subscribe to per-account events by kind),
|
||||
* - the `ApiHub` (typed wrappers around `sendRawPacket`),
|
||||
* - the `IncomingPacketPipeline` (cmd → decoder → emit on bus),
|
||||
* - the uploaded-file cache (shared between `upload_*_file` and
|
||||
* `send_msg`),
|
||||
* - the monotonic `clientSequence` / `messageRandom` counters.
|
||||
*
|
||||
* The transport is opaque: `Core` only calls `channelCtx.sendRawPacket`
|
||||
* and subscribes via `channelCtx.onPacket` so all incoming packets flow
|
||||
* into its pipeline. Swap the transport (hook → socket) and everything
|
||||
* above keeps working unchanged because `Core` never holds the `Channel`
|
||||
* itself — only the capability POJO.
|
||||
*
|
||||
* Lifecycle is managed by `Hub`: the hub registers `ChannelAdapter`s,
|
||||
* builds a `ChannelCtx` from each freshly-available channel, materialises
|
||||
* a `Core` on the way up, and calls `dispose()` on the way down. OneBot
|
||||
* consumers see `CoreCtx` (the structural projection); never `Core`
|
||||
* itself.
|
||||
*/
|
||||
export class Core implements CoreCtx {
|
||||
readonly kind: ChannelKind;
|
||||
readonly id: string;
|
||||
readonly uin: string;
|
||||
readonly identity: IdentityService;
|
||||
readonly events = new BridgeEventBus();
|
||||
readonly apis: ApiHub;
|
||||
|
||||
private readonly channelCtx_: ChannelCtx;
|
||||
private readonly pipeline_: IncomingPacketPipeline;
|
||||
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
|
||||
private readonly uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||
private disposed_ = false;
|
||||
constructor(channelCtx: ChannelCtx, identity: IdentityService = IdentityService.openForUin(channelCtx.uin)) {
|
||||
this.channelCtx_ = channelCtx;
|
||||
this.kind = channelCtx.kind;
|
||||
this.id = `${channelCtx.kind}:${channelCtx.uin}`;
|
||||
this.uin = channelCtx.uin;
|
||||
this.identity = identity;
|
||||
this.apis = buildApiHub(this);
|
||||
this.identity.setFetcher({
|
||||
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
|
||||
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
|
||||
});
|
||||
this.pipeline_ = new IncomingPacketPipeline({
|
||||
identity: this.identity,
|
||||
events: this.events,
|
||||
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
|
||||
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
|
||||
resolveStrangerProfile: async (uid) => {
|
||||
try {
|
||||
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
|
||||
if (p.uin <= 0) return null;
|
||||
return { uin: p.uin, nickname: p.nickname };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
resolveGroupJoinRequest: async (groupId, uid, subType) => {
|
||||
try {
|
||||
const requests = await this.apis.contacts.fetchGroupRequests();
|
||||
const match = requests.find(r => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
|
||||
});
|
||||
if (!match) return null;
|
||||
return { comment: match.comment, sequence: match.sequence };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
});
|
||||
this.pipeline_.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||
|
||||
// Subscribe to inbound packets from the channel. The underlying
|
||||
// `Channel` only supports a single subscriber (us); the
|
||||
// `ChannelAdapter` pumps packets through `channel.deliverPacket`,
|
||||
// which `Hub` wires into us via `channelCtx.onPacket`.
|
||||
channelCtx.onPacket((pkt: PacketInfo) => this.pipeline_.process(pkt));
|
||||
}
|
||||
|
||||
// ─── CoreCtx plumbing ────────────────────────────────────────────
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed_) return;
|
||||
this.disposed_ = true;
|
||||
this.channelCtx_.onPacket(null);
|
||||
this.identity.close();
|
||||
this.events.clear();
|
||||
}
|
||||
|
||||
get isDisposed(): boolean { return this.disposed_; }
|
||||
|
||||
// ─── Transport (proxied to the underlying Bridge) ──────────────
|
||||
|
||||
async sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<SendPacketResult> {
|
||||
return this.channelCtx_.sendRawPacket(serviceCmd, body, timeoutMs);
|
||||
}
|
||||
|
||||
// ─── Pipeline registration (used by tests + extra cmd modules) ─
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
this.pipeline_.registerCmd(cmd, parser);
|
||||
}
|
||||
|
||||
handlesCmd(cmd: string): boolean {
|
||||
return this.pipeline_.handlesCmd(cmd);
|
||||
}
|
||||
|
||||
// ─── Send-side protocol helpers (shared sequence generators) ───
|
||||
|
||||
nextClientSequence(): number {
|
||||
return ++this.clientSeq_;
|
||||
}
|
||||
|
||||
nextMessageRandom(): number {
|
||||
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
|
||||
return this.msgRandom_ & 0x7FFFFFFF;
|
||||
}
|
||||
|
||||
// ─── Uploaded-file cache ───────────────────────────────────────
|
||||
|
||||
rememberUploadedFile(meta: UploadedFileMeta): void {
|
||||
if (!meta.fileId) return;
|
||||
if (this.uploadedFileMeta_.size >= Core.UPLOADED_FILE_CACHE_MAX) {
|
||||
// Map iteration order is insertion order — drop the oldest.
|
||||
const oldest = this.uploadedFileMeta_.keys().next().value;
|
||||
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
|
||||
}
|
||||
this.uploadedFileMeta_.set(meta.fileId, meta);
|
||||
}
|
||||
|
||||
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
|
||||
if (!fileId) return undefined;
|
||||
return this.uploadedFileMeta_.get(fileId);
|
||||
}
|
||||
|
||||
// ─── Identity convenience ──────────────────────────────────────
|
||||
|
||||
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
}
|
||||
|
||||
// ─── Internal helpers ──────────────────────────────────────────
|
||||
|
||||
private async refreshMemberCache(
|
||||
groupId: number,
|
||||
refreshGroupList: boolean,
|
||||
forceMemberList: boolean,
|
||||
): Promise<boolean> {
|
||||
if (refreshGroupList) {
|
||||
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
|
||||
}
|
||||
if (!this.identity.findGroup(groupId)) return false;
|
||||
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
238
packages/core/src/hub.ts
Normal file
238
packages/core/src/hub.ts
Normal file
@@ -0,0 +1,238 @@
|
||||
import {
|
||||
makeChannelCtx,
|
||||
type Channel,
|
||||
type ChannelAdapter,
|
||||
type ChannelAdapterHost,
|
||||
type ChannelKind,
|
||||
} from '@snowluma/channel';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { Core } from './core';
|
||||
import type { CoreCtx } from './core-ctx';
|
||||
|
||||
const log = createLogger('Hub');
|
||||
|
||||
export type HubEventMap = {
|
||||
'core-online': CoreCtx;
|
||||
'core-offline': { uin: string };
|
||||
};
|
||||
|
||||
export type HubEventHandler<K extends keyof HubEventMap> = (payload: HubEventMap[K]) => void;
|
||||
export type HubEventDisposer = () => void;
|
||||
|
||||
|
||||
class HubEvents {
|
||||
private readonly listeners_ = new Map<keyof HubEventMap, Set<(p: unknown) => void>>();
|
||||
|
||||
on<K extends keyof HubEventMap>(event: K, handler: HubEventHandler<K>): HubEventDisposer {
|
||||
let set = this.listeners_.get(event);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.listeners_.set(event, set);
|
||||
}
|
||||
const wrapped = handler as (p: unknown) => void;
|
||||
set.add(wrapped);
|
||||
return () => set!.delete(wrapped);
|
||||
}
|
||||
|
||||
emit<K extends keyof HubEventMap>(event: K, payload: HubEventMap[K]): void {
|
||||
const set = this.listeners_.get(event);
|
||||
if (!set || set.size === 0) return;
|
||||
for (const handler of [...set]) {
|
||||
try {
|
||||
(handler as HubEventHandler<K>)(payload);
|
||||
} catch (err) {
|
||||
log.warn('hub listener (%s) threw: %s', event, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.listeners_.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export class Hub {
|
||||
private readonly adapters_ = new Map<ChannelKind, ChannelAdapter>();
|
||||
private readonly channelsById_ = new Map<string, Channel>();
|
||||
private readonly channelsByUin_ = new Map<string, Channel>();
|
||||
|
||||
// ─── core pool (was AccountManager) ──────────────────────────────
|
||||
private readonly cores_ = new Map<string, Core>();
|
||||
|
||||
// ─── lifecycle event bus ──────────────────────────────────────────
|
||||
readonly events = new HubEvents();
|
||||
|
||||
private started_ = false;
|
||||
private disposed_ = false;
|
||||
|
||||
// ─── adapter registration ────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Register a channel adapter. Must be called BEFORE `start()`; the
|
||||
* hub enforces at most one adapter per `kind`.
|
||||
*/
|
||||
registerAdapter(adapter: ChannelAdapter): void {
|
||||
if (this.started_) {
|
||||
throw new Error('Hub: cannot register adapters after start()');
|
||||
}
|
||||
if (this.adapters_.has(adapter.kind)) {
|
||||
throw new Error(`Hub: adapter of kind '${adapter.kind}' is already registered`);
|
||||
}
|
||||
this.adapters_.set(adapter.kind, adapter);
|
||||
}
|
||||
|
||||
getAdapter(kind: ChannelKind): ChannelAdapter | null {
|
||||
return this.adapters_.get(kind) ?? null;
|
||||
}
|
||||
|
||||
// ─── lifecycle ───────────────────────────────────────────────────
|
||||
|
||||
/** Start every registered adapter. Idempotent. */
|
||||
async start(): Promise<void> {
|
||||
if (this.started_) return;
|
||||
this.started_ = true;
|
||||
for (const [kind, adapter] of this.adapters_) {
|
||||
const host = this.makeHost(kind);
|
||||
try {
|
||||
await adapter.start(host);
|
||||
} catch (err) {
|
||||
log.warn('adapter [%s] failed to start: %s', kind,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Dispose every adapter (which removes their channels via the
|
||||
* host), then dispose any cores/channels that somehow remain.
|
||||
* Idempotent. */
|
||||
async dispose(): Promise<void> {
|
||||
if (this.disposed_) return;
|
||||
this.disposed_ = true;
|
||||
for (const [kind, adapter] of this.adapters_) {
|
||||
try {
|
||||
await adapter.dispose();
|
||||
} catch (err) {
|
||||
log.warn('adapter [%s] failed to dispose: %s', kind,
|
||||
err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
for (const core of this.cores_.values()) {
|
||||
try { core.dispose(); } catch { /* ignore */ }
|
||||
}
|
||||
for (const channel of this.channelsById_.values()) {
|
||||
try { channel.dispose(); } catch { /* ignore */ }
|
||||
}
|
||||
this.cores_.clear();
|
||||
this.channelsById_.clear();
|
||||
this.channelsByUin_.clear();
|
||||
this.events.clear();
|
||||
}
|
||||
|
||||
// ─── queries ─────────────────────────────────────────────────────
|
||||
|
||||
/** The `Core` (full business object) for a UIN, or `null` if no
|
||||
* account is online. Internal-ish — callers typically work with
|
||||
* `CoreCtx` received from the `'core-online'` event instead. */
|
||||
getCore(uin: string): Core | null {
|
||||
return this.cores_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
getCores(): readonly Core[] {
|
||||
return [...this.cores_.values()];
|
||||
}
|
||||
|
||||
/** Channel for a UIN, or `null` if the UIN is offline. */
|
||||
getChannel(uin: string): Channel | null {
|
||||
return this.channelsByUin_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
getOnlineUins(): readonly string[] {
|
||||
return [...this.channelsByUin_.keys()];
|
||||
}
|
||||
|
||||
// ─── ChannelAdapterHost implementation (per-adapter) ─────────────
|
||||
|
||||
private makeHost(kind: ChannelKind): ChannelAdapterHost {
|
||||
const adapterLog = log.child({ adapter: kind });
|
||||
return {
|
||||
log: adapterLog,
|
||||
addChannel: (channel) => this.addChannel(channel, adapterLog),
|
||||
removeChannel: (id) => this.removeChannel(id, adapterLog),
|
||||
};
|
||||
}
|
||||
|
||||
private addChannel(channel: Channel, adapterLog: Logger): void {
|
||||
if (this.disposed_) return;
|
||||
if (this.channelsById_.has(channel.id)) {
|
||||
adapterLog.warn('addChannel: id=%s already registered, ignoring', channel.id);
|
||||
return;
|
||||
}
|
||||
const existing = this.channelsByUin_.get(channel.uin);
|
||||
if (existing) {
|
||||
adapterLog.warn('addChannel: UIN=%s already has channel=%s, replacing with %s',
|
||||
channel.uin, existing.id, channel.id);
|
||||
this.channelsById_.delete(existing.id);
|
||||
this.channelsById_.set(channel.id, channel);
|
||||
this.channelsByUin_.set(channel.uin, channel);
|
||||
|
||||
this.bringCoreOffline(channel.uin);
|
||||
this.bringCoreOnline(channel.uin, channel);
|
||||
|
||||
try { existing.dispose(); } catch (err) {
|
||||
adapterLog.debug('channel.dispose() threw: %s',
|
||||
err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.channelsById_.set(channel.id, channel);
|
||||
this.channelsByUin_.set(channel.uin, channel);
|
||||
log.debug('account online: UIN=%s via %s', channel.uin, channel.id);
|
||||
this.bringCoreOnline(channel.uin, channel);
|
||||
}
|
||||
|
||||
private removeChannel(id: string, adapterLog: Logger): void {
|
||||
const channel = this.channelsById_.get(id);
|
||||
if (!channel) return;
|
||||
this.channelsById_.delete(id);
|
||||
|
||||
const current = this.channelsByUin_.get(channel.uin);
|
||||
const wasCurrent = current?.id === id;
|
||||
if (wasCurrent) {
|
||||
this.channelsByUin_.delete(channel.uin);
|
||||
log.debug('account offline: UIN=%s', channel.uin);
|
||||
this.bringCoreOffline(channel.uin);
|
||||
}
|
||||
|
||||
try { channel.dispose(); } catch (err) {
|
||||
adapterLog.debug('channel.dispose() threw: %s',
|
||||
err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
private bringCoreOnline(uin: string, channel: Channel): void {
|
||||
// Defensive: stale core on the same UIN means we missed the
|
||||
// offline event. Tear it down first so identity DB handles don't
|
||||
// leak.
|
||||
const stale = this.cores_.get(uin);
|
||||
if (stale) {
|
||||
log.warn('replacing stale core: UIN=%s id=%s', uin, stale.id);
|
||||
try { stale.dispose(); } catch { /* ignore */ }
|
||||
this.cores_.delete(uin);
|
||||
}
|
||||
const core = new Core(makeChannelCtx(channel));
|
||||
this.cores_.set(uin, core);
|
||||
this.events.emit('core-online', core);
|
||||
}
|
||||
|
||||
private bringCoreOffline(uin: string): void {
|
||||
const core = this.cores_.get(uin);
|
||||
if (!core) return;
|
||||
this.cores_.delete(uin);
|
||||
this.events.emit('core-offline', { uin });
|
||||
try { core.dispose(); } catch (err) {
|
||||
log.debug('core.dispose() threw: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,40 +1,38 @@
|
||||
import { HookManager } from '@snowluma/bridge';
|
||||
import { HookAdapter } from '@snowluma/channel-hook';
|
||||
import { SocketAdapter } from '@snowluma/channel-socket';
|
||||
import { closeLogger, createLogger } from '@snowluma/common/logger';
|
||||
import { loadRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { OneBotManager } from '@snowluma/onebot/manager';
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { Hub } from './hub';
|
||||
|
||||
const runtimeConfig = loadRuntimeConfig();
|
||||
const log = createLogger('App');
|
||||
|
||||
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
|
||||
// can drop at any moment, and a stray rejection on a detached callback (or a
|
||||
// throw that escapes one) must NOT take the whole process down — otherwise
|
||||
// Docker restarts it (dropping every session) and a bare Windows run just dies
|
||||
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
|
||||
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
|
||||
// known paths (e.g. the hook-client send deferreds) — these only catch what
|
||||
// slips through, and surface its stack so the real source can be fixed.
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
log.error('unhandledRejection (kept alive): %s',
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
|
||||
});
|
||||
process.on('uncaughtException', (error) => {
|
||||
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
|
||||
});
|
||||
|
||||
async function main() {
|
||||
log.info('SnowLuma starting');
|
||||
|
||||
const bridgeManager = new BridgeManager();
|
||||
// `Hub` is the single multi-account entry point — it owns channel
|
||||
// adapters (hook, socket), the per-uin `Core` map, and the
|
||||
// `core-online` / `core-offline` lifecycle event bus. Adapters
|
||||
// must be registered BEFORE hub.start().
|
||||
const hub = new Hub();
|
||||
const oneBotManager = new OneBotManager();
|
||||
|
||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
|
||||
if (autoLoadOnDiscovery) {
|
||||
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
||||
}
|
||||
const hookAdapter = new HookAdapter({ autoLoadOnDiscovery });
|
||||
hub.registerAdapter(hookAdapter);
|
||||
hub.registerAdapter(new SocketAdapter());
|
||||
|
||||
oneBotManager.bind(bridgeManager);
|
||||
// OneBot subscribes to Hub's two lifecycle events (`core-online` /
|
||||
// `core-offline`) to materialise / tear down its per-account
|
||||
// instances. Bind before start() so the very first login is
|
||||
// delivered to OneBot.
|
||||
oneBotManager.bind(hub);
|
||||
|
||||
await hub.start();
|
||||
|
||||
if (
|
||||
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
|
||||
@@ -42,7 +40,11 @@ async function main() {
|
||||
) {
|
||||
try {
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager);
|
||||
// The WebUI's process management surface is hook-specific (it
|
||||
// exposes load/unload/refresh by PID); we hand it the
|
||||
// adapter-owned HookManager directly. Future socket-only
|
||||
// panels would receive their adapter through the same channel.
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookAdapter.hookManager);
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
}
|
||||
@@ -53,7 +55,7 @@ async function main() {
|
||||
const shutdown = (signal: string) => async () => {
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
oneBotManager.dispose();
|
||||
hookManager.dispose();
|
||||
await hub.dispose();
|
||||
await closeLogger();
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { serve } from '@hono/node-server';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
|
||||
import type { HookManager, HookProcessInfo } from '@snowluma/channel-hook';
|
||||
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
|
||||
import type { OneBotManager } from '@snowluma/onebot/manager';
|
||||
@@ -14,17 +14,6 @@ import { fileURLToPath } from 'url';
|
||||
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
|
||||
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||
import { findAvailablePort } from './port';
|
||||
import {
|
||||
clearBackgroundImage,
|
||||
loadUiConfig,
|
||||
MAX_BACKGROUND_BYTES,
|
||||
publicAppearance,
|
||||
readBackgroundImage,
|
||||
saveUiConfig,
|
||||
sniffImageMime,
|
||||
writeBackgroundImage,
|
||||
} from './ui-config';
|
||||
import { getUpdateInfo } from './update-check';
|
||||
|
||||
const log = createLogger('WebUI');
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -150,10 +139,7 @@ export async function initWebUI(
|
||||
// ─── Auth middleware ─────────────────────────────────────────────────────
|
||||
app.use('/api/*', async (c, next) => {
|
||||
const reqPath = c.req.path;
|
||||
// `/api/ui/public` serves the cosmetic appearance subset to the
|
||||
// pre-auth login page, so it must skip the bearer check. It exposes
|
||||
// nothing sensitive (no layout, no secrets) — see ui-config.ts.
|
||||
if (reqPath === '/api/login' || reqPath === '/api/ui/public') return next();
|
||||
if (reqPath === '/api/login') return next();
|
||||
|
||||
const authHeader = c.req.header('Authorization');
|
||||
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
|
||||
@@ -296,38 +282,9 @@ export async function initWebUI(
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Background image (unauth, like /avatar) ─────────────────────────────
|
||||
// The login page needs to render the operator's background before auth, so
|
||||
// this route is intentionally public. It only serves a file the operator
|
||||
// themselves uploaded. Cache-busting is via the `?v=` version the client
|
||||
// appends; the bytes for a given version are immutable.
|
||||
app.get('/ui-asset/background', (c) => {
|
||||
const asset = readBackgroundImage();
|
||||
if (!asset) return c.text('no background', 404);
|
||||
return new Response(new Uint8Array(asset.bytes), {
|
||||
headers: {
|
||||
'Content-Type': asset.mime,
|
||||
'Cache-Control': 'public, max-age=31536000, immutable',
|
||||
// Defence-in-depth: never let an uploaded blob be interpreted as
|
||||
// anything but the sniffed image type.
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Read-only API ───────────────────────────────────────────────────────
|
||||
app.get('/api/status', (c) => c.json({ status: 'running' }));
|
||||
|
||||
// Advisory update check — compares the running build against the latest
|
||||
// GitHub stable release and links the user to it. Read-only: SnowLuma
|
||||
// never downloads or applies the update itself. `?force=1` bypasses the
|
||||
// server-side cache (the "立即检查" button). Never errors out — a failed
|
||||
// check returns `{ hasUpdate: false, error }` and the UI degrades quietly.
|
||||
app.get('/api/update/check', async (c) => {
|
||||
const force = c.req.query('force') === 'true' || c.req.query('force') === '1';
|
||||
return c.json(await getUpdateInfo(force));
|
||||
});
|
||||
|
||||
// Host system info
|
||||
let lastCpuTimes: { idle: number; total: number }[] | null = null;
|
||||
function sampleCpuLoad(): number[] {
|
||||
@@ -398,12 +355,6 @@ export async function initWebUI(
|
||||
return c.json({ list });
|
||||
});
|
||||
|
||||
// Live OneBot adapter health per account (listening / connected / client
|
||||
// counts / last-delivery), powering the dashboard's connection card.
|
||||
app.get('/api/connections', (c) => {
|
||||
return c.json({ list: oneBotManager.getConnectionStatuses() });
|
||||
});
|
||||
|
||||
app.get('/api/logs', (c) => {
|
||||
const limit = Number(c.req.query('limit') ?? 300);
|
||||
return c.json({ list: getRecentLogs(limit) });
|
||||
@@ -543,84 +494,6 @@ export async function initWebUI(
|
||||
}
|
||||
});
|
||||
|
||||
// ─── WebUI customization config (config/ui.json) ─────────────────────────
|
||||
// Appearance (A) + layout (C). The full config is bearer-gated; only the
|
||||
// cosmetic appearance subset is exposed unauthenticated for the login page.
|
||||
app.get('/api/ui', (c) => c.json({ config: loadUiConfig() }));
|
||||
|
||||
app.get('/api/ui/public', (c) => c.json({ appearance: publicAppearance() }));
|
||||
|
||||
app.post('/api/ui', async (c) => {
|
||||
// Reject oversized bodies before buffering — the normalizer caps individual
|
||||
// fields (customCss 50KB, per-widget config 4KB) but not the whole payload.
|
||||
const declaredLen = Number(c.req.header('content-length'));
|
||||
if (Number.isFinite(declaredLen) && declaredLen > 256 * 1024) {
|
||||
return c.json({ success: false, message: '配置过大' }, 413);
|
||||
}
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
try {
|
||||
const config = saveUiConfig(body);
|
||||
return c.json({ success: true, config });
|
||||
} catch (err) {
|
||||
log.warn('save ui.json failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 400);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/ui/background', async (c) => {
|
||||
// Early reject by Content-Length BEFORE parseBody() buffers the whole
|
||||
// multipart body into memory — otherwise a multi-GB upload is fully
|
||||
// materialized before the post-parse size check fires. The slack covers
|
||||
// the multipart envelope (boundary + part headers); the exact decoded
|
||||
// size is still enforced below. A chunked request with no Content-Length
|
||||
// skips this coarse guard, but the endpoint is bearer-gated to the single
|
||||
// admin, so that residual is acceptable.
|
||||
const declaredLen = Number(c.req.header('content-length'));
|
||||
if (Number.isFinite(declaredLen) && declaredLen > MAX_BACKGROUND_BYTES + 1024 * 1024) {
|
||||
return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413);
|
||||
}
|
||||
let file: unknown;
|
||||
try {
|
||||
const form = await c.req.parseBody();
|
||||
file = form['file'];
|
||||
} catch {
|
||||
return c.json({ success: false, message: '上传解析失败' }, 400);
|
||||
}
|
||||
if (!(file instanceof File)) {
|
||||
return c.json({ success: false, message: '缺少图片文件' }, 400);
|
||||
}
|
||||
if (file.size > MAX_BACKGROUND_BYTES) {
|
||||
return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413);
|
||||
}
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const mime = sniffImageMime(bytes);
|
||||
if (!mime) {
|
||||
return c.json({ success: false, message: '仅支持 PNG / JPEG / WebP 图片' }, 415);
|
||||
}
|
||||
try {
|
||||
const config = writeBackgroundImage(bytes, mime);
|
||||
return c.json({ success: true, config });
|
||||
} catch (err) {
|
||||
log.warn('write background image failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '保存图片失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/ui/background', (c) => {
|
||||
try {
|
||||
const config = clearBackgroundImage();
|
||||
return c.json({ success: true, config });
|
||||
} catch (err) {
|
||||
log.warn('clear background image failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '删除图片失败' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Static frontend ─────────────────────────────────────────────────────
|
||||
// Build path is relative to the bundled / dev __dirname. SPA fallback to
|
||||
// index.html so client-side routes (if any) keep working.
|
||||
@@ -630,11 +503,7 @@ export async function initWebUI(
|
||||
const indexHtmlPath = path.join(staticRoot, 'index.html');
|
||||
app.get('*', (c) => {
|
||||
// SPA fallback: only for navigations that didn't hit a static asset.
|
||||
if (
|
||||
c.req.path.startsWith('/api/') ||
|
||||
c.req.path.startsWith('/avatar/') ||
|
||||
c.req.path.startsWith('/ui-asset/')
|
||||
) {
|
||||
if (c.req.path.startsWith('/api/') || c.req.path.startsWith('/avatar/')) {
|
||||
return c.text('not found', 404);
|
||||
}
|
||||
if (existsSync(indexHtmlPath)) {
|
||||
|
||||
@@ -1,658 +0,0 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Server-side store for the WebUI customization config (`config/ui.json`).
|
||||
//
|
||||
// This is the single source of truth for appearance (A) + layout (C). The
|
||||
// browser caches it in localStorage only to avoid a first-paint flash; the
|
||||
// canonical copy lives here so a deployer's look + curated layout follow them
|
||||
// across devices/browsers.
|
||||
//
|
||||
// Trust boundaries that this module enforces:
|
||||
// * `normalizeAppearance` is total — any unknown/corrupt input collapses to
|
||||
// safe defaults. This matters because the cosmetic subset is served to an
|
||||
// UNAUTHENTICATED client (the login page) via `GET /api/ui/public`, so it
|
||||
// must never echo attacker-controlled garbage.
|
||||
// * The background-IMAGE lifecycle fields (`hasImage` / `imageMime` /
|
||||
// `imageVersion`) are server-managed: a plain `POST /api/ui` cannot set
|
||||
// them. Only the dedicated upload/delete endpoints mutate them. A client
|
||||
// save preserves whatever is currently on disk.
|
||||
|
||||
const log = createLogger('WebUI.UiConfig');
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const UI_CONFIG_PATH = path.join(CONFIG_DIR, 'ui.json');
|
||||
|
||||
/** Directory for operator-uploaded UI assets (currently just the background). */
|
||||
export const UI_ASSETS_DIR = path.join(CONFIG_DIR, 'ui-assets');
|
||||
/** Fixed path of the single background image (overwrite-on-upload). */
|
||||
export const BACKGROUND_IMAGE_PATH = path.join(UI_ASSETS_DIR, 'background');
|
||||
/** Reject uploads larger than this (bytes). */
|
||||
export const MAX_BACKGROUND_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
export const UI_CONFIG_VERSION = 1 as const;
|
||||
|
||||
// ─── Schema ──────────────────────────────────────────────────────────────
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system';
|
||||
export type AccentMode = 'preset' | 'custom';
|
||||
export type AccentScope = 'sidebar' | 'global';
|
||||
export type DarkIntensity = 'soft' | 'black';
|
||||
export type SidebarStyle = 'follow' | 'panel' | 'accent';
|
||||
export type BackgroundType = 'none' | 'solid' | 'gradient' | 'image';
|
||||
export type Density = 'cozy' | 'compact';
|
||||
export type TimeFormat = '12h' | '24h';
|
||||
/** Full color scheme. 'default' keeps the sky theme (driven by `mode`); the
|
||||
* Catppuccin flavors are complete palettes that also fix light/dark. */
|
||||
export type Palette =
|
||||
| 'default'
|
||||
| 'catppuccin-latte' | 'catppuccin-frappe' | 'catppuccin-macchiato' | 'catppuccin-mocha'
|
||||
| 'rose-pine' | 'rose-pine-moon' | 'rose-pine-dawn'
|
||||
| 'nord'
|
||||
| 'everforest-dark' | 'everforest-light';
|
||||
|
||||
export interface UiBackground {
|
||||
type: BackgroundType;
|
||||
/** Solid-fill colour (hex). Used when type === 'solid'. */
|
||||
color: string;
|
||||
/** Gradient preset id (frontend owns the catalogue). Used when type === 'gradient'. */
|
||||
gradient: string;
|
||||
/** Image readability overlay: 0 (image fully visible) … 1 (fully masked). */
|
||||
imageOpacity: number;
|
||||
/** Image blur in px (0…40). */
|
||||
imageBlur: number;
|
||||
// ── server-managed (upload/delete endpoints only) ──
|
||||
hasImage: boolean;
|
||||
imageMime: string;
|
||||
/** Bumped on each successful upload so the browser can cache-bust. */
|
||||
imageVersion: number;
|
||||
}
|
||||
|
||||
export interface UiAppearance {
|
||||
mode: ThemeMode;
|
||||
accentMode: AccentMode;
|
||||
/** Preset accent id (frontend catalogue: sky/blue/violet/…). */
|
||||
accentPreset: string;
|
||||
/** Custom accent colour (hex). Used when accentMode === 'custom'. */
|
||||
accentCustom: string;
|
||||
accentScope: AccentScope;
|
||||
darkIntensity: DarkIntensity;
|
||||
/** Full color scheme; 'default' = the built-in sky theme. */
|
||||
palette: Palette;
|
||||
sidebarStyle: SidebarStyle;
|
||||
background: UiBackground;
|
||||
/** Sans font preset id (frontend catalogue). */
|
||||
fontSans: string;
|
||||
/** Mono font preset id (frontend catalogue). */
|
||||
fontMono: string;
|
||||
/** Global UI scale, 0.9…1.2. */
|
||||
uiScale: number;
|
||||
/** Corner radius in rem, 0…2. */
|
||||
radius: number;
|
||||
density: Density;
|
||||
/** Soften animations (transforms off, shorter durations). */
|
||||
reduceMotion: boolean;
|
||||
/** Hard-disable all UI animations (stronger than reduceMotion). */
|
||||
disableMotion: boolean;
|
||||
highContrast: boolean;
|
||||
sidebarDefaultCollapsed: boolean;
|
||||
timeFormat: TimeFormat;
|
||||
/** Dashboard poll interval (ms); 0 = paused. */
|
||||
pollInterval: number;
|
||||
/**
|
||||
* Operator custom CSS, applied AFTER auth only (never on the login page —
|
||||
* `publicAppearance` strips it). Capped at 50 KB. The client injects it as
|
||||
* the last <style> and skips it under `?safe-mode=1` so a broken rule can't
|
||||
* lock the operator out.
|
||||
*/
|
||||
customCss: string;
|
||||
}
|
||||
|
||||
export interface UiLayoutItem {
|
||||
id: string;
|
||||
visible: boolean;
|
||||
/**
|
||||
* Grid position/size (overview blocks only; nav items omit them). The
|
||||
* client owns the widget catalogue, per-widget min sizes, and the
|
||||
* `stats`→tiles migration — the server just preserves + clamps these to
|
||||
* sane integer bounds so a corrupt file can't store absurd coords.
|
||||
*/
|
||||
x?: number;
|
||||
y?: number;
|
||||
w?: number;
|
||||
h?: number;
|
||||
/**
|
||||
* Per-widget settings (overview blocks only) — an opaque object the client
|
||||
* interprets by widget type (e.g. alerts: count + levels). The server only
|
||||
* checks it's a plain object within a size bound; it never reads the keys.
|
||||
*/
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface UiLayout {
|
||||
/** Ordered overview blocks. Frontend reconciles against its known set. */
|
||||
overviewBlocks: UiLayoutItem[];
|
||||
/** Ordered sidebar nav items, keyed by route path. */
|
||||
navItems: UiLayoutItem[];
|
||||
}
|
||||
|
||||
export interface UiHighlightRule {
|
||||
keyword: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export interface UiLogsPrefs {
|
||||
/** Log levels shown by default (client display filter). */
|
||||
visibleLevels: string[];
|
||||
/** Ring-buffer cap for the live view (100…5000). */
|
||||
maxLines: number;
|
||||
autoScroll: boolean;
|
||||
wrap: boolean;
|
||||
/** Keyword → colour row highlights. */
|
||||
highlightRules: UiHighlightRule[];
|
||||
}
|
||||
|
||||
export interface UiPages {
|
||||
/** Route the operator lands on after login (a nav path; '/' if unset). */
|
||||
defaultRoute: string;
|
||||
logs: UiLogsPrefs;
|
||||
/** Default sort key for the processes page. */
|
||||
processesSort: string;
|
||||
/** Default tab id for the node-config page ('' = first). */
|
||||
configTab: string;
|
||||
}
|
||||
|
||||
export interface UiConfig {
|
||||
version: typeof UI_CONFIG_VERSION;
|
||||
appearance: UiAppearance;
|
||||
layout: UiLayout;
|
||||
pages: UiPages;
|
||||
}
|
||||
|
||||
// ─── Defaults ────────────────────────────────────────────────────────────
|
||||
// Mirror the pre-existing ThemeContext defaults so an upgrade is a no-op
|
||||
// visually until the operator changes something.
|
||||
|
||||
const DEFAULT_BACKGROUND: UiBackground = {
|
||||
type: 'none',
|
||||
color: '#0ea5e9',
|
||||
gradient: 'none',
|
||||
imageOpacity: 0.15,
|
||||
imageBlur: 0,
|
||||
hasImage: false,
|
||||
imageMime: '',
|
||||
imageVersion: 0,
|
||||
};
|
||||
|
||||
const DEFAULT_APPEARANCE: UiAppearance = {
|
||||
mode: 'system',
|
||||
accentMode: 'preset',
|
||||
accentPreset: 'sky',
|
||||
accentCustom: '#38bdf8',
|
||||
accentScope: 'global',
|
||||
darkIntensity: 'soft',
|
||||
palette: 'default',
|
||||
sidebarStyle: 'follow',
|
||||
background: DEFAULT_BACKGROUND,
|
||||
fontSans: 'default',
|
||||
fontMono: 'default',
|
||||
uiScale: 1,
|
||||
radius: 0.75,
|
||||
density: 'cozy',
|
||||
reduceMotion: false,
|
||||
disableMotion: false,
|
||||
highContrast: false,
|
||||
sidebarDefaultCollapsed: false,
|
||||
timeFormat: '24h',
|
||||
pollInterval: 3000,
|
||||
customCss: '',
|
||||
};
|
||||
|
||||
const DEFAULT_OVERVIEW_BLOCKS: UiLayoutItem[] = [
|
||||
{ id: 'stats', visible: true },
|
||||
{ id: 'connections', visible: true },
|
||||
{ id: 'alerts', visible: true },
|
||||
{ id: 'host', visible: true },
|
||||
{ id: 'sessions', visible: true },
|
||||
];
|
||||
|
||||
const DEFAULT_NAV_ITEMS: UiLayoutItem[] = [
|
||||
{ id: '/', visible: true },
|
||||
{ id: '/processes', visible: true },
|
||||
{ id: '/config', visible: true },
|
||||
{ id: '/logs', visible: true },
|
||||
{ id: '/settings', visible: true },
|
||||
];
|
||||
|
||||
const LOG_LEVELS = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
const DEFAULT_PAGES: UiPages = {
|
||||
defaultRoute: '/',
|
||||
logs: {
|
||||
visibleLevels: [...LOG_LEVELS],
|
||||
maxLines: 1000,
|
||||
autoScroll: true,
|
||||
wrap: true,
|
||||
highlightRules: [],
|
||||
},
|
||||
processesSort: 'pid',
|
||||
configTab: '',
|
||||
};
|
||||
|
||||
export function defaultUiConfig(): UiConfig {
|
||||
return {
|
||||
version: UI_CONFIG_VERSION,
|
||||
appearance: { ...DEFAULT_APPEARANCE, background: { ...DEFAULT_BACKGROUND } },
|
||||
layout: {
|
||||
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((b) => ({ ...b })),
|
||||
navItems: DEFAULT_NAV_ITEMS.map((b) => ({ ...b })),
|
||||
},
|
||||
pages: defaultPages(),
|
||||
};
|
||||
}
|
||||
|
||||
function defaultPages(): UiPages {
|
||||
return { ...DEFAULT_PAGES, logs: { ...DEFAULT_PAGES.logs, visibleLevels: [...LOG_LEVELS], highlightRules: [] } };
|
||||
}
|
||||
|
||||
// ─── Normalization helpers ─────────────────────────────────────────────────
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
|
||||
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
|
||||
? (value as T)
|
||||
: fallback;
|
||||
}
|
||||
|
||||
function clampNum(value: unknown, min: number, max: number, fallback: number): number {
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
||||
return Math.trunc(clampNum(value, min, max, fallback));
|
||||
}
|
||||
|
||||
function isFiniteNum(value: unknown): boolean {
|
||||
if (typeof value === 'number') return Number.isFinite(value);
|
||||
return typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value));
|
||||
}
|
||||
|
||||
function boolOr(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
||||
function hexOr(value: unknown, fallback: string): string {
|
||||
return typeof value === 'string' && HEX_RE.test(value.trim()) ? value.trim() : fallback;
|
||||
}
|
||||
|
||||
/** Bounded free-form id (frontend owns the actual catalogue). */
|
||||
function idOr(value: unknown, fallback: string, maxLen = 64): string {
|
||||
if (typeof value !== 'string') return fallback;
|
||||
const v = value.trim();
|
||||
if (v.length === 0 || v.length > maxLen) return fallback;
|
||||
// Ids are slugs / route paths — refuse control chars and anything exotic.
|
||||
if (!/^[\w./:-]+$/.test(v)) return fallback;
|
||||
return v;
|
||||
}
|
||||
|
||||
function normalizeLayoutItems(value: unknown, fallback: UiLayoutItem[]): UiLayoutItem[] {
|
||||
if (!Array.isArray(value)) return fallback.map((i) => ({ ...i }));
|
||||
const seen = new Set<string>();
|
||||
const out: UiLayoutItem[] = [];
|
||||
for (const raw of value) {
|
||||
if (!isObject(raw)) continue;
|
||||
const id = idOr(raw.id, '');
|
||||
if (!id || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
const item: UiLayoutItem = { id, visible: boolOr(raw.visible, true) };
|
||||
// Grid coords are optional (overview blocks carry them; nav items don't).
|
||||
// Preserve + clamp when any are present; missing ones get safe defaults
|
||||
// and the client re-applies per-widget min sizes on load.
|
||||
if (isFiniteNum(raw.x) || isFiniteNum(raw.y) || isFiniteNum(raw.w) || isFiniteNum(raw.h)) {
|
||||
item.x = clampInt(raw.x, 0, 50, 0);
|
||||
item.y = clampInt(raw.y, 0, 1000, 0);
|
||||
item.w = clampInt(raw.w, 1, 12, 1);
|
||||
item.h = clampInt(raw.h, 1, 100, 1);
|
||||
}
|
||||
// Opaque per-widget config: keep only a plain object within a size bound;
|
||||
// the server never interprets the keys (the client does, per widget type).
|
||||
if (isObject(raw.config)) {
|
||||
try {
|
||||
if (JSON.stringify(raw.config).length <= 4096) item.config = raw.config;
|
||||
} catch { /* unserializable (cycles) → drop */ }
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
// An array that parsed to nothing usable is indistinguishable from corrupt;
|
||||
// fall back so the frontend always has a baseline to reconcile against.
|
||||
return out.length > 0 ? out : fallback.map((i) => ({ ...i }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The background-image fields are server-managed (only the upload/delete
|
||||
* endpoints mutate them). Normalization NEVER derives them from the value
|
||||
* being normalized — the caller supplies the trusted source:
|
||||
* * LOAD path → the parsed-from-disk file IS the truth (`imageStateFromParsed`).
|
||||
* * SAVE path → the current on-disk config is the truth (a client payload
|
||||
* cannot forge `hasImage`).
|
||||
*/
|
||||
export interface ServerImageState {
|
||||
hasImage: boolean;
|
||||
imageMime: string;
|
||||
imageVersion: number;
|
||||
}
|
||||
|
||||
const DEFAULT_IMAGE_STATE: ServerImageState = { hasImage: false, imageMime: '', imageVersion: 0 };
|
||||
|
||||
const KNOWN_IMAGE_MIMES = ['image/png', 'image/jpeg', 'image/webp'];
|
||||
|
||||
/** Coerce a raw background-ish object into a coherent, trusted image state. */
|
||||
function sanitizeImageState(value: unknown): ServerImageState {
|
||||
const v = isObject(value) ? value : {};
|
||||
const version = Math.trunc(clampNum(v.imageVersion, 0, Number.MAX_SAFE_INTEGER, 0));
|
||||
if (!boolOr(v.hasImage, false)) return { hasImage: false, imageMime: '', imageVersion: version };
|
||||
const mime = typeof v.imageMime === 'string' && KNOWN_IMAGE_MIMES.includes(v.imageMime) ? v.imageMime : '';
|
||||
// "Has image" with no recognizable mime is incoherent on-disk state; treat
|
||||
// it as no image so the serve path and the UI stay consistent.
|
||||
if (!mime) return { hasImage: false, imageMime: '', imageVersion: version };
|
||||
return { hasImage: true, imageMime: mime, imageVersion: version };
|
||||
}
|
||||
|
||||
/** Trusted image state read FROM a parsed-from-disk config blob. */
|
||||
function imageStateFromParsed(parsed: unknown): ServerImageState {
|
||||
if (!isObject(parsed) || !isObject(parsed.appearance)) return DEFAULT_IMAGE_STATE;
|
||||
return sanitizeImageState(parsed.appearance.background);
|
||||
}
|
||||
|
||||
function normalizeBackground(value: unknown, imageState: ServerImageState): UiBackground {
|
||||
const v = isObject(value) ? value : {};
|
||||
let type = oneOf<BackgroundType>(v.type, ['none', 'solid', 'gradient', 'image'], DEFAULT_BACKGROUND.type);
|
||||
// An image background is only valid when an image is actually stored —
|
||||
// otherwise the serve route 404s and the UI shows a broken wallpaper.
|
||||
if (type === 'image' && !imageState.hasImage) type = 'none';
|
||||
return {
|
||||
type,
|
||||
color: hexOr(v.color, DEFAULT_BACKGROUND.color),
|
||||
gradient: idOr(v.gradient, DEFAULT_BACKGROUND.gradient),
|
||||
imageOpacity: clampNum(v.imageOpacity, 0, 1, DEFAULT_BACKGROUND.imageOpacity),
|
||||
imageBlur: clampNum(v.imageBlur, 0, 40, DEFAULT_BACKGROUND.imageBlur),
|
||||
// Server-managed — taken from the caller-supplied trusted source, never
|
||||
// from the value being normalized.
|
||||
hasImage: imageState.hasImage,
|
||||
imageMime: imageState.imageMime,
|
||||
imageVersion: imageState.imageVersion,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeAppearance(value: unknown, imageState: ServerImageState = DEFAULT_IMAGE_STATE): UiAppearance {
|
||||
const v = isObject(value) ? value : {};
|
||||
return {
|
||||
mode: oneOf<ThemeMode>(v.mode, ['light', 'dark', 'system'], DEFAULT_APPEARANCE.mode),
|
||||
accentMode: oneOf<AccentMode>(v.accentMode, ['preset', 'custom'], DEFAULT_APPEARANCE.accentMode),
|
||||
accentPreset: idOr(v.accentPreset, DEFAULT_APPEARANCE.accentPreset, 32),
|
||||
accentCustom: hexOr(v.accentCustom, DEFAULT_APPEARANCE.accentCustom),
|
||||
accentScope: oneOf<AccentScope>(v.accentScope, ['sidebar', 'global'], DEFAULT_APPEARANCE.accentScope),
|
||||
darkIntensity: oneOf<DarkIntensity>(v.darkIntensity, ['soft', 'black'], DEFAULT_APPEARANCE.darkIntensity),
|
||||
palette: oneOf<Palette>(v.palette, ['default', 'catppuccin-latte', 'catppuccin-frappe', 'catppuccin-macchiato', 'catppuccin-mocha', 'rose-pine', 'rose-pine-moon', 'rose-pine-dawn', 'nord', 'everforest-dark', 'everforest-light'], DEFAULT_APPEARANCE.palette),
|
||||
sidebarStyle: oneOf<SidebarStyle>(v.sidebarStyle, ['follow', 'panel', 'accent'], DEFAULT_APPEARANCE.sidebarStyle),
|
||||
background: normalizeBackground(v.background, imageState),
|
||||
fontSans: idOr(v.fontSans, DEFAULT_APPEARANCE.fontSans),
|
||||
fontMono: idOr(v.fontMono, DEFAULT_APPEARANCE.fontMono),
|
||||
uiScale: clampNum(v.uiScale, 0.9, 1.2, DEFAULT_APPEARANCE.uiScale),
|
||||
radius: clampNum(v.radius, 0, 2, DEFAULT_APPEARANCE.radius),
|
||||
density: oneOf<Density>(v.density, ['cozy', 'compact'], DEFAULT_APPEARANCE.density),
|
||||
reduceMotion: boolOr(v.reduceMotion, DEFAULT_APPEARANCE.reduceMotion),
|
||||
disableMotion: boolOr(v.disableMotion, DEFAULT_APPEARANCE.disableMotion),
|
||||
highContrast: boolOr(v.highContrast, DEFAULT_APPEARANCE.highContrast),
|
||||
sidebarDefaultCollapsed: boolOr(v.sidebarDefaultCollapsed, DEFAULT_APPEARANCE.sidebarDefaultCollapsed),
|
||||
timeFormat: oneOf<TimeFormat>(v.timeFormat, ['12h', '24h'], DEFAULT_APPEARANCE.timeFormat),
|
||||
pollInterval: clampNum(v.pollInterval, 0, 60_000, DEFAULT_APPEARANCE.pollInterval),
|
||||
customCss: typeof v.customCss === 'string' ? v.customCss.slice(0, 50_000) : DEFAULT_APPEARANCE.customCss,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeLayout(value: unknown): UiLayout {
|
||||
const layout = isObject(value) ? value : {};
|
||||
return {
|
||||
overviewBlocks: normalizeLayoutItems(layout.overviewBlocks, DEFAULT_OVERVIEW_BLOCKS),
|
||||
navItems: normalizeLayoutItems(layout.navItems, DEFAULT_NAV_ITEMS),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeHighlightRules(value: unknown): UiHighlightRule[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const out: UiHighlightRule[] = [];
|
||||
for (const raw of value) {
|
||||
if (!isObject(raw) || typeof raw.keyword !== 'string') continue;
|
||||
const keyword = raw.keyword.trim().slice(0, 50);
|
||||
if (!keyword) continue; // drop empty / whitespace-only (would match every row)
|
||||
const color = typeof raw.color === 'string' ? raw.color.slice(0, 32) : '';
|
||||
out.push({ keyword, color });
|
||||
if (out.length >= 20) break; // cap the rule count
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizePages(value: unknown): UiPages {
|
||||
const v = isObject(value) ? value : {};
|
||||
const logs = isObject(v.logs) ? v.logs : {};
|
||||
const levels = Array.isArray(logs.visibleLevels)
|
||||
? LOG_LEVELS.filter((l) => (logs.visibleLevels as unknown[]).includes(l))
|
||||
: DEFAULT_PAGES.logs.visibleLevels;
|
||||
return {
|
||||
defaultRoute: idOr(v.defaultRoute, DEFAULT_PAGES.defaultRoute),
|
||||
logs: {
|
||||
visibleLevels: levels.length > 0 ? levels : [...LOG_LEVELS],
|
||||
maxLines: clampInt(logs.maxLines, 100, 5000, DEFAULT_PAGES.logs.maxLines),
|
||||
autoScroll: boolOr(logs.autoScroll, DEFAULT_PAGES.logs.autoScroll),
|
||||
wrap: boolOr(logs.wrap, DEFAULT_PAGES.logs.wrap),
|
||||
highlightRules: normalizeHighlightRules(logs.highlightRules),
|
||||
},
|
||||
processesSort: idOr(v.processesSort, DEFAULT_PAGES.processesSort),
|
||||
configTab: typeof v.configTab === 'string' ? v.configTab.slice(0, 64) : DEFAULT_PAGES.configTab,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeUiConfig(value: unknown, imageState: ServerImageState = DEFAULT_IMAGE_STATE): UiConfig {
|
||||
const v = isObject(value) ? value : {};
|
||||
return {
|
||||
version: UI_CONFIG_VERSION,
|
||||
appearance: normalizeAppearance(v.appearance, imageState),
|
||||
layout: normalizeLayout(v.layout),
|
||||
pages: normalizePages(v.pages),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Persistence ────────────────────────────────────────────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function atomicWrite(config: UiConfig): void {
|
||||
ensureConfigDir();
|
||||
const tmp = UI_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(tmp, UI_CONFIG_PATH);
|
||||
}
|
||||
|
||||
let cached: UiConfig | null = null;
|
||||
|
||||
/** Load + normalize the UI config, creating it from defaults if absent. */
|
||||
export function loadUiConfig(): UiConfig {
|
||||
if (cached) return cached;
|
||||
ensureConfigDir();
|
||||
|
||||
if (!fs.existsSync(UI_CONFIG_PATH)) {
|
||||
const fresh = defaultUiConfig();
|
||||
try {
|
||||
atomicWrite(fresh);
|
||||
} catch (err) {
|
||||
log.warn('failed to write initial ui.json: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(UI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
// On load, the file itself is the source of truth for the server-managed
|
||||
// image fields — so they survive restarts (don't reset to defaults).
|
||||
const normalized = normalizeUiConfig(parsed, imageStateFromParsed(parsed));
|
||||
// Re-persist only if normalization changed something (corrupt/old file),
|
||||
// so we self-heal on disk without rewriting on every boot.
|
||||
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
|
||||
try {
|
||||
atomicWrite(normalized);
|
||||
} catch {
|
||||
/* best-effort self-heal */
|
||||
}
|
||||
}
|
||||
cached = normalized;
|
||||
return normalized;
|
||||
} catch (err) {
|
||||
log.warn('ui.json unreadable; using defaults: %s', err instanceof Error ? err.message : String(err));
|
||||
const fresh = defaultUiConfig();
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a client-supplied config. The incoming appearance is normalized and
|
||||
* its server-managed background-image fields are forced to the current on-disk
|
||||
* truth (the client cannot fake `hasImage`). Returns the stored config.
|
||||
*/
|
||||
export function saveUiConfig(incoming: unknown): UiConfig {
|
||||
const current = loadUiConfig();
|
||||
const v = isObject(incoming) ? incoming : {};
|
||||
// Section-level merge: a payload may carry just `appearance` (the theme
|
||||
// editor) or just `layout` (the layout editor) without clobbering the
|
||||
// other. A missing/non-object section keeps the current on-disk value.
|
||||
// The current on-disk state is the truth for the server-managed image
|
||||
// fields — a client payload cannot forge `hasImage` etc.
|
||||
const next: UiConfig = {
|
||||
version: UI_CONFIG_VERSION,
|
||||
appearance: isObject(v.appearance)
|
||||
? normalizeAppearance(v.appearance, current.appearance.background)
|
||||
: current.appearance,
|
||||
layout: isObject(v.layout) ? normalizeLayout(v.layout) : current.layout,
|
||||
pages: isObject(v.pages) ? normalizePages(v.pages) : (current.pages ?? defaultPages()),
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** The appearance subset served unauthenticated to the login page. Strips
|
||||
* `customCss` so a broken/hostile rule can never reach the pre-auth page
|
||||
* (and so the operator can always log in to fix it). */
|
||||
export function publicAppearance(): UiAppearance {
|
||||
return { ...loadUiConfig().appearance, customCss: '' };
|
||||
}
|
||||
|
||||
// ─── Background image lifecycle ─────────────────────────────────────────────
|
||||
|
||||
const IMAGE_MIME: Record<string, string> = {
|
||||
png: 'image/png',
|
||||
jpeg: 'image/jpeg',
|
||||
webp: 'image/webp',
|
||||
};
|
||||
|
||||
/**
|
||||
* Identify an image by its magic bytes (never by a client-supplied filename or
|
||||
* Content-Type). Returns the canonical MIME, or null if it isn't a supported
|
||||
* image. Supported: PNG, JPEG, WebP.
|
||||
*/
|
||||
export function sniffImageMime(bytes: Uint8Array): string | null {
|
||||
if (bytes.length >= 8 &&
|
||||
bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 &&
|
||||
bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) {
|
||||
return IMAGE_MIME.png;
|
||||
}
|
||||
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
|
||||
return IMAGE_MIME.jpeg;
|
||||
}
|
||||
if (bytes.length >= 12 &&
|
||||
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
|
||||
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
|
||||
return IMAGE_MIME.webp;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Write the uploaded image to disk and record its metadata. Returns the config. */
|
||||
export function writeBackgroundImage(bytes: Uint8Array, mime: string): UiConfig {
|
||||
fs.mkdirSync(UI_ASSETS_DIR, { recursive: true });
|
||||
const tmp = BACKGROUND_IMAGE_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, bytes);
|
||||
fs.renameSync(tmp, BACKGROUND_IMAGE_PATH);
|
||||
|
||||
const current = loadUiConfig();
|
||||
const next: UiConfig = {
|
||||
...current,
|
||||
appearance: {
|
||||
...current.appearance,
|
||||
background: {
|
||||
...current.appearance.background,
|
||||
// Default to showing the freshly-uploaded image unless the operator
|
||||
// explicitly had a non-image background selected and we respect it;
|
||||
// switching to 'image' here matches the natural "I just set a wallpaper"
|
||||
// expectation.
|
||||
type: 'image',
|
||||
hasImage: true,
|
||||
imageMime: mime,
|
||||
imageVersion: current.appearance.background.imageVersion + 1,
|
||||
},
|
||||
},
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Remove the background image (if any) and clear its metadata. Returns the config. */
|
||||
export function clearBackgroundImage(): UiConfig {
|
||||
try {
|
||||
if (fs.existsSync(BACKGROUND_IMAGE_PATH)) fs.unlinkSync(BACKGROUND_IMAGE_PATH);
|
||||
} catch (err) {
|
||||
log.warn('failed to remove background image: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
const current = loadUiConfig();
|
||||
const next: UiConfig = {
|
||||
...current,
|
||||
appearance: {
|
||||
...current.appearance,
|
||||
background: {
|
||||
...current.appearance.background,
|
||||
// Fall back to 'none' if the image was the active background.
|
||||
type: current.appearance.background.type === 'image' ? 'none' : current.appearance.background.type,
|
||||
hasImage: false,
|
||||
imageMime: '',
|
||||
},
|
||||
},
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Read the background image bytes + MIME, or null if none is stored. */
|
||||
export function readBackgroundImage(): { bytes: Buffer; mime: string } | null {
|
||||
const { background } = loadUiConfig().appearance;
|
||||
if (!background.hasImage) return null;
|
||||
try {
|
||||
const bytes = fs.readFileSync(BACKGROUND_IMAGE_PATH);
|
||||
return { bytes, mime: background.imageMime || 'application/octet-stream' };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
// Advisory update check against the public GitHub Releases API.
|
||||
//
|
||||
// Strictly read-only (T0): SnowLuma never downloads or applies anything
|
||||
// itself — cross-platform self-update is a minefield (Windows locks loaded
|
||||
// .node/.dll/node.exe, Docker bakes the app into image layers, bare installs
|
||||
// have no supervisor). We only tell the WebUI that a newer *stable* release
|
||||
// exists and link the user to it; they download and apply manually.
|
||||
//
|
||||
// The result is cached to stay well under GitHub's 60 req/hr unauthenticated
|
||||
// rate limit, and every failure degrades silently (the UI just shows
|
||||
// "无法检查更新" rather than nagging).
|
||||
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('Update');
|
||||
|
||||
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
|
||||
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
|
||||
const FETCH_TIMEOUT_MS = 8_000;
|
||||
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
|
||||
|
||||
export interface UpdateCheckResult {
|
||||
/** The running build's version (no `v` prefix). */
|
||||
current: string;
|
||||
/** Latest stable release version, or null when the check did not complete. */
|
||||
latest: string | null;
|
||||
/** True only when `latest` is strictly newer than `current`. */
|
||||
hasUpdate: boolean;
|
||||
/** GitHub release page URL for the latest release. */
|
||||
htmlUrl: string | null;
|
||||
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
|
||||
notes: string | null;
|
||||
/** ISO timestamp the latest release was published. */
|
||||
publishedAt: string | null;
|
||||
/** When this result was produced (epoch ms). */
|
||||
checkedAt: number;
|
||||
/** Set when the check was skipped or failed; the UI degrades silently. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface GithubRelease {
|
||||
tag_name?: string;
|
||||
html_url?: string;
|
||||
body?: string;
|
||||
published_at?: string;
|
||||
}
|
||||
|
||||
function currentVersion(): string {
|
||||
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
|
||||
}
|
||||
|
||||
function isEnabled(): boolean {
|
||||
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
|
||||
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two dotted versions. Returns >0 if `a` is newer than `b`, <0 if
|
||||
* older, 0 if equal. The numeric core (major.minor.patch) compares
|
||||
* numerically; a prerelease (`-rc.1`) ranks below its release. Good enough
|
||||
* for "is the latest stable strictly newer than what we run" — and avoids
|
||||
* pulling in a `semver` runtime dependency (the dist bundle ships none).
|
||||
*/
|
||||
export function compareVersions(a: string, b: string): number {
|
||||
const parse = (v: string) => {
|
||||
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
|
||||
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
|
||||
while (nums.length < 3) nums.push(0);
|
||||
return { nums, pre };
|
||||
};
|
||||
const pa = parse(a);
|
||||
const pb = parse(b);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (pa.nums[i] !== pb.nums[i]) return pa.nums[i] - pb.nums[i];
|
||||
}
|
||||
if (pa.pre === pb.pre) return 0;
|
||||
if (!pa.pre) return 1; // release > prerelease
|
||||
if (!pb.pre) return -1;
|
||||
return pa.pre < pb.pre ? -1 : 1;
|
||||
}
|
||||
|
||||
let cache: UpdateCheckResult | null = null;
|
||||
let inflight: Promise<UpdateCheckResult> | null = null;
|
||||
|
||||
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
const base: UpdateCheckResult = {
|
||||
current,
|
||||
latest: null,
|
||||
hasUpdate: false,
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
try {
|
||||
// `/releases/latest` already excludes drafts and prereleases, so this is
|
||||
// stable-channel by construction.
|
||||
const res = await fetch(LATEST_RELEASE_URL, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': `SnowLuma/${current}`,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!res.ok) return { ...base, error: `github ${res.status}` };
|
||||
const rel = (await res.json()) as GithubRelease;
|
||||
const tag = (rel.tag_name ?? '').trim();
|
||||
if (!tag) return { ...base, error: 'no tag' };
|
||||
const latest = tag.replace(/^v/, '');
|
||||
return {
|
||||
current,
|
||||
latest,
|
||||
hasUpdate: compareVersions(latest, current) > 0,
|
||||
htmlUrl: rel.html_url ?? null,
|
||||
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
|
||||
publishedAt: rel.published_at ?? null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
} catch (e) {
|
||||
return { ...base, error: e instanceof Error ? e.message : 'network error' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the update-availability result. Cached for {@link CACHE_TTL_MS}; pass
|
||||
* `force` to bypass the cache (the WebUI's "立即检查" button). Never throws —
|
||||
* failures come back as a result with `error` set and `hasUpdate: false`, and
|
||||
* are not cached so the next check retries.
|
||||
*/
|
||||
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
|
||||
const current = currentVersion();
|
||||
if (!isEnabled()) {
|
||||
return { ...emptyResult(current), error: 'disabled' };
|
||||
}
|
||||
if (!force && cache && Date.now() - cache.checkedAt < CACHE_TTL_MS) return cache;
|
||||
if (inflight) return inflight;
|
||||
inflight = (async () => {
|
||||
const result = await fetchLatest(current);
|
||||
if (result.error) {
|
||||
log.debug('update check failed: %s', result.error);
|
||||
} else {
|
||||
cache = result; // only cache good results so transient errors retry
|
||||
if (result.hasUpdate) log.info('a newer release is available: v%s (running v%s)', result.latest, current);
|
||||
}
|
||||
return result;
|
||||
})().finally(() => {
|
||||
inflight = null;
|
||||
});
|
||||
return inflight;
|
||||
}
|
||||
|
||||
function emptyResult(current: string): UpdateCheckResult {
|
||||
return {
|
||||
current,
|
||||
latest: null,
|
||||
hasUpdate: false,
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
import { makeChannelCtx } from '@snowluma/channel';
|
||||
import { HookChannel } from '@snowluma/channel-hook';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
|
||||
import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { Core } from '../src/core';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const GROUP_ID = 123456789;
|
||||
@@ -34,28 +36,21 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
|
||||
};
|
||||
}
|
||||
|
||||
class RefreshingBridge extends Bridge {
|
||||
readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
|
||||
|
||||
constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
|
||||
super(identity);
|
||||
// `fetchGroupMemberList` moved from Bridge onto `apis.contacts`
|
||||
// under the #6 refactor — patch the method on the constructed
|
||||
// ContactsApi instance to intercept calls + record them for
|
||||
// assertions. (Direct property assignment works because the
|
||||
// method is just an own property on the Api instance, not on
|
||||
// its prototype.)
|
||||
this.apis.contacts.fetchGroupMemberList = async (
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> => {
|
||||
this.memberFetches.push({ groupId, force: Boolean(options.force) });
|
||||
for (const member of this.refreshedMembers) {
|
||||
this.identity.updateGroupMember(groupId, member);
|
||||
}
|
||||
return this.refreshedMembers;
|
||||
};
|
||||
}
|
||||
function buildCore(identity: IdentityService, refreshedMembers: GroupMemberInfo[]) {
|
||||
const channel = new HookChannel(identity.uin);
|
||||
const core = new Core(makeChannelCtx(channel), identity);
|
||||
const memberFetches: Array<{ groupId: number; force: boolean }> = [];
|
||||
core.apis.contacts.fetchGroupMemberList = async (
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> => {
|
||||
memberFetches.push({ groupId, force: Boolean(options.force) });
|
||||
for (const member of refreshedMembers) {
|
||||
core.identity.updateGroupMember(groupId, member);
|
||||
}
|
||||
return refreshedMembers;
|
||||
};
|
||||
return { core, channel, memberFetches };
|
||||
}
|
||||
|
||||
function makePacket(): PacketInfo {
|
||||
@@ -85,15 +80,15 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin>
|
||||
throw new Error('timed out waiting for group_member_join');
|
||||
}
|
||||
|
||||
describe('Bridge group member identity refresh', () => {
|
||||
describe('Core group member identity refresh', () => {
|
||||
it('forces a fresh member list before dispatching an unresolved join event', async () => {
|
||||
const member = makeGroupMember(22222, 'u_new_member');
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
const bridge = new RefreshingBridge(identity, [member]);
|
||||
const { core, channel, memberFetches } = buildCore(identity, [member]);
|
||||
const seen: GroupMemberJoin[] = [];
|
||||
|
||||
bridge.registerCmd('test.member_join', () => [{
|
||||
core.registerCmd('test.member_join', () => [{
|
||||
kind: 'group_member_join',
|
||||
time: 1710000000,
|
||||
selfUin: Number(SELF_UIN),
|
||||
@@ -103,20 +98,21 @@ describe('Bridge group member identity refresh', () => {
|
||||
userUid: member.uid,
|
||||
operatorUid: member.uid,
|
||||
}]);
|
||||
bridge.events.on('group_member_join', (event) => {
|
||||
core.events.on('group_member_join', (event: GroupMemberJoin) => {
|
||||
seen.push(event);
|
||||
});
|
||||
|
||||
bridge.onPacket(makePacket());
|
||||
channel.deliverPacket(makePacket());
|
||||
const event = await waitForEvent(seen);
|
||||
|
||||
expect(bridge.memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
|
||||
expect(memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
|
||||
expect(event.userUin).toBe(member.uin);
|
||||
expect(event.operatorUin).toBe(member.uin);
|
||||
});
|
||||
|
||||
it('remembers UID mappings from realtime request events', () => {
|
||||
const bridge = new Bridge(IdentityService.memory(SELF_UIN));
|
||||
const channel = new HookChannel(SELF_UIN);
|
||||
const core = new Core(makeChannelCtx(channel), IdentityService.memory(SELF_UIN));
|
||||
const events: QQEventVariant[] = [
|
||||
{
|
||||
kind: 'friend_request',
|
||||
@@ -140,12 +136,12 @@ describe('Bridge group member identity refresh', () => {
|
||||
},
|
||||
];
|
||||
|
||||
bridge.registerCmd('test.request_identity', () => events);
|
||||
bridge.onPacket(makeRequestPacket());
|
||||
core.registerCmd('test.request_identity', () => events);
|
||||
channel.deliverPacket(makeRequestPacket());
|
||||
|
||||
expect(bridge.identity.findUidByUin(55555)).toBe('u_friend_request');
|
||||
expect(bridge.identity.findUidByUin(66666)).toBe('u_group_request');
|
||||
expect(bridge.identity.findUinByUid('u_friend_request')).toBe(55555);
|
||||
expect(bridge.identity.findUinByUid('u_group_request')).toBe(66666);
|
||||
expect(core.identity.findUidByUin(55555)).toBe('u_friend_request');
|
||||
expect(core.identity.findUidByUin(66666)).toBe('u_group_request');
|
||||
expect(core.identity.findUinByUid('u_friend_request')).toBe(55555);
|
||||
expect(core.identity.findUinByUid('u_group_request')).toBe(66666);
|
||||
});
|
||||
});
|
||||
@@ -1,49 +1,73 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { ChannelCtx } from '@snowluma/channel';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
|
||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { Core } from '../src/core';
|
||||
|
||||
vi.mock('@snowluma/protocol/element-builder', () => ({
|
||||
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
|
||||
}));
|
||||
|
||||
describe('Bridge private media routing', () => {
|
||||
/**
|
||||
* Build a fake `ChannelCtx` POJO that captures the outbound packet
|
||||
* body for assertions. The `Core` under test consumes this ctx exactly
|
||||
* the way `Hub` would in production — via `sendRawPacket` and
|
||||
* `onPacket` only.
|
||||
*/
|
||||
function makeFakeCtx(uin: string): {
|
||||
ctx: ChannelCtx;
|
||||
getCapturedBody: () => Uint8Array | null;
|
||||
setResponse: (resp: SendPacketResult) => void;
|
||||
} {
|
||||
let capturedBody: Uint8Array | null = null;
|
||||
let response: SendPacketResult = {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
|
||||
result: 0,
|
||||
errMsg: '',
|
||||
privateSequence: 88,
|
||||
timestamp1: 1710000000,
|
||||
})),
|
||||
};
|
||||
const ctx: ChannelCtx = {
|
||||
uin,
|
||||
kind: 'inject',
|
||||
sendRawPacket: async (_cmd, body) => {
|
||||
capturedBody = body;
|
||||
return response;
|
||||
},
|
||||
onPacket: () => { /* unused */ },
|
||||
dispose: () => { /* unused */ },
|
||||
};
|
||||
return {
|
||||
ctx,
|
||||
getCapturedBody: () => capturedBody,
|
||||
setResponse: (resp) => { response = resp; },
|
||||
};
|
||||
}
|
||||
|
||||
describe('Core private media routing', () => {
|
||||
it('includes resolved uid in the final c2c send request for media messages', async () => {
|
||||
const { Bridge } = await import('../src/bridge/bridge');
|
||||
const { IdentityService } = await import('@snowluma/protocol/identity-service');
|
||||
|
||||
class TestBridge extends Bridge {
|
||||
capturedBody: Uint8Array | null = null;
|
||||
const fake = makeFakeCtx('10000');
|
||||
const core = new Core(fake.ctx, IdentityService.memory('10000'));
|
||||
// resolveUserUid lookup needs an explicit override since the
|
||||
// identity store has no mapping for the test peer.
|
||||
core.resolveUserUid = vi.fn(async (uin: number) => {
|
||||
expect(uin).toBe(12345);
|
||||
return 'u_peer_12345';
|
||||
});
|
||||
|
||||
override async resolveUserUid(uin: number): Promise<string> {
|
||||
expect(uin).toBe(12345);
|
||||
return 'u_peer_12345';
|
||||
}
|
||||
await core.apis.message.sendPrivate(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
|
||||
|
||||
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
expect(serviceCmd).toBe('MessageSvc.PbSendMsg');
|
||||
this.capturedBody = body;
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
|
||||
result: 0,
|
||||
errMsg: '',
|
||||
privateSequence: 88,
|
||||
timestamp1: 1710000000,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const bridge = new TestBridge(IdentityService.memory('10000'));
|
||||
await bridge.apis.message.sendPrivate(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
|
||||
|
||||
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
|
||||
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
|
||||
expect(fake.getCapturedBody()).toBeInstanceOf(Uint8Array);
|
||||
const request = protobuf_decode<SendMessageRequest>(fake.getCapturedBody() as Uint8Array);
|
||||
expect(request?.routingHead?.c2c).toMatchObject({
|
||||
uin: 12345,
|
||||
uid: 'u_peer_12345',
|
||||
@@ -59,25 +83,13 @@ describe('Bridge private media routing', () => {
|
||||
// BuildPacketBase` + `FileEntity.PackMessageContent`. Previous
|
||||
// implementation wrote c2c routing + richText.notOnlineFile +
|
||||
// c2cCmd=11 — the QQ-NT server rejected every c2c file send.
|
||||
const { Bridge } = await import('../src/bridge/bridge');
|
||||
const { IdentityService } = await import('@snowluma/protocol/identity-service');
|
||||
|
||||
class TestBridge extends Bridge {
|
||||
capturedBody: Uint8Array | null = null;
|
||||
override async sendRawPacket(_cmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
this.capturedBody = body;
|
||||
return {
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
|
||||
result: 0, errMsg: '', privateSequence: 88, timestamp1: 1710000000,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
const bridge = new TestBridge(IdentityService.memory('10000'));
|
||||
const fake = makeFakeCtx('10000');
|
||||
const core = new Core(fake.ctx, IdentityService.memory('10000'));
|
||||
|
||||
const fileMd5 = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
|
||||
await bridge.apis.message.sendC2cFile(67890, 'u_peer_xyz', {
|
||||
await core.apis.message.sendC2cFile(67890, 'u_peer_xyz', {
|
||||
fileId: 'uuid-abc-123',
|
||||
fileName: 'doc.txt',
|
||||
fileSize: 1024,
|
||||
@@ -85,7 +97,7 @@ describe('Bridge private media routing', () => {
|
||||
fileHash: 'hash-xyz',
|
||||
});
|
||||
|
||||
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
|
||||
const request = protobuf_decode<SendMessageRequest>(fake.getCapturedBody() as Uint8Array);
|
||||
|
||||
// Routing: must be trans0x211 with ccCmd=4 + uid, no c2c slot.
|
||||
expect(request?.routingHead?.trans0x211).toMatchObject({
|
||||
@@ -109,10 +121,6 @@ describe('Bridge private media routing', () => {
|
||||
fileSize: 1024n,
|
||||
fileHash: 'hash-xyz',
|
||||
subcmd: 1, // server-required intake validator field
|
||||
// dangerEvel and fileType are 0 — proto3 omits zero values on
|
||||
// the wire, so they're not asserted here (matches Lagrange's
|
||||
// behaviour: it sets `DangerEvel = 0` but protobuf-net also
|
||||
// skips serialising default ints).
|
||||
});
|
||||
expect(fileExtra?.file?.fileMd5).toEqual(fileMd5);
|
||||
// expireTime is now+7d; just sanity-check it landed (non-zero, plausible)
|
||||
@@ -1,5 +1,3 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbGroupTodo,
|
||||
@@ -12,11 +10,13 @@ import type {
|
||||
OidbAiVoiceReq,
|
||||
OidbAiVoiceResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/media';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// Post-namespace migration: ExtrasApi forwards 6 OIDB cmds through
|
||||
// namespaces under @snowluma/protocol/oidb-services/extras. Tests assert
|
||||
// against bridge.sendRawPacket directly.
|
||||
import { ExtrasApi, AiVoiceChatType } from '../../src/bridge/apis/extras';
|
||||
import { AiVoiceChatType, ExtrasApi } from '../../src/apis/extras';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function packResponse(body: Uint8Array) {
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
// Mirrors NapCat's `PacketMsgFileElement.{buildElement,buildContent}`
|
||||
// split.
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
@@ -44,9 +44,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
|
||||
buildSendElems: buildSendElemsMock,
|
||||
}));
|
||||
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { ForwardApi } from '../../src/apis/forward';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function uploadResponseWithResId(resId: string) {
|
||||
|
||||
@@ -16,12 +16,12 @@
|
||||
// dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115
|
||||
// dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { gunzipSync, inflateSync } from 'zlib';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendLongMsgReq, SendLongMsgResp, LongMsgResult } from '@snowluma/proto-defs/longmsg';
|
||||
import type { PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import type { Elem } from '@snowluma/proto-defs/element';
|
||||
import type { LongMsgResult, SendLongMsgReq, SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import type { PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { gunzipSync, inflateSync } from 'zlib';
|
||||
|
||||
// Don't mock element-builder — we WANT the real forward preview
|
||||
// element to land in the encoded wire bytes so we can verify the
|
||||
@@ -39,7 +39,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
|
||||
uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()),
|
||||
}));
|
||||
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import { ForwardApi } from '../../src/apis/forward';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function uploadResponseWithResId(resId: string) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
@@ -14,9 +14,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
|
||||
buildSendElems: vi.fn(async () => []),
|
||||
}));
|
||||
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { ForwardApi } from '../../src/apis/forward';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function uploadResponseWithResId(resId: string) {
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbDeleteFriend,
|
||||
OidbFriendRequestAction,
|
||||
OidbSetFriendRemark,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// Post-namespace migration: FriendApi is a thin facade over the
|
||||
// namespaces under @snowluma/protocol/oidb-services/friend. Tests assert
|
||||
// against the bridge mock's sendRawPacket directly — no need for
|
||||
// module-level bridge-oidb mocks anymore.
|
||||
import { FriendApi } from '../../src/bridge/apis/friend';
|
||||
import { FriendApi } from '../../src/apis/friend';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
describe('apis/friend', () => {
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
Oidb0x8a0Req,
|
||||
Oidb0x8a7Resp,
|
||||
Oidb0x89a_0AddOption,
|
||||
Oidb0x89a_0Search,
|
||||
Oidb0x8a0Req,
|
||||
Oidb0x8a7Resp,
|
||||
Oidb0xf16Req,
|
||||
OidbGroupRequestAction,
|
||||
OidbKickMember,
|
||||
@@ -17,11 +15,13 @@ import type {
|
||||
OidbSetAdmin,
|
||||
OidbSpecialTitle,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// Post-namespace migration: GroupAdminApi forwards through namespaces
|
||||
// under @snowluma/protocol/oidb-services/group-admin. Tests assert
|
||||
// against bridge.sendRawPacket directly — no module-level mocks.
|
||||
import { GroupAdminApi } from '../../src/bridge/apis/group-admin';
|
||||
import { GroupAdminApi } from '../../src/apis/group-admin';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function packResponse(body: Uint8Array) {
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbGroupFileCountViewResp,
|
||||
OidbGroupFileFolderResp,
|
||||
OidbGroupFileReq,
|
||||
OidbGroupFileResp,
|
||||
OidbGroupFileViewResp,
|
||||
OidbGroupFileFolderResp,
|
||||
OidbGroupSendFileReq,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-file';
|
||||
import type {
|
||||
OidbPrivateFileUploadResp,
|
||||
NTV2RichMediaResp,
|
||||
OidbPrivateFileUploadResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/media';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// Post-namespace migration: GroupFileApi forwards single-OIDB methods
|
||||
// through namespaces under @snowluma/protocol/oidb-services/group-file.
|
||||
@@ -38,7 +38,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({
|
||||
}));
|
||||
|
||||
import * as highwayClient from '@snowluma/protocol/highway';
|
||||
import { GroupFileApi } from '../../src/bridge/apis/group-file';
|
||||
import { GroupFileApi } from '../../src/apis/group-file';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function packResponse(body: Uint8Array) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// after #6 commit 1 moved the recall + markRead helpers onto MessageApi
|
||||
// and #6 commit 6 absorbed setEssence into InteractionApi.
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
@@ -13,7 +13,7 @@ vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
decodeOidbEnv: vi.fn(() => ({ body: {} })),
|
||||
}));
|
||||
|
||||
import { MessageApi } from '../../src/bridge/apis/message';
|
||||
import { MessageApi } from '../../src/apis/message';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
describe('apis/message — recall + markRead', () => {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { Oidb0x9083Resp } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// Post-namespace-migration: InteractionApi is a thin facade and
|
||||
// production code routes through the namespace path (sender →
|
||||
// sendRawPacket). Tests now assert against the bridge mock's
|
||||
// sendRawPacket directly — no need for module-level mocks on the
|
||||
// bridge-oidb internals.
|
||||
import { InteractionApi } from '../../src/bridge/apis/interaction';
|
||||
import { InteractionApi } from '../../src/apis/interaction';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
describe('apis/interaction', () => {
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
Oidb0x990Resp,
|
||||
Oidb0x112eResp,
|
||||
Oidb0x990Resp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// Post-namespace migration: MiscApi forwards 3 OIDB cmds through
|
||||
// @snowluma/protocol/oidb-services/misc namespaces. The non-OIDB
|
||||
// `getMiniAppArk` (LightAppSvc) stays inline on the facade. Tests
|
||||
// hit bridge.sendRawPacket directly.
|
||||
import { MiscApi } from '../../src/bridge/apis/misc';
|
||||
import { MiscApi } from '../../src/apis/misc';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function packResponse(body: Uint8Array) {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
GroupAvatarExtra,
|
||||
@@ -8,6 +6,8 @@ import type {
|
||||
SetStatusReq,
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
|
||||
// (substituted at the call site with the inlined codec). Mocking them on
|
||||
@@ -38,7 +38,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({
|
||||
|
||||
import * as oidb from '@snowluma/protocol/bridge-oidb';
|
||||
import * as highwayClient from '@snowluma/protocol/highway';
|
||||
import { ProfileApi } from '../../src/bridge/apis/profile';
|
||||
import { ProfileApi } from '../../src/apis/profile';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
describe('apis/profile', () => {
|
||||
@@ -52,14 +52,14 @@ describe('apis/profile', () => {
|
||||
|
||||
it('setOnlineStatus sends to status_svc.SetStatus and accepts an empty response', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100);
|
||||
await new ProfileApi(bridge as any).setOnlineStatus(11, 0, 100);
|
||||
const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus');
|
||||
});
|
||||
|
||||
it('setOnlineStatus does NOT include the customExt field 4 (varint 0x22 absent in body)', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100);
|
||||
await new ProfileApi(bridge as any).setOnlineStatus(11, 0, 100);
|
||||
const [, body] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
// proto field 4 length-delimited tag = (4 << 3) | 2 = 0x22. The
|
||||
// body should not contain that byte; if encoder ever leaks an
|
||||
@@ -69,7 +69,7 @@ describe('apis/profile', () => {
|
||||
|
||||
it('setDiyOnlineStatus hardcodes status=10 / extStatus=2000 and packs faceId+wording+faceType into customExt', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new ProfileApi(bridge as any).setDiyOnlineStatus( 1234, '摸鱼中', 2);
|
||||
await new ProfileApi(bridge as any).setDiyOnlineStatus(1234, '摸鱼中', 2);
|
||||
const [serviceCmd, body] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus');
|
||||
// Decode the wire bytes back through the same schema to assert
|
||||
@@ -90,7 +90,7 @@ describe('apis/profile', () => {
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf,
|
||||
} as any);
|
||||
await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/denied/);
|
||||
await expect(new ProfileApi(bridge as any).setDiyOnlineStatus(1, 't', 1)).rejects.toThrow(/denied/);
|
||||
});
|
||||
|
||||
it('setDiyOnlineStatus rejects when the transport itself fails', async () => {
|
||||
@@ -98,7 +98,7 @@ describe('apis/profile', () => {
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: false, gotResponse: false, errorCode: -1, errorMessage: 'pipe closed', responseData: null,
|
||||
} as any);
|
||||
await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/pipe closed/);
|
||||
await expect(new ProfileApi(bridge as any).setDiyOnlineStatus(1, 't', 1)).rejects.toThrow(/pipe closed/);
|
||||
});
|
||||
|
||||
it('setProfile is a no-op when both arguments are undefined', async () => {
|
||||
@@ -117,20 +117,20 @@ describe('apis/profile', () => {
|
||||
|
||||
it('setSelfLongNick targets 0x112a_2 wire cmd', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new ProfileApi(bridge as any).setSelfLongNick( 'hello world');
|
||||
await new ProfileApi(bridge as any).setSelfLongNick('hello world');
|
||||
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2');
|
||||
});
|
||||
|
||||
it('setInputStatus resolves UID first and sends 0xcd4_1', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new ProfileApi(bridge as any).setInputStatus( 10001, 1);
|
||||
await new ProfileApi(bridge as any).setInputStatus(10001, 1);
|
||||
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
|
||||
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xcd4_1');
|
||||
});
|
||||
|
||||
it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new ProfileApi(bridge as any).setAvatar( '/some/avatar.png');
|
||||
await new ProfileApi(bridge as any).setAvatar('/some/avatar.png');
|
||||
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
|
||||
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
|
||||
const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!;
|
||||
@@ -140,7 +140,7 @@ describe('apis/profile', () => {
|
||||
|
||||
it('setGroupAvatar uses cmdId 3000 and packs the Lagrange GroupAvatarExtra constants', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new ProfileApi(bridge as any).setGroupAvatar( 12345, '/some/group-avatar.png');
|
||||
await new ProfileApi(bridge as any).setGroupAvatar(12345, '/some/group-avatar.png');
|
||||
expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce();
|
||||
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
|
||||
const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!;
|
||||
@@ -163,7 +163,7 @@ describe('apis/profile', () => {
|
||||
vi.mocked(loadBinarySource).mockResolvedValueOnce({
|
||||
bytes: new Uint8Array(0), fileName: 'empty.png',
|
||||
} as any);
|
||||
await expect(new ProfileApi(bridge as any).setGroupAvatar( 1, 'empty.png')).rejects.toThrow(/empty/);
|
||||
await expect(new ProfileApi(bridge as any).setGroupAvatar(1, 'empty.png')).rejects.toThrow(/empty/);
|
||||
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -35,43 +35,6 @@ function commonElem(elem: any): { serviceType: number; businessType: number; pbE
|
||||
return elem.commonElem;
|
||||
}
|
||||
|
||||
function inflatePrefixedPayload(data: Uint8Array): string {
|
||||
expect(data[0]).toBe(0x01);
|
||||
return inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
|
||||
}
|
||||
|
||||
describe('element-builder / rich card encoding', () => {
|
||||
it('encodes json segments as deflated LightApp payloads and preserves non-ASCII text', async () => {
|
||||
const card = JSON.stringify({
|
||||
app: 'com.tencent.structmsg',
|
||||
view: 'music',
|
||||
prompt: '[音乐]起风了',
|
||||
meta: { music: { title: '起风了', desc: '买辣椒也用券' } },
|
||||
});
|
||||
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'json', text: card } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
|
||||
expect(elem.lightApp).toBeDefined();
|
||||
expect((elem as any).richMsg).toBeUndefined();
|
||||
expect(inflatePrefixedPayload(elem.lightApp!.data!)).toBe(card);
|
||||
});
|
||||
|
||||
it('encodes xml richMsg payloads by UTF-8 bytes, not JavaScript string length', async () => {
|
||||
const xml = '<msg serviceID="35" brief="[分享]中文卡片"></msg>';
|
||||
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'xml', text: xml, subType: 35 } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
|
||||
expect(elem.richMsg?.serviceId).toBe(35);
|
||||
expect(inflatePrefixedPayload(elem.richMsg!.template1!)).toBe(xml);
|
||||
});
|
||||
});
|
||||
|
||||
describe('element-builder / commonElem.businessType per scene', () => {
|
||||
describe('image', () => {
|
||||
it('c2c → businessType 10', async () => {
|
||||
@@ -166,7 +129,10 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', ()
|
||||
// the outer's LongMsgResult — without uniseq the QQ-NT client has
|
||||
// no way to walk the tree and has to re-fetch each inner resId.
|
||||
function decodeLightApp(elem: any): unknown {
|
||||
return JSON.parse(inflatePrefixedPayload(elem.lightApp.data));
|
||||
const data: Uint8Array = elem.lightApp.data;
|
||||
expect(data[0]).toBe(0x01); // deflate prefix
|
||||
const inflated = inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
|
||||
return JSON.parse(inflated);
|
||||
}
|
||||
|
||||
it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => {
|
||||
|
||||
@@ -110,64 +110,6 @@ describe('formatMessageSegments', () => {
|
||||
expect(out).toBe('hi [图片] @12345 @全体成员 [回复:999] [表情] [视频] [语音]');
|
||||
});
|
||||
|
||||
it('renders file segments using data.name (the OneBot field), with data.file fallback', () => {
|
||||
expect(formatMessageSegments([{ type: 'file', data: { name: '20260606_151113.wav' } }]))
|
||||
.toBe('[文件:20260606_151113.wav]');
|
||||
expect(formatMessageSegments([{ type: 'file', data: { file: 'legacy.bin' } }]))
|
||||
.toBe('[文件:legacy.bin]');
|
||||
expect(formatMessageSegments([{ type: 'file', data: {} }]))
|
||||
.toBe('[文件]');
|
||||
});
|
||||
|
||||
it('renders json card segments by extracting the card title from common ARK fields', () => {
|
||||
// mini-program share: meta.detail_1.title
|
||||
const miniApp = JSON.stringify({
|
||||
app: 'com.tencent.miniapp_01',
|
||||
meta: { detail_1: { title: '哔哩哔哩', desc: '某个视频标题' } },
|
||||
});
|
||||
expect(formatMessageSegments([{ type: 'json', data: { data: miniApp } }]))
|
||||
.toBe('[卡片:哔哩哔哩]');
|
||||
|
||||
// news share: meta.news.title
|
||||
const news = JSON.stringify({ meta: { news: { title: '新闻标题' } } });
|
||||
expect(formatMessageSegments([{ type: 'json', data: { data: news } }]))
|
||||
.toBe('[卡片:新闻标题]');
|
||||
|
||||
// QQ server-side fallback (cardId -896954183): only `prompt` is present
|
||||
const fallback = JSON.stringify({
|
||||
app: 'com.tencent.structmsg',
|
||||
prompt: '当前QQ版本不支持此应用,请升级',
|
||||
});
|
||||
expect(formatMessageSegments([{ type: 'json', data: { data: fallback } }]))
|
||||
.toBe('[卡片:当前QQ版本不支持此应用,请升级]');
|
||||
|
||||
// generic single-section meta (no recognised key, but only one section)
|
||||
const generic = JSON.stringify({ meta: { custom_section: { title: '通用卡片' } } });
|
||||
expect(formatMessageSegments([{ type: 'json', data: { data: generic } }]))
|
||||
.toBe('[卡片:通用卡片]');
|
||||
|
||||
// long titles are truncated
|
||||
const long = JSON.stringify({ prompt: 'a'.repeat(100) });
|
||||
expect(formatMessageSegments([{ type: 'json', data: { data: long } }]))
|
||||
.toBe(`[卡片:${'a'.repeat(30)}...]`);
|
||||
});
|
||||
|
||||
it('falls back to [JSON] when the card payload is unparseable or empty', () => {
|
||||
// non-string data.data
|
||||
expect(formatMessageSegments([{ type: 'json', data: {} }])).toBe('[JSON]');
|
||||
// invalid JSON
|
||||
expect(formatMessageSegments([{ type: 'json', data: { data: 'not-json{' } }]))
|
||||
.toBe('[JSON]');
|
||||
// JSON without any recognised title field
|
||||
expect(formatMessageSegments([{ type: 'json', data: { data: '{"foo":1}' } }]))
|
||||
.toBe('[JSON]');
|
||||
// empty string
|
||||
expect(formatMessageSegments([{ type: 'json', data: { data: '' } }])).toBe('[JSON]');
|
||||
// JSON array (not an object)
|
||||
expect(formatMessageSegments([{ type: 'json', data: { data: '[1,2,3]' } }]))
|
||||
.toBe('[JSON]');
|
||||
});
|
||||
|
||||
it('renders unknown segment types as [type]', () => {
|
||||
expect(formatMessageSegments([{ type: 'something_new', data: {} }]))
|
||||
.toBe('[something_new]');
|
||||
|
||||
@@ -99,81 +99,3 @@ describe('loadBinarySource maxBytes enforcement', () => {
|
||||
).rejects.toThrow(/too large: 128 > 64/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadBinarySource HTTP header hardening', () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('sends a browser User-Agent on the first attempt, without a Referer', async () => {
|
||||
const calls: Array<Record<string, string>> = [];
|
||||
globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {
|
||||
calls.push((init?.headers ?? {}) as Record<string, string>);
|
||||
return new Response(new Uint8Array([1, 2, 3]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
|
||||
await loadBinarySource('https://example.test/a.png', 'image');
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]['User-Agent']).toMatch(/Mozilla\/5\.0/);
|
||||
expect(calls[0]['Referer']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('retries with a Referer when the first fetch fails at the network level', async () => {
|
||||
// Reproduces the reported bug: an anti-bot front-end resets the
|
||||
// header-less request → undici `TypeError: fetch failed`. The retry
|
||||
// carries a Referer pointing at the resource itself and succeeds.
|
||||
const calls: Array<Record<string, string>> = [];
|
||||
globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {
|
||||
calls.push((init?.headers ?? {}) as Record<string, string>);
|
||||
if (calls.length === 1) throw new TypeError('fetch failed');
|
||||
return new Response(new Uint8Array([9, 9]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
|
||||
const loaded = await loadBinarySource('https://img.example.test/x.gif', 'image');
|
||||
expect(Array.from(loaded.bytes)).toEqual([9, 9]);
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[0]['Referer']).toBeUndefined();
|
||||
expect(calls[1]['Referer']).toBe('https://img.example.test/x.gif');
|
||||
});
|
||||
|
||||
it('retries with a Referer on a 403 (anti-hotlink)', async () => {
|
||||
let n = 0;
|
||||
globalThis.fetch = vi.fn(async () => {
|
||||
n++;
|
||||
if (n === 1) return new Response(new Uint8Array(0), { status: 403 });
|
||||
return new Response(new Uint8Array([7]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
|
||||
const loaded = await loadBinarySource('https://cdn.example.test/y.jpg', 'image');
|
||||
expect(Array.from(loaded.bytes)).toEqual([7]);
|
||||
expect(n).toBe(2);
|
||||
});
|
||||
|
||||
it('does not retry a size-limit rejection (deterministic, no second download)', async () => {
|
||||
const fetchMock = vi.fn(async () => new Response(new Uint8Array(0), {
|
||||
status: 200,
|
||||
headers: { 'content-length': String(10 * 1024 * 1024) },
|
||||
}));
|
||||
globalThis.fetch = fetchMock as typeof fetch;
|
||||
|
||||
await expect(
|
||||
loadBinarySource('https://example.test/big.bin', 'image', 1024),
|
||||
).rejects.toThrow(/too large/);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('surfaces the first error when the Referer retry also fails', async () => {
|
||||
let n = 0;
|
||||
globalThis.fetch = vi.fn(async () => {
|
||||
n++;
|
||||
throw new TypeError('fetch failed');
|
||||
}) as typeof fetch;
|
||||
|
||||
await expect(
|
||||
loadBinarySource('https://example.test/z.png', 'image'),
|
||||
).rejects.toThrow(/fetch failed/);
|
||||
expect(n).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
// highway-client.uploadHighwayHttp 的连接生命周期测试。
|
||||
//
|
||||
// 回归覆盖:当上传数据 > HIGHWAY_BLOCK_SIZE (1 MiB) 时,旧实现会复用
|
||||
// 同一个 TCP socket 在 keep-alive 模式下连续 POST,但 QQ highway 的
|
||||
// 边缘节点经常在第一次响应后立刻 FIN 关闭,导致第二次 POST 报
|
||||
// `connection closed before response`。用户上报的 1.19 MB 图片
|
||||
// (onebot retcode=1200)就是这个分支。
|
||||
//
|
||||
// 修复方案:每个 chunk 独立建一个新的 TCP 连接。本测试通过 mock
|
||||
// `net.createConnection` 计数建连次数,断言每个 chunk 一连接的不变量。
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
// highway-client 解析响应只关心 errorCode === 0 —— 一个完全空的
|
||||
// RespDataHighwayHead protobuf 体(0 字节)会被解为 ,errorCode
|
||||
// 是 undefined,走 falsy 通过分支。
|
||||
//
|
||||
// HTTP body 是 highway frame:
|
||||
// 0x28 | head_len(BE32) | body_len(BE32) | head | body | 0x29
|
||||
function buildEmptyHighwayResponseFrame(): Buffer {
|
||||
const frame = Buffer.alloc(10);
|
||||
frame[0] = 0x28;
|
||||
frame.writeUInt32BE(0, 1); // head_len
|
||||
frame.writeUInt32BE(0, 5); // body_len
|
||||
frame[9] = 0x29;
|
||||
return frame;
|
||||
}
|
||||
|
||||
function buildHttpResponse(frameBody: Buffer): Buffer {
|
||||
const headers = [
|
||||
'HTTP/1.1 200 OK',
|
||||
`Content-Length: ${frameBody.length}`,
|
||||
'Connection: close',
|
||||
'',
|
||||
'',
|
||||
].join('\r\n');
|
||||
return Buffer.concat([Buffer.from(headers, 'ascii'), frameBody]);
|
||||
}
|
||||
|
||||
// FakeSocket 模拟 net.Socket 的最小子集。highway-client 用到:
|
||||
// - 'data' / 'error' / 'close' 事件
|
||||
// - .write(data, cb) cb 会被 socketWrite 等待
|
||||
// - .destroy()
|
||||
// - .setTimeout / .once / .removeListener (继承自 EventEmitter)
|
||||
class FakeSocket extends EventEmitter {
|
||||
destroyed = false;
|
||||
// 每个 POST = 2 次 write(HTTP header + body)。第二次 write 落地后
|
||||
// 异步回放响应并立刻 close —— 复现 QQ highway 真实行为:响应一发完
|
||||
// 就 FIN,旧实现的下一次 POST 必然撞上已关闭的 socket。
|
||||
private writeCount = 0;
|
||||
private response: Buffer;
|
||||
|
||||
constructor(response: Buffer) {
|
||||
super();
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
setTimeout(_ms: number) { /* no-op */ }
|
||||
|
||||
write(_data: unknown, cb?: (err?: Error) => void): boolean {
|
||||
this.writeCount += 1;
|
||||
if (this.writeCount === 2) {
|
||||
setImmediate(() => {
|
||||
this.emit('data', this.response);
|
||||
this.emit('close');
|
||||
});
|
||||
}
|
||||
if (cb) cb();
|
||||
return true;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// vitest 把 vi.mock 工厂 hoist 到文件顶部,所以工厂里不能引用普通的
|
||||
// 顶层 const —— 那会触发 "Cannot access X before initialization"。
|
||||
// 用 vi.hoisted 让这两个值跟着 mock 一起被 hoist。
|
||||
const { createdSockets, createConnectionMock } = vi.hoisted(() => ({
|
||||
createdSockets: [] as FakeSocket[],
|
||||
createConnectionMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('net', () => ({
|
||||
default: { createConnection: createConnectionMock },
|
||||
createConnection: createConnectionMock,
|
||||
}));
|
||||
|
||||
import { uploadHighwayHttp, type HighwaySession } from '@snowluma/protocol/highway';
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
function makeBridge(): BridgeContext {
|
||||
return {
|
||||
identity: { uin: '10001' } as unknown,
|
||||
} as unknown as BridgeContext;
|
||||
}
|
||||
|
||||
function makeSession(): HighwaySession {
|
||||
return {
|
||||
sigSession: new Uint8Array([0xAA]),
|
||||
sessionKey: new Uint8Array([0xBB]),
|
||||
host: '127.0.0.1',
|
||||
port: 80,
|
||||
};
|
||||
}
|
||||
|
||||
describe('uploadHighwayHttp connection lifecycle', () => {
|
||||
beforeEach(() => {
|
||||
createdSockets.length = 0;
|
||||
createConnectionMock.mockReset();
|
||||
createConnectionMock.mockImplementation((_opts: unknown, listener?: () => void) => {
|
||||
const sock = new FakeSocket(buildHttpResponse(buildEmptyHighwayResponseFrame()));
|
||||
createdSockets.push(sock);
|
||||
// net.createConnection 在握手成功后调用 listener。同步触发即可,
|
||||
// tcpConnect 的 Promise 会立刻 resolve。
|
||||
if (listener) setImmediate(listener);
|
||||
return sock as unknown as ReturnType<typeof createConnectionMock>;
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('uses a single TCP connection for a sub-block payload', async () => {
|
||||
// 0.5 MiB → 1 chunk。覆盖 PTT / 小图的常见场景。
|
||||
const bytes = new Uint8Array(512 * 1024);
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(1);
|
||||
expect(createdSockets[0]!.destroyed).toBe(true);
|
||||
});
|
||||
|
||||
it('uses a fresh TCP connection per chunk for multi-block payloads', async () => {
|
||||
// 1.5 MiB → ceil(1.5) = 2 chunks。这正是用户上报的 1.19 MB 图片
|
||||
// 触发的代码路径:旧实现复用 socket 时第二次 POST 撞上 keep-alive
|
||||
// 关闭,新实现必须为每个 chunk 各开一个 socket。
|
||||
const bytes = new Uint8Array(Math.floor(1.5 * HIGHWAY_BLOCK_SIZE));
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
expect(createdSockets).toHaveLength(2);
|
||||
for (const sock of createdSockets) {
|
||||
expect(sock.destroyed).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('opens N connections for N chunks (3 chunks here)', async () => {
|
||||
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE));
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
|
||||
// name) — we don't need to import it directly since assertions can
|
||||
// inline-extract the kind.
|
||||
import type {
|
||||
GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin,
|
||||
GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import type { PushMsg } from '@snowluma/proto-defs/message';
|
||||
import type {
|
||||
@@ -24,7 +24,6 @@ import type {
|
||||
// we avoid an `import { FriendRecall as X }` that collides with the
|
||||
// proton import above.
|
||||
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
|
||||
type GroupAdminEvent = Extract<QQEventVariant, { kind: 'group_admin' }>;
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { subscribeLogs } from '@snowluma/common/logger';
|
||||
|
||||
@@ -348,72 +347,3 @@ describe('parseMsgPush PkgType 85 (bot self-joined a group)', () => {
|
||||
expect(event.operatorUid).toBe(admin.uid);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache fresh', () => {
|
||||
// Regression for #93: a member promoted to admin kept reading back as
|
||||
// `member` via get_group_member_info because the admin-change push only
|
||||
// emitted the notice and never patched the cached role — and that API
|
||||
// serves straight from the cache (no per-read refetch, on purpose, to
|
||||
// dodge risk-control). The decoder now mirrors the role into the cache.
|
||||
function makeGroupAdminPacket(adminUid: string, set: boolean, fromUin = GROUP_ID): PacketInfo {
|
||||
const extra = { adminUid };
|
||||
const content = protobuf_encode<GroupAdmin>({
|
||||
groupUin: GROUP_ID,
|
||||
body: set ? { extraEnable: extra } : { extraDisable: extra },
|
||||
});
|
||||
const body = protobuf_encode<PushMsg>({
|
||||
message: {
|
||||
responseHead: { fromUin },
|
||||
contentHead: { msgType: 44, timestamp: 1710000000 },
|
||||
body: { msgContent: content },
|
||||
},
|
||||
status: 0,
|
||||
});
|
||||
return {
|
||||
pid: 1, uin: SELF_UIN, serviceCmd: MSG_PUSH_CMD, seqId: 1,
|
||||
retCode: 0, fromClient: false, body,
|
||||
};
|
||||
}
|
||||
|
||||
it('promotes a cached member to admin in the identity cache (and emits set=true)', () => {
|
||||
const member = makeGroupMember(22222, 'u_member');
|
||||
const identity = makeIdentity([member]);
|
||||
|
||||
const [event] = parseMsgPush(makeGroupAdminPacket(member.uid, true), identity) as GroupAdminEvent[];
|
||||
|
||||
expect(event.kind).toBe('group_admin');
|
||||
expect(event.userUin).toBe(member.uin);
|
||||
expect(event.set).toBe(true);
|
||||
expect(identity.findGroupMember(GROUP_ID, member.uin)?.role).toBe('admin');
|
||||
});
|
||||
|
||||
it('demotes a cached admin back to member on an unset push', () => {
|
||||
const admin = { ...makeGroupMember(22222, 'u_admin'), role: 'admin' };
|
||||
const identity = makeIdentity([admin]);
|
||||
|
||||
const [event] = parseMsgPush(makeGroupAdminPacket(admin.uid, false), identity) as GroupAdminEvent[];
|
||||
|
||||
expect(event.set).toBe(false);
|
||||
expect(identity.findGroupMember(GROUP_ID, admin.uin)?.role).toBe('member');
|
||||
});
|
||||
|
||||
it('never downgrades the owner', () => {
|
||||
const owner = { ...makeGroupMember(22222, 'u_owner'), role: 'owner' };
|
||||
const identity = makeIdentity([owner]);
|
||||
|
||||
parseMsgPush(makeGroupAdminPacket(owner.uid, false), identity);
|
||||
|
||||
expect(identity.findGroupMember(GROUP_ID, owner.uin)?.role).toBe('owner');
|
||||
});
|
||||
|
||||
it('is a no-op (no throw, no phantom member) when the target is not cached', () => {
|
||||
const identity = makeIdentity();
|
||||
|
||||
const [event] = parseMsgPush(makeGroupAdminPacket('u_unknown', true), identity) as GroupAdminEvent[];
|
||||
|
||||
expect(event.kind).toBe('group_admin');
|
||||
// fromUin (the group id) is the resolve fallback — it must not be
|
||||
// confused for a real, promotable member.
|
||||
expect(identity.findGroupMember(GROUP_ID, GROUP_ID)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,13 +23,7 @@ const toPosix = (p: string) => p.replace(/\\/g, '/');
|
||||
// `@snowluma/websocket` is bundled — it's an
|
||||
// in-tree TS workspace wrapper that routes its native `.node`
|
||||
// addon through `dist/native/`. Only Node builtins stay external.
|
||||
//
|
||||
// `node:sqlite` is an experimental builtin that Node 22.x lines don't
|
||||
// list in `builtinModules`, so the `nodeModules` sweep below misses it.
|
||||
// Externalise it explicitly — otherwise Vite bundles it and swaps in a
|
||||
// browser shell, crashing the hook with `DatabaseSync is not a
|
||||
// constructor` (the bug PR #68 set out to fix).
|
||||
const external: string[] = ['node:sqlite', 'sqlite'];
|
||||
const external: string[] = [];
|
||||
|
||||
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat();
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import protobufVitePlugin from '@snowluma/proton/vite';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import protobufVitePlugin from '@snowluma/proton/vite';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [protobufVitePlugin()],
|
||||
plugins: [protobufVitePlugin({ root: path.resolve(__dirname, '../..') })],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, 'src')
|
||||
|
||||
1
packages/mcp/.gitignore
vendored
1
packages/mcp/.gitignore
vendored
@@ -1 +0,0 @@
|
||||
dist/
|
||||
@@ -1,113 +0,0 @@
|
||||
# @snowluma/mcp
|
||||
|
||||
An [MCP](https://modelcontextprotocol.io) server for the **SnowLuma OneBot action
|
||||
catalog**. It runs in two modes from one binary:
|
||||
|
||||
- **docs** (default) — read-only: every action's docs, parameters, cross-field
|
||||
constraints, and a ready-to-use **JSON Schema**, so an LLM can answer "what
|
||||
params does `set_group_ban` take?" without holding the whole catalog in context.
|
||||
- **execution** (opt-in) — when pointed at a running OneBot HTTP endpoint, the LLM
|
||||
can also *call* actions: read-only ones freely, write ones behind a gate.
|
||||
|
||||
## Docs only (default)
|
||||
|
||||
Add to your MCP client (Claude Desktop, Cline, …) — no endpoint, no execution:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"snowluma": { "command": "npx", "args": ["-y", "@snowluma/mcp"] }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Docs tools
|
||||
|
||||
- `list_actions({ category? })` — lightweight index (name / category / summary / aliases / `readOnly`).
|
||||
- `get_action({ name })` — full doc for one action incl. `inputSchema` and `readOnly` (accepts aliases).
|
||||
- `search_actions({ query })` — fuzzy match over name / summary / aliases.
|
||||
- `list_categories()` — categories and their action counts.
|
||||
|
||||
Also exposes the whole catalog as a resource: `snowluma://onebot/actions`.
|
||||
|
||||
## Execution (opt-in)
|
||||
|
||||
Point the server at a running SnowLuma instance's **OneBot HTTP endpoint** (the
|
||||
`httpServer` network adapter) and it gains two execution tools:
|
||||
|
||||
- `query_action({ action, params? })` — calls a **read-only** action (e.g. `get_*`,
|
||||
`can_*`) and returns the full OneBot response. Annotated `readOnlyHint`. Refuses
|
||||
write actions (points you to `invoke_action`).
|
||||
- `invoke_action({ action, params? })` — calls **any known** action, including ones
|
||||
with side effects (send a message, change a group, …). Annotated `destructiveHint`
|
||||
+ `openWorldHint`. **Only available in write mode.**
|
||||
|
||||
Both pass the OneBot envelope through verbatim — a logical failure (`retcode≠0`)
|
||||
comes back as data with its `wording`; only a transport failure is an error.
|
||||
|
||||
### Configuration (env)
|
||||
|
||||
| Variable | Meaning |
|
||||
| --- | --- |
|
||||
| `SNOWLUMA_MCP_ENDPOINT` | OneBot HTTP endpoint, e.g. `http://127.0.0.1:3000/`. **Absent → docs-only** (execution tools hidden). |
|
||||
| `SNOWLUMA_MCP_TOKEN` | Access token (sent as `Authorization: Bearer …`), if the endpoint requires one. |
|
||||
| `SNOWLUMA_MCP_TIMEOUT_MS` | Per-request timeout (default `30000`). |
|
||||
| `SNOWLUMA_MCP_MODE` | `docs` \| `read` \| `write`. Default: `read` when an endpoint is set, else `docs`. |
|
||||
|
||||
**Read mode** — the LLM can query read-only actions, but cannot perform any write:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"snowluma": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@snowluma/mcp"],
|
||||
"env": {
|
||||
"SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/",
|
||||
"SNOWLUMA_MCP_TOKEN": "your-access-token"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Write mode** — also enables `invoke_action` (the bot can send messages, manage
|
||||
groups, etc.). Enable deliberately:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"snowluma": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@snowluma/mcp"],
|
||||
"env": {
|
||||
"SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/",
|
||||
"SNOWLUMA_MCP_TOKEN": "your-access-token",
|
||||
"SNOWLUMA_MCP_MODE": "write"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Safety model
|
||||
|
||||
- **Read/write is classified per action** in the source specs (by what the action
|
||||
actually does, not its name) and baked into the catalog. The default is *write*:
|
||||
an action is callable via `query_action` **only** if it is explicitly read-only.
|
||||
- **The mode gate is enforced on every call**, not just by hiding tools — calling
|
||||
`invoke_action` outside write mode is refused even if a client sends it directly.
|
||||
- **Unknown actions are rejected** by both tools (only catalog actions are callable),
|
||||
so typos and non-catalog internal actions can't be driven.
|
||||
- A well-behaved client can auto-approve `query_action` (read-only) and prompt for
|
||||
`invoke_action` (destructive) using the MCP tool annotations.
|
||||
|
||||
## How it stays in sync
|
||||
|
||||
The catalog — including each action's `readOnly` flag — is a **build-time snapshot**
|
||||
generated from `@snowluma/onebot`'s live action specs (`collectActionDocs()`) on
|
||||
every build, so it auto-tracks action add/remove and read/write reclassification.
|
||||
The snapshot is pinned to the SnowLuma version it was built from; a new SnowLuma
|
||||
release republishes a fresh catalog.
|
||||
|
||||
This package is generated; do not hand-edit `src/generated/catalog.ts`.
|
||||
@@ -1,58 +0,0 @@
|
||||
{
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "1.9.10",
|
||||
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/SnowLuma/SnowLuma.git",
|
||||
"directory": "packages/mcp"
|
||||
},
|
||||
"homepage": "https://github.com/SnowLuma/SnowLuma#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/SnowLuma/SnowLuma/issues"
|
||||
},
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"snowluma-mcp": "./dist/server.js"
|
||||
},
|
||||
"main": "./dist/server.js",
|
||||
"types": "./dist/server.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "node -e \"const fs=require('node:fs');fs.rmSync('dist',{recursive:true,force:true})\"",
|
||||
"gen": "vitest run scripts/gen-catalog.test.ts",
|
||||
"prebuild": "pnpm run clean && pnpm run gen",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"prepack": "pnpm run build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"start": "node dist/server.js"
|
||||
},
|
||||
"keywords": [
|
||||
"mcp",
|
||||
"model-context-protocol",
|
||||
"onebot",
|
||||
"snowluma",
|
||||
"qq"
|
||||
],
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@snowluma/onebot": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// Catalog generator. Runs under vitest (so @snowluma/onebot/action-docs resolves
|
||||
// via the proton plugin, exactly as onebot's own tests do) and writes a build-time
|
||||
// snapshot of the OneBot action catalog into src/generated/catalog.ts.
|
||||
//
|
||||
// This is the whole "auto-track Action 增减" mechanic: the snapshot is regenerated
|
||||
// from the live specs on every build, so it can never describe a stale action set.
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { it, expect } from 'vitest';
|
||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||
|
||||
it('generates src/generated/catalog.ts from the live action specs', () => {
|
||||
const actions = collectActionDocs();
|
||||
const categories = collectCategories();
|
||||
|
||||
expect(actions.length).toBeGreaterThan(100);
|
||||
// every action must carry a composed input schema (the MCP's payoff)
|
||||
for (const a of actions) {
|
||||
expect(a.inputSchema).toBeTypeOf('object');
|
||||
expect(a.name).toBeTruthy();
|
||||
}
|
||||
|
||||
const body =
|
||||
'// GENERATED by scripts/gen-catalog.test.ts — do not edit. Run `pnpm gen`.\n' +
|
||||
'/* eslint-disable */\n' +
|
||||
"import type { CatalogAction, CatalogCategory } from '../types.js';\n\n" +
|
||||
`export const ACTIONS: CatalogAction[] = ${JSON.stringify(actions, null, 2)};\n\n` +
|
||||
`export const CATEGORIES: CatalogCategory[] = ${JSON.stringify(categories, null, 2)};\n`;
|
||||
|
||||
const dir = new URL('../src/generated/', import.meta.url);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(new URL('../src/generated/catalog.ts', import.meta.url), body);
|
||||
});
|
||||
@@ -1,69 +0,0 @@
|
||||
// Thin HTTP bridge to a running OneBot instance.
|
||||
//
|
||||
// The OneBot v11 HTTP action protocol is trivial — POST `{ action, params }` to
|
||||
// the endpoint, read back the JSON envelope — so the MCP talks to it directly
|
||||
// with `fetch`. We deliberately do NOT depend on @snowluma/sdk here: its
|
||||
// published dist is bundler-targeted ESM (extensionless relative imports) that
|
||||
// native `node` cannot resolve without a bundler, and this package is a plain
|
||||
// `tsc`-built stdio bin. The wire shape — not a shared client type — is the seam
|
||||
// (ADR-0005); tests inject a fake `ActionClient` (or a fake `fetch`).
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
/** OneBot v11 response envelope, passed through to the LLM verbatim. */
|
||||
export interface OneBotEnvelope {
|
||||
status: string;
|
||||
retcode: number;
|
||||
data?: unknown;
|
||||
message?: string;
|
||||
wording?: string;
|
||||
echo?: unknown;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ActionClient {
|
||||
/** Send one OneBot action; resolves the full envelope (even on retcode≠0),
|
||||
* rejects only on transport-level failure (timeout / connection / bad body). */
|
||||
call(action: string, params: Record<string, unknown>): Promise<OneBotEnvelope>;
|
||||
}
|
||||
|
||||
export interface HttpClientOptions {
|
||||
/** OneBot HTTP endpoint, e.g. http://127.0.0.1:3000/. */
|
||||
endpoint: string;
|
||||
accessToken?: string;
|
||||
timeoutMs?: number;
|
||||
/** Injectable fetch for tests; defaults to the global fetch. */
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
export function makeHttpClient(opts: HttpClientOptions): ActionClient {
|
||||
const fetchImpl = opts.fetch ?? globalThis.fetch;
|
||||
const timeoutMs = opts.timeoutMs && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS;
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
};
|
||||
if (opts.accessToken) headers.Authorization = `Bearer ${opts.accessToken}`;
|
||||
|
||||
return {
|
||||
async call(action, params) {
|
||||
const res = await fetchImpl(opts.endpoint, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ action, params }),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
const text = await res.text();
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
throw new Error(`OneBot returned non-JSON (HTTP ${res.status})`);
|
||||
}
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error(`OneBot returned an unexpected response (HTTP ${res.status})`);
|
||||
}
|
||||
return parsed as OneBotEnvelope;
|
||||
},
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user