Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
261d6596dc | ||
|
|
dfb6aa54c7 | ||
|
|
a9f84a2aa0 | ||
|
|
fac51cd94d | ||
|
|
aee543c7de | ||
|
|
06c8954881 | ||
|
|
c637329884 | ||
|
|
f153781208 | ||
|
|
3655f10a43 | ||
|
|
fae2f75525 | ||
|
|
39864f6e48 | ||
|
|
cde5a22ec8 | ||
|
|
d2e8222886 | ||
|
|
0c20d58a8c | ||
|
|
c0e3bd0cff | ||
|
|
b71aedaa60 | ||
|
|
a38b33c8aa | ||
|
|
675261691f | ||
|
|
a4b226f1d0 | ||
|
|
82d5f782a3 | ||
|
|
7faef1b7c0 | ||
|
|
9a455b30c6 | ||
|
|
ad21e19dc8 | ||
|
|
64c10e2856 | ||
|
|
77b16faebb | ||
|
|
90d3f7c0d6 | ||
|
|
e07090376a | ||
|
|
f936515a59 | ||
|
|
7625c18768 | ||
|
|
07988629f1 | ||
|
|
0ba5eba31c | ||
|
|
dbb5160be7 | ||
|
|
84e5254c3a | ||
|
|
8144dd9c27 | ||
|
|
5d08fc8471 | ||
|
|
16920b4444 | ||
|
|
f014defd54 | ||
|
|
0b7fb0c69d | ||
|
|
c0af18e1c2 | ||
|
|
30bcd97a3f | ||
|
|
34d05f41f5 | ||
|
|
bf5978fb51 | ||
|
|
652a817568 | ||
|
|
fb567177b4 | ||
|
|
2913a7a19b | ||
|
|
7355fe9ea4 | ||
|
|
1a0bc12ec0 | ||
|
|
72e0d6bcca | ||
|
|
60d1f0b04f | ||
|
|
23048894b5 | ||
|
|
754621de04 | ||
|
|
45d651614b | ||
|
|
6d4e8538ea | ||
|
|
636189d7c9 | ||
|
|
5b07f518cc | ||
|
|
e0d5b47488 | ||
|
|
2ffb6192dd | ||
|
|
d5af6b10ef | ||
|
|
300fa70148 | ||
|
|
6003acac56 | ||
|
|
b0bfb9e6a7 | ||
|
|
e5e6d50f2f | ||
|
|
7e59dbf79b | ||
|
|
28633f3c62 | ||
|
|
cf8e62d2ac | ||
|
|
457186419f | ||
|
|
9dfa31bdbc | ||
|
|
8dc4ff48f8 | ||
|
|
58c02d415f | ||
|
|
987ac09896 | ||
|
|
7d90820e19 | ||
|
|
ee8eb928b3 | ||
|
|
8f61b1486e | ||
|
|
44a29c6ee4 | ||
|
|
84021a19dc | ||
|
|
df0b79a87d | ||
|
|
dc26cc93ba | ||
|
|
985dfd4705 | ||
|
|
9dd46198cb | ||
|
|
7d647e0ed7 | ||
|
|
e93a17de78 | ||
|
|
de598242ab | ||
|
|
3d480fb018 | ||
|
|
5b253ea1d5 | ||
|
|
a61e0a253d | ||
|
|
056fff415c | ||
|
|
7c2923dd04 | ||
|
|
3258300539 | ||
|
|
f07f309c51 | ||
|
|
a5335687ec | ||
|
|
69ed8fc722 | ||
|
|
ac1ffc46d3 | ||
|
|
0b5087b410 | ||
|
|
043ce779e6 | ||
|
|
e9ae2ec751 | ||
|
|
69195ced93 | ||
|
|
a3a36718d6 | ||
|
|
d2a67cb560 | ||
|
|
d804a3b2e0 | ||
|
|
14e02bce3c | ||
|
|
d2c56d565b | ||
|
|
d508814dfa | ||
|
|
ac049e5cc1 | ||
|
|
cc27cd1f43 | ||
|
|
515bac4b3c | ||
|
|
6a2fd9e8f3 | ||
|
|
40c65c87bd | ||
|
|
ac39d04170 | ||
|
|
174150c5e1 | ||
|
|
56dc934106 | ||
|
|
28db1d1079 | ||
|
|
966855469d | ||
|
|
9374b8ac64 | ||
|
|
34ea2ce438 | ||
|
|
9dedcf93a8 | ||
|
|
0cc7ef2f30 | ||
|
|
d2097f77c8 | ||
|
|
46cbd29956 | ||
|
|
4fcaba2f3e | ||
|
|
4427ecd569 | ||
|
|
6d92a28e2b | ||
|
|
18f7d847ac | ||
|
|
d3092a1806 | ||
|
|
69c8960ea9 | ||
|
|
fc21d87a9b | ||
|
|
e036e70acc | ||
|
|
92cfaf24b8 | ||
|
|
15e4e261c5 | ||
|
|
7336352cd3 | ||
|
|
9b92f3825d | ||
|
|
74c727b9e3 | ||
|
|
a1f372bc9d | ||
|
|
b23607d51d | ||
|
|
a51bf60d9a | ||
|
|
003e8c2deb | ||
|
|
118bcbe83c | ||
|
|
0d63bf7415 | ||
|
|
f9252fb26d | ||
|
|
e821080ca8 | ||
|
|
b3749560c8 | ||
|
|
c3803e4ba8 | ||
|
|
f2840c7074 | ||
|
|
ad081e2149 | ||
|
|
0e4b881f76 | ||
|
|
90f26ca4f4 | ||
|
|
c4413dabb5 | ||
|
|
71be3ae2e1 | ||
|
|
3cfac51811 | ||
|
|
76c6ebc700 | ||
|
|
74b6fe97e5 | ||
|
|
4a0626f00b | ||
|
|
ba19cee07d | ||
|
|
624959f099 | ||
|
|
0110b71dd3 | ||
|
|
00ca582f1a | ||
|
|
bf932477dd | ||
|
|
f2b7ef0056 | ||
|
|
54c4641a0e | ||
|
|
08b7ab7f15 | ||
|
|
4a92dd71ad | ||
|
|
1bd0cbc359 | ||
|
|
fe567caeec | ||
|
|
231d60411b | ||
|
|
bee1e67c60 | ||
|
|
71b0bda8f4 | ||
|
|
133cfc0c0e | ||
|
|
b959783ded | ||
|
|
463e0ffb5d | ||
|
|
9d55e86b1c | ||
|
|
07449788c6 | ||
|
|
fe4af70562 | ||
|
|
545a732385 | ||
|
|
c2f22d8daf | ||
|
|
9216b54427 | ||
|
|
fd9a239241 | ||
|
|
5a4028d5dc | ||
|
|
d02e7cc3ab | ||
|
|
9938545788 | ||
|
|
7149bc8689 | ||
|
|
9802128421 | ||
|
|
a572d05c25 | ||
|
|
cb06624d12 | ||
|
|
7b93839186 | ||
|
|
d0085ec052 |
No files matched your search
@@ -0,0 +1,40 @@
|
||||
<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>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,43 @@
|
||||
# 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
|
||||
@@ -0,0 +1,109 @@
|
||||
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}"
|
||||
@@ -1,4 +1,6 @@
|
||||
<h1 align="center">❄️ SnowLuma</h1>
|
||||
<h1 align="center">
|
||||
<img src=".github/logo.svg" width="100%" alt="SnowLuma" />
|
||||
</h1>
|
||||
|
||||
<p align="center">
|
||||
<i>Next Remote Protocol Framework.</i>
|
||||
@@ -7,8 +9,7 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
|
||||
<a href="https://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://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
</p>
|
||||
|
||||
@@ -21,111 +22,29 @@
|
||||
|
||||
---
|
||||
|
||||
## 简介
|
||||
|
||||
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
|
||||
|
||||
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
|
||||
SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。
|
||||
|
||||
## 特性
|
||||
|
||||
- **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,跨重启可用。
|
||||
- **OneBot v11 兼容**:支持文本、音视频、Markdown、JSON 等消息格式。
|
||||
- **高性能架构**:TypeScript 全栈,基于 pnpm monorepo 管理,核心逻辑分离。
|
||||
- **现代化管理**:内置 WebUI 面板,支持实时日志、密码热更、多账号管理。
|
||||
- **多适配器支持**:WebSocket (Server/Client)、HTTP (Server/Post)。
|
||||
- **数据持久化**:使用 SQLite 存储好友、群组等关系数据。
|
||||
|
||||
## 快速开始
|
||||
|
||||
下载预构建发布包:
|
||||
|
||||
```bash
|
||||
# 从 Releases 下载 zip,解压到任意目录
|
||||
./launcher.bat # Windows
|
||||
```
|
||||
|
||||
或从源码开发:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
cd SnowLuma
|
||||
pnpm install
|
||||
pnpm build
|
||||
pnpm start
|
||||
```
|
||||
|
||||
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
|
||||
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
|
||||
|
||||
## 工作区
|
||||
|
||||
本仓库使用 pnpm monorepo 管理,各包职责如下:
|
||||
|
||||
| 包 | 说明 |
|
||||
| --- | --- |
|
||||
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
|
||||
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
|
||||
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
|
||||
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
|
||||
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
|
||||
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
|
||||
| [`webui`](packages/webui) | Web 管理面板前端。 |
|
||||
|
||||
## 架构
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A([QQ 客户端])
|
||||
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
|
||||
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
|
||||
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
|
||||
E([WS / HTTP / WebUI])
|
||||
|
||||
A --> B --> C --> D --> E
|
||||
```
|
||||
|
||||
## 文档
|
||||
|
||||
- [路线图](RoadMap.md)
|
||||
- [贡献指南](CONTRIBUTING.md)
|
||||
- [行为准则](CODE_OF_CONDUCT.md)
|
||||
|
||||
## 开发命令
|
||||
|
||||
```bash
|
||||
pnpm dev # 启动 core dev server
|
||||
pnpm dev:web # 启动 webui dev server
|
||||
pnpm test # 运行 core 测试
|
||||
pnpm typecheck # 全仓库 type check
|
||||
pnpm build:all # 构建 core + sdk + webui
|
||||
```
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。
|
||||
2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。
|
||||
3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。
|
||||
|
||||
## 鸣谢
|
||||
|
||||
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
|
||||
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
|
||||
参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
|
||||
## 贡献者
|
||||
---
|
||||
|
||||
感谢每一位为 SnowLuma 提交过代码的伙伴。
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" /></a>
|
||||
</p>
|
||||
|
||||
<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)
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.13",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -8,7 +8,8 @@
|
||||
"build": "pnpm --filter @snowluma/core build",
|
||||
"build:sdk": "pnpm --filter @snowluma/sdk build",
|
||||
"build:webui": "pnpm --filter webui build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && 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",
|
||||
"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,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.13",
|
||||
"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).",
|
||||
|
||||
@@ -465,6 +465,12 @@ 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,
|
||||
@@ -474,6 +480,7 @@ 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);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import https from 'https';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
@@ -8,6 +9,13 @@ 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;
|
||||
@@ -42,6 +50,7 @@ function decodeJwt(token: string): JwtPayload | null {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = new net.Socket();
|
||||
@@ -108,6 +117,93 @@ async function probePort(port: number): Promise<QqPortLoginInfo | 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') {
|
||||
@@ -119,13 +215,11 @@ async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
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);
|
||||
}
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
@@ -135,10 +229,7 @@ async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
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);
|
||||
}
|
||||
ports.add(Number(match[1]));
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
@@ -148,18 +239,41 @@ async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return { port: 0, uin: '', loggedIn: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const port of ports) {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
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 } from '../src/qq-hook-client';
|
||||
import { listLiveLinuxPipePids, QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
|
||||
@@ -42,3 +43,66 @@ describe('listLiveLinuxPipePids', () => {
|
||||
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,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.13",
|
||||
"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).",
|
||||
@@ -45,10 +45,12 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
"typescript": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
@@ -49,3 +49,70 @@ 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);
|
||||
}
|
||||
+104
-17
@@ -1,7 +1,8 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
import { currentRequestId } from './request-context';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
@@ -10,6 +11,8 @@ 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;
|
||||
}
|
||||
@@ -26,6 +29,7 @@ interface LogOptions {
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
@@ -34,6 +38,7 @@ const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
@@ -42,6 +47,7 @@ const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
@@ -53,13 +59,55 @@ const COLOR_SCOPE = 35;
|
||||
const COLOR_DIM = 2;
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const MAX_LOG_ENTRIES = 1000;
|
||||
const logEntries: LogEntry[] = [];
|
||||
|
||||
/** 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 logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
@@ -75,7 +123,7 @@ function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
@@ -110,15 +158,16 @@ function currentTime(): string {
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: number): 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}] ${message}`;
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
@@ -129,28 +178,46 @@ function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
}
|
||||
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
// Console / subscriber level filter. File output is debug-and-up always;
|
||||
// see log-file-transport.ts.
|
||||
const passesConsole = shouldLog(level);
|
||||
const message = format(...args);
|
||||
const line = render(level, options, args);
|
||||
|
||||
// `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 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) {
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
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
|
||||
@@ -162,10 +229,11 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// File transport always sees every level (debug-and-up) for post-mortem
|
||||
// value; ANSI stripping happens inside the transport. UIN routes the
|
||||
// line to its per-account sub-file in addition to the shared one.
|
||||
getFileTransport().write(line, options.uin);
|
||||
// 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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -179,8 +247,14 @@ export function closeLogger(): Promise<void> {
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
|
||||
return logEntries.slice(-n);
|
||||
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);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
@@ -191,6 +265,13 @@ 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;
|
||||
@@ -207,6 +288,7 @@ 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),
|
||||
@@ -226,3 +308,8 @@ 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';
|
||||
@@ -0,0 +1,35 @@
|
||||
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;
|
||||
}
|
||||
+106
-48
@@ -7,71 +7,102 @@ export interface RuntimeConfig {
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
/** WebUI listener bind address. '0.0.0.0' = all interfaces (default),
|
||||
* '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */
|
||||
webuiHost?: string;
|
||||
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
|
||||
* only flips serving on/off. Listener-level: change needs a restart. */
|
||||
webuiTls?: { enabled?: boolean };
|
||||
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
|
||||
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
|
||||
trustProxy?: string;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
};
|
||||
const DEFAULT_WEBUI_PORT = 5099;
|
||||
const DEFAULT_WEBUI_HOST = '0.0.0.0';
|
||||
|
||||
/**
|
||||
* Pure on-disk-object → typed config normalization (defaults + validation,
|
||||
* no fs / no env). Exported for testing; `loadRuntimeConfig` wraps it.
|
||||
*/
|
||||
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
|
||||
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure SNOWLUMA_* env → override patch (no fs). Env wins over runtime.json
|
||||
* (a trusted launcher like SnowLumaDesktop pins these per-launch without
|
||||
* rewriting the file). Absent vars produce no key.
|
||||
*/
|
||||
export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<RuntimeConfig> {
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
if (port !== undefined) out.webuiPort = port;
|
||||
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim();
|
||||
|
||||
// Present-but-"0"/"off" is a deliberate override (trust nobody), distinct
|
||||
// from "absent" — so gate on key presence, not truthiness.
|
||||
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
|
||||
if (typeof tp === 'string') out.trustProxy = tp;
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const loaded = tryLoadRuntimeConfig();
|
||||
let normalized: RuntimeConfig;
|
||||
if (!loaded) {
|
||||
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
|
||||
normalized = { ...DEFAULT_RUNTIME_CONFIG };
|
||||
} else {
|
||||
normalized = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
|
||||
};
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
const parsed = tryLoadRuntimeConfig();
|
||||
const normalized = normalizeRuntimeConfig(parsed ?? {});
|
||||
|
||||
// Persist when the file is absent or when normalization changed/backfilled
|
||||
// anything (e.g. an older runtime.json lacking webuiHost/webuiTls).
|
||||
if (parsed === null || !sameRuntimeConfig(parsed, normalized)) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
|
||||
// SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without
|
||||
// rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop)
|
||||
// pick a free port per-launch while CLI/Docker users continue to drive
|
||||
// it from runtime.json.
|
||||
const envPort = envPortOverride();
|
||||
if (envPort !== undefined) {
|
||||
normalized = { ...normalized, webuiPort: envPort };
|
||||
}
|
||||
|
||||
return normalized;
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
}
|
||||
|
||||
function envPortOverride(): number | undefined {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
if (!raw || typeof raw !== 'string') return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
/**
|
||||
* Read the persisted config (normalized, no env overrides, no write). For the
|
||||
* settings panel's GET — shows what's actually saved/editable on disk.
|
||||
*/
|
||||
export function readRuntimeConfig(): RuntimeConfig {
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||
/**
|
||||
* Persist a partial update. Merges onto the ON-DISK config (not the env-merged
|
||||
* runtime view) so an env override (e.g. SNOWLUMA_WEBUI_PORT) is never baked
|
||||
* into runtime.json. Returns the new persisted config (without env overrides).
|
||||
*/
|
||||
export function updateRuntimeConfig(patch: Partial<RuntimeConfig>): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
const next = normalizeRuntimeConfig({ ...onDisk, ...patch });
|
||||
saveRuntimeConfig(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): Record<string, unknown> | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!isObject(parsed)) return null;
|
||||
|
||||
return {
|
||||
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false),
|
||||
};
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -81,6 +112,33 @@ function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/** True when the raw on-disk object already matches the normalized config
|
||||
* on every known field (so we can skip a needless rewrite). */
|
||||
function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): boolean {
|
||||
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
|
||||
return (
|
||||
parsed.webuiPort === n.webuiPort
|
||||
&& parsed.hookAutoLoad === n.hookAutoLoad
|
||||
&& parsed.webuiHost === n.webuiHost
|
||||
&& parsedTls === n.webuiTls?.enabled
|
||||
&& parsed.trustProxy === n.trustProxy
|
||||
);
|
||||
}
|
||||
|
||||
function parsePortString(raw: unknown): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeHost(value: unknown): string {
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
return DEFAULT_WEBUI_HOST;
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime';
|
||||
|
||||
describe('normalizeRuntimeConfig', () => {
|
||||
it('applies all defaults for an empty object', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '0.0.0.0',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
});
|
||||
});
|
||||
|
||||
it('passes through valid values', () => {
|
||||
expect(normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
})).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back on invalid types', () => {
|
||||
const out = normalizeRuntimeConfig({
|
||||
webuiPort: 0, // out of range → default
|
||||
webuiHost: 123, // non-string → default
|
||||
webuiTls: 'yes', // non-object → default
|
||||
trustProxy: 5, // non-string → default
|
||||
});
|
||||
expect(out.webuiPort).toBe(5099);
|
||||
expect(out.webuiHost).toBe('0.0.0.0');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
|
||||
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
|
||||
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
|
||||
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0');
|
||||
});
|
||||
|
||||
it('rejects a non-object input back to full defaults', () => {
|
||||
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
|
||||
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRuntimeEnvOverrides', () => {
|
||||
it('returns empty when no SNOWLUMA_* vars are set', () => {
|
||||
expect(resolveRuntimeEnvOverrides({})).toEqual({});
|
||||
});
|
||||
|
||||
it('parses port / host / trustProxy from env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_WEBUI_PORT: '6700',
|
||||
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
|
||||
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
|
||||
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateRuntimeConfig (fs)', () => {
|
||||
let prevCwd: string;
|
||||
let dir: string;
|
||||
let prevPortEnv: string | undefined;
|
||||
beforeEach(async () => {
|
||||
const fs = await import('fs'); const os = await import('os'); const path = await import('path');
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
});
|
||||
afterEach(async () => {
|
||||
const fs = await import('fs');
|
||||
process.chdir(prevCwd);
|
||||
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('merges a patch over on-disk values and persists normalized', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: true });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiHost).toBe('127.0.0.1');
|
||||
expect(onDisk.webuiTls).toEqual({ enabled: true });
|
||||
});
|
||||
|
||||
it('does NOT bake an env-overridden port into the persisted file', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
process.env.SNOWLUMA_WEBUI_PORT = '9999';
|
||||
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
// Vitest config for @snowluma/common. Pure-TS package (no proton), so a
|
||||
// plain node-environment runner over tests/ is enough.
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.13",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -46,7 +46,6 @@
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -54,7 +53,7 @@
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "^24.12.2",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.18",
|
||||
"hono": "^4.12.21",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
|
||||
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
|
||||
import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail';
|
||||
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
|
||||
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
|
||||
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
@@ -104,6 +105,28 @@ export class ContactsApi {
|
||||
return groups;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single group's public detail by id via `0x88D_0` — works even for a
|
||||
* group the bot hasn't joined (used to resolve a group-invite's name). Returns
|
||||
* null when the server has no such group / denies the lookup. Deliberately
|
||||
* does NOT `rememberGroups` it — a non-member group must not pollute the
|
||||
* joined-groups roster / get_group_list.
|
||||
*/
|
||||
async fetchGroupDetail(groupId: number): Promise<QQGroupInfo | null> {
|
||||
if (!(groupId > 0)) return null;
|
||||
const resp = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const r = resp.groupInfo?.results;
|
||||
if (!r) return null;
|
||||
return {
|
||||
groupId,
|
||||
groupName: r.name ?? '',
|
||||
remark: '',
|
||||
memberCount: Number(r.memberCount ?? 0n),
|
||||
memberMax: Number(r.maxMemberCount ?? 0n),
|
||||
members: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
async fetchGroupMemberList(
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
|
||||
@@ -5,9 +5,38 @@ 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 { 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;
|
||||
@@ -88,4 +117,44 @@ 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
|
||||
}
|
||||
}
|
||||
@@ -150,7 +150,7 @@ async function buildForwardPushBody(
|
||||
msgId: random,
|
||||
sequence: seq,
|
||||
timestamp: now,
|
||||
divSeq: 0,
|
||||
c2cCmd: 0,
|
||||
},
|
||||
body: {
|
||||
richText: {
|
||||
|
||||
@@ -21,6 +21,7 @@ import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/
|
||||
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
|
||||
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
|
||||
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
|
||||
import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file';
|
||||
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
|
||||
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
|
||||
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
|
||||
@@ -604,6 +605,10 @@ export class GroupFileApi {
|
||||
return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory });
|
||||
}
|
||||
|
||||
rename(groupId: number, fileId: string, parentDirectory: string, newFileName: string): Promise<void> {
|
||||
return RenameGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, newFileName });
|
||||
}
|
||||
|
||||
// ─────────────── folders ───────────────
|
||||
|
||||
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
|
||||
|
||||
@@ -9,7 +9,8 @@ import type {
|
||||
SsoReadedReportReq,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
|
||||
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
|
||||
@@ -24,6 +25,73 @@ import type { Bridge, SendMessageReceipt } from '../bridge';
|
||||
|
||||
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
|
||||
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
|
||||
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
|
||||
|
||||
// ── Group-history fetch guards (the server frequency-limits / kicks abusive
|
||||
// pulls, so keep each request small, bound the loop, and space the sends). ──
|
||||
const HISTORY_MAX_COUNT = 200; // hard cap on messages returned per call
|
||||
const HISTORY_CHUNK_SEQ = 30; // sequence span per server request (small packet)
|
||||
const HISTORY_MAX_REQUESTS = 12; // bound the walk-back loop
|
||||
const HISTORY_MIN_GAP_MS = 300; // minimum spacing between SsoGetGroupMsg sends
|
||||
|
||||
// Serialized throttle gate: chains so concurrent callers queue, and enforces
|
||||
// at least HISTORY_MIN_GAP_MS between actual sends (the first send isn't
|
||||
// penalized). Process-wide — shared across all groups AND accounts in this
|
||||
// process — so no client can make us flood the server regardless of fan-out.
|
||||
let historyLastSendAt = 0;
|
||||
let historyGate: Promise<void> = Promise.resolve();
|
||||
function throttleHistory(): Promise<void> {
|
||||
const run = historyGate.then(async () => {
|
||||
const wait = historyLastSendAt + HISTORY_MIN_GAP_MS - Date.now();
|
||||
if (wait > 0) await new Promise<void>((resolve) => setTimeout(resolve, wait));
|
||||
historyLastSendAt = Date.now();
|
||||
});
|
||||
historyGate = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared walk-back loop for group + c2c history: pull HISTORY_CHUNK_SEQ-wide
|
||||
* windows ending at `endSeq`, throttled, walking strictly backward (handling a
|
||||
* server-side short cap via the oldest sequence actually returned), dedup by
|
||||
* sequence, until `count` (capped) is gathered or the floor is reached. Returns
|
||||
* the newest `want` items oldest→newest.
|
||||
*/
|
||||
async function walkBackHistory<T extends { msgSeq: number }>(
|
||||
endSeq: number,
|
||||
count: number,
|
||||
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
|
||||
): Promise<T[]> {
|
||||
if (!(endSeq > 0)) return [];
|
||||
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
|
||||
|
||||
const collected = new Map<number, T>(); // dedup by sequence
|
||||
let curEnd = endSeq;
|
||||
for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) {
|
||||
const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1);
|
||||
await throttleHistory();
|
||||
let batch: T[];
|
||||
try {
|
||||
batch = await fetchWindow(start, curEnd);
|
||||
} catch {
|
||||
break; // network/decode error — return whatever we have so far
|
||||
}
|
||||
if (batch.length > 0) {
|
||||
let minSeq = curEnd;
|
||||
for (const ev of batch) {
|
||||
collected.set(ev.msgSeq, ev);
|
||||
if (ev.msgSeq < minSeq) minSeq = ev.msgSeq;
|
||||
}
|
||||
curEnd = minSeq - 1; // strictly below the oldest returned (covers short caps)
|
||||
} else {
|
||||
curEnd = start - 1; // empty window (recalled/absent seqs) — skip past it
|
||||
}
|
||||
}
|
||||
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
|
||||
return all.slice(-want); // newest `want`, oldest→newest
|
||||
}
|
||||
|
||||
export class MessageApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
@@ -328,5 +396,64 @@ export class MessageApi {
|
||||
throw new Error(result.errorMessage || 'mark private message read failed');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch real group history from the server (`SsoGetGroupMsg`), ending at and
|
||||
* including `endSeq`, walking backward in small windows until `count`
|
||||
* messages are gathered or the floor is reached. Rate-limited + capped so a
|
||||
* hammering client can't make us flood the server (and get the account
|
||||
* kicked). Returns decoded `group_message` events oldest→newest.
|
||||
*/
|
||||
async getGroupHistory(groupUin: number, endSeq: number, count: number, selfUin = 0): Promise<GroupMessage[]> {
|
||||
if (!(groupUin > 0)) return [];
|
||||
return walkBackHistory(endSeq, count, (start, end) =>
|
||||
fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, end));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch real private (c2c) history from the server (`SsoGetC2cMsg`), ending
|
||||
* at and including `endSeq`. Same rate-limit + data-volume guards as the
|
||||
* group variant (they share the throttle gate). `friendUid` is the
|
||||
* conversation peer's UID. Returns decoded `friend_message` events
|
||||
* oldest→newest.
|
||||
*/
|
||||
async getC2cHistory(friendUid: string, endSeq: number, count: number, selfUin = 0): Promise<FriendMessage[]> {
|
||||
if (!friendUid) return [];
|
||||
return walkBackHistory(endSeq, count, (start, end) =>
|
||||
fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single group message by its exact sequence — `SsoGetGroupMsg` over a
|
||||
* 1-wide `[seq, seq]` range, through the shared history throttle gate. Used to
|
||||
* back-fill a replied-to message the local store never saw. Returns the
|
||||
* matching `group_message`, or null if absent / on error.
|
||||
*/
|
||||
async getGroupMessageBySeq(groupUin: number, seq: number, selfUin = 0): Promise<GroupMessage | null> {
|
||||
if (!(groupUin > 0) || !(seq > 0)) return null;
|
||||
await throttleHistory();
|
||||
try {
|
||||
const batch = await fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, seq, seq);
|
||||
return batch.find((m) => m.msgSeq === seq) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single c2c message by its exact sequence — `SsoGetC2cMsg` over a
|
||||
* 1-wide `[seq, seq]` range, through the same throttle gate. `friendUid` is the
|
||||
* conversation peer. Returns the matching `friend_message`, or null.
|
||||
*/
|
||||
async getC2cMessageBySeq(friendUid: string, seq: number, selfUin = 0): Promise<FriendMessage | null> {
|
||||
if (!friendUid || !(seq > 0)) return null;
|
||||
await throttleHistory();
|
||||
try {
|
||||
const batch = await fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, seq, seq);
|
||||
return batch.find((m) => m.msgSeq === seq) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import type { BridgeContext } from '../bridge-context';
|
||||
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 { ImageOcr, type OcrResult } from '@snowluma/protocol/oidb-services/misc/image-ocr';
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
@@ -17,6 +19,10 @@ export class MiscApi {
|
||||
return TranslateEnToZh.invoke(this.ctx, { words });
|
||||
}
|
||||
|
||||
ocrImage(imageUrl: string): Promise<OcrResult> {
|
||||
return ImageOcr.invoke(this.ctx, { imageUrl });
|
||||
}
|
||||
|
||||
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
|
||||
let appid = '1109937557'; // default: bilibili
|
||||
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
@@ -75,4 +81,15 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
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';
|
||||
@@ -247,16 +248,11 @@ export class WebApi {
|
||||
let imgHeight = 300;
|
||||
|
||||
if (options?.image) {
|
||||
let imageBuffer: Buffer;
|
||||
|
||||
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
|
||||
const response = await fetch(options.image);
|
||||
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
|
||||
imageBuffer = Buffer.from(await response.arrayBuffer());
|
||||
} else {
|
||||
const { readFileSync } = await import('fs');
|
||||
imageBuffer = readFileSync(options.image);
|
||||
}
|
||||
// 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);
|
||||
|
||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||
if (picInfo) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
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';
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
} from './apis/extras';
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
|
||||
export class Bridge implements BridgeInterface {
|
||||
readonly identity: IdentityService;
|
||||
@@ -129,12 +131,29 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
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,
|
||||
};
|
||||
}
|
||||
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
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);
|
||||
|
||||
@@ -5,7 +5,7 @@ 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;
|
||||
export type SessionClosedCallback = (uin: string, bridge: Bridge) => void;
|
||||
|
||||
interface QQSession {
|
||||
bridge: Bridge;
|
||||
@@ -18,11 +18,40 @@ export class BridgeManager {
|
||||
private pidToUin_ = new Map<number, string>();
|
||||
private pidPacketClients_ = new Map<number, PacketSender>();
|
||||
|
||||
private onSessionStarted_: SessionStartedCallback | null = null;
|
||||
private onSessionClosed_: SessionClosedCallback | null = null;
|
||||
private sessionStartedListeners_: SessionStartedCallback[] = [];
|
||||
private sessionClosedListeners_: SessionClosedCallback[] = [];
|
||||
|
||||
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
|
||||
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
|
||||
/** Additive subscription: every observer (OneBotManager, NotificationManager,
|
||||
* …) receives every session edge. (Was a single `set*Callback` setter —
|
||||
* converted to N listeners so a second observer can't clobber the first.)
|
||||
* The close edge now carries the bridge too, since callers read the last
|
||||
* nickname before it is disposed. */
|
||||
addSessionStartedListener(cb: SessionStartedCallback): void {
|
||||
this.sessionStartedListeners_.push(cb);
|
||||
}
|
||||
addSessionClosedListener(cb: SessionClosedCallback): void {
|
||||
this.sessionClosedListeners_.push(cb);
|
||||
}
|
||||
|
||||
private fireSessionStarted(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionStartedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-started listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fireSessionClosed(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionClosedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-closed listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
this.pidPacketClients_.delete(pid);
|
||||
@@ -37,7 +66,8 @@ export class BridgeManager {
|
||||
if (session.bridge.empty) {
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
if (this.onSessionClosed_) this.onSessionClosed_(uin);
|
||||
// Fire before dispose() so listeners can still read bridge.identity.
|
||||
this.fireSessionClosed(uin, session.bridge);
|
||||
session.bridge.dispose();
|
||||
}
|
||||
}
|
||||
@@ -59,9 +89,7 @@ export class BridgeManager {
|
||||
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +112,7 @@ export class BridgeManager {
|
||||
// Notify session started on first real packet
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
if (this.onSessionStarted_) {
|
||||
this.onSessionStarted_(uin, session.bridge);
|
||||
}
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
|
||||
// Dispatch packet to bridge
|
||||
|
||||
@@ -3,10 +3,27 @@ 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 { createNotificationManager } from './notifications/manager';
|
||||
|
||||
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');
|
||||
|
||||
@@ -20,13 +37,22 @@ async function main() {
|
||||
|
||||
oneBotManager.bind(bridgeManager);
|
||||
|
||||
// Global notification subsystem (account up/down → webhook). Bound AFTER
|
||||
// OneBotManager so the nickname fallback is already populated when it observes.
|
||||
const notificationManager = createNotificationManager();
|
||||
notificationManager.bind(bridgeManager);
|
||||
|
||||
if (
|
||||
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
|
||||
process.env.SNOWLUMA_DEV_WEBUI === '1'
|
||||
) {
|
||||
try {
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager);
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
|
||||
host: runtimeConfig.webuiHost,
|
||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||
trustProxy: runtimeConfig.trustProxy,
|
||||
});
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
}
|
||||
@@ -37,6 +63,7 @@ async function main() {
|
||||
const shutdown = (signal: string) => async () => {
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
oneBotManager.dispose();
|
||||
notificationManager.dispose();
|
||||
hookManager.dispose();
|
||||
await closeLogger();
|
||||
process.exit(0);
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
// Global notification-channel store + the pure template renderer.
|
||||
//
|
||||
// Mirrors the conventions of `webui/ui-config.ts` (the plan calls for this
|
||||
// explicitly): every `normalize*` is TOTAL — any unknown / corrupt input
|
||||
// collapses to a safe default, numbers clamp, unknown keys are dropped — and
|
||||
// persistence is an atomic write (tmp → rename) behind a module-level cache.
|
||||
//
|
||||
// Channels are GLOBAL (defined once here); each UIN opts into a subset via
|
||||
// `OneBotConfig.notifications.channelIds` (see packages/onebot/src/config.ts).
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const log = createLogger('Notifications.Config');
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const NOTIFICATIONS_CONFIG_PATH = path.join(CONFIG_DIR, 'notifications.json');
|
||||
|
||||
export const NOTIFICATIONS_CONFIG_VERSION = 1 as const;
|
||||
|
||||
export const DEBOUNCE_SECONDS_MIN = 0;
|
||||
export const DEBOUNCE_SECONDS_MAX = 3600;
|
||||
export const DEFAULT_DEBOUNCE_SECONDS = 30;
|
||||
|
||||
/** A channel id is a slug: it is referenced by per-UIN `channelIds`, so it must
|
||||
* be safe to use as a stable key. Kept in sync with `normalizeChannelIds` in
|
||||
* packages/onebot/src/config.ts (cross-package; can't share without a circular
|
||||
* dep — core depends on onebot, not the reverse). */
|
||||
export const CHANNEL_ID_RE = /^[\w.-]+$/;
|
||||
const CHANNEL_ID_MAX = 64;
|
||||
const CHANNEL_NAME_MAX = 128;
|
||||
const BODY_TEMPLATE_MAX = 8192;
|
||||
|
||||
/** event ∈ {offline, online}; rendered verbatim into `{event}`. */
|
||||
export type NotificationEvent = 'offline' | 'online';
|
||||
|
||||
export interface NotificationChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
bodyTemplate: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface NotificationsConfig {
|
||||
version: typeof NOTIFICATIONS_CONFIG_VERSION;
|
||||
debounceSeconds: number;
|
||||
channels: NotificationChannel[];
|
||||
}
|
||||
|
||||
/** Default body template — Server酱-style JSON ({title}/{desp}). The WebUI
|
||||
* ships additional per-vendor presets (钉钉/Discord/…) as frontend constants
|
||||
* the operator can drop in. */
|
||||
export const DEFAULT_BODY_TEMPLATE = `{
|
||||
"title": "账号状态通知:{event}",
|
||||
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
|
||||
}`;
|
||||
|
||||
export function defaultNotificationsConfig(): NotificationsConfig {
|
||||
return {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds: DEFAULT_DEBOUNCE_SECONDS,
|
||||
channels: [],
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Template renderer ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Mechanical `{key}` substitution — no logic, no conditionals, no escaping.
|
||||
* A key present in `vars` is replaced by its value; an unknown `{key}` is left
|
||||
* untouched (原样) so a typo'd placeholder is visible rather than silently
|
||||
* blanked. Pure + total (a non-string template yields '').
|
||||
*
|
||||
* **JSON safety**: When the template is valid JSON (parseable by JSON.parse),
|
||||
* values are escaped to prevent breaking the JSON structure — backslashes
|
||||
* become `\\` and double-quotes become `\"`.
|
||||
*/
|
||||
export function renderTemplate(template: string, vars: Record<string, string>): string {
|
||||
if (typeof template !== 'string') return '';
|
||||
let isJson = false;
|
||||
try {
|
||||
JSON.parse(template);
|
||||
isJson = true;
|
||||
} catch {
|
||||
// not JSON — plain text mode
|
||||
}
|
||||
return template.replace(/\{(\w+)\}/g, (match, key: string) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(vars, key)) return match;
|
||||
const val = vars[key];
|
||||
return isJson ? val.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : val;
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Normalization helpers (replicated from ui-config conventions) ──────────
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function boolOr(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
function clampInt(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.trunc(Math.min(max, Math.max(min, n)));
|
||||
}
|
||||
|
||||
function strOr(value: unknown, fallback: string, maxLen: number): string {
|
||||
return typeof value === 'string' ? value.slice(0, maxLen) : fallback;
|
||||
}
|
||||
|
||||
function normalizeChannelId(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const v = value.trim();
|
||||
if (v.length === 0 || v.length > CHANNEL_ID_MAX) return null;
|
||||
if (!CHANNEL_ID_RE.test(v)) return null;
|
||||
return v;
|
||||
}
|
||||
|
||||
function isHttpUrl(value: string): boolean {
|
||||
try {
|
||||
const u = new URL(value);
|
||||
return u.protocol === 'http:' || u.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** A channel is usable only with a valid id AND an http(s) target — anything
|
||||
* else is unusable, so the whole entry is dropped (total normalize). */
|
||||
function normalizeChannel(raw: unknown): NotificationChannel | null {
|
||||
if (!isObject(raw)) return null;
|
||||
const id = normalizeChannelId(raw.id);
|
||||
if (!id) return null;
|
||||
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
|
||||
if (!isHttpUrl(url)) return null;
|
||||
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
url,
|
||||
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
|
||||
enabled: boolOr(raw.enabled, true),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeChannels(value: unknown): NotificationChannel[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const seen = new Set<string>();
|
||||
const out: NotificationChannel[] = [];
|
||||
for (const raw of value) {
|
||||
const ch = normalizeChannel(raw);
|
||||
if (!ch) continue;
|
||||
if (seen.has(ch.id)) continue; // dedupe by id — first occurrence wins
|
||||
seen.add(ch.id);
|
||||
out.push(ch);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeNotificationsConfig(value: unknown): NotificationsConfig {
|
||||
const v = isObject(value) ? value : {};
|
||||
return {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds: clampInt(
|
||||
v.debounceSeconds,
|
||||
DEBOUNCE_SECONDS_MIN,
|
||||
DEBOUNCE_SECONDS_MAX,
|
||||
DEFAULT_DEBOUNCE_SECONDS,
|
||||
),
|
||||
channels: normalizeChannels(v.channels),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Persistence (atomic write + module-level cache) ────────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function atomicWrite(config: NotificationsConfig): void {
|
||||
ensureConfigDir();
|
||||
const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH);
|
||||
}
|
||||
|
||||
let cached: NotificationsConfig | null = null;
|
||||
|
||||
/** Load + normalize the channel store, creating it from defaults if absent. */
|
||||
export function loadNotificationsConfig(): NotificationsConfig {
|
||||
if (cached) return cached;
|
||||
ensureConfigDir();
|
||||
|
||||
if (!fs.existsSync(NOTIFICATIONS_CONFIG_PATH)) {
|
||||
const fresh = defaultNotificationsConfig();
|
||||
try {
|
||||
atomicWrite(fresh);
|
||||
} catch (err) {
|
||||
log.warn('failed to write initial notifications.json: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
const normalized = normalizeNotificationsConfig(parsed);
|
||||
// Self-heal on disk only if normalization changed something (corrupt/old).
|
||||
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
|
||||
try {
|
||||
atomicWrite(normalized);
|
||||
} catch {
|
||||
/* best-effort self-heal */
|
||||
}
|
||||
}
|
||||
cached = normalized;
|
||||
return normalized;
|
||||
} catch (err) {
|
||||
log.warn('notifications.json unreadable; using defaults: %s', err instanceof Error ? err.message : String(err));
|
||||
const fresh = defaultNotificationsConfig();
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a (possibly partial) client-supplied config. A missing `channels` or
|
||||
* `debounceSeconds` keeps the current on-disk value — section-level merge, same
|
||||
* as `saveUiConfig`. Returns the stored, normalized config.
|
||||
*/
|
||||
export function saveNotificationsConfig(incoming: unknown): NotificationsConfig {
|
||||
const current = loadNotificationsConfig();
|
||||
const v = isObject(incoming) ? incoming : {};
|
||||
const next: NotificationsConfig = {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds:
|
||||
v.debounceSeconds !== undefined
|
||||
? clampInt(v.debounceSeconds, DEBOUNCE_SECONDS_MIN, DEBOUNCE_SECONDS_MAX, DEFAULT_DEBOUNCE_SECONDS)
|
||||
: current.debounceSeconds,
|
||||
channels: Array.isArray(v.channels) ? normalizeChannels(v.channels) : current.channels,
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Per-UIN debounce state machine for online↔offline notifications.
|
||||
//
|
||||
// Uptime-Kuma semantics (grill-locked in the plan): an offline that SURVIVES
|
||||
// `debounceSeconds` fires an "offline" notification; its later recovery fires
|
||||
// the paired "online". An offline that self-heals within the window fires
|
||||
// NOTHING (the blip is suppressed). A cold online — one with no prior fired
|
||||
// offline — fires nothing (it is not a recovery).
|
||||
//
|
||||
// This module is PURE: no timers, no I/O, no clock. It only decides; the
|
||||
// manager owns the timer + the side effects. That keeps the debounce logic
|
||||
// fully unit-testable by driving a sequence of events.
|
||||
import type { NotificationEvent } from './config';
|
||||
|
||||
export type DebounceDecision =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'schedule'; delayMs: number }
|
||||
| { kind: 'cancel' }
|
||||
| { kind: 'emit'; event: NotificationEvent };
|
||||
|
||||
interface UinState {
|
||||
/** An offline debounce timer is armed but has not yet fired. */
|
||||
pending: boolean;
|
||||
/** An "offline" notification has fired and is awaiting its recovery. */
|
||||
firedOffline: boolean;
|
||||
}
|
||||
|
||||
export class DebounceMachine {
|
||||
private readonly states = new Map<string, UinState>();
|
||||
|
||||
private state(uin: string): UinState {
|
||||
let s = this.states.get(uin);
|
||||
if (!s) {
|
||||
s = { pending: false, firedOffline: false };
|
||||
this.states.set(uin, s);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Account went offline. `debounceSeconds` is read fresh from config so a
|
||||
* reload takes effect on the next transition. */
|
||||
onOffline(uin: string, debounceSeconds: number): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (s.firedOffline || s.pending) return { kind: 'none' }; // already down / already counting
|
||||
// Non-finite / non-positive → no debounce, fire immediately. Stays total:
|
||||
// never schedule a setTimeout(NaN|Infinity). Production config always
|
||||
// clamps to a finite [0,3600]; this only hardens direct callers.
|
||||
if (!Number.isFinite(debounceSeconds) || debounceSeconds <= 0) {
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
s.pending = true;
|
||||
return { kind: 'schedule', delayMs: debounceSeconds * 1000 };
|
||||
}
|
||||
|
||||
/** Account came online. */
|
||||
onOnline(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (s.pending) {
|
||||
s.pending = false;
|
||||
return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired
|
||||
}
|
||||
if (s.firedOffline) {
|
||||
s.firedOffline = false;
|
||||
return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline
|
||||
}
|
||||
return { kind: 'none' }; // cold online / already up
|
||||
}
|
||||
|
||||
/** The offline debounce window elapsed (the armed timer fired). */
|
||||
onTimerElapsed(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (!s.pending) return { kind: 'none' }; // cancelled before firing
|
||||
s.pending = false;
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
|
||||
/** Drop a UIN's state (e.g. on dispose). */
|
||||
forget(uin: string): void {
|
||||
this.states.delete(uin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// The global notification subsystem: one singleton watching ALL accounts.
|
||||
//
|
||||
// Subscribes to BridgeManager session online/offline edges, runs a per-UIN
|
||||
// debounce state machine (see debounce.ts), and on a fired transition renders
|
||||
// each opted-in + enabled channel's body template and POSTs it — recording the
|
||||
// outcome in a bounded in-memory history (lost on restart, by design).
|
||||
//
|
||||
// Side-effecting collaborators (config load, per-UIN channel ids, the outbound
|
||||
// POST, the clock) are injected so the class is fully unit-testable; the real
|
||||
// wiring lives in `createNotificationManager()` at the bottom.
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig } from '@snowluma/onebot/config';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import {
|
||||
loadNotificationsConfig,
|
||||
renderTemplate,
|
||||
type NotificationChannel,
|
||||
type NotificationEvent,
|
||||
type NotificationsConfig,
|
||||
} from './config';
|
||||
import { DebounceMachine, type DebounceDecision } from './debounce';
|
||||
|
||||
const log = createLogger('Notifications');
|
||||
|
||||
const DEFAULT_HISTORY_LIMIT = 100;
|
||||
const DEFAULT_POST_TIMEOUT_MS = 10_000;
|
||||
const FALLBACK_DEBOUNCE_SECONDS = 30;
|
||||
|
||||
/** One delivery attempt; kept only in memory (the plan forbids persistence). */
|
||||
export interface DeliveryRecord {
|
||||
time: number;
|
||||
uin: string;
|
||||
event: NotificationEvent;
|
||||
channelId: string;
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface PostResult {
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface NotificationManagerDeps {
|
||||
/** Global channel store (channels + debounceSeconds). */
|
||||
loadConfig: () => NotificationsConfig;
|
||||
/** The channel ids a UIN has opted into. */
|
||||
loadChannelIds: (uin: string) => string[];
|
||||
/** Outbound delivery — never throws; failures come back as `{ ok: false }`. */
|
||||
post: (url: string, body: string) => Promise<PostResult>;
|
||||
now: () => number;
|
||||
historyLimit?: number;
|
||||
}
|
||||
|
||||
function errMsg(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure: the channels a UIN should be notified through — globally enabled AND
|
||||
* opted into by the UIN — preserving config order. Exported for unit tests.
|
||||
*/
|
||||
export function selectChannels(channels: NotificationChannel[], enabledIds: string[]): NotificationChannel[] {
|
||||
const wanted = new Set(enabledIds);
|
||||
return channels.filter((c) => c.enabled && wanted.has(c.id));
|
||||
}
|
||||
|
||||
export class NotificationManager {
|
||||
private readonly deps: NotificationManagerDeps;
|
||||
private readonly machine = new DebounceMachine();
|
||||
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
private readonly nicknames = new Map<string, string>();
|
||||
private readonly history: DeliveryRecord[] = [];
|
||||
private readonly historyLimit: number;
|
||||
|
||||
constructor(deps: NotificationManagerDeps) {
|
||||
this.deps = deps;
|
||||
this.historyLimit = deps.historyLimit ?? DEFAULT_HISTORY_LIMIT;
|
||||
}
|
||||
|
||||
/** Subscribe to the global session online/offline edges. Register AFTER
|
||||
* OneBotManager so the nickname fallback is already populated. */
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => this.handleOnline(uin, bridge.identity.nickname));
|
||||
bridgeManager.addSessionClosedListener((uin, bridge) => this.handleOffline(uin, bridge.identity.nickname));
|
||||
}
|
||||
|
||||
handleOnline(uin: string, nickname?: string): void {
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOnline(uin));
|
||||
}
|
||||
|
||||
handleOffline(uin: string, nickname?: string): void {
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
|
||||
}
|
||||
|
||||
private debounceSeconds(): number {
|
||||
try {
|
||||
return this.deps.loadConfig().debounceSeconds;
|
||||
} catch {
|
||||
return FALLBACK_DEBOUNCE_SECONDS;
|
||||
}
|
||||
}
|
||||
|
||||
private apply(uin: string, decision: DebounceDecision): void {
|
||||
switch (decision.kind) {
|
||||
case 'schedule': {
|
||||
const existing = this.timers.get(uin);
|
||||
if (existing) clearTimeout(existing);
|
||||
const timer = setTimeout(() => {
|
||||
this.timers.delete(uin);
|
||||
this.apply(uin, this.machine.onTimerElapsed(uin));
|
||||
}, decision.delayMs);
|
||||
// Don't let a pending notification timer keep the process alive.
|
||||
if (typeof (timer as { unref?: () => void }).unref === 'function') {
|
||||
(timer as { unref: () => void }).unref();
|
||||
}
|
||||
this.timers.set(uin, timer);
|
||||
break;
|
||||
}
|
||||
case 'cancel': {
|
||||
const timer = this.timers.get(uin);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.timers.delete(uin);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'emit':
|
||||
void this.notify(uin, decision.event);
|
||||
break;
|
||||
case 'none':
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/** Render + POST a transition to every opted-in, enabled channel and record
|
||||
* the outcome. Never throws (a bad channel can't break the others). */
|
||||
async notify(uin: string, event: NotificationEvent): Promise<void> {
|
||||
let channels: NotificationChannel[];
|
||||
try {
|
||||
const cfg = this.deps.loadConfig();
|
||||
channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin));
|
||||
} catch (err) {
|
||||
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err));
|
||||
return;
|
||||
}
|
||||
if (channels.length === 0) return;
|
||||
|
||||
const nickname = this.nicknames.get(uin) || uin;
|
||||
const vars: Record<string, string> = {
|
||||
uin,
|
||||
nickname,
|
||||
event,
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
};
|
||||
|
||||
for (const ch of channels) {
|
||||
const body = renderTemplate(ch.bodyTemplate, vars);
|
||||
let result: PostResult;
|
||||
try {
|
||||
result = await this.deps.post(ch.url, body);
|
||||
} catch (err) {
|
||||
// The injected post is contracted not to throw, but guard anyway.
|
||||
result = { ok: false, error: errMsg(err) };
|
||||
}
|
||||
this.record({
|
||||
time: this.deps.now(),
|
||||
uin,
|
||||
event,
|
||||
channelId: ch.id,
|
||||
ok: result.ok,
|
||||
status: result.status,
|
||||
error: result.ok ? undefined : (result.error ?? (result.status ? `HTTP ${result.status}` : 'delivery failed')),
|
||||
});
|
||||
if (!result.ok) {
|
||||
log.warn('notify %s→%s channel=%s failed: %s', uin, event, ch.id, result.error ?? `HTTP ${result.status ?? '?'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Send a one-off test to a single channel by id — ignores `enabled` and the
|
||||
* per-UIN opt-in (you test a channel before wiring it up), with sample
|
||||
* variables. Reuses the real render+POST path; NOT recorded to history.
|
||||
* `found:false` means the channel id is unknown. */
|
||||
async testSend(channelId: string): Promise<PostResult & { found: boolean }> {
|
||||
let channel: NotificationChannel | undefined;
|
||||
try {
|
||||
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
|
||||
} catch (err) {
|
||||
return { ok: false, found: false, error: errMsg(err) };
|
||||
}
|
||||
if (!channel) return { ok: false, found: false };
|
||||
const body = renderTemplate(channel.bodyTemplate, {
|
||||
uin: '10000',
|
||||
nickname: '测试账号',
|
||||
event: 'offline',
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
});
|
||||
try {
|
||||
return { ...(await this.deps.post(channel.url, body)), found: true };
|
||||
} catch (err) {
|
||||
return { ok: false, found: true, error: errMsg(err) };
|
||||
}
|
||||
}
|
||||
|
||||
private record(rec: DeliveryRecord): void {
|
||||
this.history.push(rec);
|
||||
if (this.history.length > this.historyLimit) {
|
||||
this.history.splice(0, this.history.length - this.historyLimit);
|
||||
}
|
||||
}
|
||||
|
||||
/** Most-recent-first delivery history (capped at the buffer size). */
|
||||
getRecent(limit = this.historyLimit): DeliveryRecord[] {
|
||||
const n = Math.max(0, Math.min(Math.trunc(limit) || 0, this.history.length));
|
||||
return this.history.slice(this.history.length - n).reverse();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const timer of this.timers.values()) clearTimeout(timer);
|
||||
this.timers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Default outbound POST: a single attempt with a timeout, JSON content-type
|
||||
* (the common case for 钉钉/Discord/飞书). Never throws. */
|
||||
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
|
||||
return async (url, body) => {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
return { ok: res.ok, status: res.status, error: res.ok ? undefined : `HTTP ${res.status}` };
|
||||
} catch (err) {
|
||||
return { ok: false, error: errMsg(err) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The real, fully-wired singleton. */
|
||||
export function createNotificationManager(): NotificationManager {
|
||||
return new NotificationManager({
|
||||
loadConfig: loadNotificationsConfig,
|
||||
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
|
||||
post: createDefaultPost(),
|
||||
now: () => Date.now(),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// WebUI config backup/restore (Wave A2). Format: a zero-dep JSON bundle
|
||||
// { version, app, createdAt, files: { "<name>": { encoding, data } } }
|
||||
// over an explicit allowlist (never a whole-dir sweep) so a stray/unknown file
|
||||
// can't leak and an import can't path-traverse.
|
||||
//
|
||||
// Credentials are gated by a toggle on both export and import. The credential
|
||||
// set is: webui.json (password hash), key.pem (TLS private key), AND every
|
||||
// OneBot config (onebot.json + per-account onebot_<uin>.json) — those carry the
|
||||
// OneBot access token, so a no-credentials backup must NOT include them.
|
||||
// cert.pem is public so it always travels.
|
||||
//
|
||||
// Pure functions here (read/list/decode); the fs glue (atomic two-phase write,
|
||||
// snapshot) lives in server.ts. Restore is restart-to-apply, like A1.
|
||||
|
||||
export const BACKUP_VERSION = 1;
|
||||
export const BACKUP_APP = 'snowluma';
|
||||
|
||||
export interface BackupFileSpec {
|
||||
/** Path relative to the config dir; also the bundle key. */
|
||||
name: string;
|
||||
binary: boolean;
|
||||
/** Sensitive (private key / password hash / access token) — credential-gated. */
|
||||
credential: boolean;
|
||||
}
|
||||
|
||||
/** Static allowlist. Per-account `onebot_<uin>.json` are matched by pattern. */
|
||||
export const BACKUP_FILES: readonly BackupFileSpec[] = [
|
||||
{ name: 'runtime.json', binary: false, credential: false },
|
||||
{ name: 'ui.json', binary: false, credential: false },
|
||||
{ name: 'notifications.json', binary: false, credential: false },
|
||||
{ name: 'cert.pem', binary: false, credential: false },
|
||||
{ name: 'ui-assets/background', binary: true, credential: false },
|
||||
{ name: 'webui.json', binary: false, credential: true },
|
||||
{ name: 'key.pem', binary: false, credential: true },
|
||||
// OneBot config carries the access token → credential.
|
||||
{ name: 'onebot.json', binary: false, credential: true },
|
||||
];
|
||||
|
||||
const SPEC_BY_NAME = new Map(BACKUP_FILES.map((f) => [f.name, f]));
|
||||
const PER_UIN_ONEBOT = /^onebot_\d+\.json$/;
|
||||
|
||||
/** Resolve a file name (static or per-uin onebot pattern) to its spec, or null. */
|
||||
export function specFor(name: string): BackupFileSpec | null {
|
||||
const s = SPEC_BY_NAME.get(name);
|
||||
if (s) return s;
|
||||
if (PER_UIN_ONEBOT.test(name)) return { name, binary: false, credential: true };
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface BackupEntry { encoding: 'utf8' | 'base64'; data: string }
|
||||
export interface Backup {
|
||||
version: number;
|
||||
app: string;
|
||||
createdAt?: string;
|
||||
files: Record<string, BackupEntry>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble a bundle from the allowlist plus any per-account onebot files.
|
||||
* `readFile` returns null for missing.
|
||||
*/
|
||||
export function buildBackup(
|
||||
readFile: (name: string) => Buffer | null,
|
||||
perUinOnebotNames: readonly string[],
|
||||
opts: { includeCredentials: boolean },
|
||||
createdAt: string,
|
||||
): Backup {
|
||||
const files: Record<string, BackupEntry> = {};
|
||||
const all: BackupFileSpec[] = [
|
||||
...BACKUP_FILES,
|
||||
...perUinOnebotNames.filter((n) => PER_UIN_ONEBOT.test(n)).map((n) => ({ name: n, binary: false, credential: true })),
|
||||
];
|
||||
for (const spec of all) {
|
||||
if (spec.credential && !opts.includeCredentials) continue;
|
||||
const buf = readFile(spec.name);
|
||||
if (!buf) continue;
|
||||
files[spec.name] = spec.binary
|
||||
? { encoding: 'base64', data: buf.toString('base64') }
|
||||
: { encoding: 'utf8', data: buf.toString('utf8') };
|
||||
}
|
||||
return { version: BACKUP_VERSION, app: BACKUP_APP, createdAt, files };
|
||||
}
|
||||
|
||||
/** Validate a parsed bundle wholesale — any defect rejects the whole import. */
|
||||
export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | { ok: false; error: string } {
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
||||
return { ok: false, error: 'backup must be an object' };
|
||||
}
|
||||
const b = parsed as Record<string, unknown>;
|
||||
if (b.app !== BACKUP_APP) return { ok: false, error: 'not a SnowLuma backup' };
|
||||
if (b.version !== BACKUP_VERSION) return { ok: false, error: `unsupported backup version ${String(b.version)}` };
|
||||
if (typeof b.files !== 'object' || b.files === null || Array.isArray(b.files)) {
|
||||
return { ok: false, error: 'backup.files must be an object' };
|
||||
}
|
||||
const files = b.files as Record<string, unknown>;
|
||||
for (const [name, entry] of Object.entries(files)) {
|
||||
if (!specFor(name)) return { ok: false, error: `unknown file in backup: ${name}` };
|
||||
if (typeof entry !== 'object' || entry === null) return { ok: false, error: `malformed entry: ${name}` };
|
||||
const e = entry as Record<string, unknown>;
|
||||
if (e.encoding !== 'utf8' && e.encoding !== 'base64') return { ok: false, error: `bad encoding for ${name}` };
|
||||
if (typeof e.data !== 'string') return { ok: false, error: `bad data for ${name}` };
|
||||
}
|
||||
return { ok: true, backup: { version: BACKUP_VERSION, app: BACKUP_APP, createdAt: typeof b.createdAt === 'string' ? b.createdAt : undefined, files: files as Record<string, BackupEntry> } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide what a (validated) bundle would restore: decode each non-skipped file
|
||||
* to bytes. Pure — the caller (server.ts) does the atomic two-phase fs write so
|
||||
* a mid-restore failure can't leave a half-applied live config. Credential
|
||||
* files are skipped unless `restoreCredentials`.
|
||||
*/
|
||||
export function planRestore(
|
||||
backup: Backup,
|
||||
opts: { restoreCredentials: boolean },
|
||||
): { restore: Array<{ name: string; data: Buffer }>; skipped: string[] } {
|
||||
const restore: Array<{ name: string; data: Buffer }> = [];
|
||||
const skipped: string[] = [];
|
||||
for (const [name, entry] of Object.entries(backup.files)) {
|
||||
const spec = specFor(name);
|
||||
if (!spec) { skipped.push(name); continue; } // validated, but be defensive
|
||||
if (spec.credential && !opts.restoreCredentials) { skipped.push(name); continue; }
|
||||
restore.push({ name, data: Buffer.from(entry.data, entry.encoding) });
|
||||
}
|
||||
return { restore, skipped };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// SSE frame pusher for the debug stream (Wave A3). Drops frames under
|
||||
// backpressure (consumer slow → desiredSize <= 0) instead of buffering
|
||||
// unbounded into memory, and coalesces the drop count into a {kind:'dropped'}
|
||||
// marker emitted just before the next delivered frame. Extracted from the route
|
||||
// handler so this (easy-to-get-wrong) logic is unit-tested.
|
||||
|
||||
export interface FramePusherOptions {
|
||||
/** The stream controller's current desiredSize (null = no backpressure info). */
|
||||
desiredSize: () => number | null;
|
||||
/** Deliver an encoded SSE chunk (the caller maps this to the controller). */
|
||||
enqueue: (chunk: Uint8Array) => void;
|
||||
encode?: (s: string) => Uint8Array;
|
||||
}
|
||||
|
||||
/** Returns a `push(payload)` that frames + delivers with backpressure dropping. */
|
||||
export function createFramePusher(opts: FramePusherOptions): (payload: unknown) => void {
|
||||
const encode = opts.encode ?? ((s: string) => new TextEncoder().encode(s));
|
||||
let dropped = 0;
|
||||
return (payload: unknown): void => {
|
||||
const d = opts.desiredSize();
|
||||
if (d !== null && d <= 0) { dropped += 1; return; }
|
||||
if (dropped > 0) {
|
||||
opts.enqueue(encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`));
|
||||
dropped = 0;
|
||||
}
|
||||
opts.enqueue(encode(`data: ${JSON.stringify(payload)}\n\n`));
|
||||
};
|
||||
}
|
||||
@@ -4,16 +4,36 @@ import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
|
||||
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';
|
||||
import type { OneBotConfig } from '@snowluma/onebot/types';
|
||||
import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types';
|
||||
import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs';
|
||||
import { createServer as createHttpsServer } from 'https';
|
||||
import { Hono, type Context } from 'hono';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
|
||||
import { resolveTlsContext, validateTlsPair } from './tls';
|
||||
import { coerceSettingsPatch } from './system-settings';
|
||||
import { buildBackup, planRestore, validateBackup } from './backup';
|
||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||
import { createFramePusher } from './debug-stream';
|
||||
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';
|
||||
import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config';
|
||||
import type { NotificationManager } from '../notifications/manager';
|
||||
|
||||
const log = createLogger('WebUI');
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -47,6 +67,7 @@ const MUST_CHANGE_ALLOWLIST = new Set([
|
||||
// into access logs / Referer / browser history.
|
||||
const TOKEN_QUERY_ALLOWLIST = new Set([
|
||||
'/api/logs/stream',
|
||||
'/api/debug/stream',
|
||||
]);
|
||||
|
||||
// uin = QQ number; 5–12 digits. Used to construct config file paths,
|
||||
@@ -65,14 +86,6 @@ function purgeExpiredTokens() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the client IP for per-IP rate limiting. Default is the TCP
|
||||
* socket peer (cannot be spoofed by the client). Operators behind a
|
||||
* reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env
|
||||
* var; see `./client-ip.ts` for the accepted values.
|
||||
*/
|
||||
const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY);
|
||||
const getClientIp = makeClientIpResolver(trustProxyMode);
|
||||
|
||||
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
|
||||
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
|
||||
@@ -91,7 +104,20 @@ export async function initWebUI(
|
||||
desiredPort: number = 5099,
|
||||
oneBotManager: OneBotManager,
|
||||
hookManager?: HookManager,
|
||||
notificationManager?: NotificationManager,
|
||||
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string } = {},
|
||||
): Promise<{ port: number }> {
|
||||
// Resolve the client IP for per-IP rate limiting from the configured
|
||||
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
|
||||
// SNOWLUMA_WEBUI_TRUST_PROXY which loadRuntimeConfig already merged in).
|
||||
// Default ('') = trust the TCP socket peer only (cannot be spoofed).
|
||||
const trustProxyMode = parseTrustProxy(listener.trustProxy);
|
||||
const getClientIp = makeClientIpResolver(trustProxyMode);
|
||||
|
||||
// Actual bound port (set just before serve; findAvailablePort may bump it).
|
||||
// Read by GET /api/system/settings so the panel shows what's really live.
|
||||
let boundPort = desiredPort;
|
||||
|
||||
const auth = WebuiAuth.load();
|
||||
const initialPassword = auth.takeInitialPassword();
|
||||
if (auth.isDevMode()) {
|
||||
@@ -139,7 +165,10 @@ export async function initWebUI(
|
||||
// ─── Auth middleware ─────────────────────────────────────────────────────
|
||||
app.use('/api/*', async (c, next) => {
|
||||
const reqPath = c.req.path;
|
||||
if (reqPath === '/api/login') return next();
|
||||
// `/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();
|
||||
|
||||
const authHeader = c.req.header('Authorization');
|
||||
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
|
||||
@@ -282,9 +311,38 @@ 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[] {
|
||||
@@ -349,12 +407,264 @@ export async function initWebUI(
|
||||
});
|
||||
});
|
||||
|
||||
// ── System settings (WebUI listener) — Wave A1 ──
|
||||
// Listener-level changes (port/host/TLS) are persisted but apply only on the
|
||||
// next restart (no supervisor → no self-restart). The panel surfaces which
|
||||
// fields are currently overridden by env so edits that won't take effect are
|
||||
// visible.
|
||||
const SYSTEM_CERT_PATH = path.join('config', 'cert.pem');
|
||||
const SYSTEM_KEY_PATH = path.join('config', 'key.pem');
|
||||
const hasCert = (): boolean => existsSync(SYSTEM_CERT_PATH) && existsSync(SYSTEM_KEY_PATH);
|
||||
|
||||
app.get('/api/system/settings', (c) => {
|
||||
const disk = readRuntimeConfig();
|
||||
const envOverrides = Object.keys(resolveRuntimeEnvOverrides(process.env));
|
||||
return c.json({
|
||||
settings: {
|
||||
webuiPort: disk.webuiPort,
|
||||
webuiHost: disk.webuiHost,
|
||||
tlsEnabled: disk.webuiTls?.enabled ?? false,
|
||||
trustProxy: disk.trustProxy ?? '',
|
||||
},
|
||||
hasCert: hasCert(),
|
||||
envOverrides, // field names currently pinned by SNOWLUMA_* env vars
|
||||
listeningPort: boundPort,
|
||||
restartRequiredToApply: true,
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/system/settings', async (c) => {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const coerced = coerceSettingsPatch(body);
|
||||
if (!coerced.ok) return c.json({ success: false, message: coerced.error }, 400);
|
||||
// Enabling TLS without a usable cert would brick HTTPS on restart — block it.
|
||||
if (coerced.patch.webuiTls?.enabled && !resolveTlsContext('config').ok) {
|
||||
return c.json({ success: false, message: '启用 TLS 前请先上传有效的证书与私钥' }, 400);
|
||||
}
|
||||
const saved = updateRuntimeConfig(coerced.patch);
|
||||
return c.json({
|
||||
success: true,
|
||||
settings: {
|
||||
webuiPort: saved.webuiPort,
|
||||
webuiHost: saved.webuiHost,
|
||||
tlsEnabled: saved.webuiTls?.enabled ?? false,
|
||||
trustProxy: saved.trustProxy ?? '',
|
||||
},
|
||||
restartRequiredToApply: true,
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/system/tls/cert', async (c) => {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const cert = (body as { cert?: unknown }).cert;
|
||||
const key = (body as { key?: unknown }).key;
|
||||
if (typeof cert !== 'string' || typeof key !== 'string') {
|
||||
return c.json({ success: false, message: 'cert 和 key 必须为 PEM 字符串' }, 400);
|
||||
}
|
||||
const valid = validateTlsPair(cert, key);
|
||||
if (!valid.ok) return c.json({ success: false, message: valid.reason }, 400);
|
||||
try {
|
||||
mkdirSync('config', { recursive: true });
|
||||
writeFileSync(SYSTEM_CERT_PATH, cert.endsWith('\n') ? cert : cert + '\n', 'utf8');
|
||||
// Private key must not be world-readable (mirrors auth.ts's webui.json
|
||||
// 0600). writeFileSync's mode is ignored for an existing file, so chmod
|
||||
// explicitly afterwards.
|
||||
writeFileSync(SYSTEM_KEY_PATH, key.endsWith('\n') ? key : key + '\n', { encoding: 'utf8', mode: 0o600 });
|
||||
// Best-effort (mirrors auth.ts): the key is already written 0600 above, so
|
||||
// a rare chmod failure must not fail the request.
|
||||
try { chmodSync(SYSTEM_KEY_PATH, 0o600); } catch { /* best-effort */ }
|
||||
} catch (err) {
|
||||
log.warn('write cert/key failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '写入证书失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
return c.json({ success: true, restartRequiredToApply: true });
|
||||
});
|
||||
|
||||
app.delete('/api/system/tls/cert', (c) => {
|
||||
try {
|
||||
rmSync(SYSTEM_CERT_PATH, { force: true });
|
||||
rmSync(SYSTEM_KEY_PATH, { force: true });
|
||||
} catch (err) {
|
||||
log.warn('remove cert/key failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '删除证书失败' }, 500);
|
||||
}
|
||||
return c.json({ success: true });
|
||||
});
|
||||
|
||||
// ── Config backup / restore (Wave A2) ──
|
||||
const cfgPath = (name: string) => path.join('config', name);
|
||||
const readCfg = (name: string): Buffer | null => {
|
||||
const p = cfgPath(name);
|
||||
return existsSync(p) ? readFileSync(p) : null;
|
||||
};
|
||||
|
||||
const listPerUinOnebot = (): string[] => {
|
||||
try {
|
||||
return existsSync('config') ? readdirSync('config').filter((n) => /^onebot_\d+\.json$/.test(n)) : [];
|
||||
} catch { return []; }
|
||||
};
|
||||
|
||||
app.get('/api/system/backup/export', (c) => {
|
||||
const includeCredentials = c.req.query('credentials') === '1';
|
||||
const ts = new Date().toISOString();
|
||||
const bundle = buildBackup(readCfg, listPerUinOnebot(), { includeCredentials }, ts);
|
||||
c.header('Content-Disposition', `attachment; filename="snowluma-backup-${ts.replace(/[:.]/g, '-')}.json"`);
|
||||
// Bundle may carry the TLS private key / password hash — never cache it.
|
||||
c.header('Cache-Control', 'no-store, max-age=0');
|
||||
c.header('Pragma', 'no-cache');
|
||||
return c.json(bundle);
|
||||
});
|
||||
|
||||
app.post('/api/system/backup/import', async (c) => {
|
||||
const declaredLen = Number(c.req.header('content-length'));
|
||||
if (Number.isFinite(declaredLen) && declaredLen > 32 * 1024 * 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);
|
||||
}
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const { backup, restoreCredentials } = body as { backup?: unknown; restoreCredentials?: unknown };
|
||||
const v = validateBackup(backup);
|
||||
if (!v.ok) return c.json({ success: false, message: v.error }, 400);
|
||||
|
||||
const plan = planRestore(v.backup, { restoreCredentials: restoreCredentials === true });
|
||||
// Snapshot the current (about-to-be-overwritten) config so a restore is
|
||||
// recoverable; one timestamped dir per import.
|
||||
const snapDir = path.join('config', `.restore-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
||||
// Two-phase write for near-atomicity: stage every file as a .tmp first, then
|
||||
// rename them all. A failure during staging touches no live file; rename
|
||||
// almost never fails, shrinking the half-applied window to near zero.
|
||||
const staged: Array<{ tmp: string; dest: string; name: string }> = [];
|
||||
try {
|
||||
for (const { name } of plan.restore) {
|
||||
const src = cfgPath(name);
|
||||
if (!existsSync(src)) continue;
|
||||
const snap = path.join(snapDir, name);
|
||||
mkdirSync(path.dirname(snap), { recursive: true });
|
||||
copyFileSync(src, snap);
|
||||
}
|
||||
for (const { name, data } of plan.restore) {
|
||||
const dest = cfgPath(name);
|
||||
mkdirSync(path.dirname(dest), { recursive: true });
|
||||
const tmp = dest + '.restore.tmp';
|
||||
writeFileSync(tmp, data, name === 'key.pem' ? { mode: 0o600 } : undefined);
|
||||
staged.push({ tmp, dest, name });
|
||||
}
|
||||
for (const { tmp, dest, name } of staged) {
|
||||
renameSync(tmp, dest);
|
||||
if (name === 'key.pem') { try { chmodSync(dest, 0o600); } catch { /* best-effort */ } }
|
||||
}
|
||||
return c.json({
|
||||
success: true,
|
||||
restored: plan.restore.map((r) => r.name),
|
||||
skipped: plan.skipped,
|
||||
snapshotDir: snapDir,
|
||||
restartRequiredToApply: true,
|
||||
});
|
||||
} catch (err) {
|
||||
// Clean up any staged .tmp not yet renamed (staging-phase failure leaves
|
||||
// the live config untouched; a rare rename-phase failure may be partial,
|
||||
// recoverable from the snapshot dir).
|
||||
for (const { tmp } of staged) { try { if (existsSync(tmp)) rmSync(tmp, { force: true }); } catch { /* ignore */ } }
|
||||
log.warn('backup import failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '恢复失败;若为写入阶段失败则当前配置未改动,否则可从 config/.restore-backup-* 快照恢复' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ── Debug tools (Wave A3) ──
|
||||
// Action schemas for the tester form (declarative actions only; legacy ones
|
||||
// are invoked freeform).
|
||||
app.get('/api/debug/actions', (c) =>
|
||||
c.json({ actions: collectActionDocs(), categories: collectCategories() }));
|
||||
|
||||
// Manually invoke an action against one account. Real side effects — gated by
|
||||
// the same /api/* auth.
|
||||
app.post('/api/debug/invoke', async (c) => {
|
||||
let body: unknown;
|
||||
try { body = await c.req.json(); } catch { return c.json({ status: 'failed', message: '请求格式错误' }, 400); }
|
||||
const { uin, action, params } = (body ?? {}) as { uin?: unknown; action?: unknown; params?: unknown };
|
||||
if (typeof uin !== 'string' || !UIN_REGEX.test(uin)) return c.json({ status: 'failed', message: '无效的账号' }, 400);
|
||||
if (typeof action !== 'string' || !action) return c.json({ status: 'failed', message: 'action 必填' }, 400);
|
||||
if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) {
|
||||
return c.json({ status: 'failed', message: 'params 必须是对象' }, 400);
|
||||
}
|
||||
const inst = oneBotManager.getInstance(uin);
|
||||
if (!inst) return c.json({ status: 'failed', message: '账号不在线' }, 404);
|
||||
const result = await inst.invokeAction(action, (params ?? {}) as OneBotJsonObject);
|
||||
return c.json(result);
|
||||
});
|
||||
|
||||
// Live merged SSE of OneBot events + action calls across all accounts. Taps
|
||||
// are attached only while a client is connected (on-demand). A slow client is
|
||||
// dropped (not back-pressured onto the bot) with a periodic drop marker.
|
||||
app.get('/api/debug/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
const offs: Array<() => void> = [];
|
||||
let heartbeat: NodeJS.Timeout | undefined;
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
for (const off of offs) { try { off(); } catch { /* ignore */ } }
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try { controller.enqueue(chunk); } catch { teardown(); }
|
||||
};
|
||||
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
|
||||
const pushFrame = createFramePusher({
|
||||
desiredSize: () => controller.desiredSize,
|
||||
enqueue: raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
});
|
||||
const send = (payload: unknown) => { if (!closed) pushFrame(payload); };
|
||||
send({ kind: 'ready' });
|
||||
for (const inst of oneBotManager.getInstances()) {
|
||||
const uin = inst.uin;
|
||||
offs.push(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
|
||||
offs.push(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
|
||||
}
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/qq-list', (c) => {
|
||||
const instances = oneBotManager.getInstances();
|
||||
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
|
||||
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) });
|
||||
@@ -494,6 +804,138 @@ export async function initWebUI(
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Notifications (account up/down → webhook) ───────────────────────────
|
||||
// Global channel store (config/notifications.json); per-UIN opt-in lives in
|
||||
// OneBotConfig.notifications.channelIds. All bearer-gated — channel URLs can
|
||||
// embed secrets, so none of this is exposed unauthenticated.
|
||||
app.get('/api/notifications/config', (c) => c.json({ config: loadNotificationsConfig() }));
|
||||
|
||||
app.post('/api/notifications/config', async (c) => {
|
||||
const declaredLen = Number(c.req.header('content-length'));
|
||||
if (Number.isFinite(declaredLen) && declaredLen > 512 * 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 = saveNotificationsConfig(body);
|
||||
return c.json({ success: true, config });
|
||||
} catch (err) {
|
||||
log.warn('save notifications config failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/notifications/recent', (c) => {
|
||||
if (!notificationManager) return c.json({ recent: [] });
|
||||
const limitRaw = Number(c.req.query('limit'));
|
||||
const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.trunc(limitRaw), 100) : 100;
|
||||
return c.json({ recent: notificationManager.getRecent(limit) });
|
||||
});
|
||||
|
||||
app.post('/api/notifications/test', async (c) => {
|
||||
if (!notificationManager) return c.json({ success: false, message: '通知子系统不可用' }, 503);
|
||||
let body: { channelId?: unknown };
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const channelId = typeof body.channelId === 'string' ? body.channelId : '';
|
||||
if (!channelId) return c.json({ success: false, message: '缺少 channelId' }, 400);
|
||||
const result = await notificationManager.testSend(channelId);
|
||||
if (!result.found) return c.json({ success: false, message: '渠道不存在' }, 404);
|
||||
return c.json({
|
||||
success: result.ok,
|
||||
status: result.status,
|
||||
message: result.ok
|
||||
? '测试发送成功'
|
||||
: `测试发送失败:${result.error ?? (result.status ? `HTTP ${result.status}` : '未知错误')}`,
|
||||
});
|
||||
});
|
||||
|
||||
// ─── 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.
|
||||
@@ -503,7 +945,11 @@ 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/')) {
|
||||
if (
|
||||
c.req.path.startsWith('/api/') ||
|
||||
c.req.path.startsWith('/avatar/') ||
|
||||
c.req.path.startsWith('/ui-asset/')
|
||||
) {
|
||||
return c.text('not found', 404);
|
||||
}
|
||||
if (existsSync(indexHtmlPath)) {
|
||||
@@ -520,10 +966,27 @@ export async function initWebUI(
|
||||
if (finalPort !== desiredPort) {
|
||||
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
|
||||
}
|
||||
boundPort = finalPort;
|
||||
|
||||
const host = listener.host || '0.0.0.0';
|
||||
|
||||
// TLS: only when explicitly enabled AND the on-disk cert/key load. A bad
|
||||
// or missing cert must never brick the WebUI — fall back to HTTP + warn.
|
||||
let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined;
|
||||
let scheme = 'http';
|
||||
if (listener.tlsEnabled) {
|
||||
const tls = resolveTlsContext('config');
|
||||
if (tls.ok && tls.cert && tls.key) {
|
||||
tlsServe = { createServer: createHttpsServer, serverOptions: { cert: tls.cert, key: tls.key } };
|
||||
scheme = 'https';
|
||||
} else {
|
||||
log.warn('TLS enabled but cert/key unusable (%s) — serving over HTTP instead', tls.reason);
|
||||
}
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
serve({ fetch: app.fetch, port: finalPort }, (info) => {
|
||||
log.info(`listening http://localhost:${info.port}`);
|
||||
serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
|
||||
log.info(`listening ${scheme}://${host}:${info.port}`);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Pure validator for the POST /api/system/settings body. Rejects clearly-bad
|
||||
// input with a message (→ 400) rather than silently normalizing it, then hands
|
||||
// a clean patch to updateRuntimeConfig. Wire field `tlsEnabled` maps to the
|
||||
// nested `webuiTls.enabled`.
|
||||
|
||||
import type { RuntimeConfig } from '@snowluma/common/runtime';
|
||||
|
||||
export type SettingsPatch = Partial<Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>>;
|
||||
|
||||
export type CoerceResult =
|
||||
| { ok: true; patch: SettingsPatch }
|
||||
| { ok: false; error: string };
|
||||
|
||||
function isObject(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
export function coerceSettingsPatch(body: unknown): CoerceResult {
|
||||
if (!isObject(body)) return { ok: false, error: 'body must be an object' };
|
||||
const patch: SettingsPatch = {};
|
||||
|
||||
if ('webuiPort' in body) {
|
||||
const p = body.webuiPort;
|
||||
if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) {
|
||||
return { ok: false, error: 'webuiPort must be an integer in 1..65535' };
|
||||
}
|
||||
patch.webuiPort = p;
|
||||
}
|
||||
|
||||
if ('webuiHost' in body) {
|
||||
if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) {
|
||||
return { ok: false, error: 'webuiHost must be a non-empty string' };
|
||||
}
|
||||
patch.webuiHost = body.webuiHost.trim();
|
||||
}
|
||||
|
||||
if ('tlsEnabled' in body) {
|
||||
if (typeof body.tlsEnabled !== 'boolean') {
|
||||
return { ok: false, error: 'tlsEnabled must be a boolean' };
|
||||
}
|
||||
patch.webuiTls = { enabled: body.tlsEnabled };
|
||||
}
|
||||
|
||||
if ('trustProxy' in body) {
|
||||
if (typeof body.trustProxy !== 'string') {
|
||||
return { ok: false, error: 'trustProxy must be a string' };
|
||||
}
|
||||
patch.trustProxy = body.trustProxy;
|
||||
}
|
||||
|
||||
return { ok: true, patch };
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem
|
||||
// (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish
|
||||
// helpers: validate a pasted pair (save path) and resolve the on-disk pair
|
||||
// (boot path). Validation is `tls.createSecureContext` — it parses the PEM
|
||||
// and checks the key matches the cert; expiry is NOT checked here.
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import tls from 'tls';
|
||||
|
||||
export interface TlsValidation {
|
||||
ok: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface TlsResolution {
|
||||
ok: boolean;
|
||||
cert?: Buffer;
|
||||
key?: Buffer;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
function errMsg(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
/** Parse-validate a cert/key pair (used by the save endpoint before writing). */
|
||||
export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation {
|
||||
if (!cert || !cert.toString().trim()) return { ok: false, reason: 'certificate is empty' };
|
||||
if (!key || !key.toString().trim()) return { ok: false, reason: 'private key is empty' };
|
||||
try {
|
||||
tls.createSecureContext({ cert, key });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
}
|
||||
|
||||
/** Load + validate config/cert.pem + config/key.pem from `configDir`. */
|
||||
export function resolveTlsContext(configDir: string): TlsResolution {
|
||||
const certPath = path.join(configDir, 'cert.pem');
|
||||
const keyPath = path.join(configDir, 'key.pem');
|
||||
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) {
|
||||
return { ok: false, reason: 'cert.pem or key.pem missing in config dir' };
|
||||
}
|
||||
let cert: Buffer;
|
||||
let key: Buffer;
|
||||
try {
|
||||
cert = fs.readFileSync(certPath);
|
||||
key = fs.readFileSync(keyPath);
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
const valid = validateTlsPair(cert, key);
|
||||
if (!valid.ok) return { ok: false, reason: valid.reason };
|
||||
return { ok: true, cert, key };
|
||||
}
|
||||
@@ -0,0 +1,782 @@
|
||||
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); 'custom' uses `fontSansCustom`. */
|
||||
fontSans: string;
|
||||
/** Free-form sans font-family stack, used when `fontSans === 'custom'`. */
|
||||
fontSansCustom: string;
|
||||
/** Mono font preset id (frontend catalogue); 'custom' uses `fontMonoCustom`. */
|
||||
fontMono: string;
|
||||
/** Free-form mono font-family stack, used when `fontMono === 'custom'`. */
|
||||
fontMonoCustom: 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;
|
||||
/**
|
||||
* Theme-token overrides from the variable panel. Keys are restricted to a
|
||||
* fixed whitelist of `--token` names and values to colours / lengths, so
|
||||
* (unlike `customCss`) this is safe to serve to the unauthenticated login
|
||||
* page — `normalizeAppearance` drops unknown keys and invalid values.
|
||||
*/
|
||||
cssVars: Record<string, 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 (desktop 2D grid). Frontend reconciles vs its set. */
|
||||
overviewBlocks: UiLayoutItem[];
|
||||
/** Ordered single-column mobile overview (id+visible only; the 2D grid is
|
||||
* desktop-only). Kept separate so phone ordering never pollutes the grid. */
|
||||
overviewMobile: UiLayoutItem[];
|
||||
/** Ordered sidebar nav items, keyed by route path. */
|
||||
navItems: UiLayoutItem[];
|
||||
/** Top-bar element show/hide list (id+visible), mirroring navItems' shape. */
|
||||
topbarItems: UiLayoutItem[];
|
||||
}
|
||||
|
||||
export interface UiHighlightRule {
|
||||
keyword: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export type LogsPreset = 'dev' | 'ops' | 'minimal' | 'custom';
|
||||
|
||||
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[];
|
||||
/** Active view preset id; 'custom' = the operator hand-tuned the prefs. The
|
||||
* client owns the preset → prefs bundles; the server just stores the id. */
|
||||
preset: LogsPreset;
|
||||
}
|
||||
|
||||
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',
|
||||
fontSansCustom: '',
|
||||
fontMono: 'default',
|
||||
fontMonoCustom: '',
|
||||
uiScale: 1,
|
||||
radius: 0.75,
|
||||
density: 'cozy',
|
||||
reduceMotion: false,
|
||||
disableMotion: false,
|
||||
highContrast: false,
|
||||
sidebarDefaultCollapsed: false,
|
||||
timeFormat: '24h',
|
||||
pollInterval: 3000,
|
||||
customCss: '',
|
||||
cssVars: {},
|
||||
};
|
||||
|
||||
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 },
|
||||
];
|
||||
|
||||
// Single-column mobile order = the desktop grid catalogue's widgets, flattened
|
||||
// (stat tiles, then the cards). The client reconciles against its real
|
||||
// catalogue, so this just seeds first run; unknown ids are dropped on load.
|
||||
const DEFAULT_OVERVIEW_MOBILE: UiLayoutItem[] = [
|
||||
{ id: 'stat:status', visible: true },
|
||||
{ id: 'stat:accounts', visible: true },
|
||||
{ id: 'stat:processes', visible: true },
|
||||
{ id: 'stat:host', visible: true },
|
||||
{ id: 'stat:uptime', 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 },
|
||||
];
|
||||
|
||||
// Toggleable top-bar elements (essential ones — menu, page title, logout — are
|
||||
// pinned in the client and never appear here). The client reconciles, so a new
|
||||
// element (e.g. the kiosk button) just appears as visible.
|
||||
const DEFAULT_TOPBAR_ITEMS: UiLayoutItem[] = [
|
||||
{ id: 'status', visible: true },
|
||||
{ id: 'theme', visible: true },
|
||||
{ id: 'kiosk', 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: [],
|
||||
preset: 'custom',
|
||||
},
|
||||
processesSort: 'pid',
|
||||
configTab: '',
|
||||
};
|
||||
|
||||
export function defaultUiConfig(): UiConfig {
|
||||
return {
|
||||
version: UI_CONFIG_VERSION,
|
||||
appearance: { ...DEFAULT_APPEARANCE, background: { ...DEFAULT_BACKGROUND }, cssVars: {} },
|
||||
layout: {
|
||||
overviewBlocks: DEFAULT_OVERVIEW_BLOCKS.map((b) => ({ ...b })),
|
||||
overviewMobile: DEFAULT_OVERVIEW_MOBILE.map((b) => ({ ...b })),
|
||||
navItems: DEFAULT_NAV_ITEMS.map((b) => ({ ...b })),
|
||||
topbarItems: DEFAULT_TOPBAR_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;
|
||||
}
|
||||
|
||||
/**
|
||||
* A free-form font-family value (a single family or a comma-separated stack),
|
||||
* safe to interpolate into `--font-sans: <value>;`. Allows letters (incl. CJK),
|
||||
* digits, spaces and the punctuation real font names use, but refuses anything
|
||||
* that could break out of the declaration (`;`, `{`, `}`, control chars, etc.).
|
||||
* Empty / over-long / invalid → fallback ('' = "no custom family set").
|
||||
*/
|
||||
const FONT_FAMILY_RE = /^[\p{L}\p{N}\s,'"._-]+$/u;
|
||||
function fontFamilyOr(value: unknown, fallback: string, maxLen = 200): string {
|
||||
if (typeof value !== 'string') return fallback;
|
||||
const v = value.trim();
|
||||
if (v.length === 0) return ''; // explicitly cleared
|
||||
if (v.length > maxLen || !FONT_FAMILY_RE.test(v)) return fallback;
|
||||
return v;
|
||||
}
|
||||
|
||||
// ─── cssVars (theme-token override panel) ──────────────────────────────────
|
||||
// Both the keys (which `--token` may be set) and the values (colour / length)
|
||||
// are whitelisted so the result is safe to serve to the UNAUTHENTICATED login
|
||||
// page — it shares the trust level of palette/accent, not of `customCss`.
|
||||
|
||||
/** The `--token` names the variable panel is allowed to override. Kept in sync
|
||||
* with the surface/accent tokens `ThemeContext` actually injects. */
|
||||
const CSS_VAR_WHITELIST = new Set<string>([
|
||||
'--background', '--foreground',
|
||||
'--card', '--card-foreground',
|
||||
'--popover', '--popover-foreground',
|
||||
'--primary', '--primary-foreground',
|
||||
'--secondary', '--secondary-foreground',
|
||||
'--muted', '--muted-foreground',
|
||||
'--accent', '--accent-foreground',
|
||||
'--destructive', '--destructive-foreground',
|
||||
'--success', '--warning',
|
||||
'--border', '--input', '--ring',
|
||||
'--sidebar', '--sidebar-foreground',
|
||||
'--sidebar-primary', '--sidebar-primary-foreground',
|
||||
'--sidebar-accent', '--sidebar-accent-foreground',
|
||||
'--sidebar-border', '--sidebar-ring',
|
||||
]);
|
||||
|
||||
// A CSS colour value, restricted to forms that cannot break out of a `--token:
|
||||
// <value>;` declaration. Hex, a named colour, or a single balanced functional
|
||||
// notation (rgb/hsl/oklch/… and color-mix) over a safe char set — crucially no
|
||||
// `;`, `{`, `}`, `:` or angle brackets are permitted anywhere.
|
||||
const CSS_HEX_RE = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
||||
const CSS_NAMED_RE = /^[a-zA-Z]{1,24}$/;
|
||||
const CSS_FUNC_RE = /^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix)\([a-zA-Z0-9.,%/\s#-]{1,120}\)$/;
|
||||
function cssColorOrNull(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const v = value.trim();
|
||||
if (v.length === 0 || v.length > 128) return null;
|
||||
if (CSS_HEX_RE.test(v) || CSS_NAMED_RE.test(v) || CSS_FUNC_RE.test(v)) return v;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Keep only whitelisted token keys with valid colour values; drop the rest. */
|
||||
function normalizeCssVars(value: unknown): Record<string, string> {
|
||||
if (!isObject(value)) return {};
|
||||
const out: Record<string, string> = {};
|
||||
for (const key of Object.keys(value)) {
|
||||
if (!CSS_VAR_WHITELIST.has(key)) continue;
|
||||
const color = cssColorOrNull(value[key]);
|
||||
if (color) out[key] = color;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
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),
|
||||
fontSansCustom: fontFamilyOr(v.fontSansCustom, DEFAULT_APPEARANCE.fontSansCustom),
|
||||
fontMono: idOr(v.fontMono, DEFAULT_APPEARANCE.fontMono),
|
||||
fontMonoCustom: fontFamilyOr(v.fontMonoCustom, DEFAULT_APPEARANCE.fontMonoCustom),
|
||||
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,
|
||||
cssVars: normalizeCssVars(v.cssVars),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeLayout(value: unknown): UiLayout {
|
||||
const layout = isObject(value) ? value : {};
|
||||
return {
|
||||
overviewBlocks: normalizeLayoutItems(layout.overviewBlocks, DEFAULT_OVERVIEW_BLOCKS),
|
||||
overviewMobile: normalizeLayoutItems(layout.overviewMobile, DEFAULT_OVERVIEW_MOBILE),
|
||||
navItems: normalizeLayoutItems(layout.navItems, DEFAULT_NAV_ITEMS),
|
||||
topbarItems: normalizeLayoutItems(layout.topbarItems, DEFAULT_TOPBAR_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),
|
||||
preset: oneOf<LogsPreset>(logs.preset, ['dev', 'ops', 'minimal', 'custom'], 'custom'),
|
||||
},
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// 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(),
|
||||
};
|
||||
}
|
||||
@@ -35,6 +35,43 @@ 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 () => {
|
||||
@@ -129,10 +166,7 @@ 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 {
|
||||
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);
|
||||
return JSON.parse(inflatePrefixedPayload(elem.lightApp.data));
|
||||
}
|
||||
|
||||
it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => {
|
||||
|
||||
@@ -110,6 +110,64 @@ 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]');
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// MessageApi.getGroupHistory walk-back loop: chunking, dedup, server-short-cap
|
||||
// handling, floor termination, slice(-want). fetchGroupMessageRange is mocked
|
||||
// so this exercises the loop/cursor logic, not the wire decode (covered in
|
||||
// packages/protocol/tests/msg-push/fetch-group-history.test.ts).
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/msg-push', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@snowluma/protocol/msg-push')>();
|
||||
return { ...actual, fetchGroupMessageRange: vi.fn() };
|
||||
});
|
||||
|
||||
import { fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
|
||||
import { MessageApi } from '../src/bridge/apis/message';
|
||||
|
||||
const mockFetch = vi.mocked(fetchGroupMessageRange);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function gm(seq: number): any {
|
||||
return {
|
||||
kind: 'group_message', time: 0, selfUin: 0, senderUin: 1, msgSeq: seq,
|
||||
msgId: seq, elements: [], groupId: 9999, senderNick: '', senderCard: '', senderRole: '',
|
||||
};
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const ctx = { identity: {}, sendRawPacket: vi.fn() } as any;
|
||||
|
||||
describe('MessageApi.getGroupHistory walk-back', () => {
|
||||
beforeEach(() => mockFetch.mockReset());
|
||||
|
||||
it('walks back across short-capped windows, dedups, returns newest `want` ascending', async () => {
|
||||
// Server caps every window to its newest 10 sequences → forces walk-back.
|
||||
mockFetch.mockImplementation(async (_s, _id, _self, _g, start, end) => {
|
||||
const out = [];
|
||||
for (let s = Math.max(start, end - 9); s <= end; s++) out.push(gm(s));
|
||||
return out;
|
||||
});
|
||||
|
||||
const res = await new MessageApi(ctx).getGroupHistory(9999, 200, 50);
|
||||
|
||||
expect(res).toHaveLength(50);
|
||||
expect(res[0].msgSeq).toBe(151); // newest 50 ending at 200 → 151..200
|
||||
expect(res[res.length - 1].msgSeq).toBe(200);
|
||||
for (let i = 1; i < res.length; i++) {
|
||||
expect(res[i].msgSeq).toBeGreaterThan(res[i - 1].msgSeq); // strictly ascending, no dups
|
||||
}
|
||||
});
|
||||
|
||||
it('stops at the sequence floor when fewer messages exist than requested', async () => {
|
||||
mockFetch.mockImplementation(async (_s, _id, _self, _g, start, end) => {
|
||||
const out = [];
|
||||
for (let s = start; s <= end; s++) out.push(gm(s));
|
||||
return out;
|
||||
});
|
||||
|
||||
const res = await new MessageApi(ctx).getGroupHistory(9999, 20, 100); // only seq 1..20 exist
|
||||
expect(res.map((m) => m.msgSeq)).toEqual(Array.from({ length: 20 }, (_, i) => i + 1));
|
||||
});
|
||||
|
||||
it('caps the request count and bounds the request loop', async () => {
|
||||
let calls = 0;
|
||||
mockFetch.mockImplementation(async (_s, _id, _self, _g, _start, end) => {
|
||||
calls++;
|
||||
return [gm(end)]; // one message per window → never reaches a large `want`
|
||||
});
|
||||
|
||||
const res = await new MessageApi(ctx).getGroupHistory(9999, 100_000, 9999);
|
||||
expect(calls).toBeLessThanOrEqual(12); // HISTORY_MAX_REQUESTS
|
||||
expect(res.length).toBeLessThanOrEqual(200); // HISTORY_MAX_COUNT
|
||||
});
|
||||
|
||||
it('returns [] for an invalid anchor without sending', async () => {
|
||||
expect(await new MessageApi(ctx).getGroupHistory(0, 100, 10)).toEqual([]);
|
||||
expect(await new MessageApi(ctx).getGroupHistory(9999, 0, 10)).toEqual([]);
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -99,3 +99,81 @@ 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
// 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,
|
||||
GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin,
|
||||
} from '@snowluma/proto-defs/notify';
|
||||
import type { PushMsg } from '@snowluma/proto-defs/message';
|
||||
import type {
|
||||
@@ -24,6 +24,7 @@ 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';
|
||||
|
||||
@@ -347,3 +348,72 @@ 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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import {
|
||||
DEFAULT_BODY_TEMPLATE,
|
||||
DEFAULT_DEBOUNCE_SECONDS,
|
||||
defaultNotificationsConfig,
|
||||
normalizeNotificationsConfig,
|
||||
renderTemplate,
|
||||
} from '../src/notifications/config';
|
||||
|
||||
describe('renderTemplate — mechanical {key} substitution', () => {
|
||||
it('replaces present variables', () => {
|
||||
expect(
|
||||
renderTemplate('{nickname}({uin}) {event} @ {time}', {
|
||||
nickname: 'Bob',
|
||||
uin: '123',
|
||||
event: 'offline',
|
||||
time: '12:00',
|
||||
}),
|
||||
).toBe('Bob(123) offline @ 12:00');
|
||||
});
|
||||
|
||||
it('leaves missing placeholders untouched (原样)', () => {
|
||||
expect(renderTemplate('{a}-{b}', { a: 'x' })).toBe('x-{b}');
|
||||
});
|
||||
|
||||
it('replaces repeated occurrences', () => {
|
||||
expect(renderTemplate('{x}{x}', { x: 'ab' })).toBe('abab');
|
||||
});
|
||||
|
||||
it('leaves text with no placeholders unchanged', () => {
|
||||
expect(renderTemplate('hello', { x: '1' })).toBe('hello');
|
||||
});
|
||||
|
||||
it('does no logic — an empty value substitutes as empty', () => {
|
||||
expect(renderTemplate('[{x}]', { x: '' })).toBe('[]');
|
||||
});
|
||||
|
||||
it('is total — a non-string template yields an empty string', () => {
|
||||
expect(renderTemplate(undefined as unknown as string, {})).toBe('');
|
||||
});
|
||||
|
||||
it('does NOT re-expand a substituted value that itself contains a placeholder', () => {
|
||||
// Load-bearing invariant: replacement text is never re-scanned. A refactor
|
||||
// to a recursive/loop replace would break this while passing every other test.
|
||||
expect(renderTemplate('{a}', { a: '{b}', b: 'NESTED' })).toBe('{b}');
|
||||
});
|
||||
|
||||
it('escapes backslashes and quotes when template is JSON-like', () => {
|
||||
const tmpl = '{"text": "{val}"}';
|
||||
expect(renderTemplate(tmpl, { val: 'a"b\\c' })).toBe('{"text": "a\\"b\\\\c"}');
|
||||
});
|
||||
|
||||
it('does NOT escape when template is plain text', () => {
|
||||
expect(renderTemplate('{val}', { val: 'a"b\\c' })).toBe('a"b\\c');
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeNotificationsConfig — total normalize', () => {
|
||||
it('collapses garbage / non-objects to the full default', () => {
|
||||
const d = defaultNotificationsConfig();
|
||||
for (const junk of [undefined, null, 42, 'nope', []]) {
|
||||
expect(normalizeNotificationsConfig(junk)).toEqual(d);
|
||||
}
|
||||
});
|
||||
|
||||
it('forces version to 1 regardless of input', () => {
|
||||
expect(normalizeNotificationsConfig({ version: 99 }).version).toBe(1);
|
||||
});
|
||||
|
||||
it('clamps + truncates debounceSeconds into [0, 3600]', () => {
|
||||
expect(normalizeNotificationsConfig({ debounceSeconds: -5 }).debounceSeconds).toBe(0);
|
||||
expect(normalizeNotificationsConfig({ debounceSeconds: 99999 }).debounceSeconds).toBe(3600);
|
||||
expect(normalizeNotificationsConfig({ debounceSeconds: 30.9 }).debounceSeconds).toBe(30);
|
||||
expect(normalizeNotificationsConfig({ debounceSeconds: '45' }).debounceSeconds).toBe(45);
|
||||
expect(normalizeNotificationsConfig({ debounceSeconds: 'x' }).debounceSeconds).toBe(DEFAULT_DEBOUNCE_SECONDS);
|
||||
});
|
||||
|
||||
it('drops a non-array channels value', () => {
|
||||
expect(normalizeNotificationsConfig({ channels: 'nope' }).channels).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps a valid channel and strips unknown fields', () => {
|
||||
const { channels } = normalizeNotificationsConfig({
|
||||
channels: [
|
||||
{
|
||||
id: 'dingtalk',
|
||||
name: 'DingTalk',
|
||||
url: 'https://oapi.dingtalk.com/robot/send',
|
||||
bodyTemplate: '{event}',
|
||||
enabled: true,
|
||||
evil: 'x',
|
||||
extra: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(channels).toEqual([
|
||||
{
|
||||
id: 'dingtalk',
|
||||
name: 'DingTalk',
|
||||
url: 'https://oapi.dingtalk.com/robot/send',
|
||||
bodyTemplate: '{event}',
|
||||
enabled: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('drops channels lacking a valid id or http(s) url', () => {
|
||||
const { channels } = normalizeNotificationsConfig({
|
||||
channels: [
|
||||
{ id: '', url: 'https://a.com' }, // empty id
|
||||
{ id: 'bad id!', url: 'https://a.com' }, // invalid slug
|
||||
{ id: 'noUrl' }, // missing url
|
||||
{ id: 'ftp', url: 'ftp://a.com' }, // non-http scheme
|
||||
{ id: 'ok', url: 'http://a.com' }, // valid
|
||||
],
|
||||
});
|
||||
expect(channels.map((c) => c.id)).toEqual(['ok']);
|
||||
});
|
||||
|
||||
it('dedupes channels by id (first occurrence wins)', () => {
|
||||
const { channels } = normalizeNotificationsConfig({
|
||||
channels: [
|
||||
{ id: 'dup', url: 'https://a.com', name: 'first' },
|
||||
{ id: 'dup', url: 'https://b.com', name: 'second' },
|
||||
],
|
||||
});
|
||||
expect(channels).toHaveLength(1);
|
||||
expect(channels[0].name).toBe('first');
|
||||
expect(channels[0].url).toBe('https://a.com');
|
||||
});
|
||||
|
||||
it('defaults enabled=true, name→id, and bodyTemplate→default', () => {
|
||||
const { channels } = normalizeNotificationsConfig({ channels: [{ id: 'c1', url: 'https://a.com' }] });
|
||||
expect(channels[0].enabled).toBe(true);
|
||||
expect(channels[0].name).toBe('c1');
|
||||
expect(channels[0].bodyTemplate).toBe(DEFAULT_BODY_TEMPLATE);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadNotificationsConfig / saveNotificationsConfig (fs-backed)', () => {
|
||||
let tmp: string;
|
||||
let prevCwd: string;
|
||||
|
||||
beforeEach(() => {
|
||||
prevCwd = process.cwd();
|
||||
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-notif-'));
|
||||
process.chdir(tmp);
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(prevCwd);
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('creates a default config file when absent', async () => {
|
||||
const mod = await import('../src/notifications/config');
|
||||
const cfg = mod.loadNotificationsConfig();
|
||||
expect(cfg).toEqual(mod.defaultNotificationsConfig());
|
||||
expect(fs.existsSync(path.join('config', 'notifications.json'))).toBe(true);
|
||||
});
|
||||
|
||||
it('round-trips a saved config across a fresh module load', async () => {
|
||||
const mod = await import('../src/notifications/config');
|
||||
const saved = mod.saveNotificationsConfig({
|
||||
debounceSeconds: 60,
|
||||
channels: [{ id: 'c1', name: 'C1', url: 'https://a.com/hook', bodyTemplate: '{event}', enabled: false }],
|
||||
});
|
||||
expect(saved.debounceSeconds).toBe(60);
|
||||
expect(saved.channels).toHaveLength(1);
|
||||
|
||||
vi.resetModules();
|
||||
const mod2 = await import('../src/notifications/config');
|
||||
expect(mod2.loadNotificationsConfig()).toEqual(saved);
|
||||
});
|
||||
|
||||
it('section-merges partial saves (debounce-only keeps channels)', async () => {
|
||||
const mod = await import('../src/notifications/config');
|
||||
mod.saveNotificationsConfig({ channels: [{ id: 'c1', url: 'https://a.com' }] });
|
||||
const after = mod.saveNotificationsConfig({ debounceSeconds: 120 });
|
||||
expect(after.debounceSeconds).toBe(120);
|
||||
expect(after.channels.map((c) => c.id)).toEqual(['c1']);
|
||||
});
|
||||
|
||||
it('self-heals an unreadable file on load', async () => {
|
||||
fs.mkdirSync('config', { recursive: true });
|
||||
fs.writeFileSync(path.join('config', 'notifications.json'), '{ not valid json', 'utf8');
|
||||
const mod = await import('../src/notifications/config');
|
||||
expect(mod.loadNotificationsConfig()).toEqual(mod.defaultNotificationsConfig());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { DebounceMachine } from '../src/notifications/debounce';
|
||||
|
||||
describe('DebounceMachine — online↔offline debounce (Uptime-Kuma semantics)', () => {
|
||||
it('a cold online (no prior offline) fires nothing', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('an offline that self-heals within the window fires nothing', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'cancel' });
|
||||
// back to baseline — a later offline schedules fresh
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
});
|
||||
|
||||
it('an offline that survives the window fires offline, then recovery fires online (paired)', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
expect(m.onTimerElapsed('u')).toEqual({ kind: 'emit', event: 'offline' });
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'emit', event: 'online' });
|
||||
// after recovery completes, the next online is cold again
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('debounceSeconds<=0 fires offline immediately', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', 0)).toEqual({ kind: 'emit', event: 'offline' });
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'emit', event: 'online' });
|
||||
});
|
||||
|
||||
it('treats a non-finite debounceSeconds as no-debounce (fires immediately)', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', Number.NaN)).toEqual({ kind: 'emit', event: 'offline' });
|
||||
});
|
||||
|
||||
it('a second offline while pending is a no-op', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
expect(m.onOffline('u', 30)).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('a second offline after one already fired is a no-op', () => {
|
||||
const m = new DebounceMachine();
|
||||
m.onOffline('u', 0); // fires offline
|
||||
expect(m.onOffline('u', 0)).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('a timer elapsing after a cancel is a no-op (stale timer)', () => {
|
||||
const m = new DebounceMachine();
|
||||
m.onOffline('u', 30); // schedule
|
||||
m.onOnline('u'); // cancel
|
||||
expect(m.onTimerElapsed('u')).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('tracks UINs independently', () => {
|
||||
const m = new DebounceMachine();
|
||||
expect(m.onOffline('a', 0)).toEqual({ kind: 'emit', event: 'offline' });
|
||||
expect(m.onOffline('b', 30)).toEqual({ kind: 'schedule', delayMs: 30_000 });
|
||||
expect(m.onOnline('b')).toEqual({ kind: 'cancel' });
|
||||
expect(m.onOnline('a')).toEqual({ kind: 'emit', event: 'online' });
|
||||
});
|
||||
|
||||
it('forget() resets a UIN to baseline', () => {
|
||||
const m = new DebounceMachine();
|
||||
m.onOffline('u', 0); // fired offline
|
||||
m.forget('u');
|
||||
expect(m.onOnline('u')).toEqual({ kind: 'none' }); // state cleared → no recovery
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
NotificationManager,
|
||||
selectChannels,
|
||||
type NotificationManagerDeps,
|
||||
type PostResult,
|
||||
} from '../src/notifications/manager';
|
||||
import type { NotificationChannel, NotificationsConfig } from '../src/notifications/config';
|
||||
|
||||
function ch(over: Partial<NotificationChannel> = {}): NotificationChannel {
|
||||
return {
|
||||
id: 'c1',
|
||||
name: 'C1',
|
||||
url: 'https://hook.example/c1',
|
||||
bodyTemplate: '{event}:{uin}:{nickname}',
|
||||
enabled: true,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
describe('selectChannels (pure)', () => {
|
||||
it('keeps only enabled channels the UIN opted into, in config order', () => {
|
||||
const channels = [ch({ id: 'a' }), ch({ id: 'b', enabled: false }), ch({ id: 'c' })];
|
||||
expect(selectChannels(channels, ['c', 'a', 'b']).map((c) => c.id)).toEqual(['a', 'c']);
|
||||
});
|
||||
|
||||
it('is empty when the UIN opted into nothing', () => {
|
||||
expect(selectChannels([ch({ id: 'a' })], [])).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores opted-in ids with no matching channel', () => {
|
||||
expect(selectChannels([ch({ id: 'a' })], ['ghost'])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotificationManager — dispatch + history', () => {
|
||||
function setup(over: Partial<NotificationManagerDeps> = {}) {
|
||||
const posts: { url: string; body: string }[] = [];
|
||||
const cfg: NotificationsConfig = { version: 1, debounceSeconds: 30, channels: [ch()] };
|
||||
const deps: NotificationManagerDeps = {
|
||||
loadConfig: () => cfg,
|
||||
loadChannelIds: () => ['c1'],
|
||||
post: async (url, body): Promise<PostResult> => {
|
||||
posts.push({ url, body });
|
||||
return { ok: true, status: 200 };
|
||||
},
|
||||
now: () => 1000,
|
||||
...over,
|
||||
};
|
||||
return { posts, mgr: new NotificationManager(deps) };
|
||||
}
|
||||
|
||||
it('renders {event}{uin}{nickname} and posts to opted-in channels', async () => {
|
||||
const { posts, mgr } = setup();
|
||||
await mgr.notify('123', 'offline');
|
||||
// nickname falls back to the uin when none was captured
|
||||
expect(posts).toEqual([{ url: 'https://hook.example/c1', body: 'offline:123:123' }]);
|
||||
});
|
||||
|
||||
it('uses the nickname captured on an online/offline edge', async () => {
|
||||
const { posts, mgr } = setup();
|
||||
mgr.handleOnline('123', 'Alice'); // caches nickname; cold online → no post
|
||||
expect(posts).toHaveLength(0);
|
||||
await mgr.notify('123', 'offline');
|
||||
expect(posts[0].body).toBe('offline:123:Alice');
|
||||
});
|
||||
|
||||
it('records ok and failed deliveries, most-recent-first', async () => {
|
||||
let n = 0;
|
||||
const { mgr } = setup({
|
||||
post: async (): Promise<PostResult> => (++n === 1 ? { ok: true, status: 200 } : { ok: false, status: 500 }),
|
||||
});
|
||||
await mgr.notify('123', 'offline');
|
||||
await mgr.notify('123', 'online');
|
||||
const recent = mgr.getRecent();
|
||||
expect(recent).toHaveLength(2);
|
||||
expect(recent[0]).toMatchObject({ event: 'online', ok: false, status: 500 });
|
||||
expect(recent[1]).toMatchObject({ event: 'offline', ok: true, status: 200 });
|
||||
});
|
||||
|
||||
it('skips channels the UIN did not opt into', async () => {
|
||||
const { posts, mgr } = setup({ loadChannelIds: () => [] });
|
||||
await mgr.notify('123', 'offline');
|
||||
expect(posts).toEqual([]);
|
||||
});
|
||||
|
||||
it('a post that throws is captured as a failed record, not propagated', async () => {
|
||||
const { mgr } = setup({
|
||||
post: async (): Promise<PostResult> => {
|
||||
throw new Error('boom');
|
||||
},
|
||||
});
|
||||
await expect(mgr.notify('123', 'offline')).resolves.toBeUndefined();
|
||||
expect(mgr.getRecent()[0]).toMatchObject({ ok: false, error: 'boom' });
|
||||
});
|
||||
|
||||
it('caps history at the configured limit (oldest dropped)', async () => {
|
||||
const { mgr } = setup({ historyLimit: 3 });
|
||||
for (let i = 0; i < 5; i++) await mgr.notify('123', 'offline');
|
||||
expect(mgr.getRecent(99)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotificationManager.testSend', () => {
|
||||
function setup(over: Partial<NotificationManagerDeps> = {}) {
|
||||
const posts: { url: string; body: string }[] = [];
|
||||
const cfg: NotificationsConfig = {
|
||||
version: 1,
|
||||
debounceSeconds: 30,
|
||||
// disabled + nobody opted in — testSend must still fire it.
|
||||
channels: [ch({ id: 'c1', enabled: false, bodyTemplate: 'test:{event}:{nickname}' })],
|
||||
};
|
||||
const deps: NotificationManagerDeps = {
|
||||
loadConfig: () => cfg,
|
||||
loadChannelIds: () => [],
|
||||
post: async (url, body): Promise<PostResult> => {
|
||||
posts.push({ url, body });
|
||||
return { ok: true, status: 200 };
|
||||
},
|
||||
now: () => 1000,
|
||||
...over,
|
||||
};
|
||||
return { posts, mgr: new NotificationManager(deps) };
|
||||
}
|
||||
|
||||
it('fires a disabled / non-opted-in channel with sample vars', async () => {
|
||||
const { posts, mgr } = setup();
|
||||
const res = await mgr.testSend('c1');
|
||||
expect(res).toMatchObject({ found: true, ok: true, status: 200 });
|
||||
expect(posts).toHaveLength(1);
|
||||
expect(posts[0].body).toBe('test:offline:测试账号');
|
||||
});
|
||||
|
||||
it('returns found:false for an unknown channel and posts nothing', async () => {
|
||||
const { posts, mgr } = setup();
|
||||
expect(await mgr.testSend('ghost')).toMatchObject({ found: false, ok: false });
|
||||
expect(posts).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not record test sends in history', async () => {
|
||||
const { mgr } = setup();
|
||||
await mgr.testSend('c1');
|
||||
expect(mgr.getRecent()).toEqual([]);
|
||||
});
|
||||
|
||||
it('surfaces a failed delivery without throwing', async () => {
|
||||
const { mgr } = setup({ post: async (): Promise<PostResult> => ({ ok: false, status: 500, error: 'nope' }) });
|
||||
expect(await mgr.testSend('c1')).toMatchObject({ found: true, ok: false, status: 500 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotificationManager — debounce integration (fake timers)', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
function setup(debounceSeconds: number) {
|
||||
const events: string[] = [];
|
||||
const deps: NotificationManagerDeps = {
|
||||
loadConfig: () => ({ version: 1, debounceSeconds, channels: [ch()] }),
|
||||
loadChannelIds: () => ['c1'],
|
||||
post: async (_url, body) => {
|
||||
events.push(body.split(':')[0]);
|
||||
return { ok: true, status: 200 };
|
||||
},
|
||||
now: () => 1000,
|
||||
};
|
||||
return { events, mgr: new NotificationManager(deps) };
|
||||
}
|
||||
|
||||
it('suppresses an offline that self-heals within the window', async () => {
|
||||
const { events, mgr } = setup(30);
|
||||
mgr.handleOnline('123', 'Bob'); // cold online
|
||||
mgr.handleOffline('123', 'Bob'); // arm 30s timer
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
mgr.handleOnline('123', 'Bob'); // self-heal → cancel timer
|
||||
// The machine's state guard alone would suppress the misfire; assert the
|
||||
// manager ALSO cleared the timer (defense-in-depth a pure test can't see).
|
||||
expect((mgr as unknown as { timers: Map<string, unknown> }).timers.size).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(events).toEqual([]);
|
||||
});
|
||||
|
||||
it('fires offline after the window, then online on recovery (paired)', async () => {
|
||||
const { events, mgr } = setup(30);
|
||||
mgr.handleOffline('123', 'Bob'); // arm
|
||||
await vi.advanceTimersByTimeAsync(30_000); // window elapses → offline fires
|
||||
expect(events).toEqual(['offline']);
|
||||
mgr.handleOnline('123', 'Bob'); // recovery
|
||||
await vi.advanceTimersByTimeAsync(0); // flush the dispatch microtasks
|
||||
expect(events).toEqual(['offline', 'online']);
|
||||
});
|
||||
|
||||
it('with debounce 0, offline fires immediately', async () => {
|
||||
const { events, mgr } = setup(0);
|
||||
mgr.handleOffline('123', 'Bob');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(events).toEqual(['offline']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { BACKUP_FILES, specFor, buildBackup, validateBackup, planRestore } from '../src/webui/backup';
|
||||
|
||||
const TS = '2026-06-18T00:00:00.000Z';
|
||||
|
||||
function reader(map: Record<string, Buffer>) {
|
||||
return (name: string): Buffer | null => map[name] ?? null;
|
||||
}
|
||||
|
||||
describe('buildBackup', () => {
|
||||
it('includes present non-credential files and skips missing ones', () => {
|
||||
const b = buildBackup(reader({
|
||||
'runtime.json': Buffer.from('{"webuiPort":5099}'),
|
||||
'ui.json': Buffer.from('{}'),
|
||||
}), [], { includeCredentials: false }, TS);
|
||||
expect(b.version).toBe(1);
|
||||
expect(b.app).toBe('snowluma');
|
||||
expect(b.createdAt).toBe(TS);
|
||||
expect(Object.keys(b.files).sort()).toEqual(['runtime.json', 'ui.json']);
|
||||
expect(b.files['runtime.json']).toEqual({ encoding: 'utf8', data: '{"webuiPort":5099}' });
|
||||
});
|
||||
|
||||
it('treats all OneBot config (global + per-uin), webui.json, key.pem as credentials', () => {
|
||||
const map = {
|
||||
'runtime.json': Buffer.from('{}'),
|
||||
'webui.json': Buffer.from('{"hash":"x"}'),
|
||||
'key.pem': Buffer.from('KEY'),
|
||||
'cert.pem': Buffer.from('CERT'),
|
||||
'onebot.json': Buffer.from('{"accessToken":"t"}'),
|
||||
'onebot_12345.json': Buffer.from('{"accessToken":"t2"}'),
|
||||
};
|
||||
const perUin = ['onebot_12345.json'];
|
||||
const without = buildBackup(reader(map), perUin, { includeCredentials: false }, TS);
|
||||
// only public files survive a no-credentials export
|
||||
expect(Object.keys(without.files).sort()).toEqual(['cert.pem', 'runtime.json']);
|
||||
const withCreds = buildBackup(reader(map), perUin, { includeCredentials: true }, TS);
|
||||
expect(Object.keys(withCreds.files).sort()).toEqual(
|
||||
['cert.pem', 'key.pem', 'onebot.json', 'onebot_12345.json', 'runtime.json', 'webui.json'],
|
||||
);
|
||||
});
|
||||
|
||||
it('base64-encodes binary files (background image)', () => {
|
||||
const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
|
||||
const b = buildBackup(reader({ 'ui-assets/background': png }), [], { includeCredentials: false }, TS);
|
||||
expect(b.files['ui-assets/background']).toEqual({ encoding: 'base64', data: png.toString('base64') });
|
||||
});
|
||||
});
|
||||
|
||||
describe('specFor', () => {
|
||||
it('resolves static names and per-uin onebot pattern; rejects others', () => {
|
||||
expect(specFor('runtime.json')?.credential).toBe(false);
|
||||
expect(specFor('onebot.json')?.credential).toBe(true);
|
||||
expect(specFor('onebot_98765.json')).toEqual({ name: 'onebot_98765.json', binary: false, credential: true });
|
||||
expect(specFor('onebot_.json')).toBeNull();
|
||||
expect(specFor('../evil')).toBeNull();
|
||||
expect(specFor('onebot_12.json.bak')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateBackup', () => {
|
||||
const good = { version: 1, app: 'snowluma', files: { 'runtime.json': { encoding: 'utf8', data: '{}' } } };
|
||||
|
||||
it('accepts a well-formed bundle (incl. per-uin onebot)', () => {
|
||||
expect(validateBackup(good).ok).toBe(true);
|
||||
expect(validateBackup({ ...good, files: { 'onebot_42.json': { encoding: 'utf8', data: '{}' } } }).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a non-object / wrong app / wrong version', () => {
|
||||
expect(validateBackup(null).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, app: 'other' }).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, version: 999 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an unknown / path-traversal filename', () => {
|
||||
expect(validateBackup({ ...good, files: { '../evil': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, files: { 'unknown.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, files: { 'onebot_../x.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a malformed entry', () => {
|
||||
expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'rot13', data: 'x' } } }).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'utf8' } } }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('planRestore', () => {
|
||||
it('decodes restored files to bytes (utf8 + base64)', () => {
|
||||
const png = Buffer.from([1, 2, 3, 4]);
|
||||
const backup = {
|
||||
version: 1, app: 'snowluma',
|
||||
files: {
|
||||
'runtime.json': { encoding: 'utf8' as const, data: '{"a":1}' },
|
||||
'ui-assets/background': { encoding: 'base64' as const, data: png.toString('base64') },
|
||||
},
|
||||
};
|
||||
const { restore, skipped } = planRestore(backup, { restoreCredentials: false });
|
||||
expect(skipped).toEqual([]);
|
||||
const byName = Object.fromEntries(restore.map((r) => [r.name, r.data]));
|
||||
expect(byName['runtime.json'].toString()).toBe('{"a":1}');
|
||||
expect(byName['ui-assets/background'].equals(png)).toBe(true);
|
||||
});
|
||||
|
||||
it('skips all credential files unless restoreCredentials', () => {
|
||||
const backup = {
|
||||
version: 1, app: 'snowluma',
|
||||
files: {
|
||||
'runtime.json': { encoding: 'utf8' as const, data: '{}' },
|
||||
'webui.json': { encoding: 'utf8' as const, data: '{"hash":"x"}' },
|
||||
'key.pem': { encoding: 'utf8' as const, data: 'KEY' },
|
||||
'onebot.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' },
|
||||
'onebot_7.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' },
|
||||
},
|
||||
};
|
||||
const skip = planRestore(backup, { restoreCredentials: false });
|
||||
expect(skip.restore.map((r) => r.name)).toEqual(['runtime.json']);
|
||||
expect(skip.skipped.sort()).toEqual(['key.pem', 'onebot.json', 'onebot_7.json', 'webui.json']);
|
||||
const keep = planRestore(backup, { restoreCredentials: true });
|
||||
expect(keep.restore.map((r) => r.name).sort()).toEqual(
|
||||
['key.pem', 'onebot.json', 'onebot_7.json', 'runtime.json', 'webui.json'],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('BACKUP_FILES marks webui.json / key.pem / onebot.json as credentials, cert.pem public', () => {
|
||||
const creds = BACKUP_FILES.filter((f) => f.credential).map((f) => f.name).sort();
|
||||
expect(creds).toEqual(['key.pem', 'onebot.json', 'webui.json']);
|
||||
expect(specFor('cert.pem')?.credential).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createFramePusher } from '../src/webui/debug-stream';
|
||||
|
||||
function harness(sizes: number[]) {
|
||||
// desiredSize() returns the next scripted value each call.
|
||||
let i = 0;
|
||||
const frames: string[] = [];
|
||||
const push = createFramePusher({
|
||||
desiredSize: () => (i < sizes.length ? sizes[i++] : sizes[sizes.length - 1] ?? 1),
|
||||
enqueue: (chunk) => { frames.push(Buffer.from(chunk).toString()); },
|
||||
encode: (s) => Buffer.from(s),
|
||||
});
|
||||
return { push, frames };
|
||||
}
|
||||
|
||||
describe('createFramePusher', () => {
|
||||
it('enqueues an SSE data frame when there is headroom', () => {
|
||||
const { push, frames } = harness([1]);
|
||||
push({ kind: 'event', x: 1 });
|
||||
expect(frames).toEqual([`data: ${JSON.stringify({ kind: 'event', x: 1 })}\n\n`]);
|
||||
});
|
||||
|
||||
it('drops under backpressure (desiredSize <= 0) without enqueuing', () => {
|
||||
const { push, frames } = harness([0, -3]);
|
||||
push({ a: 1 });
|
||||
push({ a: 2 });
|
||||
expect(frames).toEqual([]);
|
||||
});
|
||||
|
||||
it('emits a coalesced dropped marker before the next delivered frame', () => {
|
||||
const { push, frames } = harness([0, 0, 5]); // drop, drop, then headroom
|
||||
push({ a: 1 });
|
||||
push({ a: 2 });
|
||||
push({ a: 3 });
|
||||
expect(frames).toEqual([
|
||||
`data: ${JSON.stringify({ kind: 'dropped', count: 2 })}\n\n`,
|
||||
`data: ${JSON.stringify({ a: 3 })}\n\n`,
|
||||
]);
|
||||
});
|
||||
|
||||
it('treats null desiredSize as always-deliver (no backpressure signal)', () => {
|
||||
let i = 0;
|
||||
const frames: string[] = [];
|
||||
const push = createFramePusher({
|
||||
desiredSize: () => (i++ === 0 ? null : 1),
|
||||
enqueue: (chunk) => { frames.push(Buffer.from(chunk).toString()); },
|
||||
encode: (s) => Buffer.from(s),
|
||||
});
|
||||
push({ a: 1 });
|
||||
expect(frames).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { coerceSettingsPatch } from '../src/webui/system-settings';
|
||||
|
||||
describe('coerceSettingsPatch', () => {
|
||||
it('accepts a full valid body and maps tlsEnabled → webuiTls.enabled', () => {
|
||||
const r = coerceSettingsPatch({ webuiPort: 8080, webuiHost: '127.0.0.1', tlsEnabled: true, trustProxy: '1' });
|
||||
expect(r).toEqual({ ok: true, patch: { webuiPort: 8080, webuiHost: '127.0.0.1', webuiTls: { enabled: true }, trustProxy: '1' } });
|
||||
});
|
||||
|
||||
it('only includes provided keys (partial patch)', () => {
|
||||
const r = coerceSettingsPatch({ webuiHost: '0.0.0.0' });
|
||||
expect(r).toEqual({ ok: true, patch: { webuiHost: '0.0.0.0' } });
|
||||
});
|
||||
|
||||
it('rejects a non-object body', () => {
|
||||
expect(coerceSettingsPatch(null).ok).toBe(false);
|
||||
expect(coerceSettingsPatch('x').ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an out-of-range or non-integer port', () => {
|
||||
expect(coerceSettingsPatch({ webuiPort: 0 }).ok).toBe(false);
|
||||
expect(coerceSettingsPatch({ webuiPort: 70000 }).ok).toBe(false);
|
||||
expect(coerceSettingsPatch({ webuiPort: 12.5 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an empty/blank host', () => {
|
||||
expect(coerceSettingsPatch({ webuiHost: ' ' }).ok).toBe(false);
|
||||
expect(coerceSettingsPatch({ webuiHost: 123 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a non-boolean tlsEnabled and non-string trustProxy', () => {
|
||||
expect(coerceSettingsPatch({ tlsEnabled: 'yes' }).ok).toBe(false);
|
||||
expect(coerceSettingsPatch({ trustProxy: 1 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts an empty-string trustProxy (trust nobody)', () => {
|
||||
expect(coerceSettingsPatch({ trustProxy: '' })).toEqual({ ok: true, patch: { trustProxy: '' } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { validateTlsPair, resolveTlsContext } from '../src/webui/tls';
|
||||
|
||||
// A throwaway self-signed pair (openssl, CN=snowluma-test). createSecureContext
|
||||
// only parses — expiry is irrelevant — so this stays valid for the test forever.
|
||||
const CERT = `-----BEGIN CERTIFICATE-----
|
||||
MIIDETCCAfmgAwIBAgIUNiu66PmcO6Do6cUaB92UKD8j3qYwDQYJKoZIhvcNAQEL
|
||||
BQAwGDEWMBQGA1UEAwwNc25vd2x1bWEtdGVzdDAeFw0yNjA2MTgwNjIwMTZaFw0z
|
||||
NjA2MTUwNjIwMTZaMBgxFjAUBgNVBAMMDXNub3dsdW1hLXRlc3QwggEiMA0GCSqG
|
||||
SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCm0sVJhqlG75gOFJVsUJOfR+oqvb9eSq4t
|
||||
k5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll2ANSjusmWN4hzpaOBBdX
|
||||
bP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23LsMsij8T4nLk4eHiOkeRfi
|
||||
uLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/KmcNtq7JrX7F7qYnYsJKLZZ
|
||||
aZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5dcZuI+KwixVKZgapG5n5R
|
||||
ghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WVhvrD6pphAgMBAAGjUzBR
|
||||
MB0GA1UdDgQWBBRW/HP12nj9fYMYNxa3jyqmnUigvTAfBgNVHSMEGDAWgBRW/HP1
|
||||
2nj9fYMYNxa3jyqmnUigvTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA
|
||||
A4IBAQCijzVQ/jHNoqu6stvkkigUv2lTKrd1EHcTZLfzwQkmNv/hfY2EMobO/Qxs
|
||||
FhmITreKFALJ/dUwTt0UTO00LV9whEgr2of4x8wwjZ9wRstY6uyRYBP85QC8+8mZ
|
||||
zWlcf611HugrmpOWjWfEVmmxdI1m26YWTn52nZFPnJqDWg2+RlLJWl55lVotbXEZ
|
||||
Fvas4Vcf2KOk0QwBQKvpt0BISeTIQhbT4GnducxSxyoXGeBQOjQNYb/vTpMn4F9U
|
||||
IAxSsfs9WVoHKXOabK8GV89BCxWoRk4UaSahTq/2Vnbgt86tWibt3lA4y49+XhA2
|
||||
6z7n9HgJAUKqhsDrYvZmM7/VZ2d5
|
||||
-----END CERTIFICATE-----
|
||||
`;
|
||||
const KEY = `-----BEGIN PRIVATE KEY-----
|
||||
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCm0sVJhqlG75gO
|
||||
FJVsUJOfR+oqvb9eSq4tk5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll
|
||||
2ANSjusmWN4hzpaOBBdXbP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23Ls
|
||||
Msij8T4nLk4eHiOkeRfiuLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/Kmc
|
||||
Ntq7JrX7F7qYnYsJKLZZaZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5d
|
||||
cZuI+KwixVKZgapG5n5RghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WV
|
||||
hvrD6pphAgMBAAECggEAJ13+u4qhIMHCnrQBzPU42PImEt8DLXOvJcc5PFM6ZJ6S
|
||||
rRHkAk60HAWV+OqOu2jS3o6NGYsJWJpWaPewVQev+zUmelDfm3TgsztfvBIh8K50
|
||||
dGFsef81tB1WnWo++K1kzUBZ4ljOV9f5hz62tWVlFubo/Vd8bsA6wEB6Jskd2fls
|
||||
ZOO0hJCb/M6IIwe3cWw4sb/YFTTLMUnVHM0aJfnQ/QH+uraRwecJMv118d0YBYVG
|
||||
DsNmYqrv9TYNBh4P9mKv6/0x8zaKsJZVLAMwHztILHItOXBfxCbSDivGWVUGiDq2
|
||||
NxEuBOgxzOelxEYzUzf7B6sjHoEeIL5wIKQbwUbmfwKBgQDZRLhucrMZPw7ous1t
|
||||
igkO32p1ku7FRxm0/JAskc66oX61KLIYbZFM9N7nTXAEs8ZGhzUkdSgxNcdHWIdK
|
||||
RI+6pd2FhhcKU1feEohlOHvZTXXEMhm61phWnN391GZXfwMKSpscqsu9kIix2jtw
|
||||
4YrzKLx82EDDHcLfBh9AtArKywKBgQDEj+7UJp5wuqz9hj+gogXeq4Buv9be1u4u
|
||||
HCJZMZzLCwVjvoqYw0n1afXP3057v8hQPGsBaxzQpOg7i1lYGGfuZ9T6T8fFrtqw
|
||||
m/LJLHhMQxeyCEQi1/EoNewvVGSwBJkLOuOs8T2WmMXmOgdHbEYdzkKtT71jst6y
|
||||
TeJ15hVuAwKBgBMK4t9LTkc4L6ZWOQsQvhp/mmUTq7m+sZIbUMeXP/c7kE9wcauS
|
||||
btm/3ImJT/gZiZdE4nN/kTY+8GhgafsoZzCEuRWq2vocs+bS2QGGIdS55Uh826R0
|
||||
ioWM2igVJaMljq6oO1AX6COFN3XfGraaDgOh3mNS0NpJEXtangKdxRRhAoGAP9SF
|
||||
t/r6hJz6RDHuQ5mZ0l9bC5vciOy+19ZnCRPlWMIxc9ySYV05jSplmqVndSQoRnX4
|
||||
QbOo3dBPYda0orj6Nx8cuFRkCTvo5GUgCFgakJlQ/o1UowQA2g/4rL35HHfBwzXS
|
||||
bXzBhUADM+owJu9wLYmneWRlmhSh4MEOAz8+QkUCgYAw0fA1Im2/ftrA2Z2IENTi
|
||||
U4cLXqeUeGJfXjIBklUmXhc4qrd/9V9eEHjackI/JI7Qhp/QfPWMXLudlSrppnNJ
|
||||
+s3dVevEKosiZbf4qtTtlmR/IifuTKjK5O94KlBT+evxNsL4Hv0b0oTsVNnEfOOl
|
||||
OUsvSYNSnfvl87tyLIxYLA==
|
||||
-----END PRIVATE KEY-----
|
||||
`;
|
||||
|
||||
describe('validateTlsPair', () => {
|
||||
it('accepts a matching cert/key pair', () => {
|
||||
expect(validateTlsPair(CERT, KEY)).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it('rejects garbage PEM with a reason', () => {
|
||||
const r = validateTlsPair('not a cert', 'not a key');
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.reason).toBeTruthy();
|
||||
});
|
||||
|
||||
it('rejects an empty cert', () => {
|
||||
expect(validateTlsPair('', KEY).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveTlsContext', () => {
|
||||
let dir: string;
|
||||
beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-tls-')); });
|
||||
afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); });
|
||||
|
||||
it('loads cert.pem + key.pem when both present and valid', () => {
|
||||
fs.writeFileSync(path.join(dir, 'cert.pem'), CERT);
|
||||
fs.writeFileSync(path.join(dir, 'key.pem'), KEY);
|
||||
const r = resolveTlsContext(dir);
|
||||
expect(r.ok).toBe(true);
|
||||
expect(r.cert?.toString()).toContain('BEGIN CERTIFICATE');
|
||||
expect(r.key?.toString()).toContain('PRIVATE KEY');
|
||||
});
|
||||
|
||||
it('fails (with reason) when files are missing', () => {
|
||||
const r = resolveTlsContext(dir);
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.reason).toMatch(/missing/i);
|
||||
});
|
||||
|
||||
it('fails when the on-disk PEM is invalid', () => {
|
||||
fs.writeFileSync(path.join(dir, 'cert.pem'), 'garbage');
|
||||
fs.writeFileSync(path.join(dir, 'key.pem'), 'garbage');
|
||||
const r = resolveTlsContext(dir);
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.reason).toBeTruthy();
|
||||
});
|
||||
});
|
||||
Binary file not shown.
@@ -1,10 +1,10 @@
|
||||
import { defineConfig, PluginOption, UserConfig } from 'vite';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { builtinModules } from 'module';
|
||||
import cp from 'vite-plugin-cp';
|
||||
import protobufVitePlugin from '@snowluma/proton/vite';
|
||||
import fs from 'fs';
|
||||
import { builtinModules } from 'module';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { defineConfig, PluginOption, UserConfig } from 'vite';
|
||||
import cp from 'vite-plugin-cp';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
@@ -20,12 +20,16 @@ const rootPkg = JSON.parse(
|
||||
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
|
||||
const toPosix = (p: string) => p.replace(/\\/g, '/');
|
||||
|
||||
// `@snowluma/websocket` and `@snowluma/sqlite` are bundled — they're
|
||||
// in-tree TS workspace wrappers that route their native `.node`
|
||||
// addons through `dist/native/`. Only Node builtins stay external;
|
||||
// the actual `better-sqlite3` JS wrapper is pulled in via the
|
||||
// `@snowluma/sqlite` re-export and bundled into `index.mjs`.
|
||||
const external: string[] = [];
|
||||
// `@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 nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat();
|
||||
|
||||
@@ -46,20 +50,8 @@ const runtimeDistFiles = ['package.json',
|
||||
// Native binaries shipped for the selected target:
|
||||
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
|
||||
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
|
||||
// * `better-sqlite3-v<abi>-*.node` – SQLite native binding consumed
|
||||
// by @snowluma/sqlite. Two ABIs
|
||||
// vendored side-by-side
|
||||
// (v127 = Node 22 LTS, v137 =
|
||||
// Node 24) so the runtime can
|
||||
// pick whichever matches the
|
||||
// host's `process.versions.modules`.
|
||||
// Vendored via
|
||||
// `tools/fetch-sqlite-prebuilts.mjs`
|
||||
// from WiseLibs's prebuild releases.
|
||||
const SQLITE_ABIS = ['v127', 'v137'];
|
||||
const nativeFiles = [
|
||||
`websocket-${targetTriple}.node`,
|
||||
...SQLITE_ABIS.map((abi) => `better-sqlite3-${abi}-${targetTriple}.node`),
|
||||
...(targetPlatform === 'win32'
|
||||
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
|
||||
: []),
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
dist/
|
||||
@@ -0,0 +1,113 @@
|
||||
# @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`.
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "1.9.13",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// 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);
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
// 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
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
// @snowluma/mcp — an MCP server for the SnowLuma OneBot action catalog.
|
||||
//
|
||||
// Two modes in one binary:
|
||||
// • docs (default, no endpoint): read-only catalog tools (list/get/search/
|
||||
// categories) + a catalog resource. Zero contact with any live instance.
|
||||
// • read / write (when SNOWLUMA_MCP_ENDPOINT is set): the catalog tools PLUS
|
||||
// execution — query_action (read-only actions) and, in write mode,
|
||||
// invoke_action (any known action) — proxied to a running OneBot instance
|
||||
// over HTTP.
|
||||
//
|
||||
// Env:
|
||||
// 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 (Bearer) for the endpoint.
|
||||
// SNOWLUMA_MCP_TIMEOUT_MS per-request timeout (default SDK 30s).
|
||||
// SNOWLUMA_MCP_MODE docs | read | write. Default: read when an
|
||||
// endpoint is set, else docs.
|
||||
//
|
||||
// NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr.
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
||||
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
||||
import {
|
||||
CallToolRequestSchema,
|
||||
ListResourcesRequestSchema,
|
||||
ListToolsRequestSchema,
|
||||
ReadResourceRequestSchema,
|
||||
} from '@modelcontextprotocol/sdk/types.js';
|
||||
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
|
||||
import { makeHttpClient, type ActionClient } from './client.js';
|
||||
import { callTool, computeTools, type Mode } from './tools.js';
|
||||
|
||||
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };
|
||||
const VERSION = pkg.version;
|
||||
|
||||
const RESOURCE_URI = 'snowluma://onebot/actions';
|
||||
|
||||
// ── resolve mode + client from the environment ────────────────────────────
|
||||
function resolveRuntime(): { mode: Mode; client?: ActionClient } {
|
||||
const endpoint = process.env.SNOWLUMA_MCP_ENDPOINT?.trim();
|
||||
const token = process.env.SNOWLUMA_MCP_TOKEN?.trim() || undefined;
|
||||
const timeoutRaw = Number(process.env.SNOWLUMA_MCP_TIMEOUT_MS);
|
||||
const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? timeoutRaw : undefined;
|
||||
const requested = process.env.SNOWLUMA_MCP_MODE?.trim().toLowerCase();
|
||||
const validRequest = requested === 'docs' || requested === 'read' || requested === 'write' ? requested : undefined;
|
||||
|
||||
if (!endpoint) {
|
||||
if (validRequest && validRequest !== 'docs') {
|
||||
console.error(`[snowluma-mcp] SNOWLUMA_MCP_MODE=${validRequest} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`);
|
||||
}
|
||||
return { mode: 'docs' };
|
||||
}
|
||||
|
||||
const mode: Mode = validRequest ?? 'read';
|
||||
if (mode === 'docs') {
|
||||
// Endpoint set but operator explicitly wants docs-only — honor it.
|
||||
return { mode: 'docs' };
|
||||
}
|
||||
const client = makeHttpClient({ endpoint, accessToken: token, timeoutMs });
|
||||
return { mode, client };
|
||||
}
|
||||
|
||||
const { mode, client } = resolveRuntime();
|
||||
|
||||
const server = new Server(
|
||||
{ name: 'snowluma-mcp', version: VERSION },
|
||||
{ capabilities: { tools: {}, resources: {} } },
|
||||
);
|
||||
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: computeTools(mode) }));
|
||||
|
||||
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
||||
const args = (req.params.arguments ?? {}) as Record<string, unknown>;
|
||||
return callTool(req.params.name, args, { mode, client });
|
||||
});
|
||||
|
||||
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
|
||||
resources: [
|
||||
{
|
||||
uri: RESOURCE_URI,
|
||||
name: 'SnowLuma OneBot action catalog',
|
||||
mimeType: 'application/json',
|
||||
description: `SnowLuma v${VERSION} 的 ${ACTIONS.length} 个 OneBot action 完整目录(文档 + JSON Schema)。`,
|
||||
},
|
||||
],
|
||||
}));
|
||||
|
||||
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
|
||||
if (req.params.uri !== RESOURCE_URI) throw new Error(`unknown resource: ${req.params.uri}`);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: RESOURCE_URI,
|
||||
mimeType: 'application/json',
|
||||
text: JSON.stringify({ version: VERSION, categories: CATEGORIES, actions: ACTIONS }, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
const where = client ? ` → ${process.env.SNOWLUMA_MCP_ENDPOINT?.trim()}` : '';
|
||||
console.error(`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories, mode=${mode}${where}`);
|
||||
@@ -0,0 +1,182 @@
|
||||
// Tool surface for the MCP — kept free of any stdio / transport / env concerns
|
||||
// so it is directly unit-testable. `server.ts` reads the environment, builds a
|
||||
// client, and wires `computeTools` / `callTool` into the MCP request handlers.
|
||||
//
|
||||
// Two execution tools partition the action space by side-effect:
|
||||
// • query_action — read-only actions only (readOnlyHint)
|
||||
// • invoke_action — any known action (destructiveHint, write mode)
|
||||
// Visibility is gated by `mode`, and `callTool` RE-checks every permission
|
||||
// (defense in depth: a client may call a tool that was never listed).
|
||||
|
||||
import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js';
|
||||
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
|
||||
import type { CatalogAction } from './types.js';
|
||||
import type { ActionClient } from './client.js';
|
||||
|
||||
export type Mode = 'docs' | 'read' | 'write';
|
||||
|
||||
// name + every alias → action, so lookups accept aliases too.
|
||||
const byName = new Map<string, CatalogAction>();
|
||||
for (const a of ACTIONS) {
|
||||
for (const n of [a.name, ...a.aliases]) byName.set(n, a);
|
||||
}
|
||||
|
||||
/** Lightweight index entry (keeps list/search payloads small). */
|
||||
function lite(a: CatalogAction) {
|
||||
return { name: a.name, category: a.category, summary: a.summary, aliases: a.aliases, readOnly: a.readOnly };
|
||||
}
|
||||
|
||||
const DOCS_TOOLS: Tool[] = [
|
||||
{
|
||||
name: 'list_actions',
|
||||
description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读)。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
annotations: { readOnlyHint: true, openWorldHint: false },
|
||||
},
|
||||
{
|
||||
name: 'get_action',
|
||||
description: '获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回、是否只读,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { name: { type: 'string', description: 'action 名(接受别名)' } },
|
||||
required: ['name'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
annotations: { readOnlyHint: true, openWorldHint: false },
|
||||
},
|
||||
{
|
||||
name: 'search_actions',
|
||||
description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { query: { type: 'string', description: '关键字' } },
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
annotations: { readOnlyHint: true, openWorldHint: false },
|
||||
},
|
||||
{
|
||||
name: 'list_categories',
|
||||
description: '列出所有分类及其 action 数量。',
|
||||
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
||||
annotations: { readOnlyHint: true, openWorldHint: false },
|
||||
},
|
||||
];
|
||||
|
||||
const EXEC_INPUT_SCHEMA = {
|
||||
type: 'object' as const,
|
||||
properties: {
|
||||
action: { type: 'string', description: 'action 名(接受别名)。先用 get_action 查它的参数 inputSchema。' },
|
||||
params: { type: 'object', description: '该 action 的参数对象', additionalProperties: true },
|
||||
},
|
||||
required: ['action'],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
function queryTool(): Tool {
|
||||
return {
|
||||
name: 'query_action',
|
||||
description: '调用一个【只读】OneBot action(如 get_*/can_*)并返回完整响应。仅接受只读 action;写操作请用 invoke_action。',
|
||||
inputSchema: EXEC_INPUT_SCHEMA,
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
};
|
||||
}
|
||||
|
||||
function invokeTool(): Tool {
|
||||
return {
|
||||
name: 'invoke_action',
|
||||
description: '调用一个 OneBot action(可产生副作用:发消息、改群、改资料等)并返回完整响应。仅在写模式可用。',
|
||||
inputSchema: EXEC_INPUT_SCHEMA,
|
||||
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
|
||||
};
|
||||
}
|
||||
|
||||
/** Tools visible for a given mode: docs always; +query in read/write; +invoke in write. */
|
||||
export function computeTools(mode: Mode): Tool[] {
|
||||
const tools: Tool[] = [...DOCS_TOOLS];
|
||||
if (mode === 'read' || mode === 'write') tools.push(queryTool());
|
||||
if (mode === 'write') tools.push(invokeTool());
|
||||
return tools;
|
||||
}
|
||||
|
||||
export type ToolResult = CallToolResult;
|
||||
|
||||
function asText(data: unknown): ToolResult {
|
||||
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
|
||||
}
|
||||
function asError(message: string): ToolResult {
|
||||
return { content: [{ type: 'text', text: message }], isError: true };
|
||||
}
|
||||
|
||||
export interface CallCtx {
|
||||
mode: Mode;
|
||||
client?: ActionClient;
|
||||
}
|
||||
|
||||
export async function callTool(name: string, args: Record<string, unknown>, ctx: CallCtx): Promise<ToolResult> {
|
||||
switch (name) {
|
||||
case 'list_actions': {
|
||||
const category = typeof args.category === 'string' ? args.category : undefined;
|
||||
const list = ACTIONS.filter((a) => !category || a.category === category).map(lite);
|
||||
return asText({ count: list.length, actions: list });
|
||||
}
|
||||
case 'get_action': {
|
||||
const q = typeof args.name === 'string' ? args.name : '';
|
||||
const action = byName.get(q);
|
||||
if (!action) return asError(`未找到 action: ${JSON.stringify(q)}。用 list_actions / search_actions 查可用项。`);
|
||||
return asText(action);
|
||||
}
|
||||
case 'search_actions': {
|
||||
const q = (typeof args.query === 'string' ? args.query : '').toLowerCase();
|
||||
const list = ACTIONS.filter(
|
||||
(a) =>
|
||||
a.name.toLowerCase().includes(q) ||
|
||||
(a.summary ?? '').toLowerCase().includes(q) ||
|
||||
a.aliases.some((al) => al.toLowerCase().includes(q)),
|
||||
).map(lite);
|
||||
return asText({ count: list.length, actions: list });
|
||||
}
|
||||
case 'list_categories':
|
||||
return asText(CATEGORIES);
|
||||
case 'query_action':
|
||||
return execute(args, ctx, 'read');
|
||||
case 'invoke_action':
|
||||
return execute(args, ctx, 'write');
|
||||
default:
|
||||
return asError(`未知工具: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Shared execution path for query_action (read) / invoke_action (write).
|
||||
* Re-checks mode + readOnly routing regardless of which tools were listed. */
|
||||
async function execute(args: Record<string, unknown>, ctx: CallCtx, kind: 'read' | 'write'): Promise<ToolResult> {
|
||||
if (kind === 'write' && ctx.mode !== 'write') {
|
||||
return asError('写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。');
|
||||
}
|
||||
if (kind === 'read' && ctx.mode !== 'read' && ctx.mode !== 'write') {
|
||||
return asError('执行未启用:需配置 SNOWLUMA_MCP_ENDPOINT。');
|
||||
}
|
||||
if (!ctx.client) return asError('未配置 OneBot 端点(SNOWLUMA_MCP_ENDPOINT),无法执行。');
|
||||
|
||||
const action = typeof args.action === 'string' ? args.action : '';
|
||||
const cat = byName.get(action);
|
||||
if (!cat) return asError(`未知 action: ${JSON.stringify(action)}。用 list_actions / search_actions 查可用项。`);
|
||||
if (kind === 'read' && !cat.readOnly) {
|
||||
return asError(`${action} 是写操作,不能用 query_action;请用 invoke_action(需 SNOWLUMA_MCP_MODE=write)。`);
|
||||
}
|
||||
|
||||
const params =
|
||||
args.params && typeof args.params === 'object' && !Array.isArray(args.params)
|
||||
? (args.params as Record<string, unknown>)
|
||||
: {};
|
||||
try {
|
||||
const envelope = await ctx.client.call(action, params);
|
||||
return asText(envelope);
|
||||
} catch (err) {
|
||||
return asError(`调用失败: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// The MCP's own view of the OneBot action catalog. Mirrors @snowluma/onebot's
|
||||
// ActionDoc, but is defined HERE so the published package does not couple to
|
||||
// onebot's internals — the generated `catalog.ts` (a build-time snapshot) is the
|
||||
// only contract (ADR-0005: the wire/data shape is the seam, not a shared type).
|
||||
|
||||
export interface CatalogParam {
|
||||
name: string;
|
||||
/** Display type ('uint' | 'int' | 'messageId' | 'string' | 'bool' | 'message' | 'enum' | 'X[]' | 'raw'). */
|
||||
type: string;
|
||||
required: boolean;
|
||||
default?: unknown;
|
||||
desc?: string;
|
||||
values?: ReadonlyArray<string | number>;
|
||||
/** JSON Schema fragment for this single field. */
|
||||
schema?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CatalogAction {
|
||||
name: string;
|
||||
aliases: string[];
|
||||
category?: string;
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
/** True only for pure data-fetch actions (no side effects). Drives the
|
||||
* read/write tool routing: read-only → query_action, else → invoke_action.
|
||||
* Classified at the source spec by what the action's `run` actually does. */
|
||||
readOnly: boolean;
|
||||
params: CatalogParam[];
|
||||
/** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */
|
||||
invariants: string[];
|
||||
/** Composed JSON Schema for the whole params object. */
|
||||
inputSchema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CatalogCategory {
|
||||
category: string;
|
||||
count: number;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { makeHttpClient } from '../src/client';
|
||||
|
||||
// Verifies the HTTP bridge: a OneBot action becomes a POST of `{ action, params }`
|
||||
// to the endpoint (with Bearer auth), and the JSON envelope comes back verbatim.
|
||||
// A fake fetch stands in for the network.
|
||||
describe('makeHttpClient — OneBot HTTP wiring', () => {
|
||||
it('POSTs {action, params} to the endpoint and returns the parsed envelope', async () => {
|
||||
const calls: Array<{ url: string; body: any; auth?: string }> = [];
|
||||
const fakeFetch = (async (url: unknown, init: any) => {
|
||||
calls.push({
|
||||
url: String(url),
|
||||
body: JSON.parse(init.body as string),
|
||||
auth: (init.headers as Record<string, string>)?.Authorization,
|
||||
});
|
||||
return new Response(JSON.stringify({ status: 'ok', retcode: 0, data: { ok: true } }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', accessToken: 'tok', fetch: fakeFetch });
|
||||
const env = await client.call('get_status', { x: 1 });
|
||||
|
||||
expect(env.status).toBe('ok');
|
||||
expect(env.retcode).toBe(0);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].url).toBe('http://127.0.0.1:9999/');
|
||||
expect(calls[0].body.action).toBe('get_status');
|
||||
expect(calls[0].body.params).toEqual({ x: 1 });
|
||||
expect(calls[0].auth).toBe('Bearer tok');
|
||||
});
|
||||
|
||||
it('propagates a transport failure as a rejection (so the tool layer can map it)', async () => {
|
||||
const fakeFetch = (async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof fetch;
|
||||
const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch });
|
||||
await expect(client.call('get_status', {})).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { computeTools, callTool } from '../src/tools';
|
||||
import type { ActionClient, OneBotEnvelope } from '../src/client';
|
||||
|
||||
type Res = Awaited<ReturnType<typeof callTool>>;
|
||||
function text(res: Res): string {
|
||||
const block = res.content?.[0];
|
||||
return block && block.type === 'text' ? block.text : '';
|
||||
}
|
||||
function parsed(res: Res): any {
|
||||
return JSON.parse(text(res));
|
||||
}
|
||||
|
||||
/** A fake ActionClient — no transport. Records the last call and returns a
|
||||
* canned envelope (overridable per test). */
|
||||
function fakeClient(impl?: (action: string, params: Record<string, unknown>) => OneBotEnvelope): ActionClient {
|
||||
return {
|
||||
call: async (action, params) => impl?.(action, params) ?? { status: 'ok', retcode: 0, data: { action, params } },
|
||||
};
|
||||
}
|
||||
|
||||
describe('computeTools — mode gating', () => {
|
||||
it('docs mode exposes only the 4 catalog tools', () => {
|
||||
expect(computeTools('docs').map((t) => t.name)).toEqual([
|
||||
'list_actions', 'get_action', 'search_actions', 'list_categories',
|
||||
]);
|
||||
});
|
||||
it('read mode adds query_action only (no invoke_action)', () => {
|
||||
const names = computeTools('read').map((t) => t.name);
|
||||
expect(names).toContain('query_action');
|
||||
expect(names).not.toContain('invoke_action');
|
||||
});
|
||||
it('write mode adds both query_action and invoke_action', () => {
|
||||
const names = computeTools('write').map((t) => t.name);
|
||||
expect(names).toContain('query_action');
|
||||
expect(names).toContain('invoke_action');
|
||||
});
|
||||
it('annotations are honest: query=readOnly, invoke=destructive', () => {
|
||||
const q = computeTools('write').find((t) => t.name === 'query_action');
|
||||
const inv = computeTools('write').find((t) => t.name === 'invoke_action');
|
||||
expect(q?.annotations?.readOnlyHint).toBe(true);
|
||||
expect(inv?.annotations?.readOnlyHint).toBe(false);
|
||||
expect(inv?.annotations?.destructiveHint).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('callTool — docs tools (no client needed)', () => {
|
||||
it('list_actions returns entries that carry readOnly', async () => {
|
||||
const data = parsed(await callTool('list_actions', {}, { mode: 'docs' }));
|
||||
expect(data.count).toBeGreaterThan(100);
|
||||
expect(typeof data.actions[0].readOnly).toBe('boolean');
|
||||
});
|
||||
it('get_action resolves a known read-only action', async () => {
|
||||
const a = parsed(await callTool('get_action', { name: 'get_status' }, { mode: 'docs' }));
|
||||
expect(a.name).toBe('get_status');
|
||||
expect(a.readOnly).toBe(true);
|
||||
});
|
||||
it('get_action on a write action reports readOnly=false', async () => {
|
||||
expect(parsed(await callTool('get_action', { name: 'send_group_msg' }, { mode: 'docs' })).readOnly).toBe(false);
|
||||
});
|
||||
it('get_action accepts an alias', async () => {
|
||||
// nc_get_rkey is an alias of get_rkey (read-only).
|
||||
const a = parsed(await callTool('get_action', { name: 'nc_get_rkey' }, { mode: 'docs' }));
|
||||
expect(a.name).toBe('get_rkey');
|
||||
});
|
||||
});
|
||||
|
||||
describe('callTool — query_action (read)', () => {
|
||||
it('executes a read-only action and passes the envelope through', async () => {
|
||||
const res = await callTool('query_action', { action: 'get_status', params: {} }, { mode: 'read', client: fakeClient() });
|
||||
expect(res.isError).toBeFalsy();
|
||||
expect(parsed(res).retcode).toBe(0);
|
||||
});
|
||||
it('refuses a write action and points to invoke_action', async () => {
|
||||
const res = await callTool('query_action', { action: 'send_group_msg', params: {} }, { mode: 'read', client: fakeClient() });
|
||||
expect(res.isError).toBe(true);
|
||||
expect(text(res)).toContain('invoke_action');
|
||||
});
|
||||
it('refuses an unknown action', async () => {
|
||||
const res = await callTool('query_action', { action: 'no_such_action' }, { mode: 'read', client: fakeClient() });
|
||||
expect(res.isError).toBe(true);
|
||||
expect(text(res)).toContain('未知 action');
|
||||
});
|
||||
it('is blocked in docs mode even when called directly (defense in depth)', async () => {
|
||||
const res = await callTool('query_action', { action: 'get_status' }, { mode: 'docs' });
|
||||
expect(res.isError).toBe(true);
|
||||
});
|
||||
it('errors clearly when no client is wired', async () => {
|
||||
const res = await callTool('query_action', { action: 'get_status' }, { mode: 'read' });
|
||||
expect(res.isError).toBe(true);
|
||||
expect(text(res)).toContain('未配置');
|
||||
});
|
||||
});
|
||||
|
||||
describe('callTool — invoke_action (write)', () => {
|
||||
it('executes a write action in write mode and forwards action+params', async () => {
|
||||
let seen: { action: string; params: Record<string, unknown> } | null = null;
|
||||
const client: ActionClient = {
|
||||
call: async (action, params) => {
|
||||
seen = { action, params };
|
||||
return { status: 'ok', retcode: 0, data: { message_id: 42 } };
|
||||
},
|
||||
};
|
||||
const res = await callTool('invoke_action', { action: 'send_group_msg', params: { group_id: 1, message: 'hi' } }, { mode: 'write', client });
|
||||
expect(res.isError).toBeFalsy();
|
||||
expect(seen!.action).toBe('send_group_msg');
|
||||
expect(seen!.params).toEqual({ group_id: 1, message: 'hi' });
|
||||
expect(parsed(res).data.message_id).toBe(42);
|
||||
});
|
||||
it('is blocked in read mode (write gate cannot be bypassed)', async () => {
|
||||
const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'read', client: fakeClient() });
|
||||
expect(res.isError).toBe(true);
|
||||
expect(text(res)).toContain('写操作未启用');
|
||||
});
|
||||
it('passes a retcode≠0 envelope through as data, NOT isError', async () => {
|
||||
const client = fakeClient(() => ({ status: 'failed', retcode: 1404, message: 'not found', wording: '未找到' }));
|
||||
const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client });
|
||||
expect(res.isError).toBeFalsy();
|
||||
expect(parsed(res).retcode).toBe(1404);
|
||||
expect(parsed(res).wording).toBe('未找到');
|
||||
});
|
||||
it('maps a transport-level throw to isError', async () => {
|
||||
const client: ActionClient = { call: async () => { throw new Error('connection refused'); } };
|
||||
const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client });
|
||||
expect(res.isError).toBe(true);
|
||||
expect(text(res)).toContain('调用失败');
|
||||
expect(text(res)).toContain('connection refused');
|
||||
});
|
||||
it('accepts a read-only action too (invoke is a superset)', async () => {
|
||||
const res = await callTool('invoke_action', { action: 'get_status', params: {} }, { mode: 'write', client: fakeClient() });
|
||||
expect(res.isError).toBeFalsy();
|
||||
});
|
||||
it('refuses an unknown action (typo safety)', async () => {
|
||||
const res = await callTool('invoke_action', { action: 'frobnicate' }, { mode: 'write', client: fakeClient() });
|
||||
expect(res.isError).toBe(true);
|
||||
expect(text(res)).toContain('未知 action');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"declaration": true,
|
||||
"noEmit": false,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Vitest config — used only to RUN the catalog generator (scripts/gen-catalog.test.ts)
|
||||
// in an environment where `@snowluma/onebot/action-docs` resolves. The proton
|
||||
// plugin provides the same bare-specifier resolver @snowluma/onebot's own tests
|
||||
// use, so importing the action specs works identically here.
|
||||
import protobufVitePlugin from '@snowluma/proton/vite';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [protobufVitePlugin()],
|
||||
test: {
|
||||
include: ['scripts/**/*.test.ts', 'tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
env: {
|
||||
SNOWLUMA_LOG_FILE: '0',
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
@@ -11,6 +11,14 @@
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./action-kit": {
|
||||
"types": "./src/action-kit.ts",
|
||||
"default": "./src/action-kit.ts"
|
||||
},
|
||||
"./action-docs": {
|
||||
"types": "./src/action-docs.ts",
|
||||
"default": "./src/action-docs.ts"
|
||||
},
|
||||
"./manager": {
|
||||
"types": "./src/manager.ts",
|
||||
"default": "./src/manager.ts"
|
||||
@@ -91,7 +99,6 @@
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// action-docs — self-generated OneBot API docs (D4).
|
||||
//
|
||||
// Walks `ActionSpec.describe()` over every declarative action and renders a
|
||||
// structured doc list + a Markdown view. The metadata is carried on the same
|
||||
// values that drive runtime validation, so docs cannot drift from behavior.
|
||||
//
|
||||
// Coverage note: the ~15 genuinely irregular actions in `actions/extended.ts`
|
||||
// that remain on the legacy `h.registerAction(...)` path are NOT ActionSpecs
|
||||
// and so do not appear here — that is the documented irregular tail.
|
||||
//
|
||||
// The serving SURFACE (WebUI panel / OpenAPI export / static markdown) is a
|
||||
// deferred product decision; this module produces format-agnostic data plus a
|
||||
// Markdown default. Point any renderer at `collectActionDocs()`.
|
||||
|
||||
import type { ActionDoc, ActionSpec, Field } from './action-kit';
|
||||
import { actions as infoActions } from './actions/info';
|
||||
import { actions as messageActions } from './actions/message';
|
||||
import { actions as friendActions } from './actions/friend';
|
||||
import { actions as groupInfoActions } from './actions/group-info';
|
||||
import { actions as groupAdminActions } from './actions/group-admin';
|
||||
import { actions as groupFileActions } from './actions/group-file';
|
||||
import { actions as requestActions } from './actions/request';
|
||||
import { actions as extendedActions } from './actions/extended';
|
||||
import { actions as groupAlbumActions } from './actions/group-album';
|
||||
|
||||
type AnySpec = ActionSpec<Record<string, Field<unknown>>>;
|
||||
|
||||
// Source file = domain category. Each doc is tagged so the MCP / UI can group.
|
||||
const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [
|
||||
{ category: '信息', specs: infoActions },
|
||||
{ category: '消息', specs: messageActions },
|
||||
{ category: '好友', specs: friendActions },
|
||||
{ category: '群信息', specs: groupInfoActions },
|
||||
{ category: '群管理', specs: groupAdminActions },
|
||||
{ category: '群文件', specs: groupFileActions },
|
||||
{ category: '请求', specs: requestActions },
|
||||
{ category: '扩展', specs: extendedActions },
|
||||
{ category: '群相册', specs: groupAlbumActions },
|
||||
];
|
||||
|
||||
/** Every declarative action's doc (with category), sorted by name. */
|
||||
export function collectActionDocs(): ActionDoc[] {
|
||||
return GROUPS
|
||||
.flatMap(({ category, specs }) => specs.map((s) => ({ ...s.describe(), category })))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Distinct categories with action counts. */
|
||||
export function collectCategories(): Array<{ category: string; count: number }> {
|
||||
return GROUPS.map(({ category, specs }) => ({ category, count: specs.length }));
|
||||
}
|
||||
|
||||
function paramRow(p: ActionDoc['params'][number]): string {
|
||||
const type = p.values ? p.values.map((v) => JSON.stringify(v)).join(' \\| ') : p.type;
|
||||
const required = p.required ? '✓' : '–';
|
||||
const def = !p.required && p.default !== undefined ? `\`${JSON.stringify(p.default)}\`` : '';
|
||||
return `| \`${p.name}\` | ${type} | ${required} | ${def} | ${p.desc ?? ''} |`;
|
||||
}
|
||||
|
||||
function renderAction(doc: ActionDoc): string {
|
||||
const lines: string[] = [];
|
||||
const alias = doc.aliases.length ? ` _(别名: ${doc.aliases.map((a) => `\`${a}\``).join(', ')})_` : '';
|
||||
const cat = doc.category ? ` · ${doc.category}` : '';
|
||||
lines.push(`### \`${doc.name}\`${cat}${alias}`);
|
||||
if (doc.summary) lines.push('', doc.summary);
|
||||
if (doc.params.length) {
|
||||
lines.push('', '| 参数 | 类型 | 必填 | 默认 | 说明 |', '| --- | --- | --- | --- | --- |');
|
||||
for (const p of doc.params) lines.push(paramRow(p));
|
||||
} else {
|
||||
lines.push('', '_无参数_');
|
||||
}
|
||||
if (doc.invariants.length) lines.push('', `**约束:** ${doc.invariants.map((i) => `\`${i}\``).join(';')}`);
|
||||
if (doc.returns) lines.push('', `**返回:** \`${doc.returns}\``);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/** Render the full Markdown doc. */
|
||||
export function renderActionDocsMarkdown(docs: readonly ActionDoc[] = collectActionDocs()): string {
|
||||
const header = [
|
||||
'# OneBot Actions',
|
||||
'',
|
||||
'> 由 `packages/onebot/src/action-docs.ts` 从各 `ActionSpec.describe()` 自动生成,请勿手改。',
|
||||
'> 仅覆盖声明式 action;`extended.ts` 中少量走 legacy `registerAction` 的不规则 action 不在此列。',
|
||||
'',
|
||||
`共 ${docs.length} 个声明式 action。`,
|
||||
'',
|
||||
];
|
||||
return header.concat(docs.map(renderAction)).join('\n') + '\n';
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
// action-kit — declarative OneBot Action definitions.
|
||||
//
|
||||
// One Action declares its param contract once (a record of `Field`s + optional
|
||||
// cross-field `rules`) and a `run` handler. The kit owns param coercion +
|
||||
// validation + the `BAD_REQUEST` shaping (naming the offending field) +
|
||||
// doc metadata. The handler receives typed, already-validated params.
|
||||
//
|
||||
// Narrow seam (ADR-0006): `ApiHandler` keeps dispatch / try-catch / response
|
||||
// wrapping. `defineAction(...).register(h, ctx)` ultimately registers a plain
|
||||
// `(params) => Promise<ApiResponse>` via `ApiHandler.registerAction`, exactly
|
||||
// like the legacy style — so old and new actions coexist during migration.
|
||||
//
|
||||
// Zero runtime npm deps (ADR-0004). Type inference via `InferParams` — no
|
||||
// hand-written param interface. Param contract is intentionally a second
|
||||
// definition from the SDK's client-side types (ADR-0005).
|
||||
//
|
||||
// Guard-rail (ADR-0007): the built-in coercers below are strict. Do NOT add a
|
||||
// lenient `union`/`refine` escape that re-introduces the silent coercion this
|
||||
// module exists to remove.
|
||||
|
||||
import { RETCODE, failedResponse } from './types';
|
||||
import type { ApiResponse, JsonObject, JsonValue } from './types';
|
||||
import type { ApiActionContext, ApiHandler } from './api-handler';
|
||||
|
||||
// ─────────────────────────── result currency ───────────────────────────
|
||||
|
||||
export type Ok<T> = { ok: true; value: T };
|
||||
/** `field` is the offending param ('' for a cross-field rule). */
|
||||
export type Err = { ok: false; field: string; reason: string };
|
||||
export type CoerceResult<T> = Ok<T> | Err;
|
||||
|
||||
const ok = <T>(value: T): Ok<T> => ({ ok: true, value });
|
||||
const err = (field: string, reason: string): Err => ({ ok: false, field, reason });
|
||||
|
||||
/** Only an absent key produces MISSING — this is what lets a present `0` /
|
||||
* `''` / `false` be distinguished from "not provided". */
|
||||
const MISSING = Symbol('missing');
|
||||
type Raw = JsonValue | typeof MISSING;
|
||||
|
||||
// ─────────────────────────── Field (param coercer) ───────────────────────────
|
||||
|
||||
/** A JSON Schema fragment (loose). Each coercer emits one; `describe()` composes
|
||||
* them into an action's `inputSchema` (consumed by docs / the MCP). */
|
||||
export type JsonSchema = Record<string, unknown>;
|
||||
|
||||
export interface FieldDoc {
|
||||
type: string;
|
||||
required: boolean;
|
||||
default?: JsonValue;
|
||||
desc?: string;
|
||||
values?: readonly (string | number)[];
|
||||
/** JSON Schema fragment for this field's value (constraints only; presence
|
||||
* and default are applied at the object level by `describe()`). */
|
||||
schema?: JsonSchema;
|
||||
}
|
||||
|
||||
export interface Field<T> {
|
||||
readonly doc: FieldDoc;
|
||||
/** Coerce the raw value at this field's key (MISSING when the key is absent). */
|
||||
coerce(raw: Raw, field: string): CoerceResult<T>;
|
||||
/** Absent ⇒ value is `undefined`; a present value still must coerce. */
|
||||
optional(): Field<T | undefined>;
|
||||
/** Absent ⇒ `value`; a present value still must coerce (so `"abc"` for a
|
||||
* numeric field is an error, not a silent fallback). */
|
||||
default(value: T): Field<T>;
|
||||
describe(text: string): Field<T>;
|
||||
/** Complete JSON Schema for this field's value (constraints + description +
|
||||
* default). Object-level required-ness is handled by `describe()`. */
|
||||
toJsonSchema(): JsonSchema;
|
||||
}
|
||||
|
||||
/** Core coerces a PRESENT value (never MISSING). Presence policy is applied
|
||||
* by the wrapping Field. */
|
||||
type Core<T> = (raw: JsonValue, field: string) => CoerceResult<T>;
|
||||
|
||||
class FieldImpl<T> implements Field<T> {
|
||||
constructor(
|
||||
private readonly core: Core<T>,
|
||||
readonly doc: FieldDoc,
|
||||
) {}
|
||||
|
||||
coerce(raw: Raw, field: string): CoerceResult<T> {
|
||||
if (raw === MISSING) {
|
||||
if (this.doc.required) return err(field, 'is required');
|
||||
return ok(this.doc.default as T); // default value, or undefined when optional
|
||||
}
|
||||
return this.core(raw, field);
|
||||
}
|
||||
|
||||
optional(): Field<T | undefined> {
|
||||
return new FieldImpl<T | undefined>(this.core as Core<T | undefined>, {
|
||||
...this.doc,
|
||||
required: false,
|
||||
default: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
default(value: T): Field<T> {
|
||||
return new FieldImpl<T>(this.core, { ...this.doc, required: false, default: value as JsonValue });
|
||||
}
|
||||
|
||||
describe(text: string): Field<T> {
|
||||
return new FieldImpl<T>(this.core, { ...this.doc, desc: text });
|
||||
}
|
||||
|
||||
toJsonSchema(): JsonSchema {
|
||||
const out: JsonSchema = { ...(this.doc.schema ?? {}) };
|
||||
if (this.doc.desc) out.description = this.doc.desc;
|
||||
if (this.doc.default !== undefined) out.default = this.doc.default;
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── coercer vocabulary `f` ───────────────────────────
|
||||
|
||||
interface IntOpts { min?: number; max?: number; nonZero?: boolean }
|
||||
|
||||
/** Accept a number or numeric string, truncate to integer (matches the legacy
|
||||
* `asNumber`), then apply bounds. Non-numeric / blank ⇒ Err. */
|
||||
function intCore(typeName: string, opts: IntOpts): Core<number> {
|
||||
return (raw, field) => {
|
||||
let n: number;
|
||||
if (typeof raw === 'number' && Number.isFinite(raw)) n = Math.trunc(raw);
|
||||
else if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) n = Math.trunc(Number(raw));
|
||||
else return err(field, `expected ${typeName}`);
|
||||
if (opts.nonZero && n === 0) return err(field, 'must not be 0');
|
||||
if (opts.min !== undefined && n < opts.min) return err(field, `must be >= ${opts.min}`);
|
||||
if (opts.max !== undefined && n > opts.max) return err(field, `must be <= ${opts.max}`);
|
||||
return ok(n);
|
||||
};
|
||||
}
|
||||
|
||||
function intSchema(opts: IntOpts): JsonSchema {
|
||||
const s: JsonSchema = { type: 'integer' };
|
||||
if (opts.min !== undefined) s.minimum = opts.min;
|
||||
if (opts.max !== undefined) s.maximum = opts.max;
|
||||
if (opts.nonZero) s.not = { const: 0 };
|
||||
return s;
|
||||
}
|
||||
|
||||
interface StrOpts { allowEmpty?: boolean; maxLen?: number }
|
||||
|
||||
function strSchema(opts: StrOpts): JsonSchema {
|
||||
const s: JsonSchema = { type: 'string' };
|
||||
if (opts.allowEmpty === false) s.minLength = 1;
|
||||
if (opts.maxLen !== undefined) s.maxLength = opts.maxLen;
|
||||
return s;
|
||||
}
|
||||
|
||||
function arrayField<E>(el: Field<E>, mustBeNonEmpty: boolean): Field<E[]> & { nonEmpty(): Field<E[]> } {
|
||||
const core: Core<E[]> = (raw, field) => {
|
||||
if (!Array.isArray(raw)) return err(field, 'expected an array');
|
||||
const out: E[] = [];
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const r = el.coerce(raw[i] as JsonValue, `${field}[${i}]`);
|
||||
if (!r.ok) return r;
|
||||
out.push(r.value);
|
||||
}
|
||||
if (mustBeNonEmpty && out.length === 0) return err(field, 'must not be empty');
|
||||
return ok(out);
|
||||
};
|
||||
const base = new FieldImpl<E[]>(core, {
|
||||
type: `${el.doc.type}[]`,
|
||||
required: true,
|
||||
schema: { type: 'array', items: el.toJsonSchema(), ...(mustBeNonEmpty ? { minItems: 1 } : {}) },
|
||||
});
|
||||
return Object.assign(base, { nonEmpty: () => arrayField(el, true) });
|
||||
}
|
||||
|
||||
export const f = {
|
||||
/** Positive integer (>0): group_id / user_id / message_id. */
|
||||
uint(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, schema: intSchema({ min: 1 }) });
|
||||
},
|
||||
/** Integer with optional bounds; allows 0 / negatives unless bounded.
|
||||
* e.g. a duration where 0 is meaningful: `f.int({ min: 0 })`. */
|
||||
int(opts: IntOpts = {}): Field<number> {
|
||||
return new FieldImpl<number>(intCore('an integer', opts), { type: 'int', required: true, schema: intSchema(opts) });
|
||||
},
|
||||
/** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a
|
||||
* signed int32 hash) — do NOT use `uint()` for message_id. */
|
||||
messageId(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, schema: intSchema({ nonZero: true }) });
|
||||
},
|
||||
/** Finite number (fractions allowed). */
|
||||
number(): Field<number> {
|
||||
return new FieldImpl<number>((raw, field) => {
|
||||
if (typeof raw === 'number' && Number.isFinite(raw)) return ok(raw);
|
||||
if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) return ok(Number(raw));
|
||||
return err(field, 'expected a number');
|
||||
}, { type: 'number', required: true, schema: { type: 'number' } });
|
||||
},
|
||||
/** String. Numbers/booleans stringify (matches legacy `asString`). Empty
|
||||
* allowed by default; `{ allowEmpty: false }` rejects ''. */
|
||||
string(opts: StrOpts = {}): Field<string> {
|
||||
return new FieldImpl<string>((raw, field) => {
|
||||
let s: string;
|
||||
if (typeof raw === 'string') s = raw;
|
||||
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
|
||||
else return err(field, 'expected a string');
|
||||
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
|
||||
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
|
||||
return ok(s);
|
||||
}, { type: 'string', required: true, schema: strSchema(opts) });
|
||||
},
|
||||
/** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */
|
||||
bool(): Field<boolean> {
|
||||
return new FieldImpl<boolean>((raw, field) => {
|
||||
if (typeof raw === 'boolean') return ok(raw);
|
||||
if (typeof raw === 'number') return ok(raw !== 0);
|
||||
if (typeof raw === 'string') {
|
||||
const t = raw.trim().toLowerCase();
|
||||
if (t === 'true' || t === '1' || t === 'yes' || t === 'on') return ok(true);
|
||||
if (t === 'false' || t === '0' || t === 'no' || t === 'off') return ok(false);
|
||||
}
|
||||
return err(field, 'expected a boolean');
|
||||
}, { type: 'bool', required: true, schema: { type: 'boolean' } });
|
||||
},
|
||||
/** OneBot message union: string | segment[] | object. A string that looks
|
||||
* like a JSON array is parsed (matches legacy `asMessage`); otherwise the
|
||||
* value passes through. Output stays `JsonValue` — downstream ctx.* accept it. */
|
||||
message(): Field<JsonValue> {
|
||||
return new FieldImpl<JsonValue>((raw, _field) => {
|
||||
if (typeof raw === 'string') {
|
||||
const t = raw.trim();
|
||||
if (t.startsWith('[') && t.endsWith(']')) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(t);
|
||||
if (Array.isArray(parsed)) return ok(parsed as JsonValue);
|
||||
} catch {
|
||||
// fall through to literal text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ok(raw);
|
||||
}, { type: 'message', required: true, schema: { description: 'OneBot message: string | segment[] | object' } });
|
||||
},
|
||||
/** Homogeneous array; `.nonEmpty()` rejects []. */
|
||||
array<E>(el: Field<E>): Field<E[]> & { nonEmpty(): Field<E[]> } {
|
||||
return arrayField(el, false);
|
||||
},
|
||||
/** Constrained literal set. */
|
||||
enum<const V extends readonly (string | number)[]>(...values: V): Field<V[number]> {
|
||||
return new FieldImpl<V[number]>((raw, field) => {
|
||||
if ((typeof raw === 'string' || typeof raw === 'number') && (values as readonly (string | number)[]).includes(raw)) {
|
||||
return ok(raw as V[number]);
|
||||
}
|
||||
return err(field, `expected one of: ${values.join(', ')}`);
|
||||
}, { type: 'enum', required: true, values, schema: { enum: [...values] } });
|
||||
},
|
||||
/** Escape hatch — pass the raw value (or undefined) through, validate nothing. */
|
||||
raw(): Field<JsonValue | undefined> {
|
||||
return new FieldImpl<JsonValue | undefined>((raw) => ok(raw), { type: 'raw', required: false, default: undefined, schema: {} });
|
||||
},
|
||||
};
|
||||
|
||||
// ─────────────────────────── type inference ───────────────────────────
|
||||
|
||||
type Spec = Record<string, Field<unknown>>;
|
||||
type FieldType<F> = F extends Field<infer T> ? T : never;
|
||||
/** Post-validation every key is present; optional/raw fields carry `undefined`
|
||||
* in their value type. */
|
||||
export type InferParams<S extends Spec> = { [K in keyof S]: FieldType<S[K]> };
|
||||
|
||||
// ─────────────────────────── cross-field rules ───────────────────────────
|
||||
|
||||
export interface CrossFieldRule {
|
||||
readonly doc: string;
|
||||
check(params: Record<string, unknown>): Err | null;
|
||||
}
|
||||
|
||||
type Key<P> = Extract<keyof P, string>;
|
||||
type Group<P> = Key<P> | Key<P>[];
|
||||
|
||||
export interface RuleBuilders<P> {
|
||||
/** Exactly one group satisfied. A group is a key, or an array of keys that
|
||||
* must ALL be present. e.g. `exactlyOneOf('message_id', ['group_id','user_id'])`. */
|
||||
exactlyOneOf(...groups: Group<P>[]): CrossFieldRule;
|
||||
atLeastOneOf(...keys: Key<P>[]): CrossFieldRule;
|
||||
requiredTogether(...keys: Key<P>[]): CrossFieldRule;
|
||||
mutuallyExclusive(...keys: Key<P>[]): CrossFieldRule;
|
||||
/** Arbitrary predicate; fails with `doc` as the reason. */
|
||||
rule(doc: string, ok: (p: P) => boolean): CrossFieldRule;
|
||||
}
|
||||
|
||||
const present = (p: Record<string, unknown>, key: string): boolean => p[key] !== undefined;
|
||||
const groupOk = (p: Record<string, unknown>, g: string | string[]): boolean =>
|
||||
Array.isArray(g) ? g.every((k) => present(p, k)) : present(p, g);
|
||||
const groupLabel = (g: string | string[]): string => (Array.isArray(g) ? `(${g.join('+')})` : g);
|
||||
|
||||
const RULES: RuleBuilders<Record<string, unknown>> = {
|
||||
exactlyOneOf(...groups) {
|
||||
const doc = `exactly one of: ${groups.map(groupLabel).join(' | ')}`;
|
||||
return {
|
||||
doc,
|
||||
check: (p) => (groups.filter((g) => groupOk(p, g)).length === 1 ? null : err('', doc)),
|
||||
};
|
||||
},
|
||||
atLeastOneOf(...keys) {
|
||||
const doc = `at least one of: ${keys.join(', ')}`;
|
||||
return { doc, check: (p) => (keys.some((k) => present(p, k)) ? null : err('', doc)) };
|
||||
},
|
||||
requiredTogether(...keys) {
|
||||
const doc = `all or none of: ${keys.join(', ')}`;
|
||||
return {
|
||||
doc,
|
||||
check: (p) => {
|
||||
const n = keys.filter((k) => present(p, k)).length;
|
||||
return n === 0 || n === keys.length ? null : err('', doc);
|
||||
},
|
||||
};
|
||||
},
|
||||
mutuallyExclusive(...keys) {
|
||||
const doc = `at most one of: ${keys.join(', ')}`;
|
||||
return { doc, check: (p) => (keys.filter((k) => present(p, k)).length <= 1 ? null : err('', doc)) };
|
||||
},
|
||||
rule(doc, okFn) {
|
||||
return { doc, check: (p) => (okFn(p as never) ? null : err('', doc)) };
|
||||
},
|
||||
};
|
||||
|
||||
// ─────────────────────────── defineAction ───────────────────────────
|
||||
|
||||
export interface ParamDoc extends FieldDoc {
|
||||
name: string;
|
||||
}
|
||||
export interface ActionDoc {
|
||||
name: string;
|
||||
aliases: string[];
|
||||
/** Domain category (set by the doc collector, e.g. 群管理/消息). */
|
||||
category?: string;
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
/** True only for pure data-fetch actions (no side effects). Drives the MCP's
|
||||
* read/write tool routing; defaults to false (treated as a write). */
|
||||
readOnly: boolean;
|
||||
params: ParamDoc[];
|
||||
invariants: string[];
|
||||
/** Composed JSON Schema for the whole params object (properties + required). */
|
||||
inputSchema: JsonSchema;
|
||||
}
|
||||
|
||||
type Handler = (params: JsonObject) => Promise<ApiResponse>;
|
||||
|
||||
export interface ActionSpec<S extends Spec> {
|
||||
readonly names: string[];
|
||||
readonly params: S;
|
||||
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
|
||||
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
|
||||
/** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */
|
||||
toHandler(ctx: ApiActionContext): Handler;
|
||||
/** Doc metadata (D4); a renderer walks this. */
|
||||
describe(): ActionDoc;
|
||||
register(h: ApiHandler, ctx: ApiActionContext): void;
|
||||
}
|
||||
|
||||
interface ActionDef<S extends Spec> {
|
||||
name: string | readonly [string, ...string[]];
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
/** Mark true ONLY for pure data-fetch actions with no side effects. Default
|
||||
* false = write. Surfaced via describe() into the catalog for the MCP's
|
||||
* read/write routing. Classify by what `run` actually does, not the name. */
|
||||
readOnly?: boolean;
|
||||
params: S;
|
||||
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
|
||||
/** `raw` is the original untouched params — an escape hatch for the
|
||||
* irregular tail (alias-key fallbacks, arbitrary nested objects). Declared
|
||||
* fields in `p` remain the validated path; reach for `raw` only for keys
|
||||
* the spec can't express. */
|
||||
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
|
||||
}
|
||||
|
||||
const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason);
|
||||
|
||||
export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
|
||||
const names = typeof def.name === 'string' ? [def.name] : [...def.name];
|
||||
const rules: readonly CrossFieldRule[] = def.rules
|
||||
? def.rules(RULES as unknown as RuleBuilders<InferParams<S>>)
|
||||
: [];
|
||||
|
||||
const parse = (raw: JsonObject): CoerceResult<InferParams<S>> => {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(def.params)) {
|
||||
const field = def.params[key];
|
||||
const value = Object.prototype.hasOwnProperty.call(raw, key) ? (raw[key] as JsonValue) : MISSING;
|
||||
const r = field.coerce(value, key);
|
||||
if (!r.ok) return r;
|
||||
out[key] = r.value;
|
||||
}
|
||||
for (const rule of rules) {
|
||||
const e = rule.check(out);
|
||||
if (e) return e;
|
||||
}
|
||||
return ok(out as InferParams<S>);
|
||||
};
|
||||
|
||||
const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => {
|
||||
const r = parse(params);
|
||||
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
|
||||
return def.run(r.value, ctx, params);
|
||||
};
|
||||
|
||||
return {
|
||||
names,
|
||||
params: def.params,
|
||||
parse,
|
||||
toHandler,
|
||||
describe: () => {
|
||||
const entries = Object.entries(def.params);
|
||||
const properties: Record<string, JsonSchema> = {};
|
||||
const required: string[] = [];
|
||||
for (const [name, field] of entries) {
|
||||
properties[name] = field.toJsonSchema();
|
||||
if (field.doc.required) required.push(name);
|
||||
}
|
||||
const inputSchema: JsonSchema = {
|
||||
type: 'object',
|
||||
properties,
|
||||
...(required.length ? { required } : {}),
|
||||
additionalProperties: true,
|
||||
};
|
||||
return {
|
||||
name: names[0],
|
||||
aliases: names.slice(1),
|
||||
summary: def.summary,
|
||||
returns: def.returns,
|
||||
readOnly: def.readOnly ?? false,
|
||||
params: entries.map(([name, field]) => ({ name, ...field.doc })),
|
||||
invariants: rules.map((rule) => rule.doc),
|
||||
inputSchema,
|
||||
};
|
||||
},
|
||||
register: (h, ctx) => {
|
||||
const handler = toHandler(ctx);
|
||||
for (const name of names) h.registerAction(name, handler);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────────────────── presets ───────────────────────────
|
||||
// `group_id` appears in 61/142 actions, `user_id` in 27 — these collapse the
|
||||
// dominant shape. The injected fields are surfaced in `describe()` so docs
|
||||
// list them even though the caller never typed them (ADR-0006 trade-off).
|
||||
|
||||
type WithGroup<S extends Spec> = S & { group_id: Field<number> };
|
||||
type WithGroupUser<S extends Spec> = S & { group_id: Field<number>; user_id: Field<number> };
|
||||
|
||||
interface PresetDef<S extends Spec, Extra> {
|
||||
name: string | readonly [string, ...string[]];
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
readOnly?: boolean;
|
||||
params?: S;
|
||||
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
|
||||
run: (p: InferParams<S> & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
|
||||
}
|
||||
|
||||
/** Pre-seeds `group_id` (uint, required). */
|
||||
export function groupAction<S extends Spec>(def: PresetDef<S, { group_id: number }>): ActionSpec<WithGroup<S>> {
|
||||
const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
|
||||
return defineAction({ ...def, params } as unknown as ActionDef<WithGroup<S>>);
|
||||
}
|
||||
|
||||
/** Pre-seeds `group_id` + `user_id` (both uint, required). */
|
||||
export function groupUserAction<S extends Spec>(
|
||||
def: PresetDef<S, { group_id: number; user_id: number }>,
|
||||
): ActionSpec<WithGroupUser<S>> {
|
||||
const params = {
|
||||
group_id: f.uint().describe('群号'),
|
||||
user_id: f.uint().describe('QQ 号'),
|
||||
...(def.params ?? {}),
|
||||
} as WithGroupUser<S>;
|
||||
return defineAction({ ...def, params } as unknown as ActionDef<WithGroupUser<S>>);
|
||||
}
|
||||
|
||||
// ─────────────────────────── registration helper ───────────────────────────
|
||||
|
||||
/** Register many specs onto an ApiHandler. Coexists with legacy
|
||||
* `h.registerAction(name, fn)` in the same `register(h, ctx)`. */
|
||||
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<ActionSpec<Spec>>): void {
|
||||
for (const spec of specs) spec.register(h, ctx);
|
||||
}
|
||||
+1465
-1047
File diff suppressed because it is too large.
Load diff
@@ -1,30 +1,47 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { defineAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'get_friend_list',
|
||||
summary: '获取好友列表',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: async (_p, ctx) => {
|
||||
if (ctx.getFriendList) {
|
||||
return okResponse(await ctx.getFriendList());
|
||||
}
|
||||
return okResponse([]);
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'get_stranger_info',
|
||||
summary: '获取陌生人信息',
|
||||
readOnly: true,
|
||||
params: { user_id: f.uint().describe('QQ 号') },
|
||||
run: async (p, ctx) => {
|
||||
const userId = p.user_id;
|
||||
if (ctx.getStrangerInfo) {
|
||||
const info = await ctx.getStrangerInfo(userId);
|
||||
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
}
|
||||
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'delete_friend',
|
||||
summary: '删除好友',
|
||||
params: { user_id: f.uint().describe('QQ 号'), block: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.friend.delete(p.user_id, p.block);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_friend_list', async () => {
|
||||
if (ctx.getFriendList) {
|
||||
return okResponse(await ctx.getFriendList());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_stranger_info', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (ctx.getStrangerInfo) {
|
||||
const info = await ctx.getStrangerInfo(userId);
|
||||
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
}
|
||||
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('delete_friend', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const block = asBoolean(params.block, false);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
await ctx.bridge.apis.friend.delete(userId, block);
|
||||
return okResponse();
|
||||
});
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,118 +1,135 @@
|
||||
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { asBoolean, asNumber, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('set_group_kick', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const reject = asBoolean(params.reject_add_request, false);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.kickMember(groupId, userId, reject);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_kick_members', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : [];
|
||||
const reject = asBoolean(params.reject_add_request, false);
|
||||
if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required');
|
||||
await ctx.bridge.apis.groupAdmin.kickMembers(groupId, userIds, reject);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_ban', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const duration = asNumber(params.duration) || 1800;
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.muteMember(groupId, userId, duration);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_whole_ban', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const enable = asBoolean(params.enable, true);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.muteAll(groupId, enable);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_add_option', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const addType = asNumber(params.add_type);
|
||||
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
|
||||
await ctx.bridge.apis.groupAdmin.setAddOption(groupId, addType);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_search', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.setSearch(groupId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_admin', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const enable = asBoolean(params.enable, true);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.setAdmin(groupId, userId, enable);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_card', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const card = asString(params.card);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.setCard(groupId, userId, card);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_name', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const name = asString(params.group_name);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.setName(groupId, name);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_leave', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.leave(groupId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_special_title', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const title = asString(params.special_title);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.setSpecialTitle(groupId, userId, title);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous_ban', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_portrait', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const file = asString(params.file);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
try {
|
||||
await ctx.bridge.apis.profile.setGroupAvatar(groupId, file);
|
||||
export const actions = [
|
||||
groupUserAction({
|
||||
name: 'set_group_kick',
|
||||
summary: '踢出群成员',
|
||||
params: { reject_add_request: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.kickMember(p.group_id, p.user_id, p.reject_add_request);
|
||||
return okResponse();
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
});
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_kick_members',
|
||||
summary: '批量踢出群成员',
|
||||
params: { user_id: f.array(f.uint()).nonEmpty(), reject_add_request: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupUserAction({
|
||||
name: 'set_group_ban',
|
||||
summary: '禁言群成员(duration=0 解除)',
|
||||
params: { duration: f.int({ min: 0 }).default(1800) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_whole_ban',
|
||||
summary: '全员禁言开关',
|
||||
params: { enable: f.bool().default(true) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.muteAll(p.group_id, p.enable);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_add_option',
|
||||
summary: '设置加群选项',
|
||||
params: { add_type: f.int({ min: 0 }).default(0) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setAddOption(p.group_id, p.add_type);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_search',
|
||||
summary: '允许群被搜索',
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupUserAction({
|
||||
name: 'set_group_admin',
|
||||
summary: '设置/取消管理员',
|
||||
params: { enable: f.bool().default(true) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setAdmin(p.group_id, p.user_id, p.enable);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupUserAction({
|
||||
name: 'set_group_card',
|
||||
summary: '设置群名片(空字符串清除)',
|
||||
params: { card: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setCard(p.group_id, p.user_id, p.card);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_name',
|
||||
summary: '设置群名',
|
||||
params: { group_name: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setName(p.group_id, p.group_name);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_leave',
|
||||
summary: '退群',
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.leave(p.group_id);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupUserAction({
|
||||
name: 'set_group_special_title',
|
||||
summary: '设置群头衔',
|
||||
params: { special_title: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setSpecialTitle(p.group_id, p.user_id, p.special_title);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
// No-op stubs (accept and ignore any params, as before).
|
||||
defineAction({ name: 'set_group_anonymous', summary: '匿名开关(未实现,返回 ok)', params: {}, run: () => okResponse() }),
|
||||
defineAction({ name: 'set_group_anonymous_ban', summary: '匿名禁言(未实现,返回 ok)', params: {}, run: () => okResponse() }),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_portrait',
|
||||
summary: '设置群头像',
|
||||
params: { file: f.string({ allowEmpty: false }) },
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
|
||||
return okResponse();
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,133 +1,132 @@
|
||||
import { groupAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { asNumber, asString } from '../api-handler';
|
||||
import type { JsonValue } from '../types';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_group_album_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
export const actions = [
|
||||
groupAction({
|
||||
name: 'get_group_album_list',
|
||||
readOnly: true,
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
|
||||
return okResponse(albumList);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
try {
|
||||
const albumList = await ctx.bridge.apis.groupAlbum.list(groupId);
|
||||
return okResponse(albumList);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
groupAction({
|
||||
name: 'upload_image_to_qun_album',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
album_name: f.string({ allowEmpty: false }),
|
||||
file: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file);
|
||||
return okResponse(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('upload_image_to_qun_album', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const albumName = asString(params.album_name);
|
||||
const file = asString(params.file);
|
||||
groupAction({
|
||||
name: 'get_group_album_media_list',
|
||||
readOnly: true,
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
attach_info: f.string().default(''),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info);
|
||||
return okResponse(mediaList as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album media list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
|
||||
if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required');
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
groupAction({
|
||||
name: 'do_group_album_comment',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
lloc: f.string({ allowEmpty: false }),
|
||||
content: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content);
|
||||
return okResponse(comment as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to comment on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
try {
|
||||
await ctx.bridge.apis.groupAlbum.upload(groupId, albumId, albumName, file);
|
||||
return okResponse(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_album_media_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const attachInfo = asString(params.attach_info) || '';
|
||||
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
|
||||
|
||||
try {
|
||||
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo);
|
||||
return okResponse(mediaList as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album media list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('do_group_album_comment', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const lloc = asString(params.lloc);
|
||||
const content = asString(params.content);
|
||||
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
|
||||
if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required');
|
||||
if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required');
|
||||
|
||||
try {
|
||||
const comment = await ctx.bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content);
|
||||
return okResponse(comment as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to comment on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('set_group_album_media_like', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const batchId = asString(params.batch_id);
|
||||
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
|
||||
|
||||
if (!groupId || !albumId || !batchId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, true);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to set like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
groupAction({
|
||||
name: 'set_group_album_media_like',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
batch_id: f.string({ allowEmpty: false }),
|
||||
lloc: f.string().optional(), // 可选参数(空串按未传处理)
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to set like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
// 取消点赞群相册媒体
|
||||
h.registerAction('cancel_group_album_media_like', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const batchId = asString(params.batch_id);
|
||||
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
|
||||
groupAction({
|
||||
name: 'cancel_group_album_media_like',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
batch_id: f.string({ allowEmpty: false }),
|
||||
lloc: f.string().optional(), // 可选参数(空串按未传处理)
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
if (!groupId || !albumId || !batchId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
|
||||
}
|
||||
groupAction({
|
||||
name: 'del_group_album_media',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
lloc: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to delete album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, false);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('del_group_album_media', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const lloc = asString(params.lloc);
|
||||
|
||||
if (!groupId || !albumId || !lloc) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.delete(groupId, albumId, lloc);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to delete album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,118 +1,175 @@
|
||||
import { defineAction, groupAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asBoolean, asNumber, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse } from '../types';
|
||||
import { okResponse } from '../types';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export const actions = [
|
||||
groupAction({
|
||||
name: 'upload_group_file',
|
||||
summary: '上传群文件',
|
||||
returns: '{ file_id: string }',
|
||||
// `folder` / `folder_id` are two aliases for one target dir; the first
|
||||
// non-empty wins, else '/'. Both default '' so the `||` chain matches the
|
||||
// legacy `asString(folder) || asString(folder_id) || '/'`.
|
||||
params: {
|
||||
file: f.string({ allowEmpty: false }),
|
||||
name: f.string().default(''),
|
||||
folder: f.string().default(''),
|
||||
folder_id: f.string().default(''),
|
||||
upload_file: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const folderId = p.folder || p.folder_id || '/';
|
||||
const result = await ctx.bridge.apis.groupFile.upload(p.group_id, p.file, p.name, folderId, p.upload_file);
|
||||
return okResponse({ file_id: result.fileId });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'upload_private_file',
|
||||
summary: '上传私聊文件',
|
||||
returns: '{ file_id: string }',
|
||||
params: {
|
||||
user_id: f.uint(),
|
||||
file: f.string({ allowEmpty: false }),
|
||||
name: f.string().default(''),
|
||||
upload_file: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.bridge.apis.groupFile.uploadPrivate(p.user_id, p.file, p.name, p.upload_file);
|
||||
return okResponse({ file_id: result.fileId });
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'get_group_file_url',
|
||||
summary: '获取群文件下载链接',
|
||||
readOnly: true,
|
||||
returns: '{ url: string }',
|
||||
// busid: legacy `asNumber(busid) || 102` mapped absent/0/invalid → 102.
|
||||
// f.int({min:0}).default(102) keeps absent → 102, but a present 0 now
|
||||
// stays 0 and a non-numeric busid is now rejected (BAD_REQUEST) instead
|
||||
// of silently becoming 102.
|
||||
params: { file_id: f.string({ allowEmpty: false }), busid: f.int({ min: 0 }).default(102) },
|
||||
run: async (p, ctx) => {
|
||||
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, p.busid) });
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'get_group_root_files',
|
||||
summary: '获取群根目录文件列表',
|
||||
readOnly: true,
|
||||
run: async (p, ctx) => {
|
||||
return okResponse(await ctx.getGroupFiles(p.group_id, '/'));
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'get_group_files_by_folder',
|
||||
summary: '获取群子目录文件列表',
|
||||
readOnly: true,
|
||||
// folder_id / folder are aliases; first non-empty wins, else '/'.
|
||||
params: { folder_id: f.string().default(''), folder: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
const folderId = p.folder_id || p.folder || '/';
|
||||
return okResponse(await ctx.getGroupFiles(p.group_id, folderId));
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'delete_group_file',
|
||||
summary: '删除群文件',
|
||||
params: { file_id: f.string({ allowEmpty: false }) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.delete(p.group_id, p.file_id);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'move_group_file',
|
||||
summary: '移动群文件',
|
||||
params: {
|
||||
file_id: f.string({ allowEmpty: false }),
|
||||
parent_directory: f.string({ allowEmpty: false }),
|
||||
target_directory: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.move(p.group_id, p.file_id, p.parent_directory, p.target_directory);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
// rename_group_file — 0x6D6_4。NapCat 入参:file_id + current_parent_directory
|
||||
// (文件当前所在目录)+ new_name。SnowLuma 的 file_id 即原始 fileId,无需 UUID 解码。
|
||||
groupAction({
|
||||
name: 'rename_group_file',
|
||||
summary: '重命名群文件',
|
||||
params: {
|
||||
file_id: f.string({ allowEmpty: false }),
|
||||
current_parent_directory: f.string().default('/'),
|
||||
new_name: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.rename(p.group_id, p.file_id, p.current_parent_directory || '/', p.new_name);
|
||||
// {ok:true} 刻意对齐 NapCat RenameGroupFile 的返回体,偏离 SnowLuma 同类
|
||||
// 文件写操作(move/delete 返回空 data)——为 NapCat 客户端 drop-in 兼容。
|
||||
return okResponse({ ok: true });
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'create_group_file_folder',
|
||||
summary: '创建群文件夹',
|
||||
params: { name: f.string({ allowEmpty: false }), parent_id: f.string().default('/') },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.createFolder(p.group_id, p.name, p.parent_id || '/');
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'delete_group_file_folder',
|
||||
summary: '删除群文件夹',
|
||||
params: { folder_id: f.string({ allowEmpty: false }) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.deleteFolder(p.group_id, p.folder_id);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'rename_group_file_folder',
|
||||
summary: '重命名群文件夹',
|
||||
// new_folder_name / name are aliases; first non-empty wins and must be
|
||||
// non-empty (legacy `asString(new_folder_name) || asString(name)` + `!newName`).
|
||||
params: { folder_id: f.string({ allowEmpty: false }), new_folder_name: f.string().default(''), name: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
const newName = p.new_folder_name || p.name;
|
||||
if (!newName) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.renameFolder(p.group_id, p.folder_id, newName);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'get_private_file_url',
|
||||
summary: '获取私聊文件下载链接',
|
||||
readOnly: true,
|
||||
returns: '{ url: string }',
|
||||
params: {
|
||||
user_id: f.uint(),
|
||||
file_id: f.string({ allowEmpty: false }),
|
||||
file_hash: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(p.user_id, p.file_id, p.file_hash) });
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('upload_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const file = asString(params.file);
|
||||
const name = asString(params.name);
|
||||
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
|
||||
const uploadFile = asBoolean(params.upload_file, true);
|
||||
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
|
||||
const result = await ctx.bridge.apis.groupFile.upload(groupId, file, name, folderId, uploadFile);
|
||||
return okResponse({ file_id: result.fileId });
|
||||
});
|
||||
|
||||
h.registerAction('upload_private_file', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const file = asString(params.file);
|
||||
const name = asString(params.name);
|
||||
const uploadFile = asBoolean(params.upload_file, true);
|
||||
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
|
||||
const result = await ctx.bridge.apis.groupFile.uploadPrivate(userId, file, name, uploadFile);
|
||||
return okResponse({ file_id: result.fileId });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_file_url', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const busId = asNumber(params.busid) || 102;
|
||||
if (!groupId || !fileId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||
}
|
||||
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(groupId, fileId, busId) });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_root_files', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
return okResponse(await ctx.getGroupFiles(groupId, '/'));
|
||||
});
|
||||
|
||||
h.registerAction('get_group_files_by_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id) || asString(params.folder) || '/';
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
return okResponse(await ctx.getGroupFiles(groupId, folderId));
|
||||
});
|
||||
|
||||
h.registerAction('delete_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
if (!groupId || !fileId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.delete(groupId, fileId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('move_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const parentDirectory = asString(params.parent_directory);
|
||||
const targetDirectory = asString(params.target_directory);
|
||||
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.move(groupId, fileId, parentDirectory, targetDirectory);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('create_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const name = asString(params.name);
|
||||
const parentId = asString(params.parent_id) || '/';
|
||||
if (!groupId || !name) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.createFolder(groupId, name, parentId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('delete_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id);
|
||||
if (!groupId || !folderId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('rename_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id);
|
||||
const newName = asString(params.new_folder_name) || asString(params.name);
|
||||
if (!groupId || !folderId || !newName) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.renameFolder(groupId, folderId, newName);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('get_private_file_url', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const fileHash = asString(params.file_hash);
|
||||
if (!userId || !fileId || !fileHash) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
|
||||
}
|
||||
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash) });
|
||||
});
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,84 +1,120 @@
|
||||
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean, asString } from '../api-handler';
|
||||
import { asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_group_list', async (params) => {
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupList) {
|
||||
return okResponse(await ctx.getGroupList(noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'get_group_list',
|
||||
summary: '获取群列表',
|
||||
readOnly: true,
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const noCache = p.no_cache;
|
||||
if (ctx.getGroupList) {
|
||||
return okResponse(await ctx.getGroupList(noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('get_group_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupInfo) {
|
||||
const info = await ctx.getGroupInfo(groupId, noCache);
|
||||
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
}
|
||||
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
});
|
||||
groupAction({
|
||||
name: 'get_group_info',
|
||||
summary: '获取群信息',
|
||||
readOnly: true,
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const groupId = p.group_id;
|
||||
const noCache = p.no_cache;
|
||||
if (ctx.getGroupInfo) {
|
||||
const info = await ctx.getGroupInfo(groupId, noCache);
|
||||
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
}
|
||||
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('get_group_member_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupMemberList) {
|
||||
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
groupAction({
|
||||
name: 'get_group_member_list',
|
||||
summary: '获取群成员列表',
|
||||
readOnly: true,
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const groupId = p.group_id;
|
||||
const noCache = p.no_cache;
|
||||
if (ctx.getGroupMemberList) {
|
||||
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('get_group_member_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupMemberInfo) {
|
||||
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
|
||||
return okResponse(info ?? {
|
||||
groupUserAction({
|
||||
name: 'get_group_member_info',
|
||||
summary: '获取群成员信息',
|
||||
readOnly: true,
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const groupId = p.group_id;
|
||||
const userId = p.user_id;
|
||||
const noCache = p.no_cache;
|
||||
if (ctx.getGroupMemberInfo) {
|
||||
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
|
||||
return okResponse(info ?? {
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
}
|
||||
return okResponse({
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
}
|
||||
return okResponse({
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
});
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('get_group_honor_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const typeStr = asString(params.type) || 'all';
|
||||
// `type` keeps the legacy `asString(x) || 'all'` semantics (absent / non-string
|
||||
// / empty-string all collapse to 'all'), which a typed string field can't
|
||||
// replicate exactly — so it stays a raw param coerced in run().
|
||||
groupAction({
|
||||
name: 'get_group_honor_info',
|
||||
summary: '获取群荣誉信息',
|
||||
readOnly: true,
|
||||
params: { type: f.raw() },
|
||||
run: async (p, ctx) => {
|
||||
const groupId = p.group_id;
|
||||
const typeStr = asString(p.type) || 'all';
|
||||
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
const typeValues = Object.values(WebHonorType) as string[];
|
||||
if (!typeValues.includes(typeStr)) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
|
||||
return okResponse(honorInfo);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
const typeValues = Object.values(WebHonorType) as string[];
|
||||
if (!typeValues.includes(typeStr)) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
|
||||
}
|
||||
defineAction({
|
||||
name: 'get_group_system_msg',
|
||||
summary: '获取群系统消息',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: async (_p, ctx) => {
|
||||
if (ctx.handleGetGroupSystemMsg) {
|
||||
return okResponse(await ctx.handleGetGroupSystemMsg());
|
||||
}
|
||||
return okResponse([]);
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
try {
|
||||
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
|
||||
return okResponse(honorInfo);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_system_msg', async () => {
|
||||
if (ctx.handleGetGroupSystemMsg) {
|
||||
return okResponse(await ctx.handleGetGroupSystemMsg());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,32 +1,63 @@
|
||||
import { defineAction, registerActions } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
|
||||
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'get_login_info',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: (_p, ctx) => {
|
||||
const login = ctx.getLoginInfo();
|
||||
return okResponse({ user_id: login.userId, nickname: login.nickname });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'get_status',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: (_p, ctx) => {
|
||||
const online = ctx.isOnline();
|
||||
return okResponse({ online, good: online });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'get_version_info',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: () => {
|
||||
return okResponse({
|
||||
app_name: 'SnowLuma',
|
||||
app_version: `${appVersion}-node`,
|
||||
protocol_version: 'v11',
|
||||
});
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'can_send_image',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: (_p, ctx) => {
|
||||
return okResponse({ yes: ctx.canSendImage?.() ?? false });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'can_send_record',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: (_p, ctx) => {
|
||||
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_login_info', async () => {
|
||||
const login = ctx.getLoginInfo();
|
||||
return okResponse({ user_id: login.userId, nickname: login.nickname });
|
||||
});
|
||||
|
||||
h.registerAction('get_status', async () => {
|
||||
const online = ctx.isOnline();
|
||||
return okResponse({ online, good: online });
|
||||
});
|
||||
|
||||
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
|
||||
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
|
||||
h.registerAction('get_version_info', async () => {
|
||||
return okResponse({
|
||||
app_name: 'SnowLuma',
|
||||
app_version: `${appVersion}-node`,
|
||||
protocol_version: 'v11',
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('can_send_image', async () => {
|
||||
return okResponse({ yes: ctx.canSendImage?.() ?? false });
|
||||
});
|
||||
|
||||
h.registerAction('can_send_record', async () => {
|
||||
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
|
||||
});
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,97 +1,117 @@
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
|
||||
import { defineAction, groupAction, registerActions, f } from '../action-kit';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('send_msg', async (params) => {
|
||||
const messageType = asString(params.message_type);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
/**
|
||||
* Re-sign image URLs in a stored message event at read time. `get_msg`
|
||||
* returns a copy persisted when the message first arrived, and image rkeys
|
||||
* expire — so walk the segment array and refresh each image URL through
|
||||
* `ctx.getImageInfo`, which mints a current rkey. Best-effort and in-place;
|
||||
* `findEvent` returns a fresh parse, so mutating the array is safe.
|
||||
*/
|
||||
async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): Promise<void> {
|
||||
const segments = event.message;
|
||||
if (!Array.isArray(segments)) return;
|
||||
for (const seg of segments) {
|
||||
if (!seg || typeof seg !== 'object') continue;
|
||||
const segment = seg as { type?: unknown; data?: Record<string, JsonValue> };
|
||||
if (segment.type !== 'image') continue;
|
||||
const data = segment.data;
|
||||
if (!data || typeof data !== 'object') continue;
|
||||
const file = typeof data.file === 'string' ? data.file
|
||||
: typeof data.file_id === 'string' ? data.file_id
|
||||
: '';
|
||||
if (!file) continue;
|
||||
try {
|
||||
const info = await ctx.getImageInfo(file);
|
||||
if (info && typeof info.url === 'string' && info.url) data.url = info.url;
|
||||
} catch {
|
||||
// Keep the stored URL when the refresh fails.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (messageType === 'group' || params.group_id !== undefined) {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
export const actions = [
|
||||
// send_msg routes on message_type / group_id presence, so the *required*
|
||||
// id is conditional — that branch stays in run(). The fields themselves
|
||||
// (message required; group_id/user_id valid uints when present) are
|
||||
// validated by the spec; message_type is left lenient for parity.
|
||||
defineAction({
|
||||
name: 'send_msg',
|
||||
summary: '发送消息(按 message_type/群号 自动路由群聊或私聊)',
|
||||
returns: '{ message_id: number }',
|
||||
params: {
|
||||
message: f.message(),
|
||||
message_type: f.string().optional(),
|
||||
group_id: f.uint().optional(),
|
||||
user_id: f.uint().optional(),
|
||||
auto_escape: f.bool().default(false),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
if (p.message_type === 'group' || p.group_id !== undefined) {
|
||||
if (p.group_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
}
|
||||
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||
if (p.user_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
}
|
||||
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
defineAction({
|
||||
name: 'send_private_msg',
|
||||
summary: '发送私聊消息',
|
||||
returns: '{ message_id: number }',
|
||||
params: { user_id: f.uint(), message: f.message(), auto_escape: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('send_private_msg', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
}
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
|
||||
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
|
||||
h.registerAction('send_group_msg', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
|
||||
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
|
||||
h.registerAction('get_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
|
||||
const data = ctx.getMessage(messageId);
|
||||
if (!data) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
}
|
||||
|
||||
const result: JsonObject = { ...data };
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? messageId) as JsonValue;
|
||||
return okResponse(result);
|
||||
});
|
||||
groupAction({
|
||||
name: 'send_group_msg',
|
||||
summary: '发送群消息',
|
||||
returns: '{ message_id: number }',
|
||||
params: { message: f.message(), auto_escape: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('delete_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
defineAction({
|
||||
name: 'get_msg',
|
||||
summary: '获取消息',
|
||||
readOnly: true,
|
||||
params: { message_id: f.messageId() },
|
||||
run: async (p, ctx) => {
|
||||
const data = ctx.getMessage(p.message_id);
|
||||
if (!data) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
const result: JsonObject = { ...data };
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? p.message_id) as JsonValue;
|
||||
await refreshStoredImageUrls(result, ctx);
|
||||
return okResponse(result);
|
||||
},
|
||||
}),
|
||||
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
|
||||
}
|
||||
defineAction({
|
||||
name: 'delete_msg',
|
||||
summary: '撤回消息',
|
||||
params: { message_id: f.messageId() },
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
|
||||
await ctx.deleteMessage(p.message_id, meta);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
await ctx.deleteMessage(messageId, meta);
|
||||
return okResponse();
|
||||
});
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,23 +1,42 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asString, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { defineAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { asString } from '../api-handler';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'set_friend_add_request',
|
||||
summary: '处理好友添加请求',
|
||||
params: {
|
||||
flag: f.string({ allowEmpty: false }),
|
||||
approve: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.friend.handleRequest(p.flag, p.approve);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'set_group_add_request',
|
||||
summary: '处理加群请求',
|
||||
params: {
|
||||
flag: f.string({ allowEmpty: false }),
|
||||
// sub_type/type pass through with a nested fallback (sub_type → type → 'add');
|
||||
// kept raw so the original asString resolution is preserved verbatim.
|
||||
sub_type: f.raw(),
|
||||
type: f.raw(),
|
||||
approve: f.bool().default(true),
|
||||
reason: f.string().default(''),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const subType = asString(p.sub_type, asString(p.type, 'add'));
|
||||
await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('set_friend_add_request', async (params) => {
|
||||
const flag = asString(params.flag);
|
||||
const approve = asBoolean(params.approve, true);
|
||||
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||
await ctx.bridge.apis.friend.handleRequest(flag, approve);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_add_request', async (params) => {
|
||||
const flag = asString(params.flag);
|
||||
const subType = asString(params.sub_type, asString(params.type, 'add'));
|
||||
const approve = asBoolean(params.approve, true);
|
||||
const reason = asString(params.reason);
|
||||
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||
await ctx.handleGroupRequest(flag, subType, approve, reason);
|
||||
return okResponse();
|
||||
});
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { summarizeParams } from '@snowluma/common/log-summary';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose, summarizeParams } from '@snowluma/common/log-summary';
|
||||
import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { register as registerExtended } from './actions/extended';
|
||||
import { register as registerFriend } from './actions/friend';
|
||||
@@ -76,13 +76,32 @@ export interface ApiActionContext {
|
||||
}>;
|
||||
getImageInfo: (file: string) => Promise<JsonObject | null>;
|
||||
getRecordInfo: (file: string) => Promise<JsonObject | null>;
|
||||
fetchPttText: (messageId: number) => Promise<{ text: string }>;
|
||||
}
|
||||
|
||||
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
|
||||
|
||||
/** A handled-action record handed to debug observers. */
|
||||
export interface ActionRecord {
|
||||
action: string;
|
||||
params: JsonObject;
|
||||
response: import('./types').ApiResponse;
|
||||
ms: number;
|
||||
}
|
||||
export type ActionObserver = (rec: ActionRecord) => void;
|
||||
|
||||
export class ApiHandler {
|
||||
private readonly handlers = new Map<string, ActionHandler>();
|
||||
private readonly log: Logger;
|
||||
/** Debug-stream taps — notified after every handled action. Attached
|
||||
* on-demand (ref-counted) by the WebUI debug stream. */
|
||||
private readonly observers = new Set<ActionObserver>();
|
||||
|
||||
/** Observe handled actions (debug). Returns an unsubscribe. */
|
||||
setObserver(cb: ActionObserver): () => void {
|
||||
this.observers.add(cb);
|
||||
return () => { this.observers.delete(cb); };
|
||||
}
|
||||
|
||||
constructor(context: ApiActionContext, uin?: number) {
|
||||
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
@@ -108,13 +127,33 @@ export class ApiHandler {
|
||||
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
|
||||
}
|
||||
|
||||
// Entry log goes to file always (debug); console only when level is
|
||||
// dialed down to debug. Caller-perspective summary lets the operator
|
||||
// grep "what did the bot get asked to do" without scraping wire logs.
|
||||
this.log.debug('%s params=%s', action, summarizeParams(params));
|
||||
// Correlate the whole request — entry, every outbound packet it triggers,
|
||||
// and the exit — under one `[req#N]` tag via AsyncLocalStorage. Only pay
|
||||
// the wrap + id allocation when trace is actually live, so the default
|
||||
// path stays allocation-free.
|
||||
if (getLogLevel() !== 'trace') {
|
||||
return this.runAction(action, handler, params);
|
||||
}
|
||||
return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params));
|
||||
}
|
||||
|
||||
private async runAction(
|
||||
action: string,
|
||||
handler: ActionHandler,
|
||||
params: JsonObject,
|
||||
): Promise<import('./types').ApiResponse> {
|
||||
// Terse breadcrumb to the log file (debug, always persisted): lets the
|
||||
// operator grep "what did the bot get asked to do" in post-mortems.
|
||||
this.log.debug('%s params=%s', action, summarizeParams(params));
|
||||
// Full request shape, memory-only (trace). Lazy producer → the deep render
|
||||
// only runs when trace is live.
|
||||
this.log.trace(() => [`${action} ⇐ %s`, renderParamsVerbose(params)]);
|
||||
|
||||
const startedAt = Date.now();
|
||||
let response: import('./types').ApiResponse;
|
||||
try {
|
||||
return await handler(params);
|
||||
response = await handler(params);
|
||||
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
|
||||
} catch (error) {
|
||||
// Action failures are almost always param-shape problems coming
|
||||
// from the OneBot client; warn (not error) is the right level so
|
||||
@@ -124,7 +163,23 @@ export class ApiHandler {
|
||||
error instanceof Error ? error.message : String(error),
|
||||
error instanceof Error ? (error.stack ?? '') : '');
|
||||
const message = error instanceof Error ? error.message : 'internal error';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
response = failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
this.notifyObservers(action, params, response, Date.now() - startedAt);
|
||||
return response;
|
||||
}
|
||||
|
||||
private notifyObservers(
|
||||
action: string,
|
||||
params: JsonObject,
|
||||
response: import('./types').ApiResponse,
|
||||
ms: number,
|
||||
): void {
|
||||
if (!this.observers.size) return;
|
||||
for (const cb of this.observers) {
|
||||
try { cb({ action, params, response, ms }); } catch (err) {
|
||||
this.log.warn('action observer error: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
MessageFormat,
|
||||
OneBotConfig,
|
||||
OneBotNetworks,
|
||||
StatusCommandConfig,
|
||||
WsClientNetwork,
|
||||
WsRole,
|
||||
WsServerNetwork,
|
||||
@@ -20,6 +21,14 @@ const CONFIG_DIR = 'config';
|
||||
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
|
||||
|
||||
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = { enabled: true, swallow: false, cooldownSeconds: 5 };
|
||||
/** Upper bound on the `#sl` reply cooldown — a year is effectively "off but sane". */
|
||||
const STATUS_COMMAND_COOLDOWN_MAX = 31_536_000;
|
||||
|
||||
function makeDefaultStatusCommand(): StatusCommandConfig {
|
||||
return { ...DEFAULT_STATUS_COMMAND };
|
||||
}
|
||||
|
||||
export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||
return {
|
||||
networks: {
|
||||
@@ -46,6 +55,8 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||
wsClients: [],
|
||||
},
|
||||
musicSignUrl: '',
|
||||
statusCommand: makeDefaultStatusCommand(),
|
||||
notifications: { channelIds: [] },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -98,6 +109,12 @@ function toJsonObject(config: OneBotConfig): JsonObject {
|
||||
wsClients: nets.wsClients.map(wsClientToJson),
|
||||
},
|
||||
musicSignUrl: config.musicSignUrl ?? '',
|
||||
statusCommand: {
|
||||
enabled: config.statusCommand.enabled,
|
||||
swallow: config.statusCommand.swallow,
|
||||
cooldownSeconds: config.statusCommand.cooldownSeconds,
|
||||
},
|
||||
notifications: { channelIds: config.notifications?.channelIds ?? [] },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -181,7 +198,60 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
|
||||
}
|
||||
|
||||
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
|
||||
return { networks, musicSignUrl };
|
||||
return {
|
||||
networks,
|
||||
musicSignUrl,
|
||||
statusCommand: parseStatusCommand(sources),
|
||||
notifications: parseNotifications(sources),
|
||||
};
|
||||
}
|
||||
|
||||
/** Last-write-wins merge of `notifications.channelIds` across config sources,
|
||||
* each id validated as a slug + deduped. Mirrors the channel-id rule in
|
||||
* packages/core/src/notifications/config.ts (CHANNEL_ID_RE) — duplicated
|
||||
* deliberately: core depends on onebot, so onebot cannot import from core. */
|
||||
function parseNotifications(sources: JsonObject[]): { channelIds: string[] } {
|
||||
let channelIds: string[] = [];
|
||||
for (const src of sources) {
|
||||
const raw = src.notifications;
|
||||
if (!isObject(raw)) continue;
|
||||
if (Array.isArray(raw.channelIds)) channelIds = normalizeChannelIds(raw.channelIds);
|
||||
}
|
||||
return { channelIds };
|
||||
}
|
||||
|
||||
function normalizeChannelIds(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
for (const item of value) {
|
||||
if (typeof item !== 'string') continue;
|
||||
const v = item.trim();
|
||||
if (!v || v.length > 64 || !/^[\w.-]+$/.test(v)) continue;
|
||||
if (seen.has(v)) continue;
|
||||
seen.add(v);
|
||||
out.push(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Last-write-wins merge of `statusCommand` across config sources, with
|
||||
* defaults filled and the cooldown clamped to a sane non-negative range. */
|
||||
function parseStatusCommand(sources: JsonObject[]): StatusCommandConfig {
|
||||
const out = makeDefaultStatusCommand();
|
||||
for (const src of sources) {
|
||||
const raw = src.statusCommand;
|
||||
if (!isObject(raw)) continue;
|
||||
if (typeof raw.enabled === 'boolean') out.enabled = raw.enabled;
|
||||
if (typeof raw.swallow === 'boolean') out.swallow = raw.swallow;
|
||||
if (raw.cooldownSeconds !== undefined) {
|
||||
out.cooldownSeconds = Math.min(
|
||||
STATUS_COMMAND_COOLDOWN_MAX,
|
||||
asNumber(raw.cooldownSeconds, DEFAULT_STATUS_COMMAND.cooldownSeconds),
|
||||
);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function collectByName<T extends { name: string }>(
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
} from './to-request';
|
||||
import { elementsToJson } from './to-segment';
|
||||
|
||||
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
|
||||
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string | Promise<string>;
|
||||
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
|
||||
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
|
||||
|
||||
|
||||
@@ -32,10 +32,15 @@ export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMember
|
||||
|
||||
export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMemberLeave): JsonObject {
|
||||
let subType: string;
|
||||
if (event.isKick) {
|
||||
subType = event.userUin === ctx.selfId ? 'kick_me' : 'kick';
|
||||
} else {
|
||||
subType = 'leave';
|
||||
switch (event.leaveType) {
|
||||
case 'disband':
|
||||
subType = 'disband';
|
||||
break;
|
||||
case 'kick':
|
||||
subType = event.userUin === ctx.selfId ? 'kick_me' : 'kick';
|
||||
break;
|
||||
default:
|
||||
subType = 'leave';
|
||||
}
|
||||
return {
|
||||
time: event.time,
|
||||
|
||||
@@ -45,7 +45,7 @@ async function elementToSegment(
|
||||
}
|
||||
|
||||
if (element.type === 'image') {
|
||||
const url = imageUrlResolver ? imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
const url = imageUrlResolver ? await imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
const data: JsonObject = {
|
||||
url,
|
||||
file: element.fileId ?? '',
|
||||
@@ -104,12 +104,22 @@ async function elementToSegment(
|
||||
|
||||
if (element.type === 'file') {
|
||||
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
const fileName = element.fileName ?? '';
|
||||
const fileSize = element.fileSize ?? 0;
|
||||
const fileId = element.fileId ?? '';
|
||||
return {
|
||||
type: 'file',
|
||||
data: {
|
||||
name: element.fileName ?? '',
|
||||
size: element.fileSize ?? 0,
|
||||
id: element.fileId ?? '',
|
||||
// NapCat/LLOneBot-style canonical fields — most downstream
|
||||
// OneBot adapters read these (`file`/`file_id`/`file_size`).
|
||||
file: fileName,
|
||||
file_id: fileId,
|
||||
file_size: fileSize,
|
||||
// Legacy SnowLuma field names, kept for backward compat with
|
||||
// any consumer that already reads name/size/id.
|
||||
name: fileName,
|
||||
size: fileSize,
|
||||
id: fileId,
|
||||
url,
|
||||
file_hash: element.fileHash ?? '',
|
||||
},
|
||||
@@ -117,12 +127,27 @@ async function elementToSegment(
|
||||
}
|
||||
|
||||
if (element.type === 'mface') {
|
||||
// Unify market faces (商城表情) to an `image` segment so OneBot clients
|
||||
// that don't special-case `mface` still render the sticker, while the
|
||||
// `emoji_id`/`emoji_package_id`/`key` markers let aware clients (and our
|
||||
// own send path) reproduce it as a real market face. Mirrors NapCat's
|
||||
// marketFaceElement → image conversion. The gxh URL is a self-contained
|
||||
// external link (no rkey), so we set it directly and skip mediaSegmentSink.
|
||||
const emojiId = element.emojiId ?? '';
|
||||
const dir = emojiId.slice(0, 2);
|
||||
const url = emojiId
|
||||
? `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif`
|
||||
: '';
|
||||
return {
|
||||
type: 'mface',
|
||||
type: 'image',
|
||||
data: {
|
||||
name: element.text ?? '',
|
||||
tab_id: element.faceId ?? 0,
|
||||
sub_type: element.subType ?? 0,
|
||||
file: emojiId ? `${dir}-${emojiId}.gif` : '',
|
||||
url,
|
||||
summary: element.text ?? '',
|
||||
sub_type: 0,
|
||||
emoji_id: emojiId,
|
||||
emoji_package_id: element.emojiPackageId ?? 0,
|
||||
key: element.emojiKey ?? '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,26 +1,34 @@
|
||||
import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { convertEvent } from './event-converter';
|
||||
import type { OneBotInstanceContext } from './instance-context';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import { backfillReplyTarget } from './modules/message-actions';
|
||||
import { deliverPttTransText, pttTransKey } from './modules/ptt-trans-waiter';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
const log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
const disposers: Array<() => void> = [];
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('group_message', async (event) => {
|
||||
cacheGroupMessageMeta(ctx, event);
|
||||
await convertAndDispatch(ctx, event);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('friend_message', async (event) => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, event.msgId);
|
||||
await convertAndDispatch(ctx, event);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
);
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('temp_message', async (event) => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
|
||||
await convertAndDispatch(ctx, event);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
);
|
||||
for (const kind of NOTICE_KINDS) {
|
||||
@@ -29,10 +37,17 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
|
||||
if (event.kind === 'group_msg_emoji_like') {
|
||||
cacheReaction(ctx, event);
|
||||
}
|
||||
await convertAndDispatch(ctx, event);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Internal-only: voice-to-text result push. Not converted to a OneBot event —
|
||||
// it just unblocks the fetch_ptt_text call waiting on this msgId.
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('ptt_trans_result', (event) => {
|
||||
deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
|
||||
}),
|
||||
);
|
||||
|
||||
return () => {
|
||||
for (const dispose of disposers) {
|
||||
@@ -58,10 +73,37 @@ const NOTICE_KINDS = [
|
||||
'group_msg_emoji_like',
|
||||
] as const satisfies readonly QQEventVariant['kind'][];
|
||||
|
||||
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
|
||||
async function convertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
|
||||
// Inbound choke point — the receive-side mirror of the outbound api-handler.
|
||||
// Correlate the whole receive chain (decode → convert, incl. any rkey-fetch
|
||||
// packets the conversion triggers, → dispatch) under one [req#N]. Only pay
|
||||
// the AsyncLocalStorage wrap + id when trace is actually live.
|
||||
if (getLogLevel() !== 'trace') {
|
||||
await runConvertAndDispatch(ctx, log, event);
|
||||
return;
|
||||
}
|
||||
await runWithRequestId(nextRequestId(), () => runConvertAndDispatch(ctx, log, event));
|
||||
}
|
||||
|
||||
async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
|
||||
// Raw inbound event, memory-only (trace). Lazy → the deep render runs only
|
||||
// when trace is live.
|
||||
log.trace(() => [`recv ${event.kind} ⇐ %s`, renderParamsVerbose(event)]);
|
||||
const startedAt = Date.now();
|
||||
const converted = await convertEvent(ctx.converterCtx, event);
|
||||
if (!converted) return;
|
||||
if (!converted) {
|
||||
log.trace(() => [`recv ${event.kind} ⇒ dropped (${Date.now() - startedAt}ms)`]);
|
||||
return;
|
||||
}
|
||||
// If this message quotes one we don't have, fetch + persist it first (gated +
|
||||
// throttled) so a consumer's get_msg on the quote resolves. No-op for the
|
||||
// common case (no reply, or the quoted message is already stored). Never let a
|
||||
// back-fill failure block delivery of the live message.
|
||||
try {
|
||||
await backfillReplyTarget(ctx, event);
|
||||
} catch { /* best-effort — dispatch the live event regardless */ }
|
||||
ctx.dispatchEvent(converted);
|
||||
log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]);
|
||||
}
|
||||
|
||||
function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEventVariant, { kind: 'group_message' }>): void {
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
getStrangerInfo,
|
||||
} from './modules/contact-actions';
|
||||
import {
|
||||
fetchPttText as fetchPttTextAction,
|
||||
getImageInfo as getCachedImageInfo,
|
||||
getRecordInfo as getCachedRecordInfo,
|
||||
} from './modules/media-actions';
|
||||
@@ -25,8 +26,8 @@ import {
|
||||
deleteMessage,
|
||||
forwardSingleMessage,
|
||||
getForwardMessage,
|
||||
getFriendMsgHistory,
|
||||
getGroupMsgHistory,
|
||||
getFriendHistory,
|
||||
getGroupHistory,
|
||||
sendGroupForwardMessage,
|
||||
sendGroupMessage,
|
||||
sendPrivateForwardMessage,
|
||||
@@ -75,8 +76,8 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
|
||||
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
|
||||
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
|
||||
getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count),
|
||||
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
|
||||
getGroupMsgHistory: (groupId, messageId, count) => getGroupHistory(ref, groupId, messageId, count),
|
||||
getFriendMsgHistory: (userId, messageId, count) => getFriendHistory(ref, userId, messageId, count),
|
||||
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
|
||||
getDownloadRKeys: () => getDownloadRKeys(bridge),
|
||||
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
|
||||
@@ -114,8 +115,9 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
complete: cachedCount >= serverCount,
|
||||
};
|
||||
},
|
||||
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
|
||||
getImageInfo: (file) => getCachedImageInfo(mediaStore, file, ref.converterCtx.imageUrlResolver),
|
||||
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
|
||||
fetchPttText: (messageId) => fetchPttTextAction(messageStore, mediaStore, bridge, ref.selfId, messageId),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,10 @@ interface CachedRKey {
|
||||
|
||||
const RKEY_REFRESH_SKEW = 60;
|
||||
const RKEY_REFRESH_COOLDOWN = 30;
|
||||
// Upper bound on how long URL resolution may block on a refresh round-trip.
|
||||
// A stuck packet send must never wedge message conversion — past this we
|
||||
// fall back to whatever the cache holds (possibly nothing).
|
||||
const RKEY_REFRESH_TIMEOUT_MS = 5000;
|
||||
const PRIVATE_IMAGE_RKEY_TYPE = 10;
|
||||
const GROUP_IMAGE_RKEY_TYPE = 20;
|
||||
const PRIVATE_VIDEO_RKEY_TYPE = 12;
|
||||
@@ -26,31 +30,39 @@ const FALLBACK_IMAGE_RKEY_TYPE = 2;
|
||||
export class RKeyCache {
|
||||
private cache = new Map<number, CachedRKey>();
|
||||
private lastRefreshAttempt = 0;
|
||||
private refreshInflight: Promise<void> | null = null;
|
||||
|
||||
warmUp(bridge: BridgeInterface, uin: string): void {
|
||||
bridge.apis.contacts.fetchDownloadRKeys().then(
|
||||
(rkeys) => {
|
||||
this.updateCache(rkeys);
|
||||
log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length);
|
||||
},
|
||||
(err) => {
|
||||
log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
|
||||
},
|
||||
this.ensureFresh(bridge).then(
|
||||
() => log.info('rkeys loaded: UIN=%s count=%d', uin, this.cache.size),
|
||||
(err) => log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err)),
|
||||
);
|
||||
}
|
||||
|
||||
resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
|
||||
async resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise<string> {
|
||||
const url = element.imageUrl ?? '';
|
||||
if (!urlNeedsRKey(url)) return url;
|
||||
|
||||
const rkey = this.findRKey(bridge, isGroup);
|
||||
// The rkey scene must follow the IMAGE's own upload context, not the
|
||||
// message currently carrying it. A c2c image forwarded into a group
|
||||
// keeps its original c2c fileid/appid (1406); signing it with the
|
||||
// group rkey just because the forward node looks like a group message
|
||||
// yields `invalid rkey` on download. So derive the scene from the
|
||||
// appid baked into the URL, and only fall back to `isGroup` when the
|
||||
// URL carries no recognised appid (legacy gchat / unknown shapes).
|
||||
// Mirrors NapCat's getImageUrlFromParsedUrl (appid 1406 → private,
|
||||
// 1407 → group).
|
||||
const primaryType = imageRKeyTypeFromUrl(url)
|
||||
?? (isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE);
|
||||
const rkey = await this.findRKeyForType(bridge, primaryType);
|
||||
if (!rkey) return url;
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
|
||||
return url + separator + encodeURIComponent(cleanRKey);
|
||||
}
|
||||
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
|
||||
|
||||
async resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise<string> {
|
||||
const url = element.url ?? '';
|
||||
if (!url || !urlNeedsRKey(url)) return url;
|
||||
|
||||
@@ -65,7 +77,7 @@ export class RKeyCache {
|
||||
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
}
|
||||
|
||||
const rkey = this.findRKeyForType(bridge, primaryType);
|
||||
const rkey = await this.findRKeyForType(bridge, primaryType);
|
||||
if (!rkey) return url;
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
@@ -89,33 +101,79 @@ export class RKeyCache {
|
||||
}
|
||||
}
|
||||
|
||||
private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null {
|
||||
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
return this.findRKeyForType(bridge, primaryType);
|
||||
}
|
||||
|
||||
private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null {
|
||||
/** Pull a still-valid rkey out of the cache, or null if missing/expiring. */
|
||||
private findInCache(primaryType: number): string | null {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
const tryFind = (type: number): string | null => {
|
||||
const cached = this.cache.get(type);
|
||||
if (!cached || !cached.value) return null;
|
||||
if (cached.expiresAt !== 0 && now + RKEY_REFRESH_SKEW >= cached.expiresAt) return null;
|
||||
return cached.value;
|
||||
};
|
||||
|
||||
let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
if (result) return result;
|
||||
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null;
|
||||
this.lastRefreshAttempt = now;
|
||||
bridge.apis.contacts.fetchDownloadRKeys().then(
|
||||
(rkeys) => this.updateCache(rkeys),
|
||||
() => { /* ignore */ },
|
||||
);
|
||||
|
||||
result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
return result;
|
||||
return tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
|
||||
}
|
||||
|
||||
private async findRKeyForType(bridge: BridgeInterface, primaryType: number): Promise<string | null> {
|
||||
const cached = this.findInCache(primaryType);
|
||||
if (cached) return cached;
|
||||
|
||||
// Cache miss or inside the expiry skew: block on a fresh fetch rather
|
||||
// than hand back a URL with a stale/absent rkey — the CDN rejects those
|
||||
// with `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Mirrors NapCat's
|
||||
// getImageUrl path, which does `if (isExpired()) await refreshRkey()`
|
||||
// before building the URL instead of refreshing in the background.
|
||||
await this.ensureFresh(bridge);
|
||||
return this.findInCache(primaryType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the rkey cache via OIDB 0x9067_202, coalescing concurrent
|
||||
* callers onto one in-flight request and backing off for
|
||||
* RKEY_REFRESH_COOLDOWN after a failed attempt so a persistently
|
||||
* unreachable server isn't hammered once per inbound image. The await is
|
||||
* bounded by RKEY_REFRESH_TIMEOUT_MS.
|
||||
*/
|
||||
private async ensureFresh(bridge: BridgeInterface): Promise<void> {
|
||||
if (!this.refreshInflight) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return;
|
||||
this.lastRefreshAttempt = now;
|
||||
this.refreshInflight = bridge.apis.contacts.fetchDownloadRKeys()
|
||||
.then((rkeys) => { this.updateCache(rkeys); })
|
||||
.catch((err) => {
|
||||
log.warn('rkey refresh failed: %s', err instanceof Error ? err.message : String(err));
|
||||
})
|
||||
.finally(() => { this.refreshInflight = null; });
|
||||
}
|
||||
|
||||
const inflight = this.refreshInflight;
|
||||
if (!inflight) return;
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<void>((resolve) => { timer = setTimeout(resolve, RKEY_REFRESH_TIMEOUT_MS); });
|
||||
try {
|
||||
await Promise.race([inflight, timeout]);
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// QQ-NT download appids embedded in the image URL query string. The scene
|
||||
// they encode is a property of the image (where it was uploaded), so they
|
||||
// outrank the carrying message's group/private context — see resolveImageUrl.
|
||||
const APPID_PRIVATE_IMAGE = '1406';
|
||||
const APPID_GROUP_IMAGE = '1407';
|
||||
|
||||
/** Map the `appid` baked into an NT download URL to its rkey type. Returns
|
||||
* null when the URL carries no recognised appid, leaving the caller to fall
|
||||
* back to the message's group/private context. */
|
||||
function imageRKeyTypeFromUrl(url: string): number | null {
|
||||
const match = url.match(/[?&]appid=(\d+)/);
|
||||
if (!match) return null;
|
||||
if (match[1] === APPID_PRIVATE_IMAGE) return PRIVATE_IMAGE_RKEY_TYPE;
|
||||
if (match[1] === APPID_GROUP_IMAGE) return GROUP_IMAGE_RKEY_TYPE;
|
||||
return null;
|
||||
}
|
||||
|
||||
function urlNeedsRKey(url: string): boolean {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format';
|
||||
import path from 'path';
|
||||
import { ApiHandler } from './api-handler';
|
||||
import { ApiHandler, type ActionObserver } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
@@ -12,16 +12,19 @@ import { MediaStore } from './media-store';
|
||||
import { MediaUrlResolver } from './media-url-resolver';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import { MessageStore } from './message-store';
|
||||
import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions';
|
||||
import { buildStatusText, matchesStatusCommand, statusCooldownElapsed } from './modules/status-command';
|
||||
import {
|
||||
HttpPostAdapter,
|
||||
HttpServerAdapter,
|
||||
OneBotNetworkManager,
|
||||
WsClientAdapter,
|
||||
WsServerAdapter,
|
||||
type AdapterStatus,
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { ReactionStore } from './reaction-store';
|
||||
import type { JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
|
||||
import type { ApiResponse, JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
@@ -36,6 +39,11 @@ export class OneBotInstance {
|
||||
private readonly reactionStore: ReactionStore;
|
||||
private readonly networkManager: OneBotNetworkManager;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
private readonly ctx: OneBotInstanceContext;
|
||||
/** Process-uptime baseline for the `#sl` status reply. */
|
||||
private readonly startedAt = Date.now();
|
||||
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
|
||||
private readonly statusCommandCooldown = new Map<string, number>();
|
||||
private disposeEventPipeline: (() => void) | null = null;
|
||||
|
||||
private readonly pids = new Set<number>();
|
||||
@@ -46,6 +54,25 @@ export class OneBotInstance {
|
||||
|
||||
get nickname(): string { return this.bridge.identity.nickname; }
|
||||
|
||||
/** Live status of this account's OneBot network adapters. */
|
||||
getConnectionStatuses(): AdapterStatus[] {
|
||||
return this.networkManager.describeStatuses();
|
||||
}
|
||||
|
||||
// ── Debug taps (WebUI debug stream / tester) ──
|
||||
/** Tap every emitted OneBot event for this account. Returns an unsubscribe. */
|
||||
subscribeDebugEvents(cb: (event: JsonObject) => void): () => void {
|
||||
return this.networkManager.subscribeDebug(cb);
|
||||
}
|
||||
/** Observe every handled action for this account. Returns an unsubscribe. */
|
||||
observeActions(cb: ActionObserver): () => void {
|
||||
return this.apiHandler.setObserver(cb);
|
||||
}
|
||||
/** Invoke an OneBot action against this account (debug tester). */
|
||||
invokeAction(action: string, params: JsonObject): Promise<ApiResponse> {
|
||||
return this.apiHandler.handle(action, params);
|
||||
}
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
@@ -84,6 +111,7 @@ export class OneBotInstance {
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
dispatchEvent: (event) => this.dispatchEvent(event),
|
||||
};
|
||||
this.ctx = ctx;
|
||||
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
|
||||
this.networkManager = new OneBotNetworkManager();
|
||||
@@ -98,6 +126,9 @@ export class OneBotInstance {
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
// Keep the shared context's config in sync so live readers (e.g. the
|
||||
// `#sl` handler reading `statusCommand`) pick up edits without a restart.
|
||||
this.ctx.config = config;
|
||||
void this.applyConfigDiff(config).catch((err) => {
|
||||
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
@@ -139,11 +170,53 @@ export class OneBotInstance {
|
||||
private dispatchEvent(event: JsonObject): void {
|
||||
this.cacheMessageEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// Built-in `#sl`: always cache + log first (a swallowed `#sl` is still
|
||||
// observable locally); only forwarding to downstream adapters is gated.
|
||||
if (this.handleStatusCommand(event)) return;
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Built-in `#sl` status command. Returns `true` when the event matched AND
|
||||
* `swallow` is configured — the caller then skips `emitEvent` so downstream
|
||||
* adapters never see it. The reply itself is fired async and rate-limited
|
||||
* per conversation; matching and replying are independent of swallowing.
|
||||
*/
|
||||
private handleStatusCommand(event: JsonObject): boolean {
|
||||
const cfg = this.ctx.config.statusCommand;
|
||||
if (!cfg.enabled) return false;
|
||||
const postType = event.post_type;
|
||||
if (postType !== 'message' && postType !== 'message_sent') return false;
|
||||
if (!matchesStatusCommand(event.message)) return false;
|
||||
|
||||
const isGroup = event.message_type === 'group';
|
||||
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);
|
||||
if (sessionId === 0) return cfg.swallow;
|
||||
|
||||
const key = `${isGroup ? 'g' : 'p'}:${sessionId}`;
|
||||
const now = Date.now();
|
||||
if (statusCooldownElapsed(this.statusCommandCooldown.get(key), now, cfg.cooldownSeconds)) {
|
||||
this.statusCommandCooldown.set(key, now);
|
||||
void this.replyStatus(isGroup, sessionId).catch((err) => {
|
||||
this.log.warn('status command reply failed: %s', err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
}
|
||||
return cfg.swallow;
|
||||
}
|
||||
|
||||
private async replyStatus(isGroup: boolean, sessionId: number): Promise<void> {
|
||||
const text = buildStatusText({
|
||||
version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev',
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
uptimeMs: Date.now() - this.startedAt,
|
||||
});
|
||||
if (isGroup) await sendGroupMessage(this.ctx, sessionId, text, true);
|
||||
else await sendPrivateMessage(this.ctx, sessionId, text, true);
|
||||
}
|
||||
|
||||
private buildNetworkContext(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: this.uin,
|
||||
|
||||
@@ -3,19 +3,27 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { BridgeManager } from '@snowluma/core/manager';
|
||||
import { loadOneBotConfig } from './config';
|
||||
import { OneBotInstance } from './instance';
|
||||
import type { AdapterStatus } from './network';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
||||
|
||||
/** Per-account OneBot connection health, surfaced to the WebUI dashboard. */
|
||||
export interface AccountConnections {
|
||||
uin: string;
|
||||
nickname: string;
|
||||
adapters: AdapterStatus[];
|
||||
}
|
||||
|
||||
export class OneBotManager {
|
||||
private readonly instances = new Map<string, OneBotInstance>();
|
||||
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.setSessionStartedCallback((uin, bridge) => {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => {
|
||||
this.onSessionStarted(uin, bridge);
|
||||
});
|
||||
|
||||
bridgeManager.setSessionClosedCallback((uin) => {
|
||||
bridgeManager.addSessionClosedListener((uin) => {
|
||||
this.onSessionClosed(uin);
|
||||
});
|
||||
}
|
||||
@@ -28,6 +36,15 @@ export class OneBotManager {
|
||||
return [...this.instances.values()];
|
||||
}
|
||||
|
||||
/** Live OneBot adapter status for every account, for the WebUI dashboard. */
|
||||
getConnectionStatuses(): AccountConnections[] {
|
||||
return this.getInstances().map((i) => ({
|
||||
uin: i.uin,
|
||||
nickname: i.nickname,
|
||||
adapters: i.getConnectionStatuses(),
|
||||
}));
|
||||
}
|
||||
|
||||
reloadConfig(uin: string): boolean {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return false;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
|
||||
export interface CachedImage {
|
||||
@@ -62,17 +62,17 @@ const TYPE_VIDEO = 'video';
|
||||
const DEFAULT_KEEP_ENTRIES = 4096;
|
||||
|
||||
export class MediaStore {
|
||||
private readonly db: DatabaseType;
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly maxEntriesPerType: number;
|
||||
|
||||
// Prepared statements (pay the parsing cost once at startup).
|
||||
private readonly upsertEntry: Statement;
|
||||
private readonly upsertKey: Statement;
|
||||
private readonly findEntryByKey: Statement;
|
||||
private readonly findEntryByPrimary: Statement;
|
||||
private readonly evictByType: Statement;
|
||||
private readonly purgeOrphanKeys: Statement;
|
||||
private readonly countByType: Statement;
|
||||
private readonly upsertEntry: StatementSync;
|
||||
private readonly upsertKey: StatementSync;
|
||||
private readonly findEntryByKey: StatementSync;
|
||||
private readonly findEntryByPrimary: StatementSync;
|
||||
private readonly evictByType: StatementSync;
|
||||
private readonly purgeOrphanKeys: StatementSync;
|
||||
private readonly countByType: StatementSync;
|
||||
|
||||
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
|
||||
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
|
||||
@@ -80,9 +80,9 @@ export class MediaStore {
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
this.upsertEntry = this.db.prepare(
|
||||
|
||||
@@ -23,6 +23,20 @@ function intOr(value: unknown, fallback = 0): number {
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
}
|
||||
|
||||
/** Build a market-face (`mface`) element from an OneBot segment's data.
|
||||
* Shared by the dedicated `mface` segment and the `image`-with-`emoji_id`
|
||||
* round-trip path. `emojiId` is the hex GUID the wire builder converts back
|
||||
* to `MarketFace.faceId`. */
|
||||
function marketFaceElement(emojiId: string, data: Record<string, unknown>): MessageElement {
|
||||
return {
|
||||
type: 'mface',
|
||||
text: String(data.summary ?? data.name ?? ''),
|
||||
emojiId,
|
||||
emojiPackageId: intOr(data.emoji_package_id ?? data.tab_id, 0),
|
||||
emojiKey: String(data.key ?? ''),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseCQParams(raw: string): Record<string, string> {
|
||||
const params: Record<string, string> = {};
|
||||
if (!raw) return params;
|
||||
@@ -114,6 +128,11 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
return id > 0 ? { type: 'reply', replySeq: id } : null;
|
||||
}
|
||||
case 'image': {
|
||||
// A market face that was surfaced as an `image` (see to-segment) can be
|
||||
// echoed straight back: when `emoji_id` is present we rebuild the market
|
||||
// face instead of re-uploading the gif as a plain picture.
|
||||
const imgEmojiId = String(data.emoji_id ?? '').trim();
|
||||
if (imgEmojiId) return marketFaceElement(imgEmojiId, data);
|
||||
return {
|
||||
type: 'image',
|
||||
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
|
||||
@@ -122,6 +141,16 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
summary: data.summary ? String(data.summary) : undefined,
|
||||
};
|
||||
}
|
||||
case 'mface': {
|
||||
// Market face (商城表情). emoji_id is the hex GUID; without it we can't
|
||||
// construct the wire element, so drop the segment.
|
||||
const emojiId = String(data.emoji_id ?? '').trim();
|
||||
if (!emojiId) {
|
||||
log.warn('[MsgParser] mface segment without emoji_id is unsupported');
|
||||
return null;
|
||||
}
|
||||
return marketFaceElement(emojiId, data);
|
||||
}
|
||||
case 'record': {
|
||||
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
|
||||
if (!source) return null;
|
||||
@@ -288,8 +317,9 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
}
|
||||
case 'file': {
|
||||
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
|
||||
if (!fileId) {
|
||||
log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)');
|
||||
const source = String(data.file ?? data.url ?? data.path ?? '').trim();
|
||||
if (!fileId && !source) {
|
||||
log.warn('[MsgParser] file segment without file_id or file/url is unsupported');
|
||||
return null;
|
||||
}
|
||||
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
|
||||
@@ -297,7 +327,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
|
||||
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
|
||||
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
|
||||
const elem: MessageElement = { type: 'file', fileId };
|
||||
const elem: MessageElement = fileId ? { type: 'file', fileId } : { type: 'file', url: source };
|
||||
if (fileName) elem.fileName = fileName;
|
||||
if (fileSize > 0) elem.fileSize = fileSize;
|
||||
if (md5Hex) elem.md5Hex = md5Hex;
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
import type { JsonObject, MessageMeta } from './types';
|
||||
|
||||
export class MessageStore {
|
||||
private readonly db: DatabaseType;
|
||||
private readonly stmtStoreEvent: Statement;
|
||||
private readonly stmtStoreMeta: Statement;
|
||||
private readonly stmtFindEvent: Statement;
|
||||
private readonly stmtFindMeta: Statement;
|
||||
private readonly stmtResolveReplyGroup: Statement;
|
||||
private readonly stmtResolveReplyPrivate: Statement;
|
||||
private readonly stmtListEventsAnchored: Statement;
|
||||
private readonly stmtListEventsLatest: Statement;
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly stmtStoreEvent: StatementSync;
|
||||
private readonly stmtStoreMeta: StatementSync;
|
||||
private readonly stmtFindEvent: StatementSync;
|
||||
private readonly stmtFindMeta: StatementSync;
|
||||
private readonly stmtResolveReplyGroup: StatementSync;
|
||||
private readonly stmtResolveReplyPrivate: StatementSync;
|
||||
private readonly stmtListEventsAnchored: StatementSync;
|
||||
private readonly stmtListEventsLatest: StatementSync;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
@@ -20,9 +20,9 @@ export class MessageStore {
|
||||
|
||||
// Replace .json extension with .db if present
|
||||
const finalPath = dbPath.replace(/\.json$/, '.db');
|
||||
this.db = new Database(finalPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(finalPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
// Prepare once. Statements survive for the lifetime of the
|
||||
|
||||
@@ -53,6 +53,13 @@ export async function getGroupList(
|
||||
}));
|
||||
}
|
||||
|
||||
// Short-TTL cache for the non-member group lookup (0x88D_0). Joined groups come
|
||||
// from the identity roster (kept fresh by fetchGroupList) and are NOT cached
|
||||
// here; this only memoizes the per-id server query so a burst of invites for the
|
||||
// same group doesn't hammer 0x88D_0 (which would risk a rate-limit / kick).
|
||||
const NON_MEMBER_GROUP_TTL_MS = 5 * 60 * 1000;
|
||||
const nonMemberGroupCache = new Map<number, { info: JsonObject; at: number }>();
|
||||
|
||||
export async function getGroupInfo(
|
||||
bridge: BridgeInterface,
|
||||
groupId: number,
|
||||
@@ -66,13 +73,37 @@ export async function getGroupInfo(
|
||||
}
|
||||
}
|
||||
const g = bridge.identity.findGroup(groupId);
|
||||
if (!g) return null;
|
||||
return {
|
||||
group_id: g.groupId,
|
||||
group_name: g.groupName,
|
||||
member_count: g.memberCount,
|
||||
max_member_count: g.memberMax,
|
||||
};
|
||||
if (g) {
|
||||
return {
|
||||
group_id: g.groupId,
|
||||
group_name: g.groupName,
|
||||
member_count: g.memberCount,
|
||||
max_member_count: g.memberMax,
|
||||
};
|
||||
}
|
||||
|
||||
// Not a joined group — fall back to the by-id server lookup so a group invite
|
||||
// can still resolve its name. Cached with a short TTL (skipped when noCache).
|
||||
if (!noCache) {
|
||||
const cached = nonMemberGroupCache.get(groupId);
|
||||
if (cached && Date.now() - cached.at < NON_MEMBER_GROUP_TTL_MS) return { ...cached.info };
|
||||
}
|
||||
try {
|
||||
const detail = await bridge.apis.contacts.fetchGroupDetail(groupId);
|
||||
if (detail) {
|
||||
const info: JsonObject = {
|
||||
group_id: detail.groupId,
|
||||
group_name: detail.groupName,
|
||||
member_count: detail.memberCount,
|
||||
max_member_count: detail.memberMax,
|
||||
};
|
||||
nonMemberGroupCache.set(groupId, { info, at: Date.now() });
|
||||
return { ...info };
|
||||
}
|
||||
} catch {
|
||||
// Server lookup failed (no such group / denied) — fall through to null.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function getGroupMemberList(
|
||||
|
||||
@@ -1,17 +1,106 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import type { ImageUrlResolver } from '../event-converter';
|
||||
import type { MediaStore } from '../media-store';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import {
|
||||
deliverPttTransText,
|
||||
failPttTransWaiter,
|
||||
pttTransKey,
|
||||
waitPttTransText,
|
||||
} from './ptt-trans-waiter';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
/**
|
||||
* Voice-to-text for a received ptt (issue #79 / NapCat `fetch_ptt_text`).
|
||||
* Resolves the message's `record` segment to its cached fingerprint
|
||||
* (uuid + md5 + duration/size/format), then drives QQ's native
|
||||
* `pttTrans.Trans{C2C,Group}PttReq` via the bridge and returns the text.
|
||||
*/
|
||||
export async function fetchPttText(
|
||||
messageStore: MessageStore,
|
||||
mediaStore: MediaStore,
|
||||
bridge: BridgeInterface,
|
||||
selfId: number,
|
||||
messageId: number,
|
||||
): Promise<{ text: string }> {
|
||||
const event = messageStore.findEvent(messageId);
|
||||
if (!event) throw new Error('消息不存在或已被撤回');
|
||||
|
||||
const segments = Array.isArray(event.message) ? event.message : [];
|
||||
let file = '';
|
||||
for (const seg of segments) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const so = seg as JsonObject;
|
||||
if (so.type !== 'record') continue;
|
||||
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) ? so.data as JsonObject : {};
|
||||
file = String(data.file ?? data.url ?? '');
|
||||
break;
|
||||
}
|
||||
if (!file) throw new Error('消息中不包含语音');
|
||||
|
||||
const cached = mediaStore.findRecord(file);
|
||||
if (!cached) throw new Error('语音不在缓存中,无法转写');
|
||||
|
||||
const isGroup = event.message_type === 'group' || cached.isGroup;
|
||||
const senderUin = Number(event.user_id) || 0;
|
||||
// c2c: receiver is self (inbound voice); group: the group uin.
|
||||
const peerUin = isGroup ? (Number(event.group_id) || cached.sessionId) : selfId;
|
||||
|
||||
// Register the waiter BEFORE triggering, so a fast async push can't race
|
||||
// ahead of us. The trigger response may carry the text inline (already
|
||||
// transcribed) — settle immediately then; otherwise the Event 0x210
|
||||
// subType-61 push resolves the waiter via the event-pipeline subscription.
|
||||
const key = pttTransKey(selfId, messageId);
|
||||
const waiter = waitPttTransText(key, 20000);
|
||||
try {
|
||||
const syncText = await bridge.apis.extras.translatePttToText({
|
||||
isGroup,
|
||||
msgId: messageId,
|
||||
senderUin,
|
||||
peerUin,
|
||||
uuid: cached.fileId || '',
|
||||
md5Hex: cached.md5Hex ?? '',
|
||||
duration: cached.duration ?? 0,
|
||||
size: cached.fileSize ?? 0,
|
||||
format: cached.voiceFormat ?? 0,
|
||||
});
|
||||
if (syncText) deliverPttTransText(key, syncText);
|
||||
} catch (e) {
|
||||
failPttTransWaiter(key, e instanceof Error ? e : new Error(String(e)));
|
||||
}
|
||||
return { text: await waiter };
|
||||
}
|
||||
|
||||
export async function getImageInfo(
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
imageUrlResolver?: ImageUrlResolver | null,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findImage(file);
|
||||
if (!cached) return null;
|
||||
const url = cached.url || cached.imageUrl || '';
|
||||
|
||||
let url = cached.url || cached.imageUrl || '';
|
||||
|
||||
// Re-sign with a current rkey at lookup time. The stored `url` was signed
|
||||
// when the message first arrived and its rkey may have since expired — the
|
||||
// CDN then rejects the download with
|
||||
// `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw
|
||||
// (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which
|
||||
// re-signs on every getImageUrl call instead of handing back a baked URL.
|
||||
if (imageUrlResolver && cached.imageUrl) {
|
||||
try {
|
||||
const element: MessageElement = { type: 'image', imageUrl: cached.imageUrl, subType: cached.subType };
|
||||
const fresh = await imageUrlResolver(element, cached.isGroup);
|
||||
if (fresh) url = fresh;
|
||||
} catch {
|
||||
// Best-effort: fall back to the stored URL on any resolver failure.
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
|
||||
import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import type { MessageSendResult } from '../api-handler';
|
||||
import { elementsToOneBotSegments } from '../event-converter';
|
||||
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
|
||||
import { segmentsToRawMessage } from '../helper/cq';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
|
||||
@@ -64,6 +64,201 @@ export async function getFriendMsgHistory(
|
||||
.map(sanitizeMessageEventForApi);
|
||||
}
|
||||
|
||||
// Deps the server-backed history fetch needs from the instance context.
|
||||
interface HistoryRef {
|
||||
bridge: BridgeInterface;
|
||||
messageStore: MessageStore;
|
||||
converterCtx: ConverterContext;
|
||||
selfId: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Group history, fetched from the server (`SsoGetGroupMsg`) instead of only the
|
||||
* local observed-message store — so it can return messages SnowLuma never saw
|
||||
* live, and (because each fetched message is persisted) reply / get_msg on old
|
||||
* messages start working too. Resolves the anchor sequence from the requested
|
||||
* message_id (or the latest observed message), then asks the bridge for the
|
||||
* `count` messages ending there. Falls back to the local store if the server
|
||||
* fetch is unavailable or empty.
|
||||
*/
|
||||
export async function getGroupHistory(
|
||||
ref: HistoryRef,
|
||||
groupId: number,
|
||||
messageId: number | undefined,
|
||||
count: number | undefined,
|
||||
): Promise<JsonObject[]> {
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) return [];
|
||||
const want = normalizeHistoryCount(count);
|
||||
|
||||
let anchorSeq = 0;
|
||||
if (Number.isInteger(messageId) && messageId !== 0) {
|
||||
const meta = ref.messageStore.findMeta(messageId as number);
|
||||
if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) {
|
||||
// Anchor we don't know — best effort from the local store.
|
||||
return getGroupMsgHistory(ref.messageStore, groupId, messageId, count);
|
||||
}
|
||||
anchorSeq = meta.sequence;
|
||||
} else {
|
||||
const latest = ref.messageStore.listSessionEvents(true, groupId, 1);
|
||||
anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0;
|
||||
}
|
||||
|
||||
if (anchorSeq > 0) {
|
||||
try {
|
||||
const events = await ref.bridge.apis.message.getGroupHistory(groupId, anchorSeq, want, ref.selfId);
|
||||
const out: JsonObject[] = [];
|
||||
for (const ev of events) {
|
||||
const json = await convertEvent(ref.converterCtx, ev);
|
||||
if (!json || json.message_type !== 'group') continue;
|
||||
persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
|
||||
out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path)
|
||||
}
|
||||
if (out.length > 0) return out;
|
||||
} catch (err) {
|
||||
log.warn('group history server fetch failed (%s); using local store', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return getGroupMsgHistory(ref.messageStore, groupId, messageId, count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Private (c2c) history — the same server-fetch + persist pattern as
|
||||
* {@link getGroupHistory}, but via `SsoGetC2cMsg` (peer = the friend's UID,
|
||||
* resolved from the uin). The anchor is the message_id's sequence (any side of
|
||||
* the conversation) or the latest observed inbound message. Falls back to the
|
||||
* local store on unknown anchor / no uid / empty / error.
|
||||
*/
|
||||
export async function getFriendHistory(
|
||||
ref: HistoryRef,
|
||||
userId: number,
|
||||
messageId: number | undefined,
|
||||
count: number | undefined,
|
||||
): Promise<JsonObject[]> {
|
||||
if (!Number.isInteger(userId) || userId <= 0) return [];
|
||||
const want = normalizeHistoryCount(count);
|
||||
|
||||
let anchorSeq = 0;
|
||||
if (Number.isInteger(messageId) && messageId !== 0) {
|
||||
const meta = ref.messageStore.findMeta(messageId as number);
|
||||
// A c2c conversation seq is shared across both directions, but self-sent
|
||||
// messages are keyed under our own uin — so accept any private anchor by
|
||||
// sequence rather than requiring targetId === userId.
|
||||
if (!meta || meta.isGroup || meta.sequence <= 0) {
|
||||
return getFriendMsgHistory(ref.messageStore, userId, messageId, count);
|
||||
}
|
||||
anchorSeq = meta.sequence;
|
||||
} else {
|
||||
// Latest observed *inbound* message from this friend (self-sent messages
|
||||
// are keyed under our own uin, not the recipient, so the store can't give
|
||||
// "latest sent to this friend"). The c2c sequence is shared across both
|
||||
// directions, so the fetch window around this anchor still includes recent
|
||||
// self-sent messages — only ones strictly newer than the last inbound are
|
||||
// missed on the unparameterized first page (a paged client catches up).
|
||||
const latest = ref.messageStore.listSessionEvents(false, userId, 1);
|
||||
anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0;
|
||||
}
|
||||
|
||||
if (anchorSeq > 0) {
|
||||
try {
|
||||
const friendUid = await ref.bridge.resolveUserUid(userId);
|
||||
if (friendUid) {
|
||||
const events = await ref.bridge.apis.message.getC2cHistory(friendUid, anchorSeq, want, ref.selfId);
|
||||
const out: JsonObject[] = [];
|
||||
for (const ev of events) {
|
||||
const json = await convertEvent(ref.converterCtx, ev);
|
||||
if (!json || json.message_type !== 'private') continue;
|
||||
persistHistoryEvent(ref.messageStore, json);
|
||||
out.push(sanitizeMessageEventForApi(json));
|
||||
}
|
||||
if (out.length > 0) return out;
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('friend history server fetch failed (%s); using local store', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return getFriendMsgHistory(ref.messageStore, userId, messageId, count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Back-fill the message a freshly-received reply points to, when the local store
|
||||
* doesn't have the full event (e.g. a message from before SnowLuma was running,
|
||||
* or one it never observed). Fetches just the quoted message from the server —
|
||||
* group via `SsoGetGroupMsg`, c2c via `SsoGetC2cMsg`, both through the shared
|
||||
* history throttle gate — and persists it under the SAME id the reply resolves
|
||||
* to, so a subsequent `get_msg` (or quote lookup) hits.
|
||||
*
|
||||
* No-op when: the event isn't a group/friend message, has no reply, the target
|
||||
* is already stored, the uid can't be resolved, the fetch returns nothing, or
|
||||
* it errors. Meant to be awaited before dispatch so the consumer's get_msg —
|
||||
* which an approval bot fires right after seeing the reply — sees the message.
|
||||
*/
|
||||
export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant): Promise<void> {
|
||||
let isGroup: boolean;
|
||||
let session: number;
|
||||
if (event.kind === 'group_message') { isGroup = true; session = event.groupId; }
|
||||
else if (event.kind === 'friend_message') { isGroup = false; session = event.senderUin; }
|
||||
else return;
|
||||
if (!Number.isInteger(session) || session <= 0) return;
|
||||
|
||||
const reply = event.elements.find(
|
||||
(e: MessageElement) => e.type === 'reply' && Number.isInteger(e.replySeq) && (e.replySeq ?? 0) > 0,
|
||||
);
|
||||
const replySeq = reply?.replySeq ?? 0;
|
||||
if (replySeq <= 0) return;
|
||||
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const targetId = hashMessageIdInt32(replySeq, session, eventName);
|
||||
if (ref.messageStore.findEvent(targetId)) return; // already have the full event
|
||||
|
||||
try {
|
||||
let fetched: GroupMessage | FriendMessage | null;
|
||||
if (isGroup) {
|
||||
fetched = await ref.bridge.apis.message.getGroupMessageBySeq(session, replySeq, ref.selfId);
|
||||
} else {
|
||||
const friendUid = await ref.bridge.resolveUserUid(session);
|
||||
if (!friendUid) return;
|
||||
fetched = await ref.bridge.apis.message.getC2cMessageBySeq(friendUid, replySeq, ref.selfId);
|
||||
}
|
||||
if (!fetched) return;
|
||||
|
||||
const json = await convertEvent(ref.converterCtx, fetched);
|
||||
if (!json) return;
|
||||
// Key under the exact id the reply resolves to (and the reply's session) so
|
||||
// get_msg(targetId) hits regardless of who sent the quoted message: a c2c
|
||||
// message the bot itself sent converts with user_id=self and would
|
||||
// otherwise key under a different session than the reply's peer.
|
||||
json.message_id = targetId;
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, json);
|
||||
} catch (err) {
|
||||
log.warn('reply-target backfill failed (%s)', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
// Persist a converted history event so reply / get_msg / future listing resolve
|
||||
// it — keyed exactly like the live pipeline (group → group_id, private → the
|
||||
// sender uin carried in user_id).
|
||||
function persistHistoryEvent(store: MessageStore, event: JsonObject): void {
|
||||
const messageId = toHistInt(event.message_id);
|
||||
if (messageId === 0) return;
|
||||
const isGroup = event.message_type === 'group';
|
||||
const sessionId = isGroup ? toHistInt(event.group_id) : toHistInt(event.user_id);
|
||||
const sequence = toHistInt(event.message_seq);
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
if (sessionId === 0) return;
|
||||
store.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
|
||||
}
|
||||
|
||||
function toHistInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n)) return Math.trunc(n);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise<void> {
|
||||
if (meta.isGroup) {
|
||||
await bridge.apis.message.recallGroup(meta.targetId, meta.sequence);
|
||||
@@ -241,54 +436,40 @@ export async function sendPrivateMessage(
|
||||
// never mixed with the regular elements. We only need it for file
|
||||
// here — video/ARK/ptt already go through commonElem so the
|
||||
// element-builder handles them inline.
|
||||
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
|
||||
// Two sub-paths:
|
||||
// a) has url/path but no file_id → uploadPrivate() which internally calls sendC2cFile()
|
||||
// b) has file_id from a prior upload_private_file → sendC2cFile() only
|
||||
const allFileElements = elements.filter(e => e.type === 'file');
|
||||
const nonFileElements = elements.filter(e => e.type !== 'file');
|
||||
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
|
||||
log.warn('[OneBot] private file segment without file_id — skipped (upload first via upload_private_file)');
|
||||
}
|
||||
|
||||
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | undefined;
|
||||
if (nonFileElements.length > 0) {
|
||||
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
|
||||
logSentMessage(false, userId, nonFileElements);
|
||||
}
|
||||
if (fileElements.length > 0) {
|
||||
// C2C file send needs the recipient's UID — resolve once and reuse.
|
||||
if (allFileElements.length > 0) {
|
||||
const userUid = await ref.bridge.resolveUserUid(userId);
|
||||
if (!userUid) {
|
||||
throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
|
||||
}
|
||||
for (const fileEl of fileElements) {
|
||||
// C2C file send requires fileSize/fileMd5/fileName to ride on the
|
||||
// wire (NotOnlineFile inside msgContent). The OneBot caller
|
||||
// usually only echoes the file_id from a previous
|
||||
// `upload_private_file`, so look up the rest from the upload
|
||||
// cache. Inline segment fields (md5/size/name) take precedence so
|
||||
// a caller that already knows everything can bypass the cache.
|
||||
const cached = ref.bridge.recallUploadedFile(fileEl.fileId!);
|
||||
const fileMd5 = fileEl.md5Hex
|
||||
? Buffer.from(fileEl.md5Hex, 'hex')
|
||||
: (cached?.fileMd5 ?? new Uint8Array(0));
|
||||
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
|
||||
// Fall back to a generic name — the QQ server resolves the
|
||||
// file by fileUuid, not name, so a missing name only affects
|
||||
// the chat bubble display.
|
||||
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
|
||||
const fileHash = fileEl.fileHash ?? cached?.fileHash;
|
||||
if (fileSize === 0 && !cached) {
|
||||
log.warn(
|
||||
'[OneBot] c2c file_id=%s sent without fileSize and no upload cache — recipient may see 0 B',
|
||||
fileEl.fileId,
|
||||
);
|
||||
if (!userUid) throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
|
||||
for (const fileEl of allFileElements) {
|
||||
if (fileEl.url && !fileEl.fileId) {
|
||||
// uploadPrivate() already calls sendC2cFile() internally — do NOT call it again.
|
||||
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
|
||||
await ref.bridge.apis.groupFile.uploadPrivate(userId, fileEl.url, name, true);
|
||||
logSentMessage(false, userId, [fileEl]);
|
||||
if (!lastReceipt) {
|
||||
lastReceipt = { messageId: 0, sequence: 0, clientSequence: 0, random: 0, timestamp: Math.floor(Date.now() / 1000) };
|
||||
}
|
||||
} else if (fileEl.fileId) {
|
||||
const cached = ref.bridge.recallUploadedFile(fileEl.fileId);
|
||||
const fileMd5 = fileEl.md5Hex ? Buffer.from(fileEl.md5Hex, 'hex') : (cached?.fileMd5 ?? new Uint8Array(0));
|
||||
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
|
||||
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
|
||||
const fileHash = fileEl.fileHash ?? cached?.fileHash;
|
||||
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId, fileName, fileSize, fileMd5, fileHash });
|
||||
logSentMessage(false, userId, [fileEl]);
|
||||
} else {
|
||||
log.warn('[OneBot] private file segment without file_id or url — skipped');
|
||||
}
|
||||
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, {
|
||||
fileId: fileEl.fileId!,
|
||||
fileName,
|
||||
fileSize,
|
||||
fileMd5,
|
||||
fileHash,
|
||||
});
|
||||
logSentMessage(false, userId, [fileEl]);
|
||||
}
|
||||
}
|
||||
if (!lastReceipt) throw new Error('message is empty');
|
||||
@@ -345,47 +526,37 @@ export async function sendGroupMessage(
|
||||
});
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
// Group `{type:'file', file_id}` segments don't ride on the elems[]
|
||||
// pipeline either. The QQ-NT server rejects PbSendMsg with a
|
||||
// transElem(24) file payload (result=79); the correct send path is a
|
||||
// dedicated OIDB call (`OidbSvcTrpcTcp.0x6d9_4`) that publishes a
|
||||
// previously-uploaded file id as a chat bubble. Mirrors the c2c-file
|
||||
// split below (private path) — both must be peeled off before the
|
||||
// regular sendGroupMessage runs.
|
||||
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
|
||||
// Two sub-paths for group file segments:
|
||||
// a) has url/path but no file_id → upload() which internally calls publish()
|
||||
// b) has file_id from a prior upload_group_file → publish() only
|
||||
const allFileElements = elements.filter(e => e.type === 'file');
|
||||
const nonFileElements = elements.filter(e => e.type !== 'file');
|
||||
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
|
||||
log.warn('[OneBot] group file segment without file_id — skipped (upload first via upload_group_file)');
|
||||
}
|
||||
|
||||
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
|
||||
if (nonFileElements.length > 0) {
|
||||
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
|
||||
logSentMessage(true, groupId, nonFileElements);
|
||||
}
|
||||
for (const fileEl of fileElements) {
|
||||
// Group-file publish has no per-message sequence/random tuple to
|
||||
// hash a messageId from — OIDB 0x6d9_4 is fire-and-forget on the
|
||||
// wire. If this is the LAST element we still need a receipt so
|
||||
// the OneBot caller can cache the id; synthesise one from the
|
||||
// file_id hash + a fresh timestamp.
|
||||
await ref.bridge.apis.groupFile.publish(groupId, fileEl.fileId!);
|
||||
for (const fileEl of allFileElements) {
|
||||
let fileId: string;
|
||||
if (fileEl.url && !fileEl.fileId) {
|
||||
// upload() already calls publish() internally — do NOT call publish() again.
|
||||
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
|
||||
const result = await ref.bridge.apis.groupFile.upload(groupId, fileEl.url, name, '/', true);
|
||||
fileId = result.fileId ?? '';
|
||||
if (!fileId) { log.warn('[OneBot] group file auto-upload returned no file_id — skipped'); continue; }
|
||||
} else if (fileEl.fileId) {
|
||||
fileId = fileEl.fileId;
|
||||
await ref.bridge.apis.groupFile.publish(groupId, fileId);
|
||||
} else {
|
||||
log.warn('[OneBot] group file segment without file_id or url — skipped');
|
||||
continue;
|
||||
}
|
||||
logSentMessage(true, groupId, [fileEl]);
|
||||
if (!lastReceipt) {
|
||||
// Use a hash of the fileId as a stable pseudo-id; this gets
|
||||
// mixed with groupId in `hashMessageIdInt32` below.
|
||||
let h = 0;
|
||||
const s = fileEl.fileId ?? '';
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
h = ((h << 5) - h + s.charCodeAt(i)) | 0;
|
||||
}
|
||||
lastReceipt = {
|
||||
messageId: 0,
|
||||
sequence: h & 0x7FFFFFFF,
|
||||
clientSequence: 0,
|
||||
random: h & 0x7FFFFFFF,
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
for (let i = 0; i < fileId.length; i++) h = ((h << 5) - h + fileId.charCodeAt(i)) | 0;
|
||||
lastReceipt = { messageId: 0, sequence: h & 0x7FFFFFFF, clientSequence: 0, random: h & 0x7FFFFFFF, timestamp: Math.floor(Date.now() / 1000) };
|
||||
}
|
||||
}
|
||||
if (!lastReceipt) throw new Error('message is empty');
|
||||
@@ -675,7 +846,16 @@ export async function getForwardMessage(
|
||||
for (const node of nodes) {
|
||||
const isGroup = node.messageType === 'group' || (node.groupId !== undefined && node.groupId > 0);
|
||||
const sessionId = isGroup ? (node.groupId ?? 0) : node.userUin;
|
||||
const segments = await elementsToOneBotSegments(node.elements, isGroup, sessionId);
|
||||
// Route forward nodes through the SAME resolver-equipped conversion the
|
||||
// normal receive path uses (to-message.ts). Without the image/media URL
|
||||
// resolvers the segments come back with raw, rkey-less download URLs —
|
||||
// exactly issue #74 (`/get_forward_msg` image url 缺少 rkey). Image rkey
|
||||
// re-signing is scene-aware via the appid in the URL (see instance-rkey).
|
||||
const segments = await elementsToOneBotSegments(
|
||||
node.elements, isGroup, sessionId,
|
||||
ref.converterCtx.imageUrlResolver,
|
||||
ref.converterCtx.mediaUrlResolver,
|
||||
);
|
||||
|
||||
const sender: JsonObject = {
|
||||
user_id: node.userUin,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// Correlates an async voice-to-text result back to the fetch_ptt_text call
|
||||
// that triggered it. QQ delivers the text via an Event 0x210 subType-61 push
|
||||
// (decoded into a `ptt_trans_result` event), not in the request response — so
|
||||
// the action registers a waiter keyed by `${selfUin}:${msgId}`, fires the
|
||||
// trigger request, and the push subscription resolves the waiter by msgId.
|
||||
|
||||
interface Pending {
|
||||
resolve: (text: string) => void;
|
||||
reject: (err: Error) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const pending = new Map<string, Pending>();
|
||||
|
||||
export function pttTransKey(selfUin: number, msgId: number): string {
|
||||
return `${selfUin}:${msgId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a waiter for `key`'s transcription. Rejects after `timeoutMs`.
|
||||
* A new waiter for the same key supersedes (rejects) the previous one.
|
||||
*/
|
||||
export function waitPttTransText(key: string, timeoutMs: number): Promise<string> {
|
||||
const existing = pending.get(key);
|
||||
if (existing) {
|
||||
clearTimeout(existing.timer);
|
||||
pending.delete(key);
|
||||
existing.reject(new Error('语音转文字请求被新的请求取代'));
|
||||
}
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
if (pending.get(key)?.timer === timer) pending.delete(key);
|
||||
reject(new Error('语音转文字超时(未收到结果推送)'));
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
pending.set(key, { resolve, reject, timer });
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve a waiting fetch_ptt_text with the recognised text. No-op if none. */
|
||||
export function deliverPttTransText(key: string, text: string): void {
|
||||
const p = pending.get(key);
|
||||
if (!p) return;
|
||||
clearTimeout(p.timer);
|
||||
pending.delete(key);
|
||||
p.resolve(text);
|
||||
}
|
||||
|
||||
/** Reject a waiter (e.g. the trigger request itself failed). No-op if none. */
|
||||
export function failPttTransWaiter(key: string, err: Error): void {
|
||||
const p = pending.get(key);
|
||||
if (!p) return;
|
||||
clearTimeout(p.timer);
|
||||
pending.delete(key);
|
||||
p.reject(err);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
|
||||
/**
|
||||
* Hardcoded trigger for the built-in status command — exact match,
|
||||
* case-insensitive, after trimming. Intentionally NOT configurable: the
|
||||
* `statusCommand.enabled` toggle is the only knob (the gate is on/off, not
|
||||
* the word).
|
||||
*/
|
||||
export const STATUS_COMMAND_TRIGGER = '#sl';
|
||||
|
||||
/**
|
||||
* True iff `message` is exactly the trigger: a single `text` segment (or a
|
||||
* bare string for string-format adapters) whose trimmed, lowercased content
|
||||
* equals {@link STATUS_COMMAND_TRIGGER}.
|
||||
*
|
||||
* Reads the segment array rather than `raw_message` to avoid CQ-encoding
|
||||
* ambiguity, and rejects mixed-segment messages (`#sl` + image/at/reply) so
|
||||
* only a pure `#sl` triggers — no `startsWith`, so `#slogan` never matches.
|
||||
*/
|
||||
export function matchesStatusCommand(message: JsonValue | undefined): boolean {
|
||||
if (typeof message === 'string') {
|
||||
return normalize(message) === STATUS_COMMAND_TRIGGER;
|
||||
}
|
||||
if (!Array.isArray(message) || message.length !== 1) return false;
|
||||
const seg = message[0];
|
||||
if (!isObject(seg) || seg.type !== 'text') return false;
|
||||
const data = isObject(seg.data) ? seg.data : null;
|
||||
const text = data && typeof data.text === 'string' ? data.text : '';
|
||||
return normalize(text) === STATUS_COMMAND_TRIGGER;
|
||||
}
|
||||
|
||||
function normalize(s: string): string {
|
||||
return s.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a reply is allowed now given the last reply time + cooldown.
|
||||
* `cooldownSeconds <= 0` disables the cooldown entirely.
|
||||
*/
|
||||
export function statusCooldownElapsed(
|
||||
lastRepliedAtMs: number | undefined,
|
||||
nowMs: number,
|
||||
cooldownSeconds: number,
|
||||
): boolean {
|
||||
if (lastRepliedAtMs === undefined) return true;
|
||||
if (cooldownSeconds <= 0) return true;
|
||||
return nowMs - lastRepliedAtMs >= cooldownSeconds * 1000;
|
||||
}
|
||||
|
||||
export interface StatusInfo {
|
||||
version: string;
|
||||
platform: string;
|
||||
arch: string;
|
||||
uptimeMs: number;
|
||||
}
|
||||
|
||||
/** Render the public-safe `#sl` reply: version + platform/arch + uptime. */
|
||||
export function buildStatusText(info: StatusInfo): string {
|
||||
return [
|
||||
'SnowLuma 状态',
|
||||
`版本: ${info.version}`,
|
||||
`平台: ${info.platform}-${info.arch}`,
|
||||
`运行时长: ${formatUptime(info.uptimeMs)}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** Human-readable uptime (zh-CN), dropping leading zero units. */
|
||||
export function formatUptime(ms: number): string {
|
||||
const totalSec = Math.max(0, Math.floor(ms / 1000));
|
||||
const days = Math.floor(totalSec / 86400);
|
||||
const hours = Math.floor((totalSec % 86400) / 3600);
|
||||
const minutes = Math.floor((totalSec % 3600) / 60);
|
||||
const seconds = totalSec % 60;
|
||||
if (days > 0) return `${days}天 ${hours}小时 ${minutes}分钟`;
|
||||
if (hours > 0) return `${hours}小时 ${minutes}分钟`;
|
||||
if (minutes > 0) return `${minutes}分钟 ${seconds}秒`;
|
||||
return `${seconds}秒`;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { ApiHandler } from '../api-handler';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, NetworkBase } from '../types';
|
||||
@@ -16,16 +17,33 @@ export enum NetworkReloadType {
|
||||
Opened = 3,
|
||||
}
|
||||
|
||||
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled';
|
||||
|
||||
/** Live runtime status of a single network adapter, surfaced to the WebUI
|
||||
* dashboard (and the per-node config cards) so the gateway's own
|
||||
* connection health is visible. `detail` is a short human string, e.g.
|
||||
* "3 个客户端" / "重连中" / "上次推送失败 14:53:01". */
|
||||
export interface AdapterStatus {
|
||||
name: string;
|
||||
kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
|
||||
status: AdapterStatusLevel;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
readonly name: string;
|
||||
protected config: C;
|
||||
protected readonly ctx: NetworkAdapterContext;
|
||||
protected readonly log: Logger;
|
||||
protected isEnabled = false;
|
||||
|
||||
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
|
||||
constructor(name: string, config: C, ctx: NetworkAdapterContext, moduleLog?: Logger) {
|
||||
this.name = name;
|
||||
this.config = structuredClone(config);
|
||||
this.ctx = ctx;
|
||||
const base = moduleLog ?? createLogger('OneBot.Network');
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? base.child({ uin: uinNum }) : base;
|
||||
}
|
||||
|
||||
get isActive(): boolean { return this.isEnabled; }
|
||||
@@ -34,7 +52,63 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
|
||||
abstract open(): void | Promise<void>;
|
||||
abstract close(): void | Promise<void>;
|
||||
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
|
||||
|
||||
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
|
||||
|
||||
/** Report live connection health for the WebUI dashboard. */
|
||||
abstract describeStatus(): AdapterStatus;
|
||||
|
||||
// ── reload: shared hot-reload state machine (template method) ──────────
|
||||
//
|
||||
// All four adapters reconcile a live config swap identically: decide
|
||||
// whether the binding changed, whether the adapter should be enabled, and
|
||||
// then open/close to reach the target state. The skeleton lives here; the
|
||||
// three things that genuinely differ per adapter are the hooks below.
|
||||
//
|
||||
// NOTE: the returned `NetworkReloadType` is a *test-observability* seam.
|
||||
// The sole production caller (`instance.applyConfigDiff`) discards it —
|
||||
// it exists so tests can assert "which transition did this config cause"
|
||||
// without poking private state. Behaviour, not the label, is the contract.
|
||||
|
||||
/** Stable string identity of the bound resource (host:port / url / token …).
|
||||
* A change here means the live binding must be torn down and re-opened. */
|
||||
protected abstract bindingSignature(config: C): string;
|
||||
|
||||
/** Whether `config` should result in an enabled adapter. Defaults to the
|
||||
* `enabled` flag; client adapters also require a target `url`. */
|
||||
protected willEnable(config: C): boolean {
|
||||
return config.enabled !== false;
|
||||
}
|
||||
|
||||
/** Refresh derived state after `this.config` has been replaced (report
|
||||
* options, role, propagation to live connections). Default: nothing. */
|
||||
protected onConfigReplaced(_next: C): void { /* no-op */ }
|
||||
|
||||
async reload(next: C): Promise<NetworkReloadType> {
|
||||
const prevSig = this.bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = this.willEnable(next);
|
||||
|
||||
this.config = structuredClone(next);
|
||||
this.onConfigReplaced(next);
|
||||
|
||||
const sigChanged = prevSig !== this.bindingSignature(next);
|
||||
if (sigChanged && wasEnabled) {
|
||||
await this.close();
|
||||
if (willEnable) {
|
||||
await this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
await this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
await this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { HttpClientNetwork, JsonObject } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { executeQuickOperation } from './quick-operation';
|
||||
|
||||
const moduleLog = createLogger('OneBot.POST');
|
||||
@@ -14,19 +14,11 @@ const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private signature_: string;
|
||||
private readonly log: Logger;
|
||||
private lastDelivery: { at: number; ok: boolean } | null = null;
|
||||
|
||||
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
super(name, config, ctx, moduleLog);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.signature_ = bindingSignature(config);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
return this.isEnabled;
|
||||
}
|
||||
|
||||
open(): void {
|
||||
@@ -39,33 +31,25 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
this.isEnabled = false;
|
||||
}
|
||||
|
||||
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false && !!next.url;
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'httpClient', status: 'disabled', detail: '未启用' };
|
||||
if (!this.lastDelivery) return { name: this.name, kind: 'httpClient', status: 'ok', detail: '已启用' };
|
||||
const at = new Date(this.lastDelivery.at).toTimeString().slice(0, 8);
|
||||
return this.lastDelivery.ok
|
||||
? { name: this.name, kind: 'httpClient', status: 'ok', detail: `上次推送成功 ${at}` }
|
||||
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
|
||||
}
|
||||
|
||||
this.config = structuredClone(next);
|
||||
protected override bindingSignature(config: HttpClientNetwork): string {
|
||||
return `${config.url}#${config.accessToken ?? ''}#${config.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
|
||||
}
|
||||
|
||||
protected override willEnable(config: HttpClientNetwork): boolean {
|
||||
return config.enabled !== false && !!config.url;
|
||||
}
|
||||
|
||||
protected override onConfigReplaced(next: HttpClientNetwork): void {
|
||||
this.options = resolveReportOptions(next);
|
||||
const newSig = bindingSignature(next);
|
||||
const sigChanged = newSig !== this.signature_;
|
||||
this.signature_ = newSig;
|
||||
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
onEvent(event: JsonObject, payload: DispatchPayload): void {
|
||||
@@ -98,6 +82,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (response.ok) {
|
||||
this.lastDelivery = { at: Date.now(), ok: true };
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (contentType.includes('application/json')) {
|
||||
const body = await response.text();
|
||||
@@ -106,9 +91,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
if (this.isEnabled) {
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
@@ -126,10 +113,6 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
}
|
||||
}
|
||||
|
||||
function bindingSignature(net: HttpClientNetwork): string {
|
||||
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
|
||||
}
|
||||
|
||||
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
|
||||
const { createHmac } = await import('crypto');
|
||||
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
@@ -7,23 +7,17 @@ import {
|
||||
} from 'http';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private readonly log: Logger;
|
||||
private listening = false;
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
return this.isEnabled;
|
||||
super(name, config, ctx, moduleLog);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
@@ -36,35 +30,19 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
close(): void {
|
||||
if (!this.isEnabled && !this.server) return;
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
this.server?.close();
|
||||
this.server = null;
|
||||
}
|
||||
|
||||
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false;
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
|
||||
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||||
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
|
||||
}
|
||||
|
||||
this.config = structuredClone(next);
|
||||
|
||||
const sigChanged = prevSig !== bindingSignature(next);
|
||||
if (sigChanged && wasEnabled) {
|
||||
this.close();
|
||||
if (willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Reopened;
|
||||
}
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
if (!wasEnabled && willEnable) {
|
||||
this.open();
|
||||
return NetworkReloadType.Opened;
|
||||
}
|
||||
if (wasEnabled && !willEnable) {
|
||||
this.close();
|
||||
return NetworkReloadType.Closed;
|
||||
}
|
||||
return NetworkReloadType.Normal;
|
||||
protected override bindingSignature(config: HttpServerNetwork): string {
|
||||
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}`;
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
|
||||
@@ -76,6 +54,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
this.server = server;
|
||||
|
||||
server.on('listening', () => {
|
||||
this.listening = true;
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
@@ -85,6 +64,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
);
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
this.listening = false;
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
@@ -213,10 +193,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
}
|
||||
}
|
||||
|
||||
function bindingSignature(net: HttpServerNetwork): string {
|
||||
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`;
|
||||
}
|
||||
|
||||
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
export {
|
||||
IOneBotNetworkAdapter,
|
||||
NetworkReloadType,
|
||||
type AdapterStatus,
|
||||
type AdapterStatusLevel,
|
||||
type NetworkAdapterContext,
|
||||
} from './adapter';
|
||||
export { HttpPostAdapter } from './http-post-adapter';
|
||||
export { HttpServerAdapter } from './http-server-adapter';
|
||||
export { OneBotNetworkManager } from './network-manager';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { buildDispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, NetworkBase } from '../types';
|
||||
import { IOneBotNetworkAdapter } from './adapter';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter';
|
||||
|
||||
const log = createLogger('OneBot.Network');
|
||||
|
||||
@@ -9,6 +9,14 @@ type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
|
||||
|
||||
export class OneBotNetworkManager {
|
||||
private readonly adapters = new Map<string, AnyAdapter>();
|
||||
/** Debug-stream taps — notified for every emitted event regardless of adapter
|
||||
* state. Attached on-demand (ref-counted) by the WebUI debug stream. */
|
||||
private readonly debugSubscribers = new Set<(event: JsonObject) => void>();
|
||||
|
||||
subscribeDebug(cb: (event: JsonObject) => void): () => void {
|
||||
this.debugSubscribers.add(cb);
|
||||
return () => { this.debugSubscribers.delete(cb); };
|
||||
}
|
||||
|
||||
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
|
||||
const existing = this.adapters.get(adapter.name);
|
||||
@@ -30,6 +38,11 @@ export class OneBotNetworkManager {
|
||||
|
||||
list(): AnyAdapter[] { return [...this.adapters.values()]; }
|
||||
|
||||
/** Live status of every registered adapter, for the WebUI dashboard. */
|
||||
describeStatuses(): AdapterStatus[] {
|
||||
return this.list().map((a) => a.describeStatus());
|
||||
}
|
||||
|
||||
hasActiveAdapters(): boolean {
|
||||
for (const a of this.adapters.values()) if (a.isActive) return true;
|
||||
return false;
|
||||
@@ -70,6 +83,14 @@ export class OneBotNetworkManager {
|
||||
}
|
||||
|
||||
async emitEvent(event: JsonObject): Promise<void> {
|
||||
// Notify debug taps first — before the adapter check — so the debug stream
|
||||
// sees every event even when no adapter is connected. Never let a tap throw
|
||||
// into the dispatch path.
|
||||
if (this.debugSubscribers.size) {
|
||||
for (const cb of this.debugSubscribers) {
|
||||
try { cb(event); } catch (err) { log.warn('debug subscriber error: %s', errMessage(err)); }
|
||||
}
|
||||
}
|
||||
if (!this.hasActiveAdapters()) return;
|
||||
const payload = buildDispatchPayload(event);
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
|
||||
Loaded 100 of 249 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user