Compare commits
233 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
157cc90397 | ||
|
|
1bd126562f | ||
|
|
e160837f8b | ||
|
|
4593ba3340 | ||
|
|
45aae92af5 | ||
|
|
839de51519 | ||
|
|
11e7584d1c | ||
|
|
f470b7a10c | ||
|
|
8b87f80951 | ||
|
|
b135752577 | ||
|
|
fd2345b772 | ||
|
|
907cfddfa3 | ||
|
|
7f391e065e | ||
|
|
9efe16237d | ||
|
|
c7b7c0b323 | ||
|
|
e2415210cd | ||
|
|
127f2cd2d6 | ||
|
|
ebadfb968b | ||
|
|
bba9b82ce9 | ||
|
|
9d1e39f25f | ||
|
|
b9d8247309 | ||
|
|
95f24ffc4a | ||
|
|
870504ae3a | ||
|
|
d497f1e6c7 | ||
|
|
e406a3bc2b | ||
|
|
4d75dc9ae3 | ||
|
|
a704f12945 | ||
|
|
9e21c3a7ef | ||
|
|
9f2eb37232 | ||
|
|
b00f5ab759 | ||
|
|
5164ba9e39 | ||
|
|
094dc12f0c | ||
|
|
0083a8fb07 | ||
|
|
61b4bd04a6 | ||
|
|
d38a0a4c1b | ||
|
|
258b7e1e72 | ||
|
|
d0498de966 | ||
|
|
67c99e1e32 | ||
|
|
8c7efc34a9 | ||
|
|
f71ed2e4db | ||
|
|
552238fd04 | ||
|
|
e3a04858b4 | ||
|
|
3428d37764 | ||
|
|
7ea1ffb497 | ||
|
|
43cd4a0b99 | ||
|
|
b9a015a4aa | ||
|
|
c572cd498f | ||
|
|
9b787dfdc1 | ||
|
|
36d557e5ea | ||
|
|
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 |
40
.github/logo.svg
vendored
Normal file
40
.github/logo.svg
vendored
Normal file
@@ -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 |
43
.github/workflows/ci.yml
vendored
Normal file
43
.github/workflows/ci.yml
vendored
Normal file
@@ -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
|
||||
109
.github/workflows/mcp-npm-publish.yml
vendored
Normal file
109
.github/workflows/mcp-npm-publish.yml
vendored
Normal file
@@ -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}"
|
||||
@@ -285,3 +285,13 @@ git push origin v1.7.0 # → 仅触发 release.yml
|
||||
- 如果只是想确认"我这么改 OK 吗",欢迎开 draft PR,先把代码亮出来再讨论。
|
||||
|
||||
感谢你愿意花时间贡献 SnowLuma —— 这个项目能走多远,取决于你们每一个人。❄️
|
||||
|
||||
## 贡献的许可 / Licensing of contributions
|
||||
|
||||
当你提交 PR,即表示你的贡献按本项目的 [`LICENSE`](LICENSE)(SnowLuma 源码可见非商业许可)授权,且你声明你有权这么做、贡献为你的原创(若含第三方材料,请在 PR 中显著标注其来源与许可证)。
|
||||
|
||||
**你保留对自己贡献的版权**,同时**授予 SnowLumaDevs 一项永久、全球、免费、不可撤销、可再许可(sublicensable)的许可**,可使用、复制、修改、分发你的贡献并基于其制作衍生作品,**包括以本项目非商业许可之外的其他条款(含商业条款)再许可与分发**——以便项目方无需逐一回头征求同意,即可在获授权的商业场景中使用社区贡献。
|
||||
|
||||
By opening a PR, you agree your contribution is licensed under the project's [`LICENSE`](LICENSE); you represent that you have the right to submit it and that it is your own work (clearly identify any third-party material in the PR).
|
||||
|
||||
**You retain copyright in your contribution** and additionally grant SnowLumaDevs a **perpetual, worldwide, royalty-free, irrevocable, sublicensable license** to use, reproduce, modify, distribute, and create derivative works of your contribution, **including the right to relicense and distribute it under terms other than this project's non-commercial license (including commercial terms)** — so the project can use community contributions in authorized commercial scenarios without seeking each contributor's consent again.
|
||||
|
||||
90
EULA.md
Normal file
90
EULA.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# SnowLuma 最终用户许可协议(EULA)/ End-User License Agreement
|
||||
|
||||
- **生效日期 / Effective date:** 2026-06-19
|
||||
- **版本 / Version:** 1.0
|
||||
- **许可方 / Licensor:** SnowLumaDevs(联系方式 / Contact: motricseven@foxmail.com)
|
||||
|
||||
> 本协议以中文与英文两种语言提供。如两版本有冲突,**以中文版本为准**。
|
||||
> This Agreement is provided in Chinese and English. **In case of any conflict, the Chinese version prevails.**
|
||||
|
||||
---
|
||||
|
||||
## 中文版
|
||||
|
||||
### 1. 定义与接受
|
||||
1.1 "**本软件**"指 SnowLuma 软件及其官方发行包,包括可执行文件、原生模块(`snowluma-*.node`)、文档及相关组件。
|
||||
1.2 "**您**"指下载、安装、运行或以其他方式使用本软件的个人或实体。
|
||||
1.3 下载、安装、运行或使用本软件,即表示您已阅读、理解并同意受本协议约束。**若您不同意本协议,请勿使用本软件并删除其全部副本。**
|
||||
|
||||
### 2. 授权范围
|
||||
2.1 本软件的**源代码**依据 GNU Affero General Public License 第 3 版(AGPL-3.0)及其第 7 条附加许可(原生模块链接例外)授权,详见随附的 `LICENSE` 文件。
|
||||
2.2 本协议是针对**发行包(二进制)**的补充条款,就 AGPL 未涵盖之事项(接受方式、可接受使用、免责、专有组件、争议解决等)作出约定。
|
||||
2.3 **本协议不减损 AGPL 授予您的任何权利。** 对于您依 AGPL 单独获取、使用、修改或分发源代码的行为,本协议不附加任何限制。
|
||||
2.4 专有组件(见第 5 条)不属于 AGPL 授权范围,依其各自条款授权。
|
||||
|
||||
### 3. 免责声明
|
||||
3.1 **非官方、无隶属**:本软件是独立的第三方互操作性项目,与腾讯公司(Tencent)及 QQ **无任何隶属、合作、授权或背书关系**。"QQ""腾讯"等名称及标识为其各自所有者的商标。
|
||||
3.2 **用途**:本软件**仅供学习、研究与技术互操作之目的**提供。
|
||||
3.3 **合规义务**:您须自行确保对本软件的使用符合一切适用法律法规,以及您所接入平台的规定(包括但不限于《QQ 用户协议》与相关服务条款)。
|
||||
3.4 **按"现状"提供**:本软件按"**现状(AS-IS)**"及"**现有(AS-AVAILABLE)**"提供,不附带任何明示或默示的担保,包括但不限于对适销性、特定用途适用性、不侵权、可用性、准确性或不中断的担保。
|
||||
3.5 **责任限制**:在适用法律允许的最大范围内,对于因使用或无法使用本软件而导致的任何直接、间接、偶然、特殊、惩罚性或后果性损害(包括但不限于账号封禁或限制、数据丢失、利润或业务损失、服务中断),SnowLumaDevs **概不承担责任**。
|
||||
3.6 **风险自负**:您理解,使用非官方协议工具接入第三方平台**可能违反该平台条款并导致账号风险**,您**自愿承担**该等风险。
|
||||
|
||||
### 4. 可接受使用
|
||||
您**不得**将本软件用于:(a) 任何违法犯罪活动;(b) 未经授权访问、干扰或破坏任何系统或网络;(c) 发送垃圾信息、实施骚扰、欺诈或传播恶意内容;(d) 侵犯他人隐私、知识产权或其他合法权益;(e) 任何违反所接入平台服务条款的行为。
|
||||
|
||||
### 5. 专有组件
|
||||
5.1 本软件可能包含或依赖**非开源的专有组件**,包括但不限于 **SnowLuma 原生模块**(`snowluma-*.node`),以及其中可能包含的任何授权、激活或技术保护措施。
|
||||
5.2 此类专有组件的**源代码不依 AGPL 提供**,受本条款约束。
|
||||
5.3 除适用法律强制性规定明确允许外,您不得对专有组件进行逆向工程、反编译或反汇编,亦不得规避、破解或绕过其授权或激活机制。
|
||||
5.4 `LICENSE` 第 7 条的链接例外仅允许将本软件与该原生模块**组合并分发**,**并不**向您授予该原生模块本身的源代码权利。
|
||||
|
||||
### 6. 终止
|
||||
若您违反本协议任何条款,本协议项下授予您的权利(**不含**您依 AGPL 单独享有的权利)将自动终止。终止后,您应停止使用并删除发行包中的专有组件。
|
||||
|
||||
### 7. 适用法律与争议解决
|
||||
本协议的订立、效力、解释、履行及争议解决,均适用**中华人民共和国大陆地区法律**(不含其冲突法规则)。因本协议引起或与之相关的任何争议,双方应首先友好协商解决;协商不成的,任何一方可向**有管辖权的人民法院**提起诉讼。
|
||||
|
||||
### 8. 协议的变更
|
||||
SnowLumaDevs 可不时更新本协议。更新后的版本将随发行包发布并注明生效日期。在更新生效后继续使用本软件,即视为您接受更新后的条款。
|
||||
|
||||
---
|
||||
|
||||
## English Version
|
||||
|
||||
### 1. Definitions and Acceptance
|
||||
1.1 "**Software**" means the SnowLuma software and its official distribution packages, including executables, native modules (`snowluma-*.node`), documentation, and related components.
|
||||
1.2 "**You**" means the individual or entity that downloads, installs, runs, or otherwise uses the Software.
|
||||
1.3 By downloading, installing, running, or using the Software, you acknowledge that you have read, understood, and agree to be bound by this Agreement. **If you do not agree, do not use the Software and delete all copies.**
|
||||
|
||||
### 2. Scope of License
|
||||
2.1 The **source code** of the Software is licensed under the GNU Affero General Public License version 3 (AGPL-3.0) together with its Section 7 additional permission (the native-addon linking exception); see the accompanying `LICENSE` file.
|
||||
2.2 This Agreement provides **supplemental terms for the binary distribution packages**, addressing matters not covered by the AGPL (acceptance, acceptable use, disclaimers, proprietary components, dispute resolution).
|
||||
2.3 **This Agreement does not diminish any rights granted to you under the AGPL.** It imposes no additional restriction on your acquisition, use, modification, or distribution of the source code under the AGPL.
|
||||
2.4 Proprietary Components (Section 5) are outside the scope of the AGPL and are licensed under their own terms.
|
||||
|
||||
### 3. Disclaimers
|
||||
3.1 **Not official; no affiliation.** The Software is an independent, third-party interoperability project and has **no affiliation, partnership, authorization, or endorsement relationship** with Tencent or QQ. "QQ", "Tencent", and related marks belong to their respective owners.
|
||||
3.2 **Purpose.** The Software is provided **solely for learning, research, and technical interoperability**.
|
||||
3.3 **Compliance.** You are responsible for ensuring that your use complies with all applicable laws and with the terms of any platform you connect to (including the QQ User Agreement and related terms of service).
|
||||
3.4 **AS-IS.** The Software is provided "**AS IS**" and "**AS AVAILABLE**", without warranties of any kind, express or implied, including merchantability, fitness for a particular purpose, non-infringement, availability, accuracy, or uninterrupted operation.
|
||||
3.5 **Limitation of liability.** To the maximum extent permitted by law, SnowLumaDevs shall **not be liable** for any direct, indirect, incidental, special, punitive, or consequential damages (including account suspension or restriction, data loss, lost profits or business, or service interruption) arising from use of or inability to use the Software.
|
||||
3.6 **Assumption of risk.** You understand that using an unofficial protocol tool to connect to a third-party platform **may violate that platform's terms and carry account risk**, which you **voluntarily assume**.
|
||||
|
||||
### 4. Acceptable Use
|
||||
You shall **not** use the Software for: (a) any unlawful activity; (b) unauthorized access to, interference with, or disruption of any system or network; (c) spam, harassment, fraud, or malicious content; (d) infringement of others' privacy, intellectual-property, or other lawful rights; or (e) any conduct that violates the terms of service of a connected platform.
|
||||
|
||||
### 5. Proprietary Components
|
||||
5.1 The Software may include or depend on **non-free proprietary components**, including but not limited to the **SnowLuma native addon** (`snowluma-*.node`) and any licensing, activation, or technical-protection measures it may contain.
|
||||
5.2 The **source code of such components is not provided under the AGPL** and is governed by these terms.
|
||||
5.3 Except to the extent expressly permitted by mandatory applicable law, you may not reverse engineer, decompile, or disassemble the Proprietary Components, nor circumvent, crack, or bypass their licensing or activation mechanisms.
|
||||
5.4 The Section 7 linking exception in `LICENSE` permits only the **combination and distribution** of the Software with the SnowLuma native addon; it does **not** grant you rights to that addon's own source code.
|
||||
|
||||
### 6. Termination
|
||||
If you breach any term of this Agreement, the rights granted to you hereunder (**excluding** rights you hold separately under the AGPL) terminate automatically. Upon termination you must cease use of and delete the Proprietary Components from the distribution package.
|
||||
|
||||
### 7. Governing Law and Disputes
|
||||
This Agreement is governed by the laws of the **mainland of the People's Republic of China** (excluding its conflict-of-laws rules). Any dispute arising out of or relating to this Agreement shall first be resolved through good-faith negotiation; failing that, either party may bring an action before a **court of competent jurisdiction**.
|
||||
|
||||
### 8. Changes
|
||||
SnowLumaDevs may update this Agreement from time to time. Updated versions will be published with the distribution package and bear an effective date. Continued use after an update takes effect constitutes acceptance of the updated terms.
|
||||
131
LICENSE
Normal file
131
LICENSE
Normal file
@@ -0,0 +1,131 @@
|
||||
SnowLuma Source-Available Non-Commercial License
|
||||
SnowLuma 源码可见非商业许可
|
||||
|
||||
Version 1.0 · 2026-06-19
|
||||
Copyright (C) 2026 SnowLumaDevs
|
||||
Contact: motricseven@foxmail.com
|
||||
|
||||
中英文如有冲突,以中文为准。
|
||||
In case of any conflict between the Chinese and English text, the Chinese
|
||||
version prevails.
|
||||
|
||||
This is NOT an open-source license as defined by the Open Source Initiative:
|
||||
it restricts commercial use and the public release of modifications. The
|
||||
source is published for transparency, study, and non-commercial self-hosting.
|
||||
本许可不是 OSI 定义的开源许可:它限制商业用途与修改版的公开发布。源码公开
|
||||
仅用于透明、学习与非商业的自托管。
|
||||
|
||||
===============================================================================
|
||||
1. Definitions / 定义
|
||||
===============================================================================
|
||||
- "Software" / "本软件": the SnowLuma source code and assets in this
|
||||
repository, excluding the Native Addon (defined below) and any third-party
|
||||
components.
|
||||
- "You" / "你": any individual or entity exercising rights under this License.
|
||||
- "Commercial Use" / "商业用途": any use primarily intended for or directed
|
||||
toward commercial advantage or monetary compensation. This includes, without
|
||||
limitation, selling or reselling the Software; offering paid hosting,
|
||||
deployment, setup, or operation services based on the Software; bundling it
|
||||
into a paid product or service; or running it to provide a service for a fee.
|
||||
包括但不限于:出售或转售本软件;提供基于本软件的付费托管、部署、代搭、代运营
|
||||
服务;将其并入付费产品或服务;或以收费方式运行本软件对外提供服务。
|
||||
- "Native Addon" / "原生附加组件": the SnowLuma native binary components shipped
|
||||
with the Software (e.g. `snowluma-*.node`, `snowluma-*.dll`, `snowluma-*.so`).
|
||||
These are a separate, proprietary component and are NOT licensed under this
|
||||
License — see Section 5.
|
||||
|
||||
===============================================================================
|
||||
2. Grant / 授权
|
||||
===============================================================================
|
||||
Subject to the conditions and restrictions below, the copyright holder grants
|
||||
You a worldwide, royalty-free, non-exclusive, non-transferable, revocable
|
||||
license to:
|
||||
在下列条件与限制下,著作权人授予你一项全球、免费、非独占、不可转让、可撤销的
|
||||
许可,允许你:
|
||||
(a) view and study the Software; 查看与学习本软件;
|
||||
(b) use and run the Software for personal or other Non-Commercial purposes;
|
||||
为个人或其他非商业目的使用与运行本软件;
|
||||
(c) modify the Software for Your own Non-Commercial use; 为自己的非商业使用
|
||||
修改本软件;
|
||||
(d) redistribute the Software under the conditions in Section 3.
|
||||
在第 3 条的条件下再分发本软件。
|
||||
|
||||
===============================================================================
|
||||
3. Redistribution Conditions / 再分发条件
|
||||
===============================================================================
|
||||
You may redistribute the Software (modified or unmodified) ONLY if ALL of the
|
||||
following are met. 仅当同时满足以下全部条件时,你方可再分发本软件(无论是否修改):
|
||||
(a) it is Non-Commercial; 属非商业性质;
|
||||
(b) the complete text of this License is included; 附带本许可的完整文本;
|
||||
(c) all copyright, attribution, and notices are retained unaltered;
|
||||
保留全部著作权、署名与声明,且不得改动;
|
||||
(d) PUBLIC release of a modified or derivative version requires the prior
|
||||
written permission of the copyright holder. Private, non-public
|
||||
modifications for Your own Non-Commercial use are permitted.
|
||||
公开发布修改版或衍生版,须事先获得著作权人书面许可;为你自己非商业使用
|
||||
而作的、不公开的修改则被允许。
|
||||
|
||||
===============================================================================
|
||||
4. Restrictions / 限制
|
||||
===============================================================================
|
||||
(a) Commercial Use of the Software in any form is PROHIBITED without the
|
||||
prior written authorization of the copyright holder.
|
||||
未经著作权人事先书面授权,禁止以任何形式对本软件进行商业使用。
|
||||
(b) You may not develop, publish, or distribute another project based on the
|
||||
Software without the prior written authorization of the copyright holder.
|
||||
未经著作权人事先书面授权,不得基于本软件开发、发布或分发另一个项目。
|
||||
(c) You may not remove, obscure, or alter any copyright, attribution, license,
|
||||
or notice. 不得移除、遮蔽或更改任何著作权、署名、许可或声明。
|
||||
|
||||
===============================================================================
|
||||
5. Native Addon / 原生附加组件
|
||||
===============================================================================
|
||||
The Native Addon is proprietary and is NOT covered by this License. It is
|
||||
distributed only as a precompiled binary bundled with the Software. No rights
|
||||
are granted to it other than to run it as bundled for the Non-Commercial use
|
||||
permitted above; in particular, no right to reverse engineer, reproduce,
|
||||
modify, redistribute separately, or relicense it is granted.
|
||||
原生附加组件为专有组件,不在本许可范围内,仅以随本软件分发的预编译二进制形式提供。
|
||||
除按上文允许的非商业用途以其随附形式运行外,不授予任何权利;尤其不授予对其进行逆向、
|
||||
复制、修改、单独再分发或再许可的权利。
|
||||
|
||||
===============================================================================
|
||||
6. Additional Permissions / 额外授权
|
||||
===============================================================================
|
||||
Any use not granted by this License — including Commercial Use and the public
|
||||
release of derivative works — requires prior written permission, which must be
|
||||
requested from and granted by the copyright holder (Contact above).
|
||||
本许可未授予的任何用途——包括商业使用及公开发布衍生作品——均须事先取得著作权人的
|
||||
书面许可(见上方联系方式)。
|
||||
|
||||
===============================================================================
|
||||
7. Third-Party Components / 第三方组件
|
||||
===============================================================================
|
||||
Third-party code and components retain their own original licenses, which
|
||||
govern those parts. 第三方代码与组件遵循其各自的原始许可,并以其许可为准。
|
||||
|
||||
===============================================================================
|
||||
8. Termination / 终止
|
||||
===============================================================================
|
||||
Any breach of this License automatically terminates the rights granted to You
|
||||
under it. 任何违反本许可的行为将自动终止你依本许可获得的权利。
|
||||
|
||||
===============================================================================
|
||||
9. Disclaimer / 免责声明
|
||||
===============================================================================
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
|
||||
LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
||||
OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
本软件按“现状”提供,不附带任何明示或默示的担保,包括但不限于适销性、特定用途
|
||||
适用性及不侵权的担保。在任何情况下,作者或著作权人均不对因本软件或其使用所引起
|
||||
的任何索赔、损害或其他责任负责。
|
||||
|
||||
===============================================================================
|
||||
10. Governing Law / 适用法律
|
||||
===============================================================================
|
||||
This License is governed by the laws of the mainland of the People's Republic
|
||||
of China, excluding its conflict-of-laws rules.
|
||||
本许可适用中华人民共和国大陆地区法律(不含其冲突法规则)。
|
||||
149
PRIVACY.md
Normal file
149
PRIVACY.md
Normal file
@@ -0,0 +1,149 @@
|
||||
# SnowLuma 隐私与数据处理说明 / Privacy & Data Handling Notice
|
||||
|
||||
- **生效日期 / Effective date:** 2026-06-19
|
||||
- **版本 / Version:** 1.0
|
||||
- **责任主体 / Provider:** SnowLumaDevs(联系方式 / Contact: motricseven@foxmail.com)
|
||||
|
||||
> 本说明以中文与英文两种语言提供。如有冲突,**以中文版本为准**。
|
||||
> Provided in Chinese and English. **In case of conflict, the Chinese version prevails.**
|
||||
|
||||
---
|
||||
|
||||
## 中文版
|
||||
|
||||
### 1. 概述
|
||||
SnowLuma 是一款**自托管**软件:它运行在**您自己的设备或服务器**上。**SnowLumaDevs(作者方)默认不收集、不接收、不存储您的任何个人数据**。本软件**不包含**任何需要联网激活、或向作者方回传信息的授权机制。
|
||||
本说明唯一例外的数据外发情形,是第 4、5 条所述的两种,且其中遥测受严格限制(第 5 条)。
|
||||
|
||||
### 2. 本软件在您设备上存储的数据
|
||||
为实现功能,本软件会在您的设备本地(如 SQLite 数据库、配置与日志文件)存储以下类别的数据。**这些数据保存在您本地、由您掌控,作者方无法访问:**
|
||||
- **账号与登录凭据**:所登录的 QQ 账号信息、会话/令牌、WebUI 登录口令(以**加盐 scrypt 哈希**形式存储,不保存明文)。
|
||||
- **关系数据**:好友、群组及成员的列表与资料。
|
||||
- **消息数据**:为实现协议转换而处理或缓存的消息(视您的配置而定)。
|
||||
- **运行配置与日志**:适配器配置、运行日志等。
|
||||
|
||||
> 说明:因 SnowLuma 是 QQ 协议工具,上述本地数据**必然**包含 QQ 账号及联系人信息。这与第 5 条"遥测绝不采集 QQ 账号/联系人"并不矛盾——本地存储 ≠ 对外传输。
|
||||
|
||||
### 3. 您作为数据控制者的责任
|
||||
当您运行本软件处理您 QQ 联系人、群成员等他人的个人信息时,**您是该等个人信息的"数据控制者/处理者"**,须自行就该等处理承担合规责任(包括取得必要同意、保障安全、响应数据主体请求等)。作者方仅提供软件工具,不参与您的数据处理活动。
|
||||
|
||||
### 4. 数据离开您设备的唯一途径
|
||||
除以下两种情形外,本软件不会将您的数据传输至任何外部目的地:
|
||||
1. **您自行配置的通知 / Webhook**:当您主动配置通知渠道(如 Webhook)时,相应内容会按**您填写的地址与设置**外发。目的地与内容由您完全掌控,作者方不经手。
|
||||
2. **匿名遥测**:见第 5 条。
|
||||
|
||||
### 5. 遥测(Telemetry)
|
||||
**模式:默认开启(opt-out)。** 您可随时关闭(见 5.3)。
|
||||
|
||||
#### 5.1 采集内容(仅匿名、聚合,无法定位到个人)
|
||||
- 应用版本、操作系统与 CPU 架构、Node.js 版本;
|
||||
- 启动次数、功能使用计数(例如启用了哪些适配器/命令,**不含其参数或内容**);
|
||||
- 匿名化的崩溃栈与错误类型。
|
||||
|
||||
#### 5.2 绝不采集(显式负面清单)
|
||||
本遥测**在任何情况下都不会**采集或传输:
|
||||
- **QQ 账号 / UIN,及好友、群、成员的身份信息**;
|
||||
- **消息内容或其元数据**、昵称、头像;
|
||||
- 手机号、邮箱或任何联系方式;
|
||||
- 凭据、令牌、密码;
|
||||
- 用于身份画像的精确 IP 地址(若服务端在传输层偶然可见 IP,将即时丢弃、不入库、不进行关联);
|
||||
- 任何可直接或间接定位到自然人的标识。
|
||||
|
||||
#### 5.3 如何关闭与告知
|
||||
- **首次运行提示**:软件首次运行时会在控制台与 WebUI 一次性告知遥测已默认开启及关闭方式。
|
||||
- **一键关闭**:可通过环境变量 `SNOWLUMA_TELEMETRY=0`、配置项或 WebUI 开关随时关闭,关闭后即刻停止采集。
|
||||
|
||||
#### 5.4 用途、共享与保留
|
||||
遥测数据**仅用于改进本软件**,**不向任何第三方出售或共享**,仅以匿名聚合形式保留必要期限。
|
||||
|
||||
#### 5.5 生效状态(重要)
|
||||
本条款完整描述了 SnowLuma 的遥测机制,但**仅对实际包含遥测代码的发行版生效**。
|
||||
> **当前生效状态(截至 2026-06-17)**:公开发行版**尚未包含**遥测代码,故本条款目前**处于未生效状态**。一旦某一发行版引入遥测,将在该版本的发布说明中明确告知,并使本条款对该版本生效。
|
||||
|
||||
### 6. 数据安全与保留
|
||||
本地数据的安全与保留由您(运营者)控制。建议您妥善保护设备访问权限、定期更新 WebUI 口令。
|
||||
|
||||
### 7. 第三方组件
|
||||
本软件可能捆绑第三方组件(如用于音视频处理的 FFmpeg)。此类组件**在您本地运行**、用于处理本地数据,**不向作者方或第三方外发**数据。
|
||||
|
||||
### 8. 未成年人
|
||||
本软件面向开发者与技术用户,**不面向未成年人**,作者方不会有意收集未成年人信息。
|
||||
|
||||
### 9. 您的权利
|
||||
由于作者方默认不持有您的任何个人数据,与您个人信息相关的访问、更正、删除等权利,应在**您本地的数据范围内**由您自行行使。如遥测启用且您有疑问,可通过第 10 条联系我们。
|
||||
|
||||
### 10. 联系方式
|
||||
隐私相关问询:**motricseven@foxmail.com**。
|
||||
|
||||
### 11. 变更
|
||||
本说明可不时更新,更新版本将注明生效日期。涉及遥测的重大变更将在发布说明中显著告知。
|
||||
|
||||
---
|
||||
|
||||
## English Version
|
||||
|
||||
### 1. Overview
|
||||
SnowLuma is **self-hosted**: it runs on **your own device or server**. **By default, SnowLumaDevs (the authors) collect, receive, and store none of your data.** The Software contains **no** activation that requires network access or transmits information back to the authors. The only data that ever leaves your device is described in Sections 4 and 5, and telemetry is strictly limited (Section 5).
|
||||
|
||||
### 2. Data the Software Stores on Your Device
|
||||
To function, the Software stores the following categories of data locally (e.g., in a SQLite database, configuration, and log files). **This data stays on your device under your control; the authors cannot access it:**
|
||||
- **Account & credentials:** the signed-in QQ account, session/tokens, and the WebUI login password (stored as a **salted scrypt hash**, never in plaintext).
|
||||
- **Relationship data:** lists and profiles of friends, groups, and members.
|
||||
- **Message data:** messages processed or cached for protocol conversion (depending on your configuration).
|
||||
- **Runtime configuration & logs.**
|
||||
|
||||
> Note: Because SnowLuma is a QQ protocol tool, this local data **necessarily** includes QQ account and contact information. This does not conflict with Section 5 ("telemetry never collects QQ account/contacts") — local storage ≠ outbound transmission.
|
||||
|
||||
### 3. You Are the Data Controller
|
||||
When you run the Software to process the personal information of your QQ contacts, group members, or other individuals, **you are the data controller/processor** for that information and are responsible for compliance (obtaining any necessary consent, securing the data, responding to data-subject requests). The authors merely provide a software tool and take no part in your processing.
|
||||
|
||||
### 4. The Only Ways Data Leaves Your Device
|
||||
The Software transmits your data to an external destination only in these two cases:
|
||||
1. **Notifications / webhooks you configure:** when you set up a notification channel (e.g., a webhook), the relevant content is sent to **the address and settings you provide**. You fully control the destination and content; the authors are not involved.
|
||||
2. **Anonymous telemetry:** see Section 5.
|
||||
|
||||
### 5. Telemetry
|
||||
**Mode: ON by default (opt-out).** You can disable it at any time (see 5.3).
|
||||
|
||||
#### 5.1 What is collected (anonymous, aggregate, non-identifying only)
|
||||
- Application version, OS and CPU architecture, Node.js version;
|
||||
- Launch counts and feature-usage counts (e.g., which adapters/commands are enabled — **never their arguments or content**);
|
||||
- Anonymized crash stacks and error types.
|
||||
|
||||
#### 5.2 Never collected (explicit negative list)
|
||||
Telemetry will **never, under any circumstances**, collect or transmit:
|
||||
- **QQ account / UIN, or the identity of any friend, group, or member**;
|
||||
- **Message content or metadata**, nicknames, avatars;
|
||||
- Phone numbers, emails, or any contact details;
|
||||
- Credentials, tokens, passwords;
|
||||
- Precise IP addresses used for profiling (any IP incidentally visible at the transport layer is discarded immediately, not stored, not correlated);
|
||||
- Any identifier that could directly or indirectly identify a natural person.
|
||||
|
||||
#### 5.3 How to disable; notice
|
||||
- **First-run notice:** on first run the Software gives a one-time notice in the console and WebUI that telemetry is on by default and how to disable it.
|
||||
- **One switch off:** disable any time via the `SNOWLUMA_TELEMETRY=0` environment variable, a config option, or the WebUI toggle; collection stops immediately.
|
||||
|
||||
#### 5.4 Use, sharing, retention
|
||||
Telemetry is used **only to improve the Software**, is **never sold or shared with any third party**, and is retained only in anonymous aggregate form for as long as necessary.
|
||||
|
||||
#### 5.5 Effective status (important)
|
||||
This Section fully describes SnowLuma's telemetry mechanism but is **effective only for builds that actually contain telemetry code.**
|
||||
> **Current status (as of 2026-06-17):** public releases **do not yet contain** telemetry code, so this Section is currently **not in effect**. If a release introduces telemetry, its release notes will say so and this Section will take effect for that release.
|
||||
|
||||
### 6. Security & Retention
|
||||
Security and retention of local data are under your (the operator's) control. Protect device access and rotate the WebUI password regularly.
|
||||
|
||||
### 7. Third-Party Components
|
||||
The Software may bundle third-party components (such as FFmpeg for media processing). These run **locally** on your device to process local data and **send nothing** to the authors or third parties.
|
||||
|
||||
### 8. Minors
|
||||
The Software targets developers and technical users, is **not directed to minors**, and the authors do not knowingly collect minors' information.
|
||||
|
||||
### 9. Your Rights
|
||||
Because the authors hold none of your personal data by default, rights of access, correction, and deletion are exercised by you **over the data on your own device**. If telemetry is enabled and you have questions, contact us (Section 10).
|
||||
|
||||
### 10. Contact
|
||||
Privacy inquiries: **motricseven@foxmail.com**.
|
||||
|
||||
### 11. Changes
|
||||
This Notice may be updated from time to time; updated versions bear an effective date. Material changes affecting telemetry will be prominently noted in release notes.
|
||||
119
README.md
119
README.md
@@ -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,39 @@
|
||||
|
||||
---
|
||||
|
||||
## 简介
|
||||
SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。
|
||||
|
||||
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
|
||||
|
||||
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
|
||||
> ⚠️ **免责声明**:SnowLuma 是独立的第三方互操作项目,**与腾讯 / QQ 无任何隶属或授权关系**。本项目**仅供学习与技术研究**,请遵守《QQ 用户协议》及适用法律;软件按"现状"提供、不附带任何担保,使用风险自负。详见 [`EULA.md`](EULA.md)。
|
||||
>
|
||||
> ⚠️ **Disclaimer**: SnowLuma is an independent, third-party interoperability project with **no affiliation with or endorsement by Tencent / QQ**, provided **for study and research only**, "as is" without warranty. Comply with the QQ User Agreement and applicable law; use at your own risk. See [`EULA.md`](EULA.md).
|
||||
|
||||
## 特性
|
||||
|
||||
- **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 存储好友、群组等关系数据。
|
||||
|
||||
## 快速开始
|
||||
|
||||
下载预构建发布包:
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。
|
||||
2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。
|
||||
3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。
|
||||
|
||||
```bash
|
||||
# 从 Releases 下载 zip,解压到任意目录
|
||||
./launcher.bat # Windows
|
||||
```
|
||||
## 许可 / License
|
||||
|
||||
或从源码开发:
|
||||
SnowLuma 采用 **源码可见非商业许可(SnowLuma Source-Available Non-Commercial License)**,见 [`LICENSE`](LICENSE)。**这不是 OSI 开源许可**:源码公开供查看、学习与非商业自托管,但**禁止任何商业使用**(出售、转售、付费托管 / 代搭 / 代运营等),公开发布修改版须事先书面授权。随附的原生附加组件(`snowluma-*.node` 等)为专有组件,不在本许可范围内。二进制发行包另受 [`EULA.md`](EULA.md) 约束;商业授权请联系 motricseven@foxmail.com。参与贡献请阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md)。
|
||||
|
||||
```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
|
||||
```
|
||||
SnowLuma is under a **source-available, non-commercial** license (see [`LICENSE`](LICENSE)) — **NOT** an OSI open-source license. The source is published for study and non-commercial self-hosting; **commercial use is prohibited** without prior written permission, and the bundled native addon (`snowluma-*.node`) is proprietary and not covered by this license.
|
||||
|
||||
## 鸣谢
|
||||
|
||||
- [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)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.9.2",
|
||||
"version": "1.10.2",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -8,7 +9,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,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.2",
|
||||
"version": "1.10.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
|
||||
@@ -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,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.2",
|
||||
"version": "1.10.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
@@ -45,10 +46,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);
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
|
||||
35
packages/common/src/request-context.ts
Normal file
35
packages/common/src/request-context.ts
Normal file
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
117
packages/common/tests/runtime.test.ts
Normal file
117
packages/common/tests/runtime.test.ts
Normal file
@@ -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
|
||||
});
|
||||
});
|
||||
10
packages/common/vitest.config.ts
Normal file
10
packages/common/vitest.config.ts
Normal file
@@ -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,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.9.2",
|
||||
"version": "1.10.2",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -46,7 +47,6 @@
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -54,7 +54,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,10 +1,13 @@
|
||||
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';
|
||||
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
|
||||
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
|
||||
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
|
||||
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
|
||||
import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
@@ -65,6 +68,16 @@ export class ContactsApi {
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
/** Server-built ARK share card (JSON string) recommending a friend. */
|
||||
getBuddyRecommendArk(userId: number, phoneNumber = ''): Promise<string> {
|
||||
return GetBuddyRecommendArk.invoke(this.ctx, { userId, phoneNumber });
|
||||
}
|
||||
|
||||
/** Server-built ARK share card (JSON string) recommending a group. */
|
||||
getGroupRecommendArk(groupId: number): Promise<string> {
|
||||
return GetGroupRecommendArk.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const friends: FriendInfo[] = [];
|
||||
let nextUin: number | null = null;
|
||||
@@ -104,6 +117,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 } = {},
|
||||
@@ -197,6 +232,13 @@ export class ContactsApi {
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** The approval msgseq captured from a private "qun.invite" card for this
|
||||
* group, or undefined if none was seen. `set_group_add_request` uses it to
|
||||
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
|
||||
getGroupInviteCardSequence(groupId: number): number | undefined {
|
||||
return this.ctx.identity.getGroupInviteCardSequence(groupId);
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
453
packages/core/src/bridge/apis/flash-transfer.ts
Normal file
453
packages/core/src/bridge/apis/flash-transfer.ts
Normal file
@@ -0,0 +1,453 @@
|
||||
// FlashTransferApi — 闪传(fileset)业务编排。
|
||||
// 复用 OIDB 基础设施(invokeOidb),协议层在 @snowluma/protocol/oidb-services/flash-transfer/。
|
||||
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { FlashFileEntry } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
|
||||
import { GetFilesetDetail } from '@snowluma/protocol/oidb-services/flash-transfer/get-fileset-detail';
|
||||
import { ListFilesets } from '@snowluma/protocol/oidb-services/flash-transfer/list-filesets';
|
||||
import { GetDownloadUrl } from '@snowluma/protocol/oidb-services/flash-transfer/get-download-url';
|
||||
import { GetFlashDownload } from '@snowluma/protocol/oidb-services/flash-transfer/get-flash-download';
|
||||
import { DeleteFlashFile } from '@snowluma/protocol/oidb-services/flash-transfer/delete-file';
|
||||
import { RenameFlashFile } from '@snowluma/protocol/oidb-services/flash-transfer/rename-file';
|
||||
import { ApplyFileset } from '@snowluma/protocol/oidb-services/flash-transfer/apply-fileset';
|
||||
import { CommitFile } from '@snowluma/protocol/oidb-services/flash-transfer/commit-file';
|
||||
import { CompleteFileset } from '@snowluma/protocol/oidb-services/flash-transfer/complete-fileset';
|
||||
import { SetFilesetStatus } from '@snowluma/protocol/oidb-services/flash-transfer/set-status';
|
||||
import { ApplyUpload } from '@snowluma/protocol/oidb-services/flash-transfer/apply-upload';
|
||||
import { PrepareUpload } from '@snowluma/protocol/oidb-services/flash-transfer/prepare-upload';
|
||||
import { SendFlashMsg } from '@snowluma/protocol/oidb-services/flash-transfer/send-flash';
|
||||
import { loadBinarySource, computeHashes } from '@snowluma/protocol/highway/utils';
|
||||
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import type { FlashSliceUploadBody, FlashSliceUploadResp, FlashFileId } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
|
||||
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
||||
import { deflateSync } from 'node:zlib';
|
||||
|
||||
/** 闪传文件信息(业务层,从 FlashFileEntry 转换)。 */
|
||||
export interface FlashFileInfo {
|
||||
filesetUuid: string;
|
||||
fileName: string;
|
||||
origName: string;
|
||||
fileSize: number;
|
||||
/** 上传/分享链接 qfile.qq.com/q/<code>。 */
|
||||
shareUrl: string;
|
||||
fileId: string;
|
||||
/** 下载链接 multimedia.qfile.qq.com/download?...&rkey=... */
|
||||
downloadUrl: string;
|
||||
}
|
||||
|
||||
function entryToInfo(e: FlashFileEntry): FlashFileInfo {
|
||||
return {
|
||||
filesetUuid: e.filesetUuid ?? '',
|
||||
fileName: e.fileName ?? '',
|
||||
origName: e.origName ?? '',
|
||||
fileSize: Number(e.fileSize ?? 0),
|
||||
shareUrl: e.uploadUrlWrap?.uploadUrl ?? '',
|
||||
fileId: e.fileIdWrap?.fileId ?? '',
|
||||
downloadUrl: e.fileIdWrap?.download?.downloadUrl ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
// 手写 PNG 编码(zlib 压缩,避免引入图像库)。缩略图用随机纯色,每次 SHA1 不同,
|
||||
// 避免命中服务端秒传缓存。
|
||||
const CRC_TABLE: Uint32Array = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
|
||||
table[n] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(buf: Buffer): number {
|
||||
let c = 0xFFFFFFFF;
|
||||
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8);
|
||||
return (c ^ 0xFFFFFFFF) >>> 0;
|
||||
}
|
||||
|
||||
function pngChunk(type: string, data: Buffer): Buffer {
|
||||
const len = Buffer.alloc(4);
|
||||
len.writeUInt32BE(data.length, 0);
|
||||
const typeBuf = Buffer.from(type, 'ascii');
|
||||
const crc = crc32(Buffer.concat([typeBuf, data]));
|
||||
const crcBuf = Buffer.alloc(4);
|
||||
crcBuf.writeUInt32BE(crc, 0);
|
||||
return Buffer.concat([len, typeBuf, data, crcBuf]);
|
||||
}
|
||||
|
||||
/** 生成 width×height 随机纯色 PNG(8-bit RGB)。每次随机颜色,SHA1 不同以避免秒传。 */
|
||||
function generatePng(width: number, height: number): Buffer {
|
||||
const r = Math.floor(Math.random() * 256);
|
||||
const g = Math.floor(Math.random() * 256);
|
||||
const b = Math.floor(Math.random() * 256);
|
||||
const rowLen = 1 + width * 3;
|
||||
const raw = Buffer.alloc(rowLen * height);
|
||||
for (let y = 0; y < height; y++) {
|
||||
const off = y * rowLen;
|
||||
raw[off] = 0; // filter none
|
||||
for (let x = 0; x < width; x++) {
|
||||
raw[off + 1 + x * 3] = r;
|
||||
raw[off + 1 + x * 3 + 1] = g;
|
||||
raw[off + 1 + x * 3 + 2] = b;
|
||||
}
|
||||
}
|
||||
const compressed = deflateSync(raw);
|
||||
const sig = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(width, 0);
|
||||
ihdr.writeUInt32BE(height, 4);
|
||||
ihdr[8] = 8; // bit depth
|
||||
ihdr[9] = 2; // color type RGB
|
||||
ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;
|
||||
return Buffer.concat([sig, pngChunk('IHDR', ihdr), pngChunk('IDAT', compressed), pngChunk('IEND', Buffer.alloc(0))]);
|
||||
}
|
||||
|
||||
export class FlashTransferApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
/** 获取文件集信息(get_fileset_info)。 */
|
||||
async getFilesetInfo(filesetUuid: string): Promise<FlashFileInfo[]> {
|
||||
const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid });
|
||||
return entries.map(entryToInfo);
|
||||
}
|
||||
|
||||
/** 获取闪传文件列表(get_flash_file_list)。同 getFilesetInfo,返回文件数组。 */
|
||||
async getFlashFileList(filesetUuid: string): Promise<FlashFileInfo[]> {
|
||||
return this.getFilesetInfo(filesetUuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拿指定文件的下载直链 + 元信息。0x93d4 返回 fileset 内所有文件(f3 repeated,
|
||||
* 多文件时每条 f6=序号、f14=主文件 fileId),按 fileIndex 选中后走 0x12a9 sub=200
|
||||
* 拿主文件直链。0x93d3/0x93d4 的 downloadUrl 字段是缩略图(appid=14903/14902),
|
||||
* 主文件必须走 0x12a9 sub=200。
|
||||
*/
|
||||
private async getFileDownload(
|
||||
filesetUuid: string, fileIndex: number = 1,
|
||||
): Promise<{ url: string; fileName: string; fileSize: number } | null> {
|
||||
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
|
||||
const meta = metas.find((m) => m.fileIndex === fileIndex);
|
||||
if (!meta || !meta.fileId) return null;
|
||||
const url = await GetFlashDownload.invoke(this.ctx, {
|
||||
filesetUuid: meta.filesetUuid,
|
||||
fileUuid: meta.fileUuid,
|
||||
fileId: meta.fileId,
|
||||
fileName: meta.fileName,
|
||||
});
|
||||
if (!url) return null;
|
||||
return { url, fileName: meta.fileName, fileSize: meta.fileSize };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取闪传文件下载链接(get_flash_file_url)。主文件直链走 0x12a9 sub=200
|
||||
* (0x93d3 的 downloadUrl 是缩略图 appid=14903,非主文件)。多文件 fileset 用
|
||||
* fileIndex 指定第几个文件(默认 1)。找不到文件或拿不到直链时抛错。
|
||||
*/
|
||||
async getFlashFileUrl(filesetUuid: string, fileIndex: number = 1): Promise<string> {
|
||||
const dl = await this.getFileDownload(filesetUuid, fileIndex);
|
||||
if (!dl || !dl.url) throw new Error('get_flash_file_url: no download url available');
|
||||
return dl.url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析闪传文件下载直链(download_fileset)。返回指定文件的下载 URL + 文件名/大小,
|
||||
* 不下载文件内容(由调用方拉)。多文件 fileset 用 fileIndex 指定第几个文件(默认 1)。
|
||||
*/
|
||||
async downloadFileset(
|
||||
filesetUuid: string,
|
||||
opts?: { fileName?: string; fileIndex?: number },
|
||||
): Promise<{ url: string; fileName: string; fileSize: number }> {
|
||||
const dl = await this.getFileDownload(filesetUuid, opts?.fileIndex ?? 1);
|
||||
if (!dl || !dl.url) throw new Error('download_fileset: no download url available');
|
||||
return dl;
|
||||
}
|
||||
|
||||
/** 获取分享链接(get_share_link)= qfile.qq.com/q/<code>。 */
|
||||
async getShareLink(filesetUuid: string): Promise<string> {
|
||||
const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid });
|
||||
return entries.find((e) => e.uploadUrlWrap?.uploadUrl)?.uploadUrlWrap?.uploadUrl ?? '';
|
||||
}
|
||||
|
||||
/** 列出当前账号的所有 fileset(OneBot 标准未定义,QQ 面板有此入口)。 */
|
||||
async listFilesets(): Promise<FlashFileInfo[]> {
|
||||
const entries = await ListFilesets.invoke(this.ctx, {});
|
||||
return entries.map(entryToInfo);
|
||||
}
|
||||
|
||||
/** 删除闪传文件(delete_flash_file)。 */
|
||||
async deleteFlashFile(filesetUuid: string): Promise<void> {
|
||||
await DeleteFlashFile.invoke(this.ctx, { filesetUuid });
|
||||
}
|
||||
|
||||
/** 重命名闪传文件(rename_flash_file)。 */
|
||||
async renameFlashFile(filesetUuid: string, newName: string): Promise<void> {
|
||||
await RenameFlashFile.invoke(this.ctx, { filesetUuid, newName });
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送闪传文件(send_flash_msg,0x93d7)。私聊:user_id→uid;群聊:group_id 直接用。
|
||||
* 0x93d7 响应无 message_id(分享 fileset,非传统消息),OneBot 层 message_id 由 action 返回 0。
|
||||
*/
|
||||
async sendFlashMsg(filesetUuid: string, target: { userId?: number; groupId?: number }): Promise<void> {
|
||||
if (target.groupId) {
|
||||
await SendFlashMsg.invoke(this.ctx, { groupId: target.groupId, filesetUuid });
|
||||
return;
|
||||
}
|
||||
const userId = target.userId;
|
||||
if (!userId) throw new Error('send_flash_msg: user_id or group_id is required');
|
||||
const targetUid = await this.ctx.identity.resolveUid(userId);
|
||||
await SendFlashMsg.invoke(this.ctx, { targetUid, filesetUuid });
|
||||
}
|
||||
|
||||
/**
|
||||
* 从分享码/链接获取 fileset_id(get_fileset_id)。code→UUID 不走 OIDB,QQ 客户端
|
||||
* 走 trpc HTTP API;分享页 qfile.qq.com/q/<code> 的 HTML 内嵌了 fileset_id(trpc
|
||||
* 接口数据),直接 GET + 正则提取即可,无需复刻带签名的 trpc 调用。
|
||||
*/
|
||||
async getFilesetIdByCode(shareCode: string): Promise<string> {
|
||||
const url = /^https?:\/\//i.test(shareCode) ? shareCode : `https://qfile.qq.com/q/${shareCode}`;
|
||||
const resp = await fetch(url);
|
||||
if (!resp.ok) throw new Error(`get_fileset_id: HTTP ${resp.status}`);
|
||||
const html = await resp.text();
|
||||
// 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。
|
||||
const m = /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(html);
|
||||
if (!m) throw new Error('get_fileset_id: fileset_id not found in share page');
|
||||
return m[1];
|
||||
}
|
||||
|
||||
// ─────────────── 文件上传 ───────────────
|
||||
|
||||
/**
|
||||
* 文件扩展名 → 闪传类型码映射。typeCode 用于 0x93cf f3,formatCode 用于
|
||||
* 0x93d0 commit f7 与 0x12a9 filesetWrap.f7(两者同值)。mp4 → 2,rar/zip → 4。
|
||||
* 未知扩展名按媒体类处理(formatCode=2),服务端按文件名扩展名判定。
|
||||
*/
|
||||
private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } {
|
||||
const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? '';
|
||||
switch (ext) {
|
||||
case 'rar': return { typeCode: 2, formatCode: 4 };
|
||||
case 'zip': return { typeCode: 6, formatCode: 4 };
|
||||
case '7z': case 'gz': case 'tar': case 'bz2': return { typeCode: 2, formatCode: 4 };
|
||||
case 'png': case 'jpg': case 'jpeg': case 'bmp': case 'gif': case 'webp':
|
||||
case 'mp4': case 'mov': case 'avi': case 'mkv':
|
||||
return { typeCode: 7, formatCode: 2 };
|
||||
default: return { typeCode: 7, formatCode: 2 };
|
||||
}
|
||||
}
|
||||
|
||||
/** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。
|
||||
* f2=SHA1, f3=filesize, f4=appid, f5=微秒时间戳, f6="prod",
|
||||
* f10=TTL(1209600), f11=16B 会话ID, f15=3B, f16="gz"。
|
||||
* f11/f15 随机生成,服务端不校验。
|
||||
* appid 决定 fileId 落在哪个槽位:主文件用 14901(0x93d4 f14.f1),
|
||||
* png 缩略图用 14903、jpg 缩略图用 14902(f13.f1)。主文件必须用 14901,
|
||||
* 否则 fileId 不会被服务端采纳进 f14,对端无法拿到主文件下载入口。 */
|
||||
private static buildFileId(sha1: Uint8Array, fileSize: number, appid: number = 14901): string {
|
||||
const fileId: FlashFileId = {
|
||||
sha1: new Uint8Array(sha1),
|
||||
fileSize,
|
||||
appid,
|
||||
timestamp: BigInt(Date.now()) * 1000n, // 微秒时间戳
|
||||
env: 'prod',
|
||||
ttl: 1209600,
|
||||
sessionId: randomBytes(16),
|
||||
field15: randomBytes(3),
|
||||
region: 'gz',
|
||||
};
|
||||
return Buffer.from(protobuf_encode<FlashFileId>(fileId)).toString('base64url');
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建闪传任务(create_flash_task)。所有文件统一走 sub=100/103+sliceupload,
|
||||
* 不走小文件 PUT——QQ 客户端即使几百 KB 的文件也走 sliceupload。只有 sliceupload
|
||||
* 路径会上报主文件 sha1/size,服务端据此把 fileset 标记为完成(对端可下载);
|
||||
* PUT 路径不上报 sha1,fileset 会卡在"上传中"无法被下载。
|
||||
*
|
||||
* 多文件:0x93d0 的 f4 是 repeated,一个 commit 请求同时携带 fileset 内所有文件
|
||||
* 条目,每条 f6=文件序号(1,2,3...)。commit 在上传前只发一次,之后 complete →
|
||||
* 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit
|
||||
* 的 f6 一致,否则文件不计入 fileset。多文件时 ApplyFileset 的 fileName 用
|
||||
* 「<首文件名>等N个文件」、fileSize 用总和——服务端据此判定 fileset 为多文件。
|
||||
*/
|
||||
async createFlashTask(files: string | string[], _name?: string, _thumbPath?: string): Promise<{ filesetId: string }> {
|
||||
const fileList = Array.isArray(files) ? files : [files];
|
||||
if (fileList.length === 0) throw new Error('create_flash_task: files is empty');
|
||||
const uploader = {
|
||||
uin: this.ctx.identity.uin,
|
||||
nickname: this.ctx.identity.nickname,
|
||||
uid: this.ctx.identity.selfUid ?? '',
|
||||
};
|
||||
// 读取所有文件,每个分配 fileUuid + 序号 + formatCode
|
||||
const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = [];
|
||||
for (let i = 0; i < fileList.length; i++) {
|
||||
const { bytes, fileName } = await loadBinarySource(fileList[i], 'flash-transfer');
|
||||
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
|
||||
items.push({ bytes: new Uint8Array(bytes), fileName, fileUuid: randomUUID(), fileIndex: i + 1, formatCode });
|
||||
}
|
||||
// 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和,
|
||||
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
|
||||
const first = items[0];
|
||||
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
|
||||
const isMulti = items.length > 1;
|
||||
const filesetName = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName;
|
||||
const totalSize = items.reduce((s, it) => s + it.bytes.length, 0);
|
||||
const apply = await ApplyFileset.invoke(this.ctx, {
|
||||
fileName: filesetName, origName: filesetName,
|
||||
fileSize: totalSize, typeCode, uploader,
|
||||
});
|
||||
const filesetUuid = apply.filesetUuid;
|
||||
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
|
||||
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
|
||||
const commitEntries = items.map((it) => ({
|
||||
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
|
||||
fileSize: it.bytes.length, formatCode: it.formatCode, fileIndex: it.fileIndex,
|
||||
}));
|
||||
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
|
||||
await CompleteFileset.invoke(this.ctx, { filesetUuid });
|
||||
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
|
||||
const prepared: { it: typeof items[0]; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
|
||||
for (const it of items) {
|
||||
const p = await this.prepareAndApply(filesetUuid, it.bytes, it.fileName, it.fileUuid, it.fileIndex, it.formatCode);
|
||||
if (p) prepared.push({ it, ...p });
|
||||
}
|
||||
for (const p of prepared) {
|
||||
await this.sliceuploadFile(p.it.bytes, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName);
|
||||
}
|
||||
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
|
||||
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
|
||||
return { filesetId: filesetUuid };
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段1:prepare(拿 rkey)+ apply(注册 fileId)。返回 sliceupload 所需的 rkey/sha1state。
|
||||
* 秒传(rkey=null)返回 null,调用方跳过 sliceupload。
|
||||
*/
|
||||
private async prepareAndApply(
|
||||
filesetUuid: string, bytes: Uint8Array, fileName: string, fileUuid: string, fileIndex: number, formatCode: number,
|
||||
): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> {
|
||||
const fileSize = bytes.length;
|
||||
const hashes = computeHashes(bytes);
|
||||
const SLICE_SIZE = 1024 * 1024;
|
||||
const sliceCount = Math.ceil(fileSize / SLICE_SIZE);
|
||||
const sha1StateV = computeSha1StateV(bytes, sliceCount, SLICE_SIZE);
|
||||
|
||||
const rkey = await PrepareUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex, fileIndex, formatCode,
|
||||
});
|
||||
if (rkey === null) return null; // 秒传
|
||||
|
||||
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize);
|
||||
await ApplyUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileId, fileName, fileSize,
|
||||
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode,
|
||||
});
|
||||
return { rkey, sha1StateV, sliceCount };
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段2:sliceupload 分片上传(所有文件 prepare+apply 完成后调用)。
|
||||
*/
|
||||
private async sliceuploadFile(
|
||||
bytes: Uint8Array, rkey: string, sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
|
||||
): Promise<void> {
|
||||
const fileSize = bytes.length;
|
||||
const SLICE_SIZE = 1024 * 1024;
|
||||
for (let i = 0; i < sliceCount; i++) {
|
||||
const start = i * SLICE_SIZE;
|
||||
const chunk = bytes.subarray(start, Math.min(start + SLICE_SIZE, fileSize));
|
||||
const chunkLen = chunk.length;
|
||||
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
|
||||
const body: FlashSliceUploadBody = {
|
||||
field1: 0,
|
||||
appid: 14901,
|
||||
field3: 2,
|
||||
payload: {
|
||||
field1: {},
|
||||
rkey,
|
||||
start,
|
||||
end: start + chunkLen - 1,
|
||||
sha1: chunkSha1,
|
||||
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
|
||||
chunk: new Uint8Array(chunk),
|
||||
},
|
||||
};
|
||||
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
|
||||
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST sliceupload 并校验响应。服务端即使 HTTP 200 也可能在业务体里返回错误,
|
||||
* 所以必须解析 f5(status),非 "success" 视为失败。label 用于错误信息定位切片来源。
|
||||
*/
|
||||
private async postSliceupload(bodyBytes: Uint8Array, label: string): Promise<void> {
|
||||
const resp = await fetch('https://multimedia.qfile.qq.com/sliceupload', {
|
||||
method: 'POST', body: bodyBytes,
|
||||
headers: {
|
||||
Accept: '*/*', Connection: 'Keep-Alive',
|
||||
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)',
|
||||
Pragma: 'no-cache', 'Cache-Control': 'no-cache',
|
||||
'Content-Length': String(bodyBytes.length),
|
||||
'X-Retried-Times': '1',
|
||||
},
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const errBody = await resp.text().catch(() => '');
|
||||
throw new Error(`${label} failed: HTTP ${resp.status} ${errBody.slice(0, 300)}`);
|
||||
}
|
||||
const respBuf = new Uint8Array(await resp.arrayBuffer());
|
||||
const sliceResp = protobuf_decode<FlashSliceUploadResp>(respBuf);
|
||||
if (sliceResp.status !== 'success') {
|
||||
throw new Error(`${label} failed: ${sliceResp.status || 'no status in response'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传占位缩略图(png+jpg)。主文件上传后调用——主文件下载入口(0x93d3 的下载
|
||||
* fileId)需要缩略图关联才会被服务端填充,不传缩略图时 bot 自身上传的 fileset
|
||||
* 无法被 download_fileset 解析。缩略图用随机纯色 PNG,无需 ffmpeg/sharp。
|
||||
* fileIndex 为缩略图在 fileset 内的序号(主文件之后递增),与 commit f6 对齐。
|
||||
*/
|
||||
private async uploadThumbnail(
|
||||
filesetUuid: string, mainFileUuid: string, thumbType: 'png' | 'jpg', fileIndex: number,
|
||||
): Promise<void> {
|
||||
// 526x360 是 QQ 客户端缩略图尺寸;1x1 会被服务端拒(HTTP 400,宽高太小)。
|
||||
const width = 526, height = 360;
|
||||
const thumbBytes = generatePng(width, height); // 随机纯色,SHA1 不同避免秒传
|
||||
const appid = thumbType === 'png' ? 14903 : 14902; // png=14903, jpg=14902
|
||||
const fileUuid = thumbType === 'png' ? randomUUID() : mainFileUuid; // png 独立,jpg 挂主文件
|
||||
const fileName = thumbType === 'png'
|
||||
? `${randomUUID().slice(0, 8)}_one.png`
|
||||
: `${createHash('md5').update(thumbBytes).digest('hex').slice(0, 32)}.jpg`;
|
||||
const hashes = computeHashes(new Uint8Array(thumbBytes));
|
||||
const fileSize = thumbBytes.length;
|
||||
const thumbFormatCode = thumbType === 'png' ? 26 : 2; // png缩略图=26, jpg缩略图=2
|
||||
const rkey = await PrepareUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex,
|
||||
fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
|
||||
});
|
||||
if (rkey === null) return; // 秒传
|
||||
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize, appid);
|
||||
await ApplyUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileId, fileName, fileSize,
|
||||
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
|
||||
});
|
||||
// sliceupload(缩略图小,1 片,Sha1StateV=[标准 SHA1])
|
||||
const sha1StateV = computeSha1StateV(new Uint8Array(thumbBytes), 1, fileSize);
|
||||
const body: FlashSliceUploadBody = {
|
||||
field1: 0, appid, field3: 2,
|
||||
payload: {
|
||||
field1: {}, rkey,
|
||||
start: 0, end: fileSize - 1,
|
||||
sha1: new Uint8Array(hashes.sha1),
|
||||
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
|
||||
chunk: new Uint8Array(thumbBytes),
|
||||
},
|
||||
};
|
||||
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
|
||||
await this.postSliceupload(bodyBytes, 'thumbnail sliceupload');
|
||||
}
|
||||
}
|
||||
@@ -150,7 +150,7 @@ async function buildForwardPushBody(
|
||||
msgId: random,
|
||||
sequence: seq,
|
||||
timestamp: now,
|
||||
divSeq: 0,
|
||||
c2cCmd: 0,
|
||||
},
|
||||
body: {
|
||||
richText: {
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
|
||||
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
|
||||
import { GetDoubtBuddyReq, type DoubtBuddyRequest } from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
|
||||
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
|
||||
import { RejectDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/reject-doubt-buddy-req';
|
||||
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
export type { DoubtBuddyRequest };
|
||||
|
||||
export class FriendApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
@@ -26,4 +31,19 @@ export class FriendApi {
|
||||
setRemark(userId: number, remark: string): Promise<void> {
|
||||
return SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
|
||||
/** List doubtful friend-add requests (可能认识的人). */
|
||||
getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
|
||||
return GetDoubtBuddyReq.invoke(this.ctx, { count });
|
||||
}
|
||||
|
||||
/** Approve a doubtful friend-add request by its uid (the list item's flag). */
|
||||
approveDoubtRequest(uid: string): Promise<void> {
|
||||
return ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
}
|
||||
|
||||
/** Reject (delete/decline) a doubtful friend-add request by its uid. */
|
||||
rejectDoubtRequest(uid: string): Promise<void> {
|
||||
return RejectDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,11 +12,17 @@ import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set
|
||||
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
|
||||
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
|
||||
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
|
||||
import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/modify-group-ext-info';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
export class GroupAdminApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
/** Set the group's robot-add option (switch / examine) via group ext-info. */
|
||||
setRobotAddOption(groupId: number, robotMemberSwitch?: number, robotMemberExamine?: number): Promise<void> {
|
||||
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
|
||||
}
|
||||
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { ContactsApi } from './contacts';
|
||||
import { ExtrasApi } from './extras';
|
||||
import { FlashTransferApi } from './flash-transfer';
|
||||
import { ForwardApi } from './forward';
|
||||
import { FriendApi } from './friend';
|
||||
import { GroupAdminApi } from './group-admin';
|
||||
@@ -10,6 +11,7 @@ import { InteractionApi } from './interaction';
|
||||
import { MessageApi } from './message';
|
||||
import { MiscApi } from './misc';
|
||||
import { ProfileApi } from './profile';
|
||||
import { QzoneApi } from './qzone';
|
||||
import { WebApi } from './web';
|
||||
|
||||
export interface ApiHub {
|
||||
@@ -23,12 +25,16 @@ export interface ApiHub {
|
||||
readonly groupFile: GroupFileApi;
|
||||
/** Group photo album: list/upload/comment/like/delete + media listing. */
|
||||
readonly groupAlbum: GroupAlbumApi;
|
||||
/** Personal QQ-Zone (个人空间): 说说 list + (future) publish/like/comment. */
|
||||
readonly qzone: QzoneApi;
|
||||
/** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */
|
||||
readonly interaction: InteractionApi;
|
||||
/** Friend roster mutations: handleRequest / delete / setRemark. */
|
||||
readonly friend: FriendApi;
|
||||
/** Personal profile: status / avatar / nickname / likes / custom-faces. */
|
||||
readonly profile: ProfileApi;
|
||||
/** QQ 闪传(fileset 文件集): 上传/查询/分享/发送/删除/重命名。 */
|
||||
readonly flashTransfer: FlashTransferApi;
|
||||
/** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */
|
||||
readonly forward: ForwardApi;
|
||||
/** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */
|
||||
@@ -54,9 +60,11 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
|
||||
groupAdmin: new GroupAdminApi(ctx),
|
||||
groupFile: new GroupFileApi(ctx),
|
||||
groupAlbum: new GroupAlbumApi(ctx),
|
||||
qzone: new QzoneApi(ctx),
|
||||
interaction: new InteractionApi(ctx),
|
||||
friend: new FriendApi(ctx),
|
||||
profile: new ProfileApi(ctx),
|
||||
flashTransfer: new FlashTransferApi(ctx),
|
||||
forward: new ForwardApi(ctx),
|
||||
misc: new MiscApi(ctx),
|
||||
extras: new ExtrasApi(ctx),
|
||||
@@ -78,5 +86,7 @@ export { InteractionApi } from './interaction';
|
||||
export { MessageApi } from './message';
|
||||
export { MiscApi } from './misc';
|
||||
export { ProfileApi } from './profile';
|
||||
export { QzoneApi } from './qzone';
|
||||
export { FlashTransferApi, type FlashFileInfo } from './flash-transfer';
|
||||
export { WebApi } from './web';
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,11 @@ import type {
|
||||
SetStatusReq,
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face';
|
||||
import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face';
|
||||
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
|
||||
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
|
||||
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
|
||||
@@ -147,4 +152,73 @@ export class ProfileApi {
|
||||
const faceIds = resp.item?.faceIds || [];
|
||||
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`);
|
||||
}
|
||||
|
||||
/** 删除一个收藏表情(custom face)。emoji_id 来自 fetchCustomFace 返回的 URL 路径段。 */
|
||||
deleteCustomFace(emojiId: string): Promise<void> {
|
||||
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加收藏表情(custom face)。imageSource 支持 file:///、base64://、http(s)://
|
||||
* (复用 highway utils 的 loadBinarySource)。返回新 emoji_id。
|
||||
*/
|
||||
async addCustomFace(imageSource: string): Promise<string> {
|
||||
const { bytes } = await loadBinarySource(imageSource, 'custom-face');
|
||||
return AddCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, imageBytes: bytes });
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改收藏表情(custom face)备注。emoji_id 来自 fetchCustomFace 返回的
|
||||
* URL 路径段;md5 从 emoji_id 中段解析,无需调用方单独提供。desc 为空串
|
||||
* 则清空备注。
|
||||
*/
|
||||
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
|
||||
return ModifyCustomFace.invoke(this.ctx, {
|
||||
emojiId,
|
||||
md5: md5FromEmojiId(emojiId),
|
||||
desc,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 收藏表情(custom face)移到最前。QQ 客户端只有"移动到最前",协议层
|
||||
* (0x902f 的 f3=1)也只支持最前,不支持移到其他位置。两步流程:先 0x902f
|
||||
* 移动指令,再 0x902e opType=2 上传新顺序(fetch 当前列表把目标挪到第一)。
|
||||
* 两步都发才生效。
|
||||
*/
|
||||
async moveCustomFaceToFront(emojiId: string): Promise<void> {
|
||||
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
|
||||
const urls = await this.fetchCustomFace(1000);
|
||||
const ids = urls.map((url) => {
|
||||
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
|
||||
return m ? m[1] : '';
|
||||
}).filter(Boolean);
|
||||
const idx = ids.indexOf(emojiId);
|
||||
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
|
||||
// 新顺序:目标挪到第一,其余按原顺序
|
||||
const reordered = ids.slice();
|
||||
reordered.splice(idx, 1);
|
||||
reordered.unshift(emojiId);
|
||||
// 2. 0x902f 移动指令(f3=1 = 移到最前)
|
||||
await OrderCustomFace.invoke(this.ctx, { emojiId, position: 1 });
|
||||
// 3. 0x902e opType=2 上传新顺序
|
||||
await MoveCustomFace.invoke(this.ctx, {
|
||||
emojis: reordered.map((id) => ({ emojiId: id, md5: md5FromEmojiId(id) })),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 emoji_id `<uin>_0_0_0_<MD5>_0_0` 提取中段 32 位大写 hex MD5。
|
||||
* 格式固定(fetch/delete/move 共用),取第 5 段。解析失败抛错——比静默
|
||||
* 传空串让服务端拒绝更早定位问题。
|
||||
*/
|
||||
function md5FromEmojiId(emojiId: string): string {
|
||||
const parts = emojiId.split('_');
|
||||
// 期望形如 `<uin>_0_0_0_<md5>_0_0`,共 7 段,md5 在 index 4。
|
||||
const md5 = parts[4];
|
||||
if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) {
|
||||
throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`);
|
||||
}
|
||||
return md5.toUpperCase();
|
||||
}
|
||||
|
||||
76
packages/core/src/bridge/apis/qzone.ts
Normal file
76
packages/core/src/bridge/apis/qzone.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
commentQzoneMsg,
|
||||
deleteQzoneMsg,
|
||||
getQzoneFeeds,
|
||||
getQzoneMsgList,
|
||||
publishQzoneMsg,
|
||||
setQzoneLike,
|
||||
type QzoneCommentResult,
|
||||
type QzoneFeedsResult,
|
||||
type QzoneMsgListResult,
|
||||
type QzonePublishResult,
|
||||
} from '@snowluma/protocol/web/qzone';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
/**
|
||||
* Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes,
|
||||
* comments — all over the cookie-backed qzone.qq.com CGIs, reusing the same
|
||||
* `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi. Distinct from the
|
||||
* group-album surface, which lives on GroupAlbumApi.
|
||||
*/
|
||||
export class QzoneApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
/**
|
||||
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
|
||||
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
|
||||
*/
|
||||
async getMsgList(targetUin?: number, pos = 0, num = 20): Promise<QzoneMsgListResult> {
|
||||
const uin = targetUin && targetUin > 0 ? targetUin.toString() : this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneMsgList(cookieObject, uin, pos, num);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
|
||||
* 始终以机器人自己的身份拉取好友动态。
|
||||
*/
|
||||
async getFeeds(pageNum = 1, count = 10): Promise<QzoneFeedsResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
|
||||
}
|
||||
|
||||
/** 发表一条纯文字说说,返回新说说的 tid。始终发到机器人自己的空间。 */
|
||||
async publish(content: string): Promise<QzonePublishResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content);
|
||||
}
|
||||
|
||||
/** 删除机器人自己空间的一条说说(按 tid)。 */
|
||||
async delete(tid: string): Promise<void> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
|
||||
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
|
||||
*/
|
||||
async like(tid: string, targetUin: number | undefined, like: boolean, abstime = 0): Promise<void> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await setQzoneLike(cookieObject, selfUin, owner, tid, like, abstime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
|
||||
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
|
||||
*/
|
||||
async comment(tid: string, content: string, targetUin: number | undefined): Promise<QzoneCommentResult> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
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';
|
||||
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
|
||||
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
|
||||
import {
|
||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||
getGroupNoticeWebAPI,
|
||||
@@ -226,6 +228,16 @@ export class WebApi {
|
||||
return honorInfo;
|
||||
}
|
||||
|
||||
// ─────────────── group sign-in (打卡) ───────────────
|
||||
|
||||
/** Today's group sign-in list via qun.qq.com. [] when the group has no
|
||||
* sign-ins; THROWS on transport / auth failure (caller maps to failed). */
|
||||
async getSignedList(groupId: number): Promise<SignedListMember[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return getDaySignedListWebAPI(cookieObject, groupId.toString(), bridge.identity.uin.toString());
|
||||
}
|
||||
|
||||
// ─────────────── group notice ───────────────
|
||||
|
||||
async sendNotice(
|
||||
@@ -247,16 +259,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);
|
||||
|
||||
250
packages/core/src/notifications/config.ts
Normal file
250
packages/core/src/notifications/config.ts
Normal file
@@ -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;
|
||||
}
|
||||
82
packages/core/src/notifications/debounce.ts
Normal file
82
packages/core/src/notifications/debounce.ts
Normal file
@@ -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);
|
||||
}
|
||||
}
|
||||
255
packages/core/src/notifications/manager.ts
Normal file
255
packages/core/src/notifications/manager.ts
Normal file
@@ -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(),
|
||||
});
|
||||
}
|
||||
125
packages/core/src/webui/backup.ts
Normal file
125
packages/core/src/webui/backup.ts
Normal file
@@ -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 };
|
||||
}
|
||||
184
packages/core/src/webui/consent.ts
Normal file
184
packages/core/src/webui/consent.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createHash } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const log = createLogger('WebUI.Consent');
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const CONSENT_CONFIG_PATH = path.join(CONFIG_DIR, 'consent.json');
|
||||
|
||||
// The two legal documents shown at the consent gate. Source of truth is the
|
||||
// repo-root markdown; the build copies them next to the bundle (dist/) so the
|
||||
// same lookup works in a packaged deploy. See vite.config.ts cp targets.
|
||||
const AGREEMENT_FILES = [
|
||||
{ id: 'eula' as const, file: 'EULA.md' },
|
||||
{ id: 'privacy' as const, file: 'PRIVACY.md' },
|
||||
];
|
||||
|
||||
export interface AgreementDoc {
|
||||
id: 'eula' | 'privacy';
|
||||
/** First markdown `# ` heading, for the tab/section title. */
|
||||
title: string;
|
||||
/** Declared "Version: x" from the doc — display only, NOT the consent key. */
|
||||
declaredVersion: string;
|
||||
/** Declared effective date (YYYY-MM-DD) — display only. */
|
||||
effectiveDate: string;
|
||||
/** Full markdown body the frontend renders. */
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ConsentRecord {
|
||||
/** The content-hash agreements version that was accepted. */
|
||||
version: string;
|
||||
/** ISO timestamp of acceptance. */
|
||||
acceptedAt: string;
|
||||
}
|
||||
|
||||
export interface AgreementsPayload {
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/**
|
||||
* True when the operator must (re-)accept: the agreements carry real text
|
||||
* AND the stored consent version differs from the current one. A missing or
|
||||
* unreadable agreement set fails OPEN (no gate) so a broken bundle can never
|
||||
* lock the admin out of their own panel.
|
||||
*/
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
}
|
||||
|
||||
// ── Agreement loading (pure-ish; file read + parse, cached) ─────────────────
|
||||
|
||||
/**
|
||||
* Resolve an agreement file across the dev and packaged layouts. In dev the
|
||||
* server runs from source (`__dirname` = packages/core/src/webui); in a build
|
||||
* it is the single bundled dist/index.mjs (`__dirname` = dist/) with the docs
|
||||
* copied alongside. cwd is not reliable (dev cwd = packages/core, prod = repo
|
||||
* root or dist/), so we probe a handful of candidates and take the first hit.
|
||||
*/
|
||||
function resolveAgreementFile(file: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, file), // packaged: dist/<file>
|
||||
path.resolve(__dirname, '..', '..', '..', '..', file), // dev tsx: repoRoot/<file>
|
||||
path.resolve(process.cwd(), file), // started from repo root
|
||||
path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
} catch {
|
||||
/* unreadable candidate, try next */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Extract title / declared version / effective date from a doc body. */
|
||||
export function parseAgreementMeta(text: string): {
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
} {
|
||||
const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? '';
|
||||
// Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines.
|
||||
const declaredVersion =
|
||||
text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.\-]*)/)?.[1]?.trim() ?? '';
|
||||
const effectiveDate =
|
||||
text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? '';
|
||||
return { title, declaredVersion, effectiveDate };
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical agreements version = short sha256 over each doc's id + body.
|
||||
* Deliberately content-derived, NOT app-version-derived: it stays stable when
|
||||
* only the app is upgraded (so a one-time consent survives across versions),
|
||||
* and changes the moment any agreement's TEXT changes (forcing re-consent).
|
||||
*/
|
||||
export function computeAgreementsVersion(docs: { id: string; text: string }[]): string {
|
||||
const hash = createHash('sha256');
|
||||
for (const doc of docs) {
|
||||
hash.update(doc.id);
|
||||
hash.update('\0');
|
||||
hash.update(doc.text);
|
||||
hash.update('\0');
|
||||
}
|
||||
return hash.digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
let cache: { docs: AgreementDoc[]; version: string } | null = null;
|
||||
|
||||
/** Load + parse both agreements and compute the version. Cached per process. */
|
||||
export function loadAgreements(): { docs: AgreementDoc[]; version: string } {
|
||||
if (cache) return cache;
|
||||
const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => {
|
||||
const resolved = resolveAgreementFile(file);
|
||||
let text = '';
|
||||
if (resolved) {
|
||||
try {
|
||||
text = fs.readFileSync(resolved, 'utf8');
|
||||
} catch (err) {
|
||||
log.warn('failed to read %s: %s', file, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else {
|
||||
log.warn('agreement file not found (looked for %s near the bundle and repo root)', file);
|
||||
}
|
||||
const meta = parseAgreementMeta(text);
|
||||
return { id, title: meta.title, declaredVersion: meta.declaredVersion, effectiveDate: meta.effectiveDate, text };
|
||||
});
|
||||
cache = { docs, version: computeAgreementsVersion(docs) };
|
||||
return cache;
|
||||
}
|
||||
|
||||
// ── Consent persistence (config/consent.json, atomic) ───────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function isConsentRecord(value: unknown): value is ConsentRecord {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string';
|
||||
}
|
||||
|
||||
export function loadConsentRecord(): ConsentRecord | null {
|
||||
try {
|
||||
if (!fs.existsSync(CONSENT_CONFIG_PATH)) return null;
|
||||
const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isConsentRecord(parsed) ? parsed : null;
|
||||
} catch (err) {
|
||||
log.warn('consent.json unreadable, treating as no consent: %s', err instanceof Error ? err.message : String(err));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(record: ConsentRecord): void {
|
||||
ensureConfigDir();
|
||||
const tmp = CONSENT_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: 'utf8' });
|
||||
fs.renameSync(tmp, CONSENT_CONFIG_PATH);
|
||||
}
|
||||
|
||||
/** Persist that the operator accepted `version`. Returns the stored record. */
|
||||
export function recordConsent(version: string): ConsentRecord {
|
||||
const record: ConsentRecord = { version, acceptedAt: new Date().toISOString() };
|
||||
atomicWrite(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
/** True when the agreements carry real text and the stored consent is stale. */
|
||||
export function isConsentRequired(): boolean {
|
||||
const { docs, version } = loadAgreements();
|
||||
const hasContent = docs.some((d) => d.text.trim().length > 0);
|
||||
if (!hasContent) return false; // fail open: never brick the panel on a broken bundle
|
||||
return loadConsentRecord()?.version !== version;
|
||||
}
|
||||
|
||||
/** Public payload for GET /api/agreements (texts + version + consentRequired). */
|
||||
export function getAgreementsPayload(): AgreementsPayload {
|
||||
const { docs, version } = loadAgreements();
|
||||
return { version, consentRequired: isConsentRequired(), documents: docs };
|
||||
}
|
||||
28
packages/core/src/webui/debug-stream.ts
Normal file
28
packages/core/src/webui/debug-stream.ts
Normal file
@@ -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,38 @@ 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 { execSync } from 'child_process';
|
||||
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 { getAgreementsPayload, isConsentRequired, loadAgreements, recordConsent } from './consent';
|
||||
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));
|
||||
@@ -38,6 +60,23 @@ const MUST_CHANGE_ALLOWLIST = new Set([
|
||||
'/api/auth/state',
|
||||
'/api/auth/check-strength',
|
||||
'/api/auth/change-password',
|
||||
// Consent is collected AFTER login but BEFORE the forced password change, so
|
||||
// reading + recording it must be reachable while the session mustChangePassword.
|
||||
'/api/agreements',
|
||||
'/api/agreements/record-consent',
|
||||
'/api/logout',
|
||||
]);
|
||||
|
||||
// Endpoints reachable while consent is still pending. Everything else is 403'd
|
||||
// with consentRequired:true until the operator accepts — the same server-side
|
||||
// enforcement pattern as MUST_CHANGE_ALLOWLIST, so the consent gate is real and
|
||||
// not merely a frontend convention. Ordered BEFORE the must-change gate so a
|
||||
// fresh install must consent first, then set its password.
|
||||
const CONSENT_ALLOWLIST = new Set([
|
||||
'/api/status',
|
||||
'/api/auth/state',
|
||||
'/api/agreements',
|
||||
'/api/agreements/record-consent',
|
||||
'/api/logout',
|
||||
]);
|
||||
|
||||
@@ -47,6 +86,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 +105,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`, {
|
||||
@@ -87,11 +119,213 @@ async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentTy
|
||||
return { body, contentType };
|
||||
}
|
||||
|
||||
// ── Host system info (cached at module level, invariant over process lifetime) ──
|
||||
|
||||
function detectDistro(): string {
|
||||
// Helper: extract major.minor.patch from a kernel version string
|
||||
const parseKernel = (v: string): string | null => { const m = v.match(/(\d+\.\d+\.\d+)/); return m?.[1] ?? null; };
|
||||
|
||||
// ── Linux ──────────────────────────────────────────────────────────
|
||||
if (os.platform() === 'linux') {
|
||||
const kernelRelease = os.release();
|
||||
const kernelVer = parseKernel(kernelRelease);
|
||||
|
||||
// Normalize RHEL-family distro names before comparison.
|
||||
// /proc/version typically shows "Red Hat" (GCC build tag) even on
|
||||
// Rocky / Alma / Oracle Linux, while /etc/os-release carries the
|
||||
// actual distro name. Treat the whole family as a single group so
|
||||
// they are never considered "disagreeing".
|
||||
const isRhelFamily = (name: string): boolean =>
|
||||
/^(red hat|centos|rocky|alma|oracle|scientific|anolis|tencentos|bclinux|opencloudos)/.test(name);
|
||||
|
||||
// Extract distro version from kernel release string.
|
||||
// Distros embed their version in the kernel ABI / build tag:
|
||||
// Debian: "6.8.12-1-deb13-amd64" → 13
|
||||
// RHEL family: "4.18.0-513.el9.x86_64" → 9
|
||||
// Fedora: "6.8.12-300.fc40.x86_64" → 40
|
||||
// Amazon Linux: "6.1.158-178.288.amzn2023" → 2023
|
||||
// Mageia: "6.8.12-1.mga10" → 10
|
||||
const kernelDistroVer = (distro: string | null): string | null => {
|
||||
if (!distro) return null;
|
||||
const lr = kernelRelease.toLowerCase();
|
||||
const ld = distro.toLowerCase();
|
||||
if (ld === 'debian') { const m = lr.match(/deb(\d+)/); if (m) return m[1]; }
|
||||
if (isRhelFamily(ld)) { const m = lr.match(/el(\d+)/); if (m) return m[1]; }
|
||||
if (ld === 'fedora') { const m = lr.match(/fc(\d+)/); if (m) return m[1]; }
|
||||
if (ld === 'amazon' || ld.includes('amazon')) { const m = lr.match(/amzn(\d+)/); if (m) return m[1]; }
|
||||
if (ld === 'mageia') { const m = lr.match(/mga(\d+)/); if (m) return m[1]; }
|
||||
if (ld === 'armbian') { const m = lr.match(/armbian(\d+)/); if (m) return m[1]; }
|
||||
if (ld === 'dietpi') { const m = lr.match(/dietpi(\d+)/); if (m) return m[1]; }
|
||||
if (ld.includes('libreelec')) { const m = lr.match(/libreelec(\d+)/); if (m) return m[1]; }
|
||||
if (ld.includes('coreelec')) { const m = lr.match(/coreelec(\d+)/); if (m) return m[1]; }
|
||||
return null;
|
||||
};
|
||||
|
||||
// Source A: /proc/version (host kernel build, crosses container boundary)
|
||||
let hostName: string | null = null;
|
||||
try {
|
||||
const raw = readFileSync('/proc/version', 'utf8').trim();
|
||||
const vm = raw.match(/^Linux version\s+(\S+)/);
|
||||
if (vm) {
|
||||
// Step 1: kernel release string — embedded distros embed their name
|
||||
// here (e.g. "6.6.16-armbian", "6.1.60-dietpi"). More reliable than
|
||||
// the GCC build tag, which often shows the cross-compilation toolchain
|
||||
// (e.g. "Ubuntu" for Armbian / DietPi) rather than the actual OS.
|
||||
const releaseStr = vm[1].toLowerCase();
|
||||
const releaseNameMatch = releaseStr.match(/(armbian|dietpi|libreelec|coreelec)/);
|
||||
if (releaseNameMatch) {
|
||||
const nameMap: Record<string, string> = {
|
||||
armbian: 'Armbian',
|
||||
dietpi: 'DietPi',
|
||||
libreelec: 'LibreELEC',
|
||||
coreelec: 'CoreELEC',
|
||||
};
|
||||
hostName = nameMap[releaseNameMatch[1]] ?? releaseNameMatch[1];
|
||||
} else {
|
||||
// Step 2: GCC build tag — matches the distribution that compiled
|
||||
// the running kernel (e.g. "(Ubuntu ...)", "(Debian ...)",
|
||||
// "(Red Hat ...)").
|
||||
const dm = raw.match(/\b(Debian|Ubuntu|Red Hat|CentOS|Fedora|Alpine|Arch|Gentoo|SUSE|Proxmox|OpenWrt|Deepin|Kylin|openEuler|Anolis|UOS|Linux Mint|Slackware|Manjaro|NixOS|Void|Mageia|Kali|Amazon|Solus|Alibaba|Armbian|DietPi|Raspbian)\b/i);
|
||||
hostName = dm ? dm[1] : null;
|
||||
}
|
||||
}
|
||||
} catch { /* source A unavailable */ }
|
||||
|
||||
// Source B: /etc/os-release (container / local OS)
|
||||
let osReleaseName: string | null = null;
|
||||
let osReleaseVer: string | null = null;
|
||||
try {
|
||||
for (const f of ['/etc/os-release', '/usr/lib/os-release']) {
|
||||
if (!existsSync(f)) continue;
|
||||
const raw = readFileSync(f, 'utf8');
|
||||
const get = (k: string) => { const m = raw.match(new RegExp(`^${k}=("?)(.+?)\\1$`, 'm')); return m?.[2] ?? null; };
|
||||
const pretty = get('PRETTY_NAME') || get('NAME');
|
||||
const ver = get('VERSION_ID');
|
||||
if (pretty) {
|
||||
const nm = pretty.match(/^([^0-9]+)/);
|
||||
osReleaseName = nm ? nm[1].trim() : pretty;
|
||||
osReleaseVer = ver;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch { /* source B unavailable */ }
|
||||
|
||||
// Decide which source to trust for the distro name & version
|
||||
let finalName: string;
|
||||
let finalVer: string | null;
|
||||
|
||||
if (hostName && osReleaseName) {
|
||||
// Normalize and compare: e.g. "Debian" vs "Debian GNU/Linux" → match.
|
||||
// RHEL family members (Red Hat, CentOS, Rocky, Alma, Oracle, Scientific)
|
||||
// are normalised to the same group — /proc/version usually shows "Red Hat"
|
||||
// (GCC build tag) even when the actual distro is Rocky / Alma / Oracle.
|
||||
const a = hostName.toLowerCase();
|
||||
const b = osReleaseName.toLowerCase();
|
||||
if (a.includes(b) || b.includes(a) || (isRhelFamily(a) && isRhelFamily(b))) {
|
||||
// Agree → prefer version from kernel release, fall back to os-release
|
||||
finalName = osReleaseName;
|
||||
finalVer = kernelDistroVer(hostName) ?? osReleaseVer;
|
||||
} else {
|
||||
// Disagree → host kernel build wins (crosses container boundary)
|
||||
finalName = hostName;
|
||||
finalVer = kernelDistroVer(hostName);
|
||||
}
|
||||
} else if (hostName) {
|
||||
finalName = hostName;
|
||||
finalVer = kernelDistroVer(hostName);
|
||||
} else if (osReleaseName) {
|
||||
finalName = osReleaseName;
|
||||
finalVer = kernelDistroVer(osReleaseName) ?? osReleaseVer;
|
||||
} else {
|
||||
// Source C: legacy release files
|
||||
for (const [path, prefix] of [
|
||||
['/etc/alpine-release', 'Alpine Linux '],
|
||||
['/etc/redhat-release', ''],
|
||||
['/etc/debian_version', 'Debian '],
|
||||
] as [string, string][]) {
|
||||
try {
|
||||
if (existsSync(path)) {
|
||||
const raw = prefix + readFileSync(path, 'utf8').trim();
|
||||
return kernelVer ? `${raw} (kernel ${kernelVer})` : raw;
|
||||
}
|
||||
} catch { /* try next */ }
|
||||
}
|
||||
return kernelVer ? `Linux (kernel ${kernelVer})` : 'Linux';
|
||||
}
|
||||
|
||||
// Unified output: <Name> <version> (kernel <kernel>)
|
||||
const base = finalVer ? `${finalName} ${finalVer}` : finalName;
|
||||
return kernelVer ? `${base} (kernel ${kernelVer})` : base;
|
||||
}
|
||||
|
||||
// ── Windows ────────────────────────────────────────────────────────
|
||||
if (os.platform() === 'win32') {
|
||||
try {
|
||||
const productName = execSync(
|
||||
'reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v ProductName',
|
||||
{ encoding: 'utf8', timeout: 3000, stdio: 'pipe' },
|
||||
);
|
||||
const m = productName.match(/ProductName\s+REG_SZ\s+(.+)/);
|
||||
let name = m ? m[1].trim() : `Windows ${os.release()}`;
|
||||
// ProductName is still "Windows 10 Pro" on Windows 11 — check build number.
|
||||
try {
|
||||
const buildOut = execSync(
|
||||
'reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v CurrentBuildNumber',
|
||||
{ encoding: 'utf8', timeout: 3000, stdio: 'pipe' },
|
||||
);
|
||||
const bm = buildOut.match(/CurrentBuildNumber\s+REG_SZ\s+(\d+)/);
|
||||
if (bm && parseInt(bm[1], 10) >= 22000) {
|
||||
name = name.replace(/^Windows 10/, 'Windows 11');
|
||||
}
|
||||
} catch { /* keep name as-is */ }
|
||||
return name;
|
||||
} catch { /* fall through */ }
|
||||
return `Windows ${os.release()}`;
|
||||
}
|
||||
|
||||
return os.platform();
|
||||
}
|
||||
|
||||
function normalizeArch(arch: string): string {
|
||||
const map: Record<string, string> = {
|
||||
loong64: 'LoongArch',
|
||||
riscv64: 'RISC-V',
|
||||
mips: 'MIPS',
|
||||
mipsel: 'MIPS (LE)',
|
||||
arm: 'ARM',
|
||||
arm64: 'ARM64',
|
||||
x64: 'x86_64',
|
||||
ia32: 'x86',
|
||||
s390: 'S/390',
|
||||
s390x: 'S/390x',
|
||||
ppc: 'PowerPC',
|
||||
ppc64: 'PowerPC64',
|
||||
ppc64le: 'PowerPC64 (LE)',
|
||||
};
|
||||
return map[arch] ?? arch;
|
||||
}
|
||||
|
||||
const CACHED_DISTRO = (() => { try { return detectDistro(); } catch { return os.platform(); } })();
|
||||
const CACHED_ARCH_LABEL = normalizeArch(os.arch());
|
||||
|
||||
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()) {
|
||||
@@ -114,6 +348,12 @@ export async function initWebUI(
|
||||
log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For');
|
||||
}
|
||||
|
||||
// Memoized once at startup (agreements version is fixed per process; a text
|
||||
// change ships with a redeploy that restarts us). Flipped to false the moment
|
||||
// consent is recorded, so the middleware never touches disk per request.
|
||||
let consentGatePending = isConsentRequired();
|
||||
if (consentGatePending) log.info('awaiting EULA/PRIVACY consent before the panel unlocks');
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
// ─── Anti-indexing ───────────────────────────────────────────────────────
|
||||
@@ -139,7 +379,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) : '';
|
||||
@@ -152,6 +395,17 @@ export async function initWebUI(
|
||||
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
|
||||
}
|
||||
|
||||
// Consent gate (before the password gate): block everything outside the
|
||||
// consent allowlist until the operator has accepted the current agreements.
|
||||
// `consentGatePending` is memoized (see below) so this is a Set lookup, not
|
||||
// a disk read, on the hot path.
|
||||
if (consentGatePending && !CONSENT_ALLOWLIST.has(reqPath)) {
|
||||
return c.json(
|
||||
{ status: 'failed', message: '请先阅读并同意用户协议与隐私政策', consentRequired: true },
|
||||
403,
|
||||
);
|
||||
}
|
||||
|
||||
if (info.mustChangePassword && !MUST_CHANGE_ALLOWLIST.has(reqPath)) {
|
||||
return c.json({ status: 'failed', message: '请先修改密码', mustChangePassword: true }, 403);
|
||||
}
|
||||
@@ -257,6 +511,41 @@ export async function initWebUI(
|
||||
return c.json({ success: true, requireRelogin: true });
|
||||
});
|
||||
|
||||
// ─── EULA / PRIVACY consent ──────────────────────────────────────────────
|
||||
// Both are bearer-gated (consent is collected AFTER login) and live in the
|
||||
// consent + must-change allowlists so they're reachable during onboarding.
|
||||
// The version is content-derived, so consent is stable across app upgrades
|
||||
// and re-prompted only when the agreement text itself changes.
|
||||
app.get('/api/agreements', (c) => c.json(getAgreementsPayload()));
|
||||
|
||||
app.post('/api/agreements/record-consent', async (c) => {
|
||||
let body: { version?: unknown };
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const version = typeof body.version === 'string' ? body.version : '';
|
||||
const current = loadAgreements().version;
|
||||
// Reject a stale/blank version so a client that read an older agreement set
|
||||
// can't record consent that the server would then treat as current.
|
||||
if (!version || version !== current) {
|
||||
return c.json(
|
||||
{ success: false, message: '协议版本已更新,请刷新后重新确认', currentVersion: current },
|
||||
409,
|
||||
);
|
||||
}
|
||||
try {
|
||||
recordConsent(version);
|
||||
} catch (err) {
|
||||
log.warn('record consent failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
consentGatePending = false; // unlock the rest of the API for this process
|
||||
log.info('agreements consent recorded (version=%s)', version);
|
||||
return c.json({ success: true, version });
|
||||
});
|
||||
|
||||
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
|
||||
app.get('/avatar/:uin', async (c) => {
|
||||
const uin = c.req.param('uin');
|
||||
@@ -282,10 +571,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' }));
|
||||
|
||||
// Host system info
|
||||
// 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));
|
||||
});
|
||||
|
||||
let lastCpuTimes: { idle: number; total: number }[] | null = null;
|
||||
function sampleCpuLoad(): number[] {
|
||||
const cpus = os.cpus();
|
||||
@@ -320,7 +637,9 @@ export async function initWebUI(
|
||||
hostname: os.hostname(),
|
||||
platform: os.platform(),
|
||||
arch: os.arch(),
|
||||
archLabel: CACHED_ARCH_LABEL,
|
||||
release: os.release(),
|
||||
distro: CACHED_DISTRO,
|
||||
uptime: os.uptime(),
|
||||
processUptime: process.uptime(),
|
||||
nodeVersion: process.version,
|
||||
@@ -349,12 +668,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 +1065,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 +1206,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 +1227,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();
|
||||
});
|
||||
});
|
||||
|
||||
52
packages/core/src/webui/system-settings.ts
Normal file
52
packages/core/src/webui/system-settings.ts
Normal file
@@ -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 };
|
||||
}
|
||||
57
packages/core/src/webui/tls.ts
Normal file
57
packages/core/src/webui/tls.ts
Normal file
@@ -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 };
|
||||
}
|
||||
782
packages/core/src/webui/ui-config.ts
Normal file
782
packages/core/src/webui/ui-config.ts
Normal file
@@ -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;
|
||||
sidebarPinned: 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,
|
||||
sidebarPinned: 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),
|
||||
sidebarPinned: boolOr(v.sidebarPinned, DEFAULT_APPEARANCE.sidebarPinned),
|
||||
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;
|
||||
}
|
||||
}
|
||||
163
packages/core/src/webui/update-check.ts
Normal file
163
packages/core/src/webui/update-check.ts
Normal file
@@ -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(),
|
||||
};
|
||||
}
|
||||
106
packages/core/tests/actions/qzone.test.ts
Normal file
106
packages/core/tests/actions/qzone.test.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import * as qzoneWeb from '@snowluma/protocol/web/qzone';
|
||||
import { QzoneApi } from '../../src/bridge/apis/qzone';
|
||||
import { mockApiHub, mockBridge } from './_helpers';
|
||||
|
||||
// QzoneApi is the only place the string(identity.uin)/number(action param)
|
||||
// boundary is crossed, so its target_uin defaulting + the `> 0` guard are
|
||||
// worth locking. We stub the protocol-layer getQzoneMsgList and the web
|
||||
// cookie fetch so the test asserts purely what the bridge passes down.
|
||||
|
||||
describe('apis/qzone', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
function bridgeWithWeb() {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const fetchSpy = vi
|
||||
.spyOn(qzoneWeb, 'getQzoneMsgList')
|
||||
.mockResolvedValue({ total: 0, msglist: [] });
|
||||
return { bridge, getCookies, fetchSpy };
|
||||
}
|
||||
|
||||
it('defaults target_uin to the bot\'s own uin and uses default pos/num', async () => {
|
||||
const { bridge, getCookies, fetchSpy } = bridgeWithWeb();
|
||||
await new QzoneApi(bridge as never).getMsgList();
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
// identity.uin is '10001' (a string) — passed straight through.
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 0, 20);
|
||||
});
|
||||
|
||||
it('treats target_uin 0 as absent and falls back to own uin', async () => {
|
||||
const { bridge, fetchSpy } = bridgeWithWeb();
|
||||
await new QzoneApi(bridge as never).getMsgList(0);
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 0, 20);
|
||||
});
|
||||
|
||||
it('passes a real target_uin (stringified) plus pos/num through', async () => {
|
||||
const { bridge, fetchSpy } = bridgeWithWeb();
|
||||
await new QzoneApi(bridge as never).getMsgList(20002, 5, 50);
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '20002', 5, 50);
|
||||
});
|
||||
|
||||
it('getFeeds always uses the bot\'s own uin and threads pageNum/count', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const feedsSpy = vi.spyOn(qzoneWeb, 'getQzoneFeeds').mockResolvedValue({ feeds: [], has_more: false });
|
||||
await new QzoneApi(bridge as never).getFeeds(3, 20);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20);
|
||||
});
|
||||
|
||||
it('publish posts to the bot\'s own space with the given content', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
|
||||
const out = await new QzoneApi(bridge as never).publish('hello');
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello');
|
||||
expect(out).toEqual({ tid: 'T', time: 1 });
|
||||
});
|
||||
|
||||
it('delete removes a feed by tid from the bot\'s own space', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const delSpy = vi.spyOn(qzoneWeb, 'deleteQzoneMsg').mockResolvedValue();
|
||||
await new QzoneApi(bridge as never).delete('TID9');
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(delSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'TID9');
|
||||
});
|
||||
|
||||
it('like defaults the feed owner to self and passes opUin=self + like flag', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const likeSpy = vi.spyOn(qzoneWeb, 'setQzoneLike').mockResolvedValue();
|
||||
await new QzoneApi(bridge as never).like('TIDX', undefined, true, 1700000000);
|
||||
// opUin = self ('10001'), owner defaults to self when target_uin absent; abstime threaded
|
||||
expect(likeSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', true, 1700000000);
|
||||
});
|
||||
|
||||
it('like targets a friend\'s space (owner = target_uin) and threads the unlike flag + abstime default', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const likeSpy = vi.spyOn(qzoneWeb, 'setQzoneLike').mockResolvedValue();
|
||||
await new QzoneApi(bridge as never).like('TIDX', 20002, false);
|
||||
// abstime defaults to 0 when omitted
|
||||
expect(likeSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', false, 0);
|
||||
});
|
||||
|
||||
it('comment defaults the feed owner to self and posts as self', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '1' });
|
||||
const out = await new QzoneApi(bridge as never).comment('TIDX', 'nice', undefined);
|
||||
// selfUin='10001' commenter; owner defaults to self
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice');
|
||||
expect(out).toEqual({ comment_id: '1' });
|
||||
});
|
||||
|
||||
it('comment targets a friend\'s feed (owner = target_uin), commenter stays self', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '2' });
|
||||
await new QzoneApi(bridge as never).comment('TIDX', 'nice', 20002);
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice');
|
||||
});
|
||||
});
|
||||
@@ -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]');
|
||||
|
||||
78
packages/core/tests/group-history-walkback.test.ts
Normal file
78
packages/core/tests/group-history-walkback.test.ts
Normal file
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
161
packages/core/tests/highway/highway-client.test.ts
Normal file
161
packages/core/tests/highway/highway-client.test.ts
Normal file
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
194
packages/core/tests/notifications-config.test.ts
Normal file
194
packages/core/tests/notifications-config.test.ts
Normal file
@@ -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());
|
||||
});
|
||||
});
|
||||
71
packages/core/tests/notifications-debounce.test.ts
Normal file
71
packages/core/tests/notifications-debounce.test.ts
Normal file
@@ -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
|
||||
});
|
||||
});
|
||||
199
packages/core/tests/notifications-manager.test.ts
Normal file
199
packages/core/tests/notifications-manager.test.ts
Normal file
@@ -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']);
|
||||
});
|
||||
});
|
||||
128
packages/core/tests/webui-backup.test.ts
Normal file
128
packages/core/tests/webui-backup.test.ts
Normal file
@@ -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);
|
||||
});
|
||||
52
packages/core/tests/webui-debug-stream.test.ts
Normal file
52
packages/core/tests/webui-debug-stream.test.ts
Normal file
@@ -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);
|
||||
});
|
||||
});
|
||||
39
packages/core/tests/webui-system-settings.test.ts
Normal file
39
packages/core/tests/webui-system-settings.test.ts
Normal file
@@ -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: '' } });
|
||||
});
|
||||
});
|
||||
102
packages/core/tests/webui-tls.test.ts
Normal file
102
packages/core/tests/webui-tls.test.ts
Normal file
@@ -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();
|
||||
});
|
||||
});
|
||||
BIN
packages/core/tests/webui-ui-config.test.ts
Normal file
BIN
packages/core/tests/webui-ui-config.test.ts
Normal file
Binary file not shown.
108
packages/core/tests/webui/consent.test.ts
Normal file
108
packages/core/tests/webui/consent.test.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import {
|
||||
computeAgreementsVersion,
|
||||
parseAgreementMeta,
|
||||
recordConsent,
|
||||
loadConsentRecord,
|
||||
} from '@/webui/consent';
|
||||
|
||||
describe('computeAgreementsVersion', () => {
|
||||
it('is deterministic for identical input', () => {
|
||||
const docs = [
|
||||
{ id: 'eula', text: 'A' },
|
||||
{ id: 'privacy', text: 'B' },
|
||||
];
|
||||
expect(computeAgreementsVersion(docs)).toBe(computeAgreementsVersion(docs));
|
||||
});
|
||||
|
||||
it('changes when any agreement TEXT changes (forces re-consent)', () => {
|
||||
const before = computeAgreementsVersion([
|
||||
{ id: 'eula', text: 'terms v1' },
|
||||
{ id: 'privacy', text: 'privacy v1' },
|
||||
]);
|
||||
const after = computeAgreementsVersion([
|
||||
{ id: 'eula', text: 'terms v2' }, // edited
|
||||
{ id: 'privacy', text: 'privacy v1' },
|
||||
]);
|
||||
expect(after).not.toBe(before);
|
||||
});
|
||||
|
||||
it('is independent of app version — same text => same version', () => {
|
||||
// The function takes only doc id+text, never an app version, so an app
|
||||
// upgrade with unchanged docs yields an identical version (stable consent).
|
||||
const v1 = computeAgreementsVersion([{ id: 'eula', text: 'same' }]);
|
||||
const v2 = computeAgreementsVersion([{ id: 'eula', text: 'same' }]);
|
||||
expect(v1).toBe(v2);
|
||||
});
|
||||
|
||||
it('is not fooled by id/text boundary shifting', () => {
|
||||
const a = computeAgreementsVersion([{ id: 'eula', text: 'x' }]);
|
||||
const b = computeAgreementsVersion([{ id: 'eu', text: 'lax' }]);
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseAgreementMeta', () => {
|
||||
it('pulls title / declared version / effective date from a bilingual doc', () => {
|
||||
const text = [
|
||||
'# SnowLuma 最终用户许可协议(EULA)/ End-User License Agreement',
|
||||
'',
|
||||
'- **生效日期 / Effective date:** 2026-06-19',
|
||||
'- **版本 / Version:** 1.0',
|
||||
'',
|
||||
'正文…',
|
||||
].join('\n');
|
||||
const meta = parseAgreementMeta(text);
|
||||
expect(meta.title).toBe('SnowLuma 最终用户许可协议(EULA)/ End-User License Agreement');
|
||||
expect(meta.declaredVersion).toBe('1.0');
|
||||
expect(meta.effectiveDate).toBe('2026-06-19');
|
||||
});
|
||||
|
||||
it('degrades gracefully on empty text', () => {
|
||||
expect(parseAgreementMeta('')).toEqual({ title: '', declaredVersion: '', effectiveDate: '' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('consent persistence', () => {
|
||||
let tmp: string;
|
||||
let cwd: string;
|
||||
|
||||
beforeEach(() => {
|
||||
cwd = process.cwd();
|
||||
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-consent-'));
|
||||
process.chdir(tmp);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(cwd);
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('records and reads back the accepted version', () => {
|
||||
expect(loadConsentRecord()).toBeNull();
|
||||
const rec = recordConsent('abc123');
|
||||
expect(rec.version).toBe('abc123');
|
||||
expect(Date.parse(rec.acceptedAt)).not.toBeNaN();
|
||||
|
||||
const loaded = loadConsentRecord();
|
||||
expect(loaded?.version).toBe('abc123');
|
||||
expect(fs.existsSync(path.join('config', 'consent.json'))).toBe(true);
|
||||
});
|
||||
|
||||
it('staleness check: stored version != current => re-consent needed', () => {
|
||||
recordConsent('old-version');
|
||||
const stored = loadConsentRecord();
|
||||
// mirrors isConsentRequired()'s comparison against the current version
|
||||
expect(stored?.version !== 'new-version').toBe(true);
|
||||
expect(stored?.version !== 'old-version').toBe(false);
|
||||
});
|
||||
|
||||
it('ignores a malformed consent.json (treated as no consent)', () => {
|
||||
fs.mkdirSync('config', { recursive: true });
|
||||
fs.writeFileSync(path.join('config', 'consent.json'), '{ not json');
|
||||
expect(loadConsentRecord()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -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`]
|
||||
: []),
|
||||
@@ -91,6 +83,19 @@ if (missingNatives.length > 0) {
|
||||
);
|
||||
}
|
||||
|
||||
// Legal docs are served by the WebUI consent gate; a missing one would silently
|
||||
// disable consent in the shipped build, so fail the build instead (mirrors the
|
||||
// native-binary guard above).
|
||||
const missingAgreements = ['EULA.md', 'PRIVACY.md'].filter(
|
||||
(f) => !fs.existsSync(path.resolve(repoRoot, f)),
|
||||
);
|
||||
if (missingAgreements.length > 0) {
|
||||
throw new Error(
|
||||
`Missing legal documents required by the WebUI consent gate:\n` +
|
||||
missingAgreements.map((f) => ` - ${path.resolve(repoRoot, f)}`).join('\n'),
|
||||
);
|
||||
}
|
||||
|
||||
const BaseConfigPlugin: PluginOption[] = [
|
||||
// Proton substitutes every `protobuf_encode<T>` / `protobuf_decode<T>`
|
||||
// call site with a monomorphized codec at build time. WITHOUT this
|
||||
@@ -117,6 +122,13 @@ const BaseConfigPlugin: PluginOption[] = [
|
||||
dest: path.join(distDir, 'native', 'ffmpeg'),
|
||||
flatten: true,
|
||||
},
|
||||
// Legal docs served verbatim by the WebUI consent gate. Copied next to
|
||||
// the bundle so consent.ts's path probe finds them in a packaged deploy.
|
||||
...['EULA.md', 'PRIVACY.md'].map((file) => ({
|
||||
src: toPosix(path.resolve(repoRoot, file)),
|
||||
dest: distDir,
|
||||
flatten: true,
|
||||
})),
|
||||
]
|
||||
})
|
||||
];
|
||||
|
||||
1
packages/mcp/.gitignore
vendored
Normal file
1
packages/mcp/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
dist/
|
||||
113
packages/mcp/README.md
Normal file
113
packages/mcp/README.md
Normal file
@@ -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`.
|
||||
59
packages/mcp/package.json
Normal file
59
packages/mcp/package.json
Normal file
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "1.10.2",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
32
packages/mcp/scripts/gen-catalog.test.ts
Normal file
32
packages/mcp/scripts/gen-catalog.test.ts
Normal file
@@ -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);
|
||||
});
|
||||
69
packages/mcp/src/client.ts
Normal file
69
packages/mcp/src/client.ts
Normal file
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
7397
packages/mcp/src/generated/catalog.ts
Normal file
7397
packages/mcp/src/generated/catalog.ts
Normal file
File diff suppressed because it is too large
Load Diff
106
packages/mcp/src/server.ts
Normal file
106
packages/mcp/src/server.ts
Normal file
@@ -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}`);
|
||||
182
packages/mcp/src/tools.ts
Normal file
182
packages/mcp/src/tools.ts
Normal file
@@ -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)}`);
|
||||
}
|
||||
}
|
||||
38
packages/mcp/src/types.ts
Normal file
38
packages/mcp/src/types.ts
Normal file
@@ -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;
|
||||
}
|
||||
39
packages/mcp/tests/client.test.ts
Normal file
39
packages/mcp/tests/client.test.ts
Normal file
@@ -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();
|
||||
});
|
||||
});
|
||||
138
packages/mcp/tests/tools.test.ts
Normal file
138
packages/mcp/tests/tools.test.ts
Normal file
@@ -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');
|
||||
});
|
||||
});
|
||||
13
packages/mcp/tsconfig.json
Normal file
13
packages/mcp/tsconfig.json
Normal file
@@ -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/**/*"]
|
||||
}
|
||||
17
packages/mcp/vitest.config.ts
Normal file
17
packages/mcp/vitest.config.ts
Normal file
@@ -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,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.9.2",
|
||||
"version": "1.10.2",
|
||||
"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 +12,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 +100,6 @@
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
91
packages/onebot/src/action-docs.ts
Normal file
91
packages/onebot/src/action-docs.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
// 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';
|
||||
import { actions as qzoneActions } from './actions/qzone';
|
||||
|
||||
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 },
|
||||
{ category: '空间', specs: qzoneActions },
|
||||
];
|
||||
|
||||
/** 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';
|
||||
}
|
||||
483
packages/onebot/src/action-kit.ts
Normal file
483
packages/onebot/src/action-kit.ts
Normal file
@@ -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);
|
||||
}
|
||||
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,162 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
// get_qun_album_list — NapCat-named/shaped variant of get_group_album_list.
|
||||
// NapCat's own impl calls the kernel AlbumService (trpc, not statically
|
||||
// recoverable); we instead reuse the qun_list_album_v2 web API (the same one
|
||||
// get_group_album_list uses) and reshape into NapCat's
|
||||
// {album_list, attach_info, has_more} envelope. The web endpoint fetches up
|
||||
// to 1000 albums in one shot, so attach_info/has_more are ''/false (no cursor
|
||||
// pagination); cover_url isn't returned by this endpoint.
|
||||
groupAction({
|
||||
name: 'get_qun_album_list',
|
||||
readOnly: true,
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
|
||||
return okResponse({
|
||||
album_list: albumList.map((a) => ({
|
||||
album_id: a.id,
|
||||
album_name: a.name,
|
||||
create_time: a.createTime,
|
||||
pic_num: a.picNum,
|
||||
})),
|
||||
attach_info: '',
|
||||
has_more: false,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get qun album list';
|
||||
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: '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);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
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: '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);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
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);
|
||||
}
|
||||
});
|
||||
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);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
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,123 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
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);
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
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');
|
||||
}
|
||||
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||
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 });
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
|
||||
}
|
||||
|
||||
await ctx.deleteMessage(messageId, meta);
|
||||
return okResponse();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
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 });
|
||||
},
|
||||
}),
|
||||
|
||||
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 });
|
||||
},
|
||||
}),
|
||||
|
||||
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 });
|
||||
},
|
||||
}),
|
||||
|
||||
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) {
|
||||
log.warn('[get_msg] miss message_id=%d', p.message_id);
|
||||
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);
|
||||
},
|
||||
}),
|
||||
|
||||
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();
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
|
||||
156
packages/onebot/src/actions/qzone.ts
Normal file
156
packages/onebot/src/actions/qzone.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import { defineAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import type { JsonValue } from '../types';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export const actions = [
|
||||
// get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。
|
||||
// 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。
|
||||
// 复用 qzone.qq.com 的 cookie/g_tk 基建(与群相册同源),纯 web,无 trpc。
|
||||
defineAction({
|
||||
name: 'get_qzone_msg_list',
|
||||
readOnly: true,
|
||||
summary: '获取 QQ 空间说说列表(默认机器人自己的空间)',
|
||||
params: {
|
||||
target_uin: f.uint().describe('目标 QQ 号,省略则取机器人自己').optional(),
|
||||
pos: f.int({ min: 0 }).describe('起始偏移').default(0),
|
||||
num: f.int({ min: 1, max: 100 }).describe('本页数量').default(20),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.qzone.getMsgList(p.target_uin, p.pos, p.num);
|
||||
return okResponse(res as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get qzone msg list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
// get_qzone_feeds — 获取好友动态(feed)。只读,始终以机器人自己身份拉取。
|
||||
// 每条 feed 含结构化字段 + 预渲染 html 原样透传(深度解析交由调用方)。
|
||||
defineAction({
|
||||
name: 'get_qzone_feeds',
|
||||
readOnly: true,
|
||||
summary: '获取 QQ 空间好友动态(feed);page_num 仅首页可靠,深翻页需时间游标(暂未实现)',
|
||||
params: {
|
||||
page_num: f.int({ min: 1 }).describe('页码(1 起;仅首页可靠)').default(1),
|
||||
count: f.int({ min: 1, max: 50 }).describe('本页数量').default(10),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count);
|
||||
return okResponse(res as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get qzone feeds';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
// send_qzone_msg — 发表一条纯文字说说。写操作,发到机器人自己的空间。
|
||||
// 返回新说说的 tid(供后续 delete/comment/like 使用)。
|
||||
// 注意:发说说为主动行为,高频会被 Qzone 风控,调用方需自行限流。
|
||||
defineAction({
|
||||
name: 'send_qzone_msg',
|
||||
summary: '发表一条纯文字说说(QQ 空间)',
|
||||
params: {
|
||||
content: f.string({ allowEmpty: false }).describe('说说正文'),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.qzone.publish(p.content);
|
||||
return okResponse(res as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to publish qzone msg';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
// delete_qzone_msg — 删除机器人自己空间的一条说说(按 tid)。写操作。
|
||||
defineAction({
|
||||
name: 'delete_qzone_msg',
|
||||
summary: '删除一条说说(QQ 空间,按 tid)',
|
||||
params: {
|
||||
tid: f.string({ allowEmpty: false }).describe('说说 tid(来自 get_qzone_msg_list / send_qzone_msg)'),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
await ctx.bridge.apis.qzone.delete(p.tid);
|
||||
return okResponse(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to delete qzone msg';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
// like_qzone — 给一条说说点赞。target_uin 省略=机器人自己空间;点赞好友说说传其 uin。
|
||||
// abstime=该说说的发表时间(unix 秒,来自 get_qzone_feeds/get_qzone_msg_list),
|
||||
// 传真实值更可靠;不传按 0。写操作;高频点赞会被 Qzone 风控,调用方需限流。
|
||||
defineAction({
|
||||
name: 'like_qzone',
|
||||
summary: '给一条说说点赞(QQ 空间)',
|
||||
params: {
|
||||
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
|
||||
target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
|
||||
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, true, p.abstime);
|
||||
return okResponse(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to like qzone msg';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
// unlike_qzone — 取消对一条说说的点赞。参数同 like_qzone。写操作。
|
||||
// 注意:取消赞端点(internal_unlike_app)暂未经真机核实,待抓包确认。
|
||||
defineAction({
|
||||
name: 'unlike_qzone',
|
||||
summary: '取消对一条说说的点赞(QQ 空间;取消赞端点待真机核实)',
|
||||
params: {
|
||||
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
|
||||
target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
|
||||
abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, false, p.abstime);
|
||||
return okResponse(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to unlike qzone msg';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
// comment_qzone — 评论一条说说。target_uin=说说所属 QQ 号(省略=机器人自己空间)。
|
||||
// 写操作;高频评论会被 Qzone 风控,调用方需限流。
|
||||
defineAction({
|
||||
name: 'comment_qzone',
|
||||
summary: '评论一条说说(QQ 空间)',
|
||||
params: {
|
||||
tid: f.string({ allowEmpty: false }).describe('说说 tid'),
|
||||
content: f.string({ allowEmpty: false }).describe('评论内容'),
|
||||
target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin);
|
||||
return okResponse(res as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to comment qzone msg';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
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';
|
||||
@@ -9,6 +9,7 @@ import { register as registerGroupFile } from './actions/group-file';
|
||||
import { register as registerGroupInfo } from './actions/group-info';
|
||||
import { register as registerInfo } from './actions/info';
|
||||
import { register as registerMessage } from './actions/message';
|
||||
import { register as registerQzone } from './actions/qzone';
|
||||
import { register as registerRequest } from './actions/request';
|
||||
import type { ForwardPreviewMeta } from './modules/message-actions';
|
||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
@@ -76,13 +77,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;
|
||||
@@ -95,6 +115,7 @@ export class ApiHandler {
|
||||
registerRequest(this, context);
|
||||
registerExtended(this, context);
|
||||
registerGroupAlbum(this, context);
|
||||
registerQzone(this, context);
|
||||
}
|
||||
|
||||
registerAction(action: string, handler: ActionHandler): void {
|
||||
@@ -108,13 +129,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 +165,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,
|
||||
|
||||
@@ -7,6 +7,9 @@ import type {
|
||||
MessageIdResolver,
|
||||
} from './index';
|
||||
import { resolveReplyId } from './utils';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
export async function elementsToJson(
|
||||
elements: MessageElement[],
|
||||
@@ -19,10 +22,17 @@ export async function elementsToJson(
|
||||
): Promise<JsonArray> {
|
||||
const result: JsonArray = [];
|
||||
for (const element of elements) {
|
||||
result.push(await elementToSegment(
|
||||
element, isGroup, sessionId,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
|
||||
));
|
||||
// One malformed element shouldn't drop the whole message — skip it (with a
|
||||
// breadcrumb) and keep converting the rest.
|
||||
try {
|
||||
result.push(await elementToSegment(
|
||||
element, isGroup, sessionId,
|
||||
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
|
||||
));
|
||||
} catch (err) {
|
||||
log.warn('segment convert skipped type=%s (%s)', element.type,
|
||||
err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -45,7 +55,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 +114,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 +137,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,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user