Compare commits
54 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
117
README.md
117
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,29 @@
|
||||
|
||||
---
|
||||
|
||||
## 简介
|
||||
|
||||
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
|
||||
|
||||
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
|
||||
SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。
|
||||
|
||||
## 特性
|
||||
|
||||
- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。
|
||||
- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。
|
||||
- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。
|
||||
- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。
|
||||
- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。
|
||||
- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。
|
||||
- **OneBot v11 兼容**:支持文本、音视频、Markdown、JSON 等消息格式。
|
||||
- **高性能架构**:TypeScript 全栈,基于 pnpm monorepo 管理,核心逻辑分离。
|
||||
- **现代化管理**:内置 WebUI 面板,支持实时日志、密码热更、多账号管理。
|
||||
- **多适配器支持**:WebSocket (Server/Client)、HTTP (Server/Post)。
|
||||
- **数据持久化**:使用 SQLite 存储好友、群组等关系数据。
|
||||
|
||||
## 快速开始
|
||||
|
||||
下载预构建发布包:
|
||||
|
||||
```bash
|
||||
# 从 Releases 下载 zip,解压到任意目录
|
||||
./launcher.bat # Windows
|
||||
```
|
||||
|
||||
或从源码开发:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
cd SnowLuma
|
||||
pnpm install
|
||||
pnpm build
|
||||
pnpm start
|
||||
```
|
||||
|
||||
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
|
||||
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
|
||||
|
||||
## 工作区
|
||||
|
||||
本仓库使用 pnpm monorepo 管理,各包职责如下:
|
||||
|
||||
| 包 | 说明 |
|
||||
| --- | --- |
|
||||
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
|
||||
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
|
||||
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
|
||||
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
|
||||
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
|
||||
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
|
||||
| [`webui`](packages/webui) | Web 管理面板前端。 |
|
||||
|
||||
## 架构
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A([QQ 客户端])
|
||||
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
|
||||
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
|
||||
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
|
||||
E([WS / HTTP / WebUI])
|
||||
|
||||
A --> B --> C --> D --> E
|
||||
```
|
||||
|
||||
## 文档
|
||||
|
||||
- [路线图](RoadMap.md)
|
||||
- [贡献指南](CONTRIBUTING.md)
|
||||
- [行为准则](CODE_OF_CONDUCT.md)
|
||||
|
||||
## 开发命令
|
||||
|
||||
```bash
|
||||
pnpm dev # 启动 core dev server
|
||||
pnpm dev:web # 启动 webui dev server
|
||||
pnpm test # 运行 core 测试
|
||||
pnpm typecheck # 全仓库 type check
|
||||
pnpm build:all # 构建 core + sdk + webui
|
||||
```
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。
|
||||
2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。
|
||||
3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。
|
||||
|
||||
## 鸣谢
|
||||
|
||||
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
|
||||
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
|
||||
参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
|
||||
## 贡献者
|
||||
---
|
||||
|
||||
感谢每一位为 SnowLuma 提交过代码的伙伴。
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" /></a>
|
||||
</p>
|
||||
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
|
||||
</a>
|
||||
|
||||
## Star 趋势
|
||||
|
||||
<a href="https://star-history.com/#SnowLuma/SnowLuma&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 社区
|
||||
|
||||
- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
|
||||
- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"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).",
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"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).",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -46,7 +46,6 @@
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -9,6 +9,7 @@ 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';
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
@@ -75,4 +76,15 @@ export class MiscApi {
|
||||
sendGroupSign(groupId: number): Promise<void> {
|
||||
return SendGroupSign.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
async getDecryptKey(dbSalt: string): Promise<string> {
|
||||
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
|
||||
}
|
||||
if (!result.dbKey) {
|
||||
throw new Error('Decrypt key is empty');
|
||||
}
|
||||
return result.dbKey;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
|
||||
@@ -247,16 +248,11 @@ export class WebApi {
|
||||
let imgHeight = 300;
|
||||
|
||||
if (options?.image) {
|
||||
let imageBuffer: Buffer;
|
||||
|
||||
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
|
||||
const response = await fetch(options.image);
|
||||
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
|
||||
imageBuffer = Buffer.from(await response.arrayBuffer());
|
||||
} else {
|
||||
const { readFileSync } = await import('fs');
|
||||
imageBuffer = readFileSync(options.image);
|
||||
}
|
||||
// Route through loadBinarySource so the group-notice image download
|
||||
// gets the same browser-UA + Referer-retry hardening as every other
|
||||
// media fetch — and http/file/base64 source handling for free.
|
||||
const loaded = await loadBinarySource(options.image, 'group-notice image');
|
||||
const imageBuffer = Buffer.from(loaded.bytes);
|
||||
|
||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||
if (picInfo) {
|
||||
|
||||
@@ -355,6 +355,12 @@ export async function initWebUI(
|
||||
return c.json({ list });
|
||||
});
|
||||
|
||||
// Live OneBot adapter health per account (listening / connected / client
|
||||
// counts / last-delivery), powering the dashboard's connection card.
|
||||
app.get('/api/connections', (c) => {
|
||||
return c.json({ list: oneBotManager.getConnectionStatuses() });
|
||||
});
|
||||
|
||||
app.get('/api/logs', (c) => {
|
||||
const limit = Number(c.req.query('limit') ?? 300);
|
||||
return c.json({ list: getRecentLogs(limit) });
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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`]
|
||||
: []),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"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>'`.",
|
||||
@@ -91,7 +91,6 @@
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { asBoolean, asMessage, asNumber, asString } from '../api-handler';
|
||||
import type { ForwardPreviewMeta } from '../modules/message-actions';
|
||||
@@ -1175,6 +1176,35 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('request_decrypt_key', async (params) => {
|
||||
const dbPath = asString(params.db_path);
|
||||
if (!dbPath) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'db_path is required');
|
||||
}
|
||||
|
||||
try {
|
||||
const buffer = Buffer.alloc(128);
|
||||
const fileHandle = await readFile(dbPath);
|
||||
|
||||
if (fileHandle.length < 0xaf) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short');
|
||||
}
|
||||
|
||||
fileHandle.copy(buffer, 0, 0x2f, 0xaf);
|
||||
const dbSalt = buffer.toString('utf8');
|
||||
|
||||
if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string');
|
||||
}
|
||||
|
||||
const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase());
|
||||
|
||||
return okResponse({ db_key: dbKey });
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function hexToBytes(hex: string): Uint8Array {
|
||||
|
||||
@@ -3,6 +3,35 @@ import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
/**
|
||||
* 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.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('send_msg', async (params) => {
|
||||
const messageType = asString(params.message_type);
|
||||
@@ -77,6 +106,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? messageId) as JsonValue;
|
||||
await refreshStoredImageUrls(result, ctx);
|
||||
return okResponse(result);
|
||||
});
|
||||
|
||||
|
||||
@@ -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,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||
wsClients: [],
|
||||
},
|
||||
musicSignUrl: '',
|
||||
statusCommand: makeDefaultStatusCommand(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -98,6 +108,11 @@ 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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -181,7 +196,26 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
|
||||
}
|
||||
|
||||
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
|
||||
return { networks, musicSignUrl };
|
||||
return { networks, musicSignUrl, statusCommand: parseStatusCommand(sources) };
|
||||
}
|
||||
|
||||
/** 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;
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ async function elementToSegment(
|
||||
}
|
||||
|
||||
if (element.type === 'image') {
|
||||
const url = imageUrlResolver ? imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
const url = imageUrlResolver ? await imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
const data: JsonObject = {
|
||||
url,
|
||||
file: element.fileId ?? '',
|
||||
|
||||
@@ -114,7 +114,7 @@ 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),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -12,12 +12,15 @@ 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';
|
||||
@@ -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,11 @@ 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();
|
||||
}
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
@@ -84,6 +97,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 +112,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 +156,53 @@ export class OneBotInstance {
|
||||
private dispatchEvent(event: JsonObject): void {
|
||||
this.cacheMessageEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// Built-in `#sl`: always cache + log first (a swallowed `#sl` is still
|
||||
// observable locally); only forwarding to downstream adapters is gated.
|
||||
if (this.handleStatusCommand(event)) return;
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Built-in `#sl` status command. Returns `true` when the event matched AND
|
||||
* `swallow` is configured — the caller then skips `emitEvent` so downstream
|
||||
* adapters never see it. The reply itself is fired async and rate-limited
|
||||
* per conversation; matching and replying are independent of swallowing.
|
||||
*/
|
||||
private handleStatusCommand(event: JsonObject): boolean {
|
||||
const cfg = this.ctx.config.statusCommand;
|
||||
if (!cfg.enabled) return false;
|
||||
const postType = event.post_type;
|
||||
if (postType !== 'message' && postType !== 'message_sent') return false;
|
||||
if (!matchesStatusCommand(event.message)) return false;
|
||||
|
||||
const isGroup = event.message_type === 'group';
|
||||
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);
|
||||
if (sessionId === 0) return cfg.swallow;
|
||||
|
||||
const key = `${isGroup ? 'g' : 'p'}:${sessionId}`;
|
||||
const now = Date.now();
|
||||
if (statusCooldownElapsed(this.statusCommandCooldown.get(key), now, cfg.cooldownSeconds)) {
|
||||
this.statusCommandCooldown.set(key, now);
|
||||
void this.replyStatus(isGroup, sessionId).catch((err) => {
|
||||
this.log.warn('status command reply failed: %s', err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
}
|
||||
return cfg.swallow;
|
||||
}
|
||||
|
||||
private async replyStatus(isGroup: boolean, sessionId: number): Promise<void> {
|
||||
const text = buildStatusText({
|
||||
version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev',
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
uptimeMs: Date.now() - this.startedAt,
|
||||
});
|
||||
if (isGroup) await sendGroupMessage(this.ctx, sessionId, text, true);
|
||||
else await sendPrivateMessage(this.ctx, sessionId, text, true);
|
||||
}
|
||||
|
||||
private buildNetworkContext(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: this.uin,
|
||||
|
||||
@@ -3,10 +3,18 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { BridgeManager } from '@snowluma/core/manager';
|
||||
import { loadOneBotConfig } from './config';
|
||||
import { OneBotInstance } from './instance';
|
||||
import type { AdapterStatus } from './network';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
||||
|
||||
/** Per-account OneBot connection health, surfaced to the WebUI dashboard. */
|
||||
export interface AccountConnections {
|
||||
uin: string;
|
||||
nickname: string;
|
||||
adapters: AdapterStatus[];
|
||||
}
|
||||
|
||||
export class OneBotManager {
|
||||
private readonly instances = new Map<string, OneBotInstance>();
|
||||
|
||||
@@ -28,6 +36,15 @@ export class OneBotManager {
|
||||
return [...this.instances.values()];
|
||||
}
|
||||
|
||||
/** Live OneBot adapter status for every account, for the WebUI dashboard. */
|
||||
getConnectionStatuses(): AccountConnections[] {
|
||||
return this.getInstances().map((i) => ({
|
||||
uin: i.uin,
|
||||
nickname: i.nickname,
|
||||
adapters: i.getConnectionStatuses(),
|
||||
}));
|
||||
}
|
||||
|
||||
reloadConfig(uin: string): boolean {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return false;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
|
||||
export interface CachedImage {
|
||||
@@ -62,17 +62,17 @@ const TYPE_VIDEO = 'video';
|
||||
const DEFAULT_KEEP_ENTRIES = 4096;
|
||||
|
||||
export class MediaStore {
|
||||
private readonly db: DatabaseType;
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly maxEntriesPerType: number;
|
||||
|
||||
// Prepared statements (pay the parsing cost once at startup).
|
||||
private readonly upsertEntry: Statement;
|
||||
private readonly upsertKey: Statement;
|
||||
private readonly findEntryByKey: Statement;
|
||||
private readonly findEntryByPrimary: Statement;
|
||||
private readonly evictByType: Statement;
|
||||
private readonly purgeOrphanKeys: Statement;
|
||||
private readonly countByType: Statement;
|
||||
private readonly upsertEntry: StatementSync;
|
||||
private readonly upsertKey: StatementSync;
|
||||
private readonly findEntryByKey: StatementSync;
|
||||
private readonly findEntryByPrimary: StatementSync;
|
||||
private readonly evictByType: StatementSync;
|
||||
private readonly purgeOrphanKeys: StatementSync;
|
||||
private readonly countByType: StatementSync;
|
||||
|
||||
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
|
||||
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
|
||||
@@ -80,9 +80,9 @@ export class MediaStore {
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
this.upsertEntry = this.db.prepare(
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
import type { JsonObject, MessageMeta } from './types';
|
||||
|
||||
export class MessageStore {
|
||||
private readonly db: DatabaseType;
|
||||
private readonly stmtStoreEvent: Statement;
|
||||
private readonly stmtStoreMeta: Statement;
|
||||
private readonly stmtFindEvent: Statement;
|
||||
private readonly stmtFindMeta: Statement;
|
||||
private readonly stmtResolveReplyGroup: Statement;
|
||||
private readonly stmtResolveReplyPrivate: Statement;
|
||||
private readonly stmtListEventsAnchored: Statement;
|
||||
private readonly stmtListEventsLatest: Statement;
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly stmtStoreEvent: StatementSync;
|
||||
private readonly stmtStoreMeta: StatementSync;
|
||||
private readonly stmtFindEvent: StatementSync;
|
||||
private readonly stmtFindMeta: StatementSync;
|
||||
private readonly stmtResolveReplyGroup: StatementSync;
|
||||
private readonly stmtResolveReplyPrivate: StatementSync;
|
||||
private readonly stmtListEventsAnchored: StatementSync;
|
||||
private readonly stmtListEventsLatest: StatementSync;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
@@ -20,9 +20,9 @@ export class MessageStore {
|
||||
|
||||
// Replace .json extension with .db if present
|
||||
const finalPath = dbPath.replace(/\.json$/, '.db');
|
||||
this.db = new Database(finalPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(finalPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
// Prepare once. Statements survive for the lifetime of the
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import type { ImageUrlResolver } from '../event-converter';
|
||||
import type { MediaStore } from '../media-store';
|
||||
import type { JsonObject } from '../types';
|
||||
|
||||
@@ -8,10 +10,29 @@ const log = createLogger('OneBot');
|
||||
export async function getImageInfo(
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
imageUrlResolver?: ImageUrlResolver | null,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findImage(file);
|
||||
if (!cached) return null;
|
||||
const url = cached.url || cached.imageUrl || '';
|
||||
|
||||
let url = cached.url || cached.imageUrl || '';
|
||||
|
||||
// Re-sign with a current rkey at lookup time. The stored `url` was signed
|
||||
// when the message first arrived and its rkey may have since expired — the
|
||||
// CDN then rejects the download with
|
||||
// `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw
|
||||
// (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which
|
||||
// re-signs on every getImageUrl call instead of handing back a baked URL.
|
||||
if (imageUrlResolver && cached.imageUrl) {
|
||||
try {
|
||||
const element: MessageElement = { type: 'image', imageUrl: cached.imageUrl, subType: cached.subType };
|
||||
const fresh = await imageUrlResolver(element, cached.isGroup);
|
||||
if (fresh) url = fresh;
|
||||
} catch {
|
||||
// Best-effort: fall back to the stored URL on any resolver failure.
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url,
|
||||
|
||||
@@ -675,7 +675,16 @@ export async function getForwardMessage(
|
||||
for (const node of nodes) {
|
||||
const isGroup = node.messageType === 'group' || (node.groupId !== undefined && node.groupId > 0);
|
||||
const sessionId = isGroup ? (node.groupId ?? 0) : node.userUin;
|
||||
const segments = await elementsToOneBotSegments(node.elements, isGroup, sessionId);
|
||||
// Route forward nodes through the SAME resolver-equipped conversion the
|
||||
// normal receive path uses (to-message.ts). Without the image/media URL
|
||||
// resolvers the segments come back with raw, rkey-less download URLs —
|
||||
// exactly issue #74 (`/get_forward_msg` image url 缺少 rkey). Image rkey
|
||||
// re-signing is scene-aware via the appid in the URL (see instance-rkey).
|
||||
const segments = await elementsToOneBotSegments(
|
||||
node.elements, isGroup, sessionId,
|
||||
ref.converterCtx.imageUrlResolver,
|
||||
ref.converterCtx.mediaUrlResolver,
|
||||
);
|
||||
|
||||
const sender: JsonObject = {
|
||||
user_id: node.userUin,
|
||||
|
||||
82
packages/onebot/src/modules/status-command.ts
Normal file
82
packages/onebot/src/modules/status-command.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
|
||||
/**
|
||||
* Hardcoded trigger for the built-in status command — exact match,
|
||||
* case-insensitive, after trimming. Intentionally NOT configurable: the
|
||||
* `statusCommand.enabled` toggle is the only knob (the gate is on/off, not
|
||||
* the word).
|
||||
*/
|
||||
export const STATUS_COMMAND_TRIGGER = '#sl';
|
||||
|
||||
/**
|
||||
* True iff `message` is exactly the trigger: a single `text` segment (or a
|
||||
* bare string for string-format adapters) whose trimmed, lowercased content
|
||||
* equals {@link STATUS_COMMAND_TRIGGER}.
|
||||
*
|
||||
* Reads the segment array rather than `raw_message` to avoid CQ-encoding
|
||||
* ambiguity, and rejects mixed-segment messages (`#sl` + image/at/reply) so
|
||||
* only a pure `#sl` triggers — no `startsWith`, so `#slogan` never matches.
|
||||
*/
|
||||
export function matchesStatusCommand(message: JsonValue | undefined): boolean {
|
||||
if (typeof message === 'string') {
|
||||
return normalize(message) === STATUS_COMMAND_TRIGGER;
|
||||
}
|
||||
if (!Array.isArray(message) || message.length !== 1) return false;
|
||||
const seg = message[0];
|
||||
if (!isObject(seg) || seg.type !== 'text') return false;
|
||||
const data = isObject(seg.data) ? seg.data : null;
|
||||
const text = data && typeof data.text === 'string' ? data.text : '';
|
||||
return normalize(text) === STATUS_COMMAND_TRIGGER;
|
||||
}
|
||||
|
||||
function normalize(s: string): string {
|
||||
return s.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a reply is allowed now given the last reply time + cooldown.
|
||||
* `cooldownSeconds <= 0` disables the cooldown entirely.
|
||||
*/
|
||||
export function statusCooldownElapsed(
|
||||
lastRepliedAtMs: number | undefined,
|
||||
nowMs: number,
|
||||
cooldownSeconds: number,
|
||||
): boolean {
|
||||
if (lastRepliedAtMs === undefined) return true;
|
||||
if (cooldownSeconds <= 0) return true;
|
||||
return nowMs - lastRepliedAtMs >= cooldownSeconds * 1000;
|
||||
}
|
||||
|
||||
export interface StatusInfo {
|
||||
version: string;
|
||||
platform: string;
|
||||
arch: string;
|
||||
uptimeMs: number;
|
||||
}
|
||||
|
||||
/** Render the public-safe `#sl` reply: version + platform/arch + uptime. */
|
||||
export function buildStatusText(info: StatusInfo): string {
|
||||
return [
|
||||
'SnowLuma 状态',
|
||||
`版本: ${info.version}`,
|
||||
`平台: ${info.platform}-${info.arch}`,
|
||||
`运行时长: ${formatUptime(info.uptimeMs)}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** Human-readable uptime (zh-CN), dropping leading zero units. */
|
||||
export function formatUptime(ms: number): string {
|
||||
const totalSec = Math.max(0, Math.floor(ms / 1000));
|
||||
const days = Math.floor(totalSec / 86400);
|
||||
const hours = Math.floor((totalSec % 86400) / 3600);
|
||||
const minutes = Math.floor((totalSec % 3600) / 60);
|
||||
const seconds = totalSec % 60;
|
||||
if (days > 0) return `${days}天 ${hours}小时 ${minutes}分钟`;
|
||||
if (hours > 0) return `${hours}小时 ${minutes}分钟`;
|
||||
if (minutes > 0) return `${minutes}分钟 ${seconds}秒`;
|
||||
return `${seconds}秒`;
|
||||
}
|
||||
@@ -16,6 +16,19 @@ export enum NetworkReloadType {
|
||||
Opened = 3,
|
||||
}
|
||||
|
||||
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled';
|
||||
|
||||
/** Live runtime status of a single network adapter, surfaced to the WebUI
|
||||
* dashboard (and the per-node config cards) so the gateway's own
|
||||
* connection health is visible. `detail` is a short human string, e.g.
|
||||
* "3 个客户端" / "重连中" / "上次推送失败 14:53:01". */
|
||||
export interface AdapterStatus {
|
||||
name: string;
|
||||
kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
|
||||
status: AdapterStatusLevel;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
readonly name: string;
|
||||
protected config: C;
|
||||
@@ -37,4 +50,7 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
|
||||
|
||||
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
|
||||
|
||||
/** Report live connection health for the WebUI dashboard. */
|
||||
abstract describeStatus(): AdapterStatus;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { HttpClientNetwork, JsonObject } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { executeQuickOperation } from './quick-operation';
|
||||
|
||||
const moduleLog = createLogger('OneBot.POST');
|
||||
@@ -15,6 +15,7 @@ const DEFAULT_TIMEOUT_MS = 5000;
|
||||
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private signature_: string;
|
||||
private lastDelivery: { at: number; ok: boolean } | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
|
||||
@@ -39,6 +40,15 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
this.isEnabled = false;
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'httpClient', status: 'disabled', detail: '未启用' };
|
||||
if (!this.lastDelivery) return { name: this.name, kind: 'httpClient', status: 'ok', detail: '已启用' };
|
||||
const at = new Date(this.lastDelivery.at).toTimeString().slice(0, 8);
|
||||
return this.lastDelivery.ok
|
||||
? { name: this.name, kind: 'httpClient', status: 'ok', detail: `上次推送成功 ${at}` }
|
||||
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
|
||||
}
|
||||
|
||||
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
|
||||
const wasEnabled = this.isEnabled;
|
||||
const willEnable = next.enabled !== false && !!next.url;
|
||||
@@ -98,6 +108,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (response.ok) {
|
||||
this.lastDelivery = { at: Date.now(), ok: true };
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (contentType.includes('application/json')) {
|
||||
const body = await response.text();
|
||||
@@ -106,9 +117,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
this.lastDelivery = { at: Date.now(), ok: false };
|
||||
if (this.isEnabled) {
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
|
||||
@@ -7,13 +7,14 @@ import {
|
||||
} from 'http';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private listening = false;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
@@ -36,10 +37,17 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
close(): void {
|
||||
if (!this.isEnabled && !this.server) return;
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
this.server?.close();
|
||||
this.server = null;
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
|
||||
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||||
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
|
||||
}
|
||||
|
||||
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
@@ -76,6 +84,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
this.server = server;
|
||||
|
||||
server.on('listening', () => {
|
||||
this.listening = true;
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
@@ -85,6 +94,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
);
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
this.listening = false;
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
export {
|
||||
IOneBotNetworkAdapter,
|
||||
NetworkReloadType,
|
||||
type AdapterStatus,
|
||||
type AdapterStatusLevel,
|
||||
type NetworkAdapterContext,
|
||||
} from './adapter';
|
||||
export { HttpPostAdapter } from './http-post-adapter';
|
||||
export { HttpServerAdapter } from './http-server-adapter';
|
||||
export { OneBotNetworkManager } from './network-manager';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { buildDispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, NetworkBase } from '../types';
|
||||
import { IOneBotNetworkAdapter } from './adapter';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter';
|
||||
|
||||
const log = createLogger('OneBot.Network');
|
||||
|
||||
@@ -30,6 +30,11 @@ export class OneBotNetworkManager {
|
||||
|
||||
list(): AnyAdapter[] { return [...this.adapters.values()]; }
|
||||
|
||||
/** Live status of every registered adapter, for the WebUI dashboard. */
|
||||
describeStatuses(): AdapterStatus[] {
|
||||
return this.list().map((a) => a.describeStatus());
|
||||
}
|
||||
|
||||
hasActiveAdapters(): boolean {
|
||||
for (const a of this.adapters.values()) if (a.isActive) return true;
|
||||
return false;
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Client');
|
||||
@@ -16,6 +16,7 @@ const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
|
||||
|
||||
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private socket: WebSocket | null = null;
|
||||
private connected = false;
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
@@ -46,6 +47,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
close(): void {
|
||||
this.explicitlyClosed = true;
|
||||
this.isEnabled = false;
|
||||
this.connected = false;
|
||||
this.cancelReconnect();
|
||||
if (this.socket) {
|
||||
safeClose(this.socket);
|
||||
@@ -53,6 +55,12 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
}
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'wsClient', status: 'disabled', detail: '未启用' };
|
||||
if (this.connected) return { name: this.name, kind: 'wsClient', status: 'ok', detail: '已连接' };
|
||||
return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' };
|
||||
}
|
||||
|
||||
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
@@ -108,6 +116,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
this.socket = socket;
|
||||
|
||||
socket.on('open', () => {
|
||||
this.connected = true;
|
||||
this.log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
});
|
||||
@@ -120,6 +129,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
|
||||
socket.on('close', () => {
|
||||
this.socket = null;
|
||||
this.connected = false;
|
||||
if (this.explicitlyClosed || !this.isEnabled) return;
|
||||
this.scheduleReconnect();
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Server');
|
||||
@@ -22,6 +22,7 @@ interface ForwardConn {
|
||||
|
||||
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private listening = false;
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
private readonly log: Logger;
|
||||
@@ -57,12 +58,19 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
for (const ws of [...this.connections.keys()]) safeClose(ws);
|
||||
this.connections.clear();
|
||||
this.wss?.close();
|
||||
this.wss = null;
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
|
||||
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||||
return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` };
|
||||
}
|
||||
|
||||
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
|
||||
const prevSig = bindingSignature(this.config);
|
||||
const wasEnabled = this.isEnabled;
|
||||
@@ -111,6 +119,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
this.wss = wss;
|
||||
|
||||
wss.on('listening', () => {
|
||||
this.listening = true;
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
@@ -121,6 +130,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
});
|
||||
|
||||
wss.on('error', (err: Error) => {
|
||||
this.listening = false;
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
|
||||
export class ReactionStore {
|
||||
private readonly db: DatabaseType;
|
||||
private readonly stmtUpsert: Statement;
|
||||
private readonly stmtRemove: Statement;
|
||||
private readonly stmtList: Statement;
|
||||
private readonly stmtCount: Statement;
|
||||
private readonly stmtCountByEmoji: Statement;
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly stmtUpsert: StatementSync;
|
||||
private readonly stmtRemove: StatementSync;
|
||||
private readonly stmtList: StatementSync;
|
||||
private readonly stmtCount: StatementSync;
|
||||
private readonly stmtCountByEmoji: StatementSync;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
this.stmtUpsert = this.db.prepare(
|
||||
|
||||
@@ -63,11 +63,29 @@ export interface OneBotNetworks {
|
||||
wsClients: WsClientNetwork[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Built-in `#sl` status command. The trigger word is hardcoded (`#sl`,
|
||||
* exact match, case-insensitive); only these toggles are configurable.
|
||||
*/
|
||||
export interface StatusCommandConfig {
|
||||
/** Master on/off. Default `true` — built-in, but freely disableable. */
|
||||
enabled: boolean;
|
||||
/**
|
||||
* When `true`, a matched `#sl` is NOT forwarded to downstream adapters
|
||||
* (it is still cached, logged, and replied to). Default `false` (pass-through).
|
||||
*/
|
||||
swallow: boolean;
|
||||
/** Per-conversation reply cooldown in seconds. `0` disables it. Default `5`. */
|
||||
cooldownSeconds: number;
|
||||
}
|
||||
|
||||
/** Per-UIN OneBot configuration. */
|
||||
export interface OneBotConfig {
|
||||
networks: OneBotNetworks;
|
||||
/** Music card signing service URL (optional). */
|
||||
musicSignUrl?: string;
|
||||
/** Built-in `#sl` status command settings. Always present after normalization. */
|
||||
statusCommand: StatusCommandConfig;
|
||||
}
|
||||
|
||||
export interface MessageMeta {
|
||||
|
||||
@@ -25,6 +25,7 @@ describe('makeDefaultOneBotConfig', () => {
|
||||
expect(config.networks.wsServers[0].reportSelfMessage).toBe(false);
|
||||
expect(config.networks.wsClients).toEqual([]);
|
||||
expect(config.musicSignUrl).toBe('');
|
||||
expect(config.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -57,6 +58,26 @@ describe('loadOneBotConfig', () => {
|
||||
// Legacy keys must not appear in the persisted file.
|
||||
expect(onDisk.httpServers).toBeUndefined();
|
||||
expect(onDisk.wsServers).toBeUndefined();
|
||||
// statusCommand is materialised with defaults on a fresh install.
|
||||
expect(onDisk.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 });
|
||||
});
|
||||
|
||||
it('fills statusCommand defaults and clamps a negative cooldown', () => {
|
||||
const uin = '10042';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(dir, `onebot_${uin}.json`),
|
||||
JSON.stringify({
|
||||
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
|
||||
statusCommand: { swallow: true, cooldownSeconds: -3 },
|
||||
}),
|
||||
);
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
expect(config.statusCommand.enabled).toBe(true); // default filled (absent in file)
|
||||
expect(config.statusCommand.swallow).toBe(true); // taken from file
|
||||
expect(config.statusCommand.cooldownSeconds).toBe(0); // negative clamped to 0
|
||||
});
|
||||
|
||||
it('migrates legacy per-type arrays into networks groups', () => {
|
||||
|
||||
137
packages/onebot/tests/instance-rkey.test.ts
Normal file
137
packages/onebot/tests/instance-rkey.test.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { RKeyCache } from '../src/instance-rkey';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
|
||||
// The screenshot URL: a raw QQ-NT multimedia download link with no rkey yet.
|
||||
// appid 1407 = group image, 1406 = private/c2c image (see instance-rkey).
|
||||
const NT_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC';
|
||||
const NT_PRIVATE_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1406&fileid=XYZ';
|
||||
const GROUP_IMAGE_TYPE = 20;
|
||||
const PRIVATE_IMAGE_TYPE = 10;
|
||||
|
||||
function nowSec(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
function makeBridge(fetchImpl: () => Promise<unknown[]>) {
|
||||
const fetchDownloadRKeys = vi.fn(fetchImpl);
|
||||
return { bridge: { apis: { contacts: { fetchDownloadRKeys } } }, fetchDownloadRKeys };
|
||||
}
|
||||
|
||||
function freshGroupRkey(value = 'GROUPKEY') {
|
||||
return [{ rkey: value, type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 }];
|
||||
}
|
||||
|
||||
function freshBothRkeys() {
|
||||
return [
|
||||
{ rkey: 'PRIVATEKEY', type: PRIVATE_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
|
||||
{ rkey: 'GROUPKEY', type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
|
||||
];
|
||||
}
|
||||
|
||||
function imageEl(): MessageElement {
|
||||
return { type: 'image', imageUrl: NT_IMAGE_URL };
|
||||
}
|
||||
|
||||
function privateImageEl(): MessageElement {
|
||||
return { type: 'image', imageUrl: NT_PRIVATE_IMAGE_URL };
|
||||
}
|
||||
|
||||
describe('RKeyCache.resolveImageUrl', () => {
|
||||
it('awaits a refresh on a cold cache and appends the rkey', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
|
||||
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`);
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('coalesces concurrent cold-cache lookups into a single fetch', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const urls = await Promise.all([
|
||||
cache.resolveImageUrl(bridge as never, imageEl(), true),
|
||||
cache.resolveImageUrl(bridge as never, imageEl(), true),
|
||||
cache.resolveImageUrl(bridge as never, imageEl(), true),
|
||||
]);
|
||||
|
||||
expect(urls).toEqual(Array(3).fill(`${NT_IMAGE_URL}&rkey=GROUPKEY`));
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('serves a still-valid rkey from cache without re-fetching', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('falls back to the unsigned URL (no throw) when the refresh fails', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => { throw new Error('oidb down'); });
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
|
||||
|
||||
expect(url).toBe(NT_IMAGE_URL);
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('uses the private rkey type for c2c images (appid 1406)', async () => {
|
||||
const { bridge } = makeBridge(async () => freshBothRkeys());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), false);
|
||||
|
||||
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=PRIVATEKEY`);
|
||||
});
|
||||
|
||||
// The scene follows the image's own appid, not the carrying message — the
|
||||
// crux of `/get_forward_msg` rkey correctness (issue #74): a c2c image
|
||||
// forwarded into a group must still be signed with the private rkey.
|
||||
it('signs an appid-1406 image with the private rkey even when isGroup is true', async () => {
|
||||
const { bridge } = makeBridge(async () => freshBothRkeys());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), true);
|
||||
|
||||
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=PRIVATEKEY`);
|
||||
});
|
||||
|
||||
it('signs an appid-1407 image with the group rkey even when isGroup is false', async () => {
|
||||
const { bridge } = makeBridge(async () => freshBothRkeys());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), false);
|
||||
|
||||
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`);
|
||||
});
|
||||
|
||||
it('falls back to the isGroup scene when the URL carries no appid', async () => {
|
||||
const noAppidUrl = 'https://multimedia.nt.qq.com.cn/download?fileid=NOAPPID';
|
||||
const { bridge } = makeBridge(async () => freshBothRkeys());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(
|
||||
bridge as never, { type: 'image', imageUrl: noAppidUrl }, true,
|
||||
);
|
||||
|
||||
expect(url).toBe(`${noAppidUrl}&rkey=GROUPKEY`);
|
||||
});
|
||||
|
||||
it('leaves non-NT URLs untouched and never fetches', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
const el: MessageElement = { type: 'image', imageUrl: 'https://gchat.qpic.cn/foo.jpg' };
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, el, true);
|
||||
|
||||
expect(url).toBe('https://gchat.qpic.cn/foo.jpg');
|
||||
expect(fetchDownloadRKeys).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
63
packages/onebot/tests/media-actions.test.ts
Normal file
63
packages/onebot/tests/media-actions.test.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { getImageInfo } from '../src/modules/media-actions';
|
||||
import type { CachedImage, MediaStore } from '../src/media-store';
|
||||
|
||||
const RAW = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC';
|
||||
|
||||
function fakeStore(image: CachedImage | null): MediaStore {
|
||||
return { findImage: () => image } as unknown as MediaStore;
|
||||
}
|
||||
|
||||
function cachedImage(overrides: Partial<CachedImage> = {}): CachedImage {
|
||||
return {
|
||||
file: 'ABC.jpg',
|
||||
url: `${RAW}&rkey=STALE`, // signed when the message arrived; now expired
|
||||
fileSize: 100,
|
||||
fileName: 'ABC.jpg',
|
||||
subType: 0,
|
||||
summary: '',
|
||||
isGroup: true,
|
||||
sessionId: 123,
|
||||
imageUrl: RAW, // raw, unsigned — the basis for re-signing
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('getImageInfo — rkey re-signing at lookup time', () => {
|
||||
it('re-signs from the raw imageUrl via the resolver', async () => {
|
||||
const resolver = vi.fn(async (el: MessageElement) => `${el.imageUrl}&rkey=FRESH`);
|
||||
|
||||
const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver);
|
||||
|
||||
expect(info?.url).toBe(`${RAW}&rkey=FRESH`);
|
||||
expect(info?.file).toBe(`${RAW}&rkey=FRESH`);
|
||||
expect(resolver).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'image', imageUrl: RAW }),
|
||||
true, // isGroup carried through
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the stored URL when no resolver is wired', async () => {
|
||||
const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg');
|
||||
expect(info?.url).toBe(`${RAW}&rkey=STALE`);
|
||||
});
|
||||
|
||||
it('falls back to the stored URL when the resolver throws', async () => {
|
||||
const resolver = vi.fn(async () => { throw new Error('rkey fetch failed'); });
|
||||
const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver);
|
||||
expect(info?.url).toBe(`${RAW}&rkey=STALE`);
|
||||
});
|
||||
|
||||
it('skips re-signing when no raw imageUrl is stored', async () => {
|
||||
const resolver = vi.fn(async () => 'should-not-be-used');
|
||||
const info = await getImageInfo(fakeStore(cachedImage({ imageUrl: '' })), 'ABC.jpg', resolver);
|
||||
expect(resolver).not.toHaveBeenCalled();
|
||||
expect(info?.url).toBe(`${RAW}&rkey=STALE`);
|
||||
});
|
||||
|
||||
it('returns null when the image is not cached', async () => {
|
||||
const info = await getImageInfo(fakeStore(null), 'missing.jpg');
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -413,6 +413,33 @@ describe('parseMessage', () => {
|
||||
const parsed = JSON.parse(result[0].text!);
|
||||
expect(parsed.meta.contact.type).toBe('group');
|
||||
});
|
||||
|
||||
it('parses signed music cards and buildSendElems preserves non-ASCII JSON', async () => {
|
||||
const card = JSON.stringify({
|
||||
app: 'com.tencent.structmsg',
|
||||
view: 'music',
|
||||
prompt: '[音乐]风中有朵雨做的云',
|
||||
meta: { music: { title: '风中有朵雨做的云', desc: '孟庭苇' } },
|
||||
});
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({
|
||||
ok: true,
|
||||
text: async () => card,
|
||||
})));
|
||||
|
||||
try {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'music', data: { type: '163', id: '123456' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'json', text: card }]);
|
||||
|
||||
const protoElems = await buildSendElems(result);
|
||||
expect(protoElems).toHaveLength(1);
|
||||
expect(protoElems[0].lightApp?.data?.[0]).toBe(0x01);
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('single segment object', () => {
|
||||
|
||||
103
packages/onebot/tests/status-command.test.ts
Normal file
103
packages/onebot/tests/status-command.test.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
STATUS_COMMAND_TRIGGER,
|
||||
buildStatusText,
|
||||
formatUptime,
|
||||
matchesStatusCommand,
|
||||
statusCooldownElapsed,
|
||||
} from '../src/modules/status-command';
|
||||
import type { JsonValue } from '../src/types';
|
||||
|
||||
function textSeg(text: string): JsonValue {
|
||||
return [{ type: 'text', data: { text } }] as unknown as JsonValue;
|
||||
}
|
||||
|
||||
describe('matchesStatusCommand', () => {
|
||||
it('matches a single text segment equal to the trigger', () => {
|
||||
expect(matchesStatusCommand(textSeg('#sl'))).toBe(true);
|
||||
});
|
||||
|
||||
it('is case-insensitive and trims surrounding whitespace', () => {
|
||||
expect(matchesStatusCommand(textSeg('#SL'))).toBe(true);
|
||||
expect(matchesStatusCommand(textSeg(' #Sl '))).toBe(true);
|
||||
});
|
||||
|
||||
it('matches a bare string (string-format adapters)', () => {
|
||||
expect(matchesStatusCommand('#sl' as unknown as JsonValue)).toBe(true);
|
||||
expect(matchesStatusCommand(' #SL ' as unknown as JsonValue)).toBe(true);
|
||||
});
|
||||
|
||||
it('does NOT match as a prefix — only exact', () => {
|
||||
expect(matchesStatusCommand(textSeg('#slogan'))).toBe(false);
|
||||
expect(matchesStatusCommand(textSeg('#sl help'))).toBe(false);
|
||||
expect(matchesStatusCommand(textSeg('你好 #sl'))).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects mixed-segment messages', () => {
|
||||
const mixed = [
|
||||
{ type: 'text', data: { text: '#sl' } },
|
||||
{ type: 'image', data: { file: 'x.png' } },
|
||||
] as unknown as JsonValue;
|
||||
expect(matchesStatusCommand(mixed)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects non-text leading segments and empty/garbage input', () => {
|
||||
expect(matchesStatusCommand([{ type: 'at', data: { qq: '1' } }] as unknown as JsonValue)).toBe(false);
|
||||
expect(matchesStatusCommand([] as unknown as JsonValue)).toBe(false);
|
||||
expect(matchesStatusCommand(undefined)).toBe(false);
|
||||
expect(matchesStatusCommand(123 as unknown as JsonValue)).toBe(false);
|
||||
});
|
||||
|
||||
it('exposes the hardcoded trigger', () => {
|
||||
expect(STATUS_COMMAND_TRIGGER).toBe('#sl');
|
||||
});
|
||||
});
|
||||
|
||||
describe('statusCooldownElapsed', () => {
|
||||
it('allows the first reply (no prior timestamp)', () => {
|
||||
expect(statusCooldownElapsed(undefined, 1_000, 5)).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores the cooldown when set to 0 or negative', () => {
|
||||
expect(statusCooldownElapsed(1_000, 1_500, 0)).toBe(true);
|
||||
expect(statusCooldownElapsed(1_000, 1_000, -1)).toBe(true);
|
||||
});
|
||||
|
||||
it('blocks within the window and allows once elapsed', () => {
|
||||
const last = 10_000;
|
||||
expect(statusCooldownElapsed(last, last + 4_999, 5)).toBe(false);
|
||||
expect(statusCooldownElapsed(last, last + 5_000, 5)).toBe(true);
|
||||
expect(statusCooldownElapsed(last, last + 9_999, 5)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatUptime', () => {
|
||||
it('drops leading zero units', () => {
|
||||
expect(formatUptime(0)).toBe('0秒');
|
||||
expect(formatUptime(45_000)).toBe('45秒');
|
||||
expect(formatUptime(90_000)).toBe('1分钟 30秒');
|
||||
expect(formatUptime(3_600_000)).toBe('1小时 0分钟');
|
||||
expect(formatUptime((26 * 3600 + 12 * 60) * 1000)).toBe('1天 2小时 12分钟');
|
||||
});
|
||||
|
||||
it('never goes negative', () => {
|
||||
expect(formatUptime(-5_000)).toBe('0秒');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildStatusText', () => {
|
||||
it('renders version / platform / uptime, no leaked uin or topology', () => {
|
||||
const text = buildStatusText({
|
||||
version: '1.9.3-node',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
uptimeMs: 90_000,
|
||||
});
|
||||
expect(text).toContain('SnowLuma');
|
||||
expect(text).toContain('版本: 1.9.3-node');
|
||||
expect(text).toContain('平台: linux-x64');
|
||||
expect(text).toContain('运行时长: 1分钟 30秒');
|
||||
// public-safe: must not echo a uin or connection count
|
||||
expect(text).not.toMatch(/uin|连接|adapter/i);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/proto-defs",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
|
||||
import type { pb, pb_optional, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
|
||||
|
||||
// Re-exported from the legacy oidb-action module while large protocol groups
|
||||
// are split into focused files.
|
||||
@@ -13,7 +13,11 @@ export interface OidbMuteMember {
|
||||
body?: pb<3, OidbMuteMemberBody>;
|
||||
}
|
||||
export interface OidbMuteAllState {
|
||||
state?: pb<17, uint_32>;
|
||||
// Explicit presence: the unmute request sends state=0, which proto3 would
|
||||
// otherwise omit — leaving an empty `muteState` the server can't tell apart
|
||||
// from the other commands sharing OIDB (0x89A, 0) (SetSearch / SetAddOption,
|
||||
// disambiguated by body shape). pb_optional forces the 0 onto the wire.
|
||||
state?: pb_optional<17, uint_32>;
|
||||
}
|
||||
export interface OidbMuteAll {
|
||||
groupUin?: pb<1, uint_32>;
|
||||
@@ -90,13 +94,19 @@ export interface OidbSetAdmin {
|
||||
uid?: pb<2, string>;
|
||||
isAdmin?: pb<3, bool>;
|
||||
}
|
||||
// 0x8FC_3 (set member card) shares its wire shape with 0x8FC_2 (special
|
||||
// title): the body wrapper sits at tag 3, and the card name at tag 8 —
|
||||
// NOT tags 2/2. Sending body@2 / targetName@2 makes the server miss both
|
||||
// and reject with `OIDB error 1007`. Cross-checked byte-for-byte against:
|
||||
// dev/Lagrange.Core/…/Request/OidbSvcTrpcTcp0x8FC.cs (Body=3, TargetName=8)
|
||||
// dev/napcatQQInside/…/proto/oidb/Oidb.0x8FC_2.ts (body=3, targetName=8)
|
||||
export interface OidbRenameMemberBody {
|
||||
targetUid?: pb<1, string>;
|
||||
targetName?: pb<2, string>;
|
||||
targetName?: pb<8, string>;
|
||||
}
|
||||
export interface OidbRenameMember {
|
||||
groupUin?: pb<1, uint_32>;
|
||||
body?: pb<2, OidbRenameMemberBody>;
|
||||
body?: pb<3, OidbRenameMemberBody>;
|
||||
}
|
||||
export interface OidbRenameGroupBody {
|
||||
targetName?: pb<1, string>;
|
||||
@@ -112,7 +122,8 @@ export interface OidbSpecialTitleBody {
|
||||
}
|
||||
export interface OidbSpecialTitle {
|
||||
groupUin?: pb<1, uint_32>;
|
||||
body?: pb<2, OidbSpecialTitleBody>;
|
||||
// Same family as 0x8FC_3 above — body wrapper is tag 3, not 2.
|
||||
body?: pb<3, OidbSpecialTitleBody>;
|
||||
}
|
||||
// 0x7E5_104 (FriendLike) request body. Field numbers 11/12/13 (NOT
|
||||
// 1/2/3) — the server reads `targetUid` from tag 11 and rejects with
|
||||
@@ -657,4 +668,22 @@ export interface GroupAvatarExtra {
|
||||
field3?: pb<3, GroupAvatarExtraField3>;
|
||||
field5?: pb<5, uint_32>;
|
||||
field6?: pb<6, uint_32>;
|
||||
}
|
||||
}
|
||||
|
||||
export interface Oidb0xcdeReqBodyInfo {
|
||||
db_salt?: pb<1, string>;
|
||||
}
|
||||
|
||||
export interface Oidb0xcdeReq {
|
||||
info?: pb<2, Oidb0xcdeReqBodyInfo>;
|
||||
sessionData?: pb<10, bytes>;
|
||||
}
|
||||
|
||||
export interface Oidb0xcdeRespBodyInfo {
|
||||
dbKey?: pb<1, string>;
|
||||
}
|
||||
|
||||
export interface Oidb0xcdeResp {
|
||||
info?: pb<2, Oidb0xcdeRespBodyInfo>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
|
||||
@@ -107,6 +107,10 @@
|
||||
"types": "./src/oidb-services/misc/send-group-sign.ts",
|
||||
"default": "./src/oidb-services/misc/send-group-sign.ts"
|
||||
},
|
||||
"./oidb-services/misc/request-decrypt-key": {
|
||||
"types": "./src/oidb-services/misc/request-decrypt-key.ts",
|
||||
"default": "./src/oidb-services/misc/request-decrypt-key.ts"
|
||||
},
|
||||
"./oidb-services/web/force-fetch-client-key": {
|
||||
"types": "./src/oidb-services/web/force-fetch-client-key.ts",
|
||||
"default": "./src/oidb-services/web/force-fetch-client-key.ts"
|
||||
@@ -368,8 +372,7 @@
|
||||
"dependencies": {
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*"
|
||||
"@snowluma/proton": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
|
||||
@@ -105,32 +105,31 @@ function makeReplyElem(element: MessageElement): ProtoElem {
|
||||
return { srcMsg };
|
||||
}
|
||||
|
||||
function makeDeflatedPayload(content: string): Uint8Array {
|
||||
const deflated = deflateSync(Buffer.from(content, 'utf8'));
|
||||
const payload = new Uint8Array(deflated.length + 1);
|
||||
payload[0] = 0x01;
|
||||
payload.set(deflated, 1);
|
||||
return payload;
|
||||
}
|
||||
|
||||
function makeJsonElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: 1,
|
||||
template1: payload,
|
||||
lightApp: {
|
||||
data: makeDeflatedPayload(content),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeXmlElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
|
||||
template1: payload,
|
||||
template1: makeDeflatedPayload(content),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -208,14 +207,9 @@ function makeForwardElem(element: MessageElement): ProtoElem {
|
||||
};
|
||||
|
||||
const json = JSON.stringify(lightApp);
|
||||
const deflated = deflateSync(Buffer.from(json, 'utf8'));
|
||||
const payload = new Uint8Array(deflated.length + 1);
|
||||
payload[0] = 0x01; // 0x01 prefix = deflated JSON (vs 0x00 = uncompressed XML)
|
||||
payload.set(deflated, 1);
|
||||
|
||||
return {
|
||||
lightApp: {
|
||||
data: payload,
|
||||
data: makeDeflatedPayload(json),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -202,7 +202,14 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
const onClose = () => finish(() => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||
else reject(new Error('connection closed before response'));
|
||||
// QQ 的 highway 边缘节点对单连接多 POST 的 keep-alive 支持不稳定:
|
||||
// 第一次 POST 拿到响应后服务器经常立刻 FIN 关闭,下一次写入的请求体
|
||||
// 走到一个已被对端 close 的 socket 上,触发这里。诊断信息把已收到的
|
||||
// 字节数和是否解析到 header 一起带出来,便于区分 “连接刚握手就被关”
|
||||
// 和 “响应读到一半被截断” 两种情况。
|
||||
else reject(new Error(
|
||||
`connection closed before response (received=${buf.length}B, headerSeen=${headerEnd >= 0})`
|
||||
));
|
||||
});
|
||||
|
||||
socket.on('data', onData);
|
||||
@@ -225,42 +232,60 @@ export async function uploadHighwayHttp(
|
||||
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
|
||||
try {
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
// Surface every diagnostic the highway response carries so
|
||||
// user reports of `error_code=921` and friends include the
|
||||
// server-side context (segHead.retCode, chunk size, file md5)
|
||||
// — without these we can't tell apart a malformed-payload
|
||||
// reject, a session-ticket mismatch, or a per-account rate-
|
||||
// limit.
|
||||
const segRetCode = resp.msgSegHead?.retCode ?? 0;
|
||||
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
|
||||
throw new Error(
|
||||
`highway upload error_code=${resp.errorCode}` +
|
||||
` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` +
|
||||
` offset=${offset} segRetCode=${segRetCode}` +
|
||||
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
|
||||
);
|
||||
}
|
||||
offset += chunkSize;
|
||||
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||
// 每个 chunk 一个独立的 TCP 连接。
|
||||
//
|
||||
// 旧实现整个文件复用同一个 socket,依赖 `Connection: keep-alive` 跑多次
|
||||
// POST。但 QQ highway 边缘节点(以及链路上的代理/NAT)经常在第一次响应
|
||||
// 之后立刻 FIN 关闭连接,导致第二个 chunk 写入一个已被对端关闭的 socket,
|
||||
// `readHttpResponseBody` 立刻收到 `close` 事件并抛 `connection closed
|
||||
// before response`。
|
||||
//
|
||||
// 现象上的体现:≤1 MB 的图片/PTT 因为只发一个 chunk,不会触发;超过 1 MB
|
||||
// 的图片或视频(HIGHWAY_BLOCK_SIZE = 1 MiB)必然失败。
|
||||
//
|
||||
// 改成每 chunk 一连接代价可忽略:
|
||||
// - 单个 1 MB chunk 的传输时间远大于 TCP 建连开销;
|
||||
// - QQ 服务端反正也不希望客户端长时间占用连接;
|
||||
// - 与 NapCat / Lagrange 在大文件上传时的连接生命周期一致。
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
let responseBody: Uint8Array;
|
||||
try {
|
||||
responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||
} finally {
|
||||
socket.destroy();
|
||||
}
|
||||
} finally {
|
||||
socket.destroy();
|
||||
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
// Surface every diagnostic the highway response carries so
|
||||
// user reports of `error_code=921` and friends include the
|
||||
// server-side context (segHead.retCode, chunk size, file md5)
|
||||
// — without these we can't tell apart a malformed-payload
|
||||
// reject, a session-ticket mismatch, or a per-account rate-
|
||||
// limit.
|
||||
const segRetCode = resp.msgSegHead?.retCode ?? 0;
|
||||
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
|
||||
throw new Error(
|
||||
`highway upload error_code=${resp.errorCode}` +
|
||||
` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` +
|
||||
` offset=${offset} segRetCode=${segRetCode}` +
|
||||
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
|
||||
);
|
||||
}
|
||||
offset += chunkSize;
|
||||
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,19 @@ const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
|
||||
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
const FETCH_TIMEOUT_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Browser-like User-Agent for remote media downloads. Many image / CDN
|
||||
* hosts (and anti-hotlink front-ends) reject or RST a header-less,
|
||||
* non-browser request — which surfaces as undici `TypeError: fetch
|
||||
* failed` rather than a clean 403. Sending a normal browser UA on every
|
||||
* request (and retrying with a Referer when the first try is refused) is
|
||||
* what lets NapCat fetch sources our bare `fetch(source)` couldn't.
|
||||
* Cross-checked against
|
||||
* `dev/napcatQQInside/packages/napcat-common/src/file.ts:101-142,359-369`.
|
||||
*/
|
||||
const DOWNLOAD_USER_AGENT =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
@@ -65,6 +78,14 @@ export function resolveLocalFilePath(source: string): string | null {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tag a size-limit error so the HTTP retry path leaves it alone — retrying
|
||||
* a too-large response just re-downloads the same oversized body.
|
||||
*/
|
||||
function tooLarge(message: string): Error {
|
||||
return Object.assign(new Error(message), { noRetry: true });
|
||||
}
|
||||
|
||||
export async function loadBinarySource(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
@@ -81,49 +102,79 @@ export async function loadBinarySource(
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
// Stream the body incrementally so a server that omits or
|
||||
// understates Content-Length can't make us buffer a chunked response
|
||||
// past maxBytes — `await resp.arrayBuffer()` would happily allocate
|
||||
// the entire payload before we get a chance to length-check it.
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
|
||||
// A single fetch attempt with the given headers. Streams the body
|
||||
// incrementally so a server that omits or understates Content-Length
|
||||
// can't make us buffer a chunked response past maxBytes — `await
|
||||
// resp.arrayBuffer()` would happily allocate the entire payload before
|
||||
// we get a chance to length-check it. Size-limit rejections are tagged
|
||||
// `noRetry` so the outer retry doesn't re-download an oversized body.
|
||||
const attempt = async (headers: Record<string, string>): Promise<LoadedBinary> => {
|
||||
const resp = await fetch(source, {
|
||||
headers,
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw tooLarge(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
};
|
||||
|
||||
// First try with a browser UA only. On any non-size failure — a
|
||||
// network-level `fetch failed` (connection reset by an anti-bot
|
||||
// front-end) or a 403/4xx from anti-hotlink — retry once with a
|
||||
// Referer pointing at the resource itself, the common bypass for
|
||||
// same-origin hotlink checks. Mirrors NapCat's with/without-Referer
|
||||
// strategy.
|
||||
const baseHeaders: Record<string, string> = {
|
||||
'User-Agent': DOWNLOAD_USER_AGENT,
|
||||
Accept: '*/*',
|
||||
};
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw new Error(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
return await attempt(baseHeaders);
|
||||
} catch (err) {
|
||||
if ((err as { noRetry?: boolean } | null)?.noRetry) throw err;
|
||||
try {
|
||||
return await attempt({ ...baseHeaders, Referer: source });
|
||||
} catch {
|
||||
throw err;
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
const filePath = resolveLocalFilePath(source);
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import path from 'path';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
UserProfileInfo, GroupRequestInfo,
|
||||
} from './qq-info';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from './qq-info';
|
||||
|
||||
const moduleLogger = createLogger('Identity');
|
||||
|
||||
@@ -109,14 +111,14 @@ export class IdentityService {
|
||||
private readonly uidByUin = new Map<number, string>();
|
||||
|
||||
// ─── Persistence + fetcher ───
|
||||
private readonly db: DatabaseType | null;
|
||||
private readonly db: DatabaseSync | null;
|
||||
// Prepared-statement cache. Every `.prepare(sql)` call in this
|
||||
// service re-parses the SQL — that's the SQLite anti-pattern
|
||||
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
|
||||
// call sites stay readable (no need to enumerate 20+ named fields
|
||||
// upfront); the Map lookup is O(1) hash + string-eq, which is
|
||||
// negligible next to the SQL parse it replaces.
|
||||
private readonly stmtCache_ = new Map<string, Statement>();
|
||||
private readonly stmtCache_ = new Map<string, StatementSync>();
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
@@ -134,16 +136,16 @@ export class IdentityService {
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
this.loadSnapshot();
|
||||
}
|
||||
|
||||
/** Cached `prepare(sql)`. First call per unique SQL parses; later
|
||||
* calls reuse the same `Statement` object. See `stmtCache_`. */
|
||||
private pstmt(sql: string): Statement {
|
||||
private pstmt(sql: string): StatementSync {
|
||||
let cached = this.stmtCache_.get(sql);
|
||||
if (cached !== undefined) return cached;
|
||||
cached = this.db!.prepare(sql);
|
||||
|
||||
@@ -117,9 +117,19 @@ export async function invokeOidb<TCtx extends OidbSender, TReq, TResp, TParams,
|
||||
: `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`;
|
||||
|
||||
const result = await ctx.sendRawPacket(wireName, reqBytes, timeoutMs);
|
||||
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
|
||||
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
|
||||
|
||||
if (!result.success) {
|
||||
if (result.errorCode && result.errorCode !== 0) {
|
||||
throw new OidbError(
|
||||
result.errorCode,
|
||||
result.errorMessage || '',
|
||||
spec.command,
|
||||
subCommand
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const respBytes = result.responseData ?? new Uint8Array(0);
|
||||
if (respBytes.length > 0) {
|
||||
const meta = protobuf_decode<OidbBaseMeta>(respBytes);
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { Oidb0xcdeReq, Oidb0xcdeResp } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
export namespace RequestDbKey {
|
||||
export const command = 0xcde;
|
||||
export const subCommand = 2;
|
||||
|
||||
export interface Params {
|
||||
db_salt: string;
|
||||
sessionData?: Uint8Array;
|
||||
}
|
||||
|
||||
export interface Result {
|
||||
success: boolean;
|
||||
dbKey?: string;
|
||||
errorCode?: number;
|
||||
errorMsg?: string;
|
||||
}
|
||||
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const serialize = (_ctx: Deps, p: Params): Oidb0xcdeReq => {
|
||||
const req: Oidb0xcdeReq = {
|
||||
info: {
|
||||
db_salt: p.db_salt,
|
||||
}
|
||||
};
|
||||
if (p.sessionData) {
|
||||
req.sessionData = p.sessionData;
|
||||
}
|
||||
return req;
|
||||
};
|
||||
|
||||
export const deserialize = (_ctx: Deps, body: Oidb0xcdeResp): string => {
|
||||
const dbKey = body.info?.dbKey;
|
||||
|
||||
if (!dbKey) {
|
||||
throw new Error('Oidb 0xcde_2 payload empty (Missing dbKey)');
|
||||
}
|
||||
return dbKey;
|
||||
};
|
||||
|
||||
export const encode = (env: OidbBase<Oidb0xcdeReq>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<Oidb0xcdeReq>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<Oidb0xcdeResp> =>
|
||||
protobuf_decode<OidbBase<Oidb0xcdeResp>>(bytes);
|
||||
|
||||
export const invoke = async (deps: Deps, params: Params): Promise<Result> => {
|
||||
try {
|
||||
const key = await invokeOidb(deps, RequestDbKey, params);
|
||||
return {
|
||||
success: true,
|
||||
dbKey: key,
|
||||
};
|
||||
} catch (error: any) {
|
||||
const code = error?.code ?? -1;
|
||||
|
||||
return {
|
||||
success: false,
|
||||
errorCode: code,
|
||||
errorMsg: code === 1006
|
||||
? "数据库不匹配!检查数据库是否属于当前帐号"
|
||||
: (error?.serverMsg || error?.message || "网络或包结构解析失败"),
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -26,12 +26,18 @@ describe('MuteAll namespace', () => {
|
||||
expect(env.body).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF } });
|
||||
});
|
||||
|
||||
it('enable=false emits state=0', async () => {
|
||||
it('enable=false forces state=0 ONTO the wire (so the server can disambiguate)', async () => {
|
||||
const deps = makeDeps();
|
||||
await MuteAll.invoke(deps, { groupId: 12345, enable: false });
|
||||
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbMuteAll>>(bytes);
|
||||
// proto3 default 0 fields are omitted on the wire.
|
||||
expect(env.body?.muteState?.state ?? 0).toBe(0);
|
||||
expect(env.body?.muteState?.state).toBe(0);
|
||||
// The fix (issue #70): state=0 is a `pb_optional<>` field, so it must be
|
||||
// PRESENT on the wire — field 17 (varint tag 0x88 0x01) + value 0x00 — not
|
||||
// omitted. An empty `muteState` is indistinguishable from the other
|
||||
// commands sharing OIDB (0x89A, 0), so the server rejects unmute with 1007.
|
||||
const arr = Array.from(bytes);
|
||||
const hasStateField = arr.some((_, i) => arr[i] === 0x88 && arr[i + 1] === 0x01 && arr[i + 2] === 0x00);
|
||||
expect(hasStateField).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/proton",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
|
||||
|
||||
8
packages/proton/protobuf.d.ts
vendored
8
packages/proton/protobuf.d.ts
vendored
@@ -3,6 +3,14 @@
|
||||
export type pb<_ProtoNumber extends number, Type> = Type;
|
||||
/** Marks a repeated protobuf field: `ids: pb_repeated<fieldNumber, Type>` → Type[] */
|
||||
export type pb_repeated<_ProtoNumber extends number, Type> = Type[];
|
||||
/**
|
||||
* Marks a singular field with **explicit presence** (proto3 `optional`): it
|
||||
* serialises whenever the value is present, INCLUDING its zero/default value
|
||||
* — unlike `pb<>`, which omits zeros. Use when the wire peer needs the field
|
||||
* present to disambiguate, e.g. an OIDB sub-command keyed on body shape where
|
||||
* a zero must still appear on the wire. `name: pb_optional<fieldNumber, Type>`.
|
||||
*/
|
||||
export type pb_optional<_ProtoNumber extends number, Type> = Type;
|
||||
|
||||
// ── Protobuf primitive types ──────────────────────────────────────────
|
||||
export type uint_32 = number;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import ts from 'typescript';
|
||||
import {
|
||||
WireType,
|
||||
PB_MARKER, PB_REPEATED_MARKER,
|
||||
PB_MARKER, PB_REPEATED_MARKER, PB_OPTIONAL_MARKER,
|
||||
type ProtobufField, type ProtobufMessage,
|
||||
type GenericProtobufTemplate, type GenericFieldTemplate,
|
||||
} from './types.js';
|
||||
@@ -85,7 +85,7 @@ function parsePbTypeRef(
|
||||
// Resolve the marker name through aliased imports so `import { pb as P }`
|
||||
// / `import { pb_repeated as PR }` still match the marker constants.
|
||||
const marker = resolveImportedTypeName(t.typeName.text);
|
||||
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null;
|
||||
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER && marker !== PB_OPTIONAL_MARKER) return null;
|
||||
const ta = t.typeArguments;
|
||||
if (!ta || ta.length !== 2) return null;
|
||||
const fnNode = ta[0];
|
||||
@@ -129,6 +129,7 @@ function extractField(
|
||||
isMessage: false, // placeholder
|
||||
isOptional: member.questionToken != null,
|
||||
isRepeated: parsed.marker === PB_REPEATED_MARKER,
|
||||
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -149,6 +150,7 @@ function extractGenericField(
|
||||
isTypeParam: tpSet.has(raw),
|
||||
isOptional: member.questionToken != null,
|
||||
isRepeated: parsed.marker === PB_REPEATED_MARKER,
|
||||
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
|
||||
};
|
||||
// If the field's type-arg is itself a generic instantiation (`Wrapper<U>`,
|
||||
// where U is a type param of the enclosing template), capture the original
|
||||
|
||||
@@ -89,6 +89,7 @@ export function monomorphizeTypeNode(
|
||||
isMessage: false,
|
||||
isOptional: f.isOptional,
|
||||
isRepeated: f.isRepeated,
|
||||
explicitPresence: f.explicitPresence,
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -99,6 +100,7 @@ export function monomorphizeTypeNode(
|
||||
isMessage: false,
|
||||
isOptional: f.isOptional,
|
||||
isRepeated: f.isRepeated,
|
||||
explicitPresence: f.explicitPresence,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,14 @@ export interface ProtobufField {
|
||||
isMessage: boolean;
|
||||
isOptional: boolean;
|
||||
isRepeated: boolean;
|
||||
/**
|
||||
* Explicit presence (proto3 `optional`), set only by the `pb_optional<>`
|
||||
* marker. When true, a scalar field serialises even at its zero/default
|
||||
* value. Distinct from `isOptional` (which merely tracks the TS `?` and is
|
||||
* true for almost every field) — the encoder keys off THIS flag, never
|
||||
* `isOptional`, so existing `pb<>` fields are unaffected.
|
||||
*/
|
||||
explicitPresence: boolean;
|
||||
}
|
||||
|
||||
export interface ProtobufMessage {
|
||||
@@ -34,6 +42,8 @@ export interface GenericFieldTemplate {
|
||||
isTypeParam: boolean;
|
||||
isOptional: boolean;
|
||||
isRepeated: boolean;
|
||||
/** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */
|
||||
explicitPresence: boolean;
|
||||
/**
|
||||
* For fields whose type-arg is itself a generic instantiation
|
||||
* (e.g. `wrapped: pb<5, Wrapper<U>>` where `U` is a template type
|
||||
@@ -70,3 +80,4 @@ export const PRIMITIVE_TYPE_MAP: Record<string, { wireType: WireType; defaultVal
|
||||
/** Marker identifiers recognised in type references */
|
||||
export const PB_MARKER = 'pb';
|
||||
export const PB_REPEATED_MARKER = 'pb_repeated';
|
||||
export const PB_OPTIONAL_MARKER = 'pb_optional';
|
||||
|
||||
@@ -91,6 +91,14 @@ export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry
|
||||
|
||||
function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType, isMessage } = field;
|
||||
// `pb_optional<>` scalar → serialise even at the zero value (proto3 explicit
|
||||
// presence). Message fields already emit on `!= null`, so they stay on the
|
||||
// default path; only scalars need the dedicated guard. Every `pb<>` /
|
||||
// `pb_repeated<>` field has `explicitPresence === false` and so takes the
|
||||
// untouched branches below — their generated code is byte-for-byte unchanged.
|
||||
if (field.explicitPresence && !isMessage) {
|
||||
return buildExplicitPresenceScalarBlock(field, index);
|
||||
}
|
||||
const valueVar = `_f${index}`;
|
||||
const cacheVar = `_c${index}`;
|
||||
const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length;
|
||||
@@ -318,6 +326,221 @@ function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
return { declare: [], size: [], write: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Encoder block for a singular scalar field marked `pb_optional<>` (proto3
|
||||
* explicit presence). Identical to the default scalar paths EXCEPT the guard
|
||||
* is `!= null` instead of `!= null && !== <default>`, so the field — and a
|
||||
* `bool`'s real value — is written even when zero/false/empty. Reached only
|
||||
* when `field.explicitPresence === true`, so default `pb<>` fields never run
|
||||
* this code.
|
||||
*/
|
||||
function buildExplicitPresenceScalarBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType } = field;
|
||||
const valueVar = `_f${index}`;
|
||||
const cacheVar = `_c${index}`;
|
||||
const isLenDelim = typeName === 'string' || typeName === 'bytes';
|
||||
const tagLength = computeTagBytes(fieldNumber, isLenDelim ? 2 : wireType).length;
|
||||
const declareVal = ` const ${valueVar} = obj.${name};`;
|
||||
const present = `${valueVar} != null`;
|
||||
|
||||
if (typeName === 'string') {
|
||||
return {
|
||||
declare: [declareVal, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` ${cacheVar} = __utf8Len(${valueVar});`,
|
||||
` const _len = ${cacheVar};`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = ${cacheVar};`,
|
||||
writeVarint('_len', ' '),
|
||||
` offset = __utf8Write(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bytes') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` const _len = ${valueVar}.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = ${valueVar}.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(${valueVar}, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bool') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 1};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` buf[offset++] = ${valueVar} ? 1 : 0;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isVarint64(typeName)) {
|
||||
const bigintExpr = bigintVarintExpr(typeName, valueVar);
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
` size += ${tagLength};`,
|
||||
` size += __varint64Size(_val);`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` offset = __writeVarint64(buf, offset, _val);`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'sint_32') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '),
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Varint) {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [
|
||||
` if (${present}) {`,
|
||||
` const _val = ${valueVar} >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`${valueVar} >>> 0`, ' '),
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'float') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` offset = __writeFloat32(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit32) {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` const _val = ${valueVar};`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'double') {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFloat64(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isFixed64BigInt(typeName)) {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFixed64(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit64) {
|
||||
return {
|
||||
declare: [declareVal],
|
||||
size: [` if (${present}) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${present}) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` const _val = ${valueVar};`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return { declare: [], size: [], write: [] };
|
||||
}
|
||||
|
||||
function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType, isMessage } = field;
|
||||
const arrayVar = `_f${index}`;
|
||||
|
||||
@@ -25,6 +25,7 @@ function cloneField(field: ProtobufField): ProtobufField {
|
||||
isMessage: field.isMessage,
|
||||
isOptional: field.isOptional,
|
||||
isRepeated: field.isRepeated,
|
||||
explicitPresence: field.explicitPresence ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -139,3 +139,43 @@ interface DoubleMsg {
|
||||
expect(result.values[1]).toBeCloseTo(-0.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pb_optional explicit presence', () => {
|
||||
it('serialises a zero scalar (where pb<> would omit it)', () => {
|
||||
const { enc, dec } = makeRoundTripFromSchema(
|
||||
`interface OptMsg { forced: pb_optional<1, uint_32>; }`,
|
||||
'OptMsg',
|
||||
);
|
||||
// field 1, varint, value 0 → tag 0x08 then payload 0x00 (NOT empty).
|
||||
expect(Array.from(enc({ forced: 0 }))).toEqual([0x08, 0x00]);
|
||||
expect(dec(enc({ forced: 0 })).forced).toBe(0);
|
||||
});
|
||||
|
||||
it('still omits the field when the value is absent (undefined)', () => {
|
||||
const { enc } = makeRoundTripFromSchema(
|
||||
`interface OptMsg2 { forced: pb_optional<1, uint_32>; }`,
|
||||
'OptMsg2',
|
||||
);
|
||||
expect(enc({}).length).toBe(0);
|
||||
});
|
||||
|
||||
it('does not change a sibling plain pb<> field (it still omits its zero)', () => {
|
||||
const { enc, dec } = makeRoundTripFromSchema(
|
||||
`interface MixMsg { plain: pb<1, uint_32>; forced: pb_optional<2, uint_32>; }`,
|
||||
'MixMsg',
|
||||
);
|
||||
// plain=0 omitted (unchanged); only forced=0 is emitted (field 2 → tag 0x10).
|
||||
expect(Array.from(enc({ plain: 0, forced: 0 }))).toEqual([0x10, 0x00]);
|
||||
expect(dec(enc({ plain: 7, forced: 9 }))).toEqual({ plain: 7, forced: 9 });
|
||||
});
|
||||
|
||||
it('forces a false bool onto the wire', () => {
|
||||
const { enc, dec } = makeRoundTripFromSchema(
|
||||
`interface BoolOpt { flag: pb_optional<1, bool>; }`,
|
||||
'BoolOpt',
|
||||
);
|
||||
expect(Array.from(enc({ flag: false }))).toEqual([0x08, 0x00]);
|
||||
expect(dec(enc({ flag: false })).flag).toBe(false);
|
||||
expect(Array.from(enc({ flag: true }))).toEqual([0x08, 0x01]);
|
||||
});
|
||||
});
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/runtime",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"name": "@snowluma/sqlite",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma SQLite wrapper. Exposes the `better-sqlite3` Database constructor + Statement type, but loads the native `.node` binding from `dist/native/sqlite/<platform>-<arch>/` at runtime instead of going through `bindings('better_sqlite3.node')` + `node_modules/.../build/Release/`. The vendored prebuilds under `packages/runtime/native/sqlite/` get copied into the dist tree by `vite-plugin-cp` during the @snowluma/core build, mirroring how `websocket-*.node` and `ffmpegAddon.*.node` are handled. The end result: production artifacts ship as a single self-contained dist/ directory with no `dist/node_modules/` and no install step at runtime.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/node": "^24.12.2",
|
||||
"better-sqlite3": "12.10.0",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import BetterSqlite3 from 'better-sqlite3';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// Re-export the public types/classes consumers need. `Database` and
|
||||
// `Statement` come straight from better-sqlite3 — we only intercept
|
||||
// the constructor at call time, not the class shape.
|
||||
export type { Database, Options, RunResult, Statement } from 'better-sqlite3';
|
||||
|
||||
function triplet(): string {
|
||||
return `${process.platform}-${process.arch}`;
|
||||
}
|
||||
|
||||
function abi(): string {
|
||||
// `process.versions.modules` is the NODE_MODULE_VERSION the running
|
||||
// Node binary expects — e.g. "127" for Node 22, "137" for Node 24.
|
||||
// Stays in sync with whatever the host actually does at load time.
|
||||
return `v${process.versions.modules}`;
|
||||
}
|
||||
|
||||
function locateBinding(): string {
|
||||
const tri = triplet();
|
||||
const fileName = `better-sqlite3-${abi()}-${tri}.node`;
|
||||
// Two candidate locations, tried in order:
|
||||
// 1. Production: dist/native/better-sqlite3-<triplet>.node
|
||||
// — `import.meta.url` resolves to dist/ at runtime (the wrapper
|
||||
// is bundled into index.mjs alongside it).
|
||||
// 2. Dev: <repo>/packages/runtime/native/better-sqlite3-<triplet>.node
|
||||
// — `import.meta.url` resolves to packages/sqlite/src/index.ts;
|
||||
// walk up to repo root + into runtime/native.
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const distCandidate = join(here, 'native', fileName);
|
||||
if (existsSync(distCandidate)) return distCandidate;
|
||||
|
||||
// From packages/sqlite/src ⇢ go up to packages/, then into
|
||||
// runtime/native. (Two `..` segments, not three — `src` → `sqlite/`
|
||||
// → `packages/`, then descend into `runtime/native`.)
|
||||
const devCandidate = resolve(here, '..', '..', 'runtime', 'native', fileName);
|
||||
if (existsSync(devCandidate)) return devCandidate;
|
||||
|
||||
throw new Error(
|
||||
`@snowluma/sqlite: could not locate ${fileName}. ` +
|
||||
`Tried:\n ${distCandidate}\n ${devCandidate}\n` +
|
||||
`Run \`node tools/fetch-sqlite-prebuilts.mjs\` to vendor the missing platform binary.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Load the native addon once at module import — keeping it module-
|
||||
// scoped so the require() cost is paid exactly once per process.
|
||||
let addon: unknown | null = null;
|
||||
function loadAddon(): unknown {
|
||||
if (addon) return addon;
|
||||
const bindingPath = locateBinding();
|
||||
// better-sqlite3 expects the addon to be loaded via the CJS
|
||||
// require() mechanism (N-API init runs through it). createRequire
|
||||
// is the ESM-safe way to do that with an absolute path.
|
||||
const req = createRequire(import.meta.url);
|
||||
addon = req(bindingPath);
|
||||
return addon;
|
||||
}
|
||||
|
||||
// Drop-in `Database` factory. Matches the better-sqlite3 default-
|
||||
// export signature exactly: `new Database(filename[, options])` →
|
||||
// `Database` instance.
|
||||
//
|
||||
// We can't just `class extends BetterSqlite3` because better-sqlite3's
|
||||
// default export is a function that returns the instance (the `new
|
||||
// Database(...)` shape works through that function's `new.target`
|
||||
// check). Wrapping at the function-call boundary keeps that contract
|
||||
// intact.
|
||||
type BetterSqlite3Type = typeof BetterSqlite3;
|
||||
type DatabaseInstance = InstanceType<BetterSqlite3Type>;
|
||||
type DatabaseOptions = ConstructorParameters<BetterSqlite3Type>[1];
|
||||
type BetterSqlite3Constructor = new (filename?: string | Buffer, options?: DatabaseOptions) => DatabaseInstance;
|
||||
|
||||
const Database = function Database(filename?: string | Buffer, options?: DatabaseOptions): DatabaseInstance {
|
||||
const opts = { ...(options ?? {}), nativeBinding: loadAddon() } as DatabaseOptions;
|
||||
// better-sqlite3 的默认导出同时支持函数调用和 new 调用;这里只需要构造器形态。
|
||||
return new (BetterSqlite3 as unknown as BetterSqlite3Constructor)(filename, opts);
|
||||
} as unknown as BetterSqlite3Type;
|
||||
|
||||
export default Database;
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/websocket",
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "webui",
|
||||
"private": true,
|
||||
"version": "1.9.2",
|
||||
"version": "1.9.4",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -21,6 +21,11 @@ function AuthBoundary() {
|
||||
const [authed, setAuthed] = useState(false);
|
||||
const [mustChange, setMustChange] = useState(false);
|
||||
const [status, setStatus] = useState('未连接');
|
||||
// The password from *this* session's login, carried into the forced
|
||||
// change-password gate so it doesn't have to render an old-password field
|
||||
// (which browsers autofill, misleading users on upgrade). Stays undefined
|
||||
// for a returning session that's already authed but still must change.
|
||||
const [loginPassword, setLoginPassword] = useState<string | undefined>(undefined);
|
||||
|
||||
const client = useMemo<ApiClient>(
|
||||
() =>
|
||||
@@ -63,14 +68,21 @@ function AuthBoundary() {
|
||||
</div>
|
||||
) : !authed ? (
|
||||
<LoginGate
|
||||
onAuthed={(needsChange) => {
|
||||
onAuthed={(needsChange, password) => {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
setMustChange(needsChange);
|
||||
setLoginPassword(password);
|
||||
}}
|
||||
/>
|
||||
) : mustChange ? (
|
||||
<ForcedChangePasswordGate onSuccess={() => setMustChange(false)} />
|
||||
<ForcedChangePasswordGate
|
||||
knownOldPassword={loginPassword}
|
||||
onSuccess={() => {
|
||||
setMustChange(false);
|
||||
setLoginPassword(undefined);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<SessionProvider value={{ status, onLogoutComplete: handleLogoutComplete }}>
|
||||
<RouterProvider router={appRouter} />
|
||||
@@ -81,13 +93,13 @@ function AuthBoundary() {
|
||||
);
|
||||
}
|
||||
|
||||
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) {
|
||||
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) {
|
||||
const api = useApi();
|
||||
const handleLogin = useCallback(
|
||||
async (password: string) => {
|
||||
const result = await api.login(password);
|
||||
if (!result.ok) return { success: false, error: result.message };
|
||||
onAuthed(result.mustChangePassword);
|
||||
onAuthed(result.mustChangePassword, password);
|
||||
return { success: true };
|
||||
},
|
||||
[api, onAuthed],
|
||||
@@ -95,11 +107,17 @@ function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) {
|
||||
return <LoginPage onLogin={handleLogin} />;
|
||||
}
|
||||
|
||||
function ForcedChangePasswordGate({ onSuccess }: { onSuccess: () => void }) {
|
||||
function ForcedChangePasswordGate({
|
||||
knownOldPassword,
|
||||
onSuccess,
|
||||
}: {
|
||||
knownOldPassword?: string;
|
||||
onSuccess: () => void;
|
||||
}) {
|
||||
const api = useApi();
|
||||
return (
|
||||
<ChangePasswordPage
|
||||
forced
|
||||
knownOldPassword={knownOldPassword}
|
||||
checkStrength={(p) => api.checkPasswordStrength(p)}
|
||||
submit={(o, n) => api.changePassword(o, n)}
|
||||
onSuccess={onSuccess}
|
||||
|
||||
48
packages/webui/src/components/change-password-dialog.tsx
Normal file
48
packages/webui/src/components/change-password-dialog.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { ChangePasswordForm } from '@/components/pages/change-password-form';
|
||||
import { useApi } from '@/lib/api';
|
||||
|
||||
interface ChangePasswordDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Fired after the password is changed successfully (dialog closes itself). */
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-app "修改访问密码" modal. The forced first-time flow uses the full-screen
|
||||
* ChangePasswordPage; this is the voluntary change a logged-in admin triggers
|
||||
* from 设置 → 账号安全. Both share ChangePasswordForm, so behaviour is identical.
|
||||
*/
|
||||
export function ChangePasswordDialog({ open, onOpenChange, onSuccess }: ChangePasswordDialogProps) {
|
||||
const api = useApi();
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>修改访问密码</DialogTitle>
|
||||
<DialogDescription>
|
||||
设置一个全新的强密码后,其它会话将被立即下线,需要重新登录。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<ChangePasswordForm
|
||||
checkStrength={(p) => api.checkPasswordStrength(p)}
|
||||
submit={(o, n) => api.changePassword(o, n)}
|
||||
onSuccess={() => {
|
||||
onSuccess();
|
||||
onOpenChange(false);
|
||||
}}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
idPrefix="dialog-cpw"
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
// "通用设置" tab — fields that apply to the whole OneBotInstance rather
|
||||
// than any specific adapter. Currently just the music-sign service URL,
|
||||
// but the layout has room for additional cross-cutting toggles.
|
||||
// than any specific adapter: the music-sign service URL and the built-in
|
||||
// `#sl` status command. Edits here mark the config dirty and are persisted
|
||||
// via the page's explicit top-right 保存 (a continuously-edited surface).
|
||||
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import type { OneBotConfig } from '@/types';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import type { OneBotConfig, StatusCommandConfig } from '@/types';
|
||||
|
||||
interface GeneralSettingsTabProps {
|
||||
config: OneBotConfig;
|
||||
@@ -12,6 +14,10 @@ interface GeneralSettingsTabProps {
|
||||
}
|
||||
|
||||
export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps) {
|
||||
const sc = config.statusCommand;
|
||||
const setStatusCommand = (patch: Partial<StatusCommandConfig>) =>
|
||||
onChange({ ...config, statusCommand: { ...sc, ...patch } });
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5 rounded-lg border bg-card/40 p-4">
|
||||
@@ -26,6 +32,57 @@ export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps
|
||||
用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 rounded-lg border bg-card/40 p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<Label>
|
||||
内置状态命令 <code className="font-mono text-xs">#sl</code>
|
||||
</Label>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
|
||||
收到纯文本 <code className="font-mono">#sl</code> 时回复 SnowLuma 版本 / 平台 / 运行时长。任何人可触发,关闭后完全不响应。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={sc.enabled}
|
||||
onChange={(v) => setStatusCommand({ enabled: v })}
|
||||
ariaLabel="启用 #sl 状态命令"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start justify-between gap-3 border-t pt-3">
|
||||
<div className="min-w-0">
|
||||
<Label className={sc.enabled ? undefined : 'text-muted-foreground'}>不转发给下游(swallow)</Label>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
|
||||
开启后,命中的 <code className="font-mono">#sl</code> 不再投递给已连接的 Bot(仍会回复并本地记录)。默认关闭即透传。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={sc.swallow}
|
||||
onChange={(v) => setStatusCommand({ swallow: v })}
|
||||
ariaLabel="吞掉 #sl 不转发给下游"
|
||||
disabled={!sc.enabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5 border-t pt-3">
|
||||
<Label className={sc.enabled ? undefined : 'text-muted-foreground'}>回复冷却(秒)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
className="w-32 tabular-nums"
|
||||
value={sc.cooldownSeconds}
|
||||
disabled={!sc.enabled}
|
||||
onChange={(e) => {
|
||||
const n = Math.trunc(Number(e.target.value));
|
||||
setStatusCommand({ cooldownSeconds: Number.isFinite(n) && n >= 0 ? n : 0 });
|
||||
}}
|
||||
/>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
同一会话在该秒数内重复 <code className="font-mono">#sl</code> 不再回复,防刷屏。<code className="font-mono">0</code> 表示不限制。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,13 +7,30 @@ import { motion } from 'motion/react';
|
||||
import { Pencil, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { AdapterCommon } from './defaults';
|
||||
import type { AdapterStatus } from '@/types';
|
||||
|
||||
const LIVE_STYLE: Record<AdapterStatus['status'], string> = {
|
||||
ok: 'bg-success/10 text-success',
|
||||
warn: 'bg-warning/10 text-warning',
|
||||
down: 'bg-destructive/10 text-destructive',
|
||||
disabled: 'bg-muted text-muted-foreground',
|
||||
};
|
||||
const LIVE_LABEL: Record<AdapterStatus['status'], string> = {
|
||||
ok: '正常',
|
||||
warn: '注意',
|
||||
down: '异常',
|
||||
disabled: '未启用',
|
||||
};
|
||||
|
||||
interface NodeSummaryCardProps<T extends AdapterCommon> {
|
||||
item: T;
|
||||
summary: string;
|
||||
duplicateName: boolean;
|
||||
/** Live runtime status from the OneBot manager, matched by adapter name. */
|
||||
liveStatus?: AdapterStatus;
|
||||
onToggleEnabled: (next: boolean) => void;
|
||||
onEdit: () => void;
|
||||
onDelete: () => void;
|
||||
@@ -23,6 +40,7 @@ export function NodeSummaryCard<T extends AdapterCommon>({
|
||||
item,
|
||||
summary,
|
||||
duplicateName,
|
||||
liveStatus,
|
||||
onToggleEnabled,
|
||||
onEdit,
|
||||
onDelete,
|
||||
@@ -51,6 +69,14 @@ export function NodeSummaryCard<T extends AdapterCommon>({
|
||||
{!enabled && (
|
||||
<Badge variant="secondary" className="font-normal">已停用</Badge>
|
||||
)}
|
||||
{liveStatus && (
|
||||
<span
|
||||
className={cn('rounded px-1.5 py-0.5 text-[10px] font-medium', LIVE_STYLE[liveStatus.status])}
|
||||
title={liveStatus.detail}
|
||||
>
|
||||
{LIVE_LABEL[liveStatus.status]} · {liveStatus.detail}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-mono text-xs text-muted-foreground tabular-nums">{summary}</div>
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
|
||||
@@ -101,30 +127,3 @@ export function NodeSummaryCard<T extends AdapterCommon>({
|
||||
);
|
||||
}
|
||||
|
||||
interface ToggleSwitchProps {
|
||||
value: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={value ? 'true' : 'false'}
|
||||
aria-label={ariaLabel}
|
||||
onClick={() => onChange(!value)}
|
||||
className={cn(
|
||||
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border transition-colors',
|
||||
value ? 'border-primary bg-primary' : 'border-input bg-muted',
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
className="inline-block size-4 rounded-full bg-background shadow-sm"
|
||||
animate={{ x: value ? 22 : 4 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { useRouterState } from '@tanstack/react-router';
|
||||
import { Sheet, SheetContent } from '@/components/ui/sheet';
|
||||
import { Sheet, SheetContent, SheetDescription, SheetTitle } from '@/components/ui/sheet';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Sidebar } from '@/components/layout/sidebar';
|
||||
import { TopBar } from '@/components/layout/top-bar';
|
||||
@@ -44,6 +44,11 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
|
||||
{isMobile && (
|
||||
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
|
||||
<SheetContent side="left" className="w-64 max-w-[80vw] p-0">
|
||||
{/* Radix Dialog (the Sheet primitive) requires an accessible name +
|
||||
description; the nav itself is the visible content, so these are
|
||||
screen-reader-only. */}
|
||||
<SheetTitle className="sr-only">导航菜单</SheetTitle>
|
||||
<SheetDescription className="sr-only">切换 SnowLuma 控制台的页面。</SheetDescription>
|
||||
<Sidebar onItemClick={() => setMobileOpen(false)} />
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
@@ -62,7 +67,7 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
|
||||
|
||||
<main className={cn('flex min-h-0 flex-1 flex-col')}>
|
||||
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
|
||||
<div className="mx-auto w-full max-w-7xl px-4 py-5 sm:px-6 sm:py-6 lg:px-8">
|
||||
<div className="mx-auto w-full max-w-7xl px-4 py-5 sm:px-6 sm:py-6 lg:px-8 2xl:max-w-[1600px]">
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={pathname}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { LayoutDashboard, Settings, SlidersHorizontal, Terminal } from 'lucide-react';
|
||||
import { LayoutDashboard, PlugZap, Settings, SlidersHorizontal, Terminal } from 'lucide-react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Link, useRouterState } from '@tanstack/react-router';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
@@ -16,6 +16,7 @@ export interface NavItem {
|
||||
|
||||
export const NAV_ITEMS: NavItem[] = [
|
||||
{ to: '/', label: '总览', icon: LayoutDashboard, description: '主机与服务状态' },
|
||||
{ to: '/processes', label: '进程注入', icon: PlugZap, description: '加载 / 卸载 / 登录' },
|
||||
{ to: '/config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' },
|
||||
{ to: '/logs', label: '日志', icon: Terminal, description: '实时事件流' },
|
||||
{ to: '/settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
|
||||
|
||||
262
packages/webui/src/components/pages/change-password-form.tsx
Normal file
262
packages/webui/src/components/pages/change-password-form.tsx
Normal file
@@ -0,0 +1,262 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { Check, Eye, EyeOff, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface PasswordRule {
|
||||
id: string;
|
||||
label: string;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export interface ChangePasswordFormProps {
|
||||
/**
|
||||
* When provided, the "current password" field is omitted entirely and this
|
||||
* value is used as the old password.
|
||||
*
|
||||
* Used by the forced first-time flow: the old password is *exactly* what
|
||||
* the user just logged in with, so we fill it ourselves. Rendering the
|
||||
* field at all let Edge/Chrome password-managers autofill it on upgrade —
|
||||
* users saw it pre-filled, assumed it was correct, and could never save
|
||||
* (the autofilled value was stale / not the temp password). Dropping the
|
||||
* field removes the trap entirely.
|
||||
*/
|
||||
knownOldPassword?: string;
|
||||
/** Sends `{ password }`; returns the rule list + valid flag. */
|
||||
checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
/** Sends `{ oldPassword, newPassword }`. Returns success or error message. */
|
||||
submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>;
|
||||
/** Called after a successful submit. */
|
||||
onSuccess: () => void;
|
||||
/** When provided, a cancel button is shown (used by the settings dialog). */
|
||||
onCancel?: () => void;
|
||||
/** Disambiguates input ids if two instances ever mount at once. */
|
||||
idPrefix?: string;
|
||||
submitLabel?: string;
|
||||
}
|
||||
|
||||
export function ChangePasswordForm({
|
||||
knownOldPassword,
|
||||
checkStrength,
|
||||
submit,
|
||||
onSuccess,
|
||||
onCancel,
|
||||
idPrefix = 'cpw',
|
||||
submitLabel = '保存新密码',
|
||||
}: ChangePasswordFormProps) {
|
||||
const carriesOld = knownOldPassword !== undefined;
|
||||
|
||||
const [oldPassword, setOldPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [showOld, setShowOld] = useState(false);
|
||||
const [showNew, setShowNew] = useState(false);
|
||||
const [rules, setRules] = useState<PasswordRule[]>([]);
|
||||
const [valid, setValid] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const effectiveOld = carriesOld ? (knownOldPassword as string) : oldPassword;
|
||||
const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword;
|
||||
const canSubmit =
|
||||
!submitting && effectiveOld.length > 0 && valid && confirmMatches && effectiveOld !== newPassword;
|
||||
|
||||
// Debounce the strength check so we don't slam the API on every keystroke.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const handle = window.setTimeout(async () => {
|
||||
try {
|
||||
const res = await checkStrength(newPassword);
|
||||
if (cancelled) return;
|
||||
setRules(res.rules);
|
||||
setValid(res.valid);
|
||||
} catch {
|
||||
/* ignore – the form will just stay disabled */
|
||||
}
|
||||
}, 180);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearTimeout(handle);
|
||||
};
|
||||
}, [newPassword, checkStrength]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!canSubmit) return;
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const res = await submit(effectiveOld, newPassword);
|
||||
if (res.success) {
|
||||
onSuccess();
|
||||
} else {
|
||||
setError(res.message || '修改失败');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : '网络错误');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
{!carriesOld && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`${idPrefix}-old`}>当前密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={`${idPrefix}-old`}
|
||||
type={showOld ? 'text' : 'password'}
|
||||
autoComplete="current-password"
|
||||
value={oldPassword}
|
||||
onChange={(e) => setOldPassword(e.target.value)}
|
||||
placeholder="输入当前访问密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowOld((v) => !v)}
|
||||
aria-label={showOld ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showOld ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`${idPrefix}-new`}>新密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={`${idPrefix}-new`}
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
placeholder="设置新的强密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowNew((v) => !v)}
|
||||
aria-label={showNew ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showNew ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`${idPrefix}-confirm`}>确认新密码</Label>
|
||||
<Input
|
||||
id={`${idPrefix}-confirm`}
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="再次输入新密码"
|
||||
className="h-10 text-sm"
|
||||
/>
|
||||
{confirmPassword.length > 0 && !confirmMatches && (
|
||||
<span className="text-[11px] text-destructive">两次输入的密码不一致</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<RuleList rules={rules} />
|
||||
|
||||
<AnimatePresence>
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="rounded-md bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{onCancel && (
|
||||
<Button type="button" variant="ghost" onClick={onCancel} className="h-10">
|
||||
取消
|
||||
</Button>
|
||||
)}
|
||||
<Button type="submit" disabled={!canSubmit} className="ml-auto h-10">
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="size-4 animate-spin" /> 提交中…
|
||||
</>
|
||||
) : (
|
||||
submitLabel
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function RuleList({ rules }: { rules: PasswordRule[] }) {
|
||||
// Initial empty state: show a placeholder set so the user knows the rules
|
||||
// exist even before any input.
|
||||
const display = useMemo<PasswordRule[]>(() => {
|
||||
if (rules.length > 0) return rules;
|
||||
return [
|
||||
{ id: 'length', label: '长度不少于 10 位', ok: false },
|
||||
{ id: 'lower', label: '至少包含一个小写字母', ok: false },
|
||||
{ id: 'upper', label: '至少包含一个大写字母', ok: false },
|
||||
{ id: 'special', label: '至少包含一个特殊字符', ok: false },
|
||||
{ id: 'no-space', label: '不得包含空格', ok: false },
|
||||
];
|
||||
}, [rules]);
|
||||
|
||||
return (
|
||||
<ul className="grid gap-1.5 rounded-lg border bg-muted/30 p-3">
|
||||
{display.map((rule) => (
|
||||
<li key={rule.id} className="flex items-center gap-2">
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{
|
||||
backgroundColor: rule.ok ? 'color-mix(in oklab, var(--primary) 20%, transparent)' : 'transparent',
|
||||
borderColor: rule.ok ? 'var(--primary)' : 'var(--border)',
|
||||
scale: rule.ok ? [1, 1.18, 1] : 1,
|
||||
}}
|
||||
transition={{ duration: 0.25 }}
|
||||
className={cn('flex size-4 items-center justify-center rounded-full border')}
|
||||
>
|
||||
<AnimatePresence>
|
||||
{rule.ok && (
|
||||
<motion.span
|
||||
key="check"
|
||||
initial={{ opacity: 0, scale: 0.4 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.4 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
>
|
||||
<Check className="size-3 text-primary" strokeWidth={3} />
|
||||
</motion.span>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.span>
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{ color: rule.ok ? 'var(--foreground)' : 'var(--muted-foreground)' }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="text-xs"
|
||||
>
|
||||
{rule.label}
|
||||
</motion.span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -1,104 +1,40 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { Check, Eye, EyeOff, KeyRound, Loader2, ShieldAlert } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { motion } from 'motion/react';
|
||||
import { ShieldAlert } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ThemeToggle } from '@/components/theme-toggle';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ChangePasswordForm, type PasswordRule } from '@/components/pages/change-password-form';
|
||||
|
||||
export interface PasswordRule {
|
||||
id: string;
|
||||
label: string;
|
||||
ok: boolean;
|
||||
}
|
||||
// Re-exported so existing importers (e.g. the API client) keep resolving
|
||||
// `PasswordRule` from this module after the form was extracted.
|
||||
export type { PasswordRule };
|
||||
|
||||
interface ChangePasswordPageProps {
|
||||
/** When true, this is the forced first-time change flow. */
|
||||
forced?: boolean;
|
||||
/** Heading shown above the form. */
|
||||
/**
|
||||
* The password the user just logged in with. Passed straight through to the
|
||||
* form as `knownOldPassword`, so the forced flow never renders an
|
||||
* old-password field for a browser to autofill. See change-password-form.
|
||||
*/
|
||||
knownOldPassword?: string;
|
||||
title?: string;
|
||||
/** Subheading. */
|
||||
description?: string;
|
||||
/** Sends `{ password }` and returns the rule list + valid flag. */
|
||||
checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
/** Sends `{ oldPassword, newPassword }`. Returns success or error message. */
|
||||
submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>;
|
||||
/** Called after a successful submit. */
|
||||
onSuccess: () => void;
|
||||
/** Called when user cancels (only available when not forced). */
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-screen "you must set a new password before continuing" gate, shown
|
||||
* once right after the first login with a generated temp password. The
|
||||
* in-app "修改访问密码" action uses ChangePasswordDialog instead.
|
||||
*/
|
||||
export function ChangePasswordPage({
|
||||
forced = false,
|
||||
title,
|
||||
description,
|
||||
knownOldPassword,
|
||||
title = '请先设置新的访问密码',
|
||||
description = '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。',
|
||||
checkStrength,
|
||||
submit,
|
||||
onSuccess,
|
||||
onCancel,
|
||||
}: ChangePasswordPageProps) {
|
||||
const [oldPassword, setOldPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [showOld, setShowOld] = useState(false);
|
||||
const [showNew, setShowNew] = useState(false);
|
||||
const [rules, setRules] = useState<PasswordRule[]>([]);
|
||||
const [valid, setValid] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword;
|
||||
const canSubmit =
|
||||
!submitting && oldPassword.length > 0 && valid && confirmMatches && oldPassword !== newPassword;
|
||||
|
||||
// Debounce the strength check so we don't slam the API on every keystroke.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const handle = window.setTimeout(async () => {
|
||||
try {
|
||||
const res = await checkStrength(newPassword);
|
||||
if (cancelled) return;
|
||||
setRules(res.rules);
|
||||
setValid(res.valid);
|
||||
} catch {
|
||||
/* ignore – the form will just stay disabled */
|
||||
}
|
||||
}, 180);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearTimeout(handle);
|
||||
};
|
||||
}, [newPassword, checkStrength]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!canSubmit) return;
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const res = await submit(oldPassword, newPassword);
|
||||
if (res.success) {
|
||||
onSuccess();
|
||||
} else {
|
||||
setError(res.message || '修改失败');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : '网络错误');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const computedTitle = title ?? (forced ? '请先设置新的访问密码' : '修改访问密码');
|
||||
const computedDescription =
|
||||
description ??
|
||||
(forced
|
||||
? '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。'
|
||||
: '设置一个全新的强密码后,其他会话将被立即下线,需要重新登录。');
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
|
||||
<div
|
||||
@@ -128,176 +64,26 @@ export function ChangePasswordPage({
|
||||
<CardContent className="p-7 sm:p-9">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20">
|
||||
{forced ? (
|
||||
<ShieldAlert className="size-6 text-primary" />
|
||||
) : (
|
||||
<KeyRound className="size-6 text-primary" />
|
||||
)}
|
||||
<ShieldAlert className="size-6 text-primary" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-lg font-semibold tracking-tight">{computedTitle}</h1>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">{computedDescription}</p>
|
||||
<h1 className="text-lg font-semibold tracking-tight">{title}</h1>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="old">当前密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="old"
|
||||
type={showOld ? 'text' : 'password'}
|
||||
autoComplete="current-password"
|
||||
value={oldPassword}
|
||||
onChange={(e) => setOldPassword(e.target.value)}
|
||||
placeholder="输入当前访问密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowOld((v) => !v)}
|
||||
aria-label={showOld ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showOld ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="new">新密码</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="new"
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
placeholder="设置新的强密码"
|
||||
className="h-10 pr-10 text-sm"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowNew((v) => !v)}
|
||||
aria-label={showNew ? '隐藏密码' : '显示密码'}
|
||||
tabIndex={-1}
|
||||
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
{showNew ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="confirm">确认新密码</Label>
|
||||
<Input
|
||||
id="confirm"
|
||||
type={showNew ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="再次输入新密码"
|
||||
className="h-10 text-sm"
|
||||
/>
|
||||
{confirmPassword.length > 0 && !confirmMatches && (
|
||||
<span className="text-[11px] text-destructive">两次输入的密码不一致</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<RuleList rules={rules} />
|
||||
|
||||
<AnimatePresence>
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="rounded-md bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{!forced && onCancel && (
|
||||
<Button type="button" variant="ghost" onClick={onCancel} className="h-10">
|
||||
取消
|
||||
</Button>
|
||||
)}
|
||||
<Button type="submit" disabled={!canSubmit} className="ml-auto h-10">
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="size-4 animate-spin" /> 提交中…
|
||||
</>
|
||||
) : (
|
||||
'保存新密码'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="mt-6">
|
||||
<ChangePasswordForm
|
||||
knownOldPassword={knownOldPassword}
|
||||
checkStrength={checkStrength}
|
||||
submit={submit}
|
||||
onSuccess={onSuccess}
|
||||
idPrefix="forced-cpw"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RuleList({ rules }: { rules: PasswordRule[] }) {
|
||||
// Initial empty state: show a placeholder set so the user knows the rules
|
||||
// exist even before any input.
|
||||
const display = useMemo<PasswordRule[]>(() => {
|
||||
if (rules.length > 0) return rules;
|
||||
return [
|
||||
{ id: 'length', label: '长度不少于 10 位', ok: false },
|
||||
{ id: 'lower', label: '至少包含一个小写字母', ok: false },
|
||||
{ id: 'upper', label: '至少包含一个大写字母', ok: false },
|
||||
{ id: 'special', label: '至少包含一个特殊字符', ok: false },
|
||||
{ id: 'no-space', label: '不得包含空格', ok: false },
|
||||
];
|
||||
}, [rules]);
|
||||
|
||||
return (
|
||||
<ul className="grid gap-1.5 rounded-lg border bg-muted/30 p-3">
|
||||
{display.map((rule) => (
|
||||
<li key={rule.id} className="flex items-center gap-2">
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{
|
||||
backgroundColor: rule.ok ? 'color-mix(in oklab, var(--primary) 20%, transparent)' : 'transparent',
|
||||
borderColor: rule.ok ? 'var(--primary)' : 'var(--border)',
|
||||
scale: rule.ok ? [1, 1.18, 1] : 1,
|
||||
}}
|
||||
transition={{ duration: 0.25 }}
|
||||
className={cn(
|
||||
'flex size-4 items-center justify-center rounded-full border',
|
||||
)}
|
||||
>
|
||||
<AnimatePresence>
|
||||
{rule.ok && (
|
||||
<motion.span
|
||||
key="check"
|
||||
initial={{ opacity: 0, scale: 0.4 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.4 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
>
|
||||
<Check className="size-3 text-primary" strokeWidth={3} />
|
||||
</motion.span>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.span>
|
||||
<motion.span
|
||||
initial={false}
|
||||
animate={{ color: rule.ok ? 'var(--foreground)' : 'var(--muted-foreground)' }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="text-xs"
|
||||
>
|
||||
{rule.label}
|
||||
</motion.span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { Badge } from '@/components/ui/badge';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type {
|
||||
AdapterStatus,
|
||||
NetworkKind,
|
||||
OneBotConfig,
|
||||
OneBotNetworks,
|
||||
@@ -39,7 +40,7 @@ type DialogState =
|
||||
// index: null → create with `seed`, otherwise edit the item at that position.
|
||||
|
||||
export function ConfigPage() {
|
||||
const { qqList, selectedUin, setSelectedUin } = useAppState();
|
||||
const { qqList, connections, selectedUin, setSelectedUin } = useAppState();
|
||||
const {
|
||||
config,
|
||||
setConfig,
|
||||
@@ -56,7 +57,11 @@ export function ConfigPage() {
|
||||
});
|
||||
|
||||
const [activeTab, setActiveTab] = useState<TabKey>('general');
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||
// Default the account strip to its 56px avatar-only form on narrow screens
|
||||
// (≤lg) so the editor pane isn't squeezed; the user can still expand it.
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(
|
||||
() => typeof window !== 'undefined' && window.matchMedia('(max-width: 1024px)').matches,
|
||||
);
|
||||
const [confirmSave, setConfirmSave] = useState(false);
|
||||
// The edit dialog is modal and blocks every other click in the page,
|
||||
// so `selectedUin` cannot change while it's open — no defensive close
|
||||
@@ -68,40 +73,56 @@ export function ConfigPage() {
|
||||
[pendingSwitchUin, qqList],
|
||||
);
|
||||
|
||||
// Per-kind helpers (typed at the call site so the dialog's onSubmit
|
||||
// payload is exactly the kind's adapter shape).
|
||||
function updateKind<K extends NetworkKind>(kind: K, next: OneBotNetworks[K]): void {
|
||||
// Live adapter status for the selected account, keyed by adapter name so
|
||||
// each summary card can light up its real connection state.
|
||||
const liveStatusByName = useMemo(() => {
|
||||
const acc = connections.find((c) => c.uin === selectedUin);
|
||||
const map = new Map<string, AdapterStatus>();
|
||||
for (const a of acc?.adapters ?? []) map.set(a.name, a);
|
||||
return map;
|
||||
}, [connections, selectedUin]);
|
||||
|
||||
// A discrete node mutation (create / edit / delete / enable-toggle) is
|
||||
// persisted the moment it happens — clicking 保存 inside the editor dialog
|
||||
// (or flipping the enable switch) IS the save. This removes the old
|
||||
// two-step trap where editing a token in the dialog only marked the config
|
||||
// "dirty" until you also pressed the top-right 保存, which silently cost
|
||||
// many users their token edits. The general-settings tab keeps its explicit
|
||||
// top-right save (it's a continuously-edited free-form surface).
|
||||
function commitKind<K extends NetworkKind>(kind: K, nextList: OneBotNetworks[K]): void {
|
||||
if (!config) return;
|
||||
setConfig({ ...config, networks: { ...config.networks, [kind]: next } });
|
||||
const next = { ...config, networks: { ...config.networks, [kind]: nextList } };
|
||||
setConfig(next);
|
||||
void save(next);
|
||||
}
|
||||
|
||||
function handleCreate<K extends NetworkKind>(kind: K, item: OneBotNetworks[K][number]): void {
|
||||
if (!config) return;
|
||||
const list = config.networks[kind] as OneBotNetworks[K];
|
||||
updateKind(kind, [...list, item] as OneBotNetworks[K]);
|
||||
commitKind(kind, [...list, item] as OneBotNetworks[K]);
|
||||
}
|
||||
|
||||
function handleEdit<K extends NetworkKind>(kind: K, index: number, item: OneBotNetworks[K][number]): void {
|
||||
if (!config) return;
|
||||
const list = config.networks[kind] as OneBotNetworks[K];
|
||||
const next = list.map((it, i) => (i === index ? item : it)) as OneBotNetworks[K];
|
||||
updateKind(kind, next);
|
||||
commitKind(kind, list.map((it, i) => (i === index ? item : it)) as OneBotNetworks[K]);
|
||||
}
|
||||
|
||||
function handleDelete<K extends NetworkKind>(kind: K, index: number): void {
|
||||
if (!config) return;
|
||||
const list = config.networks[kind] as OneBotNetworks[K];
|
||||
const next = list.filter((_, i) => i !== index) as OneBotNetworks[K];
|
||||
updateKind(kind, next);
|
||||
commitKind(kind, list.filter((_, i) => i !== index) as OneBotNetworks[K]);
|
||||
}
|
||||
|
||||
function handleToggleEnabled<K extends NetworkKind>(kind: K, index: number, enabled: boolean): void {
|
||||
if (!config) return;
|
||||
const list = config.networks[kind] as OneBotNetworks[K];
|
||||
const next = list.map((it, i) =>
|
||||
i === index ? ({ ...it, enabled: enabled ? undefined : false } as OneBotNetworks[K][number]) : it,
|
||||
) as OneBotNetworks[K];
|
||||
updateKind(kind, next);
|
||||
commitKind(
|
||||
kind,
|
||||
list.map((it, i) =>
|
||||
i === index ? ({ ...it, enabled: enabled ? undefined : false } as OneBotNetworks[K][number]) : it,
|
||||
) as OneBotNetworks[K],
|
||||
);
|
||||
}
|
||||
|
||||
const openCreate = (kind: NetworkKind) => {
|
||||
@@ -159,6 +180,7 @@ export function ConfigPage() {
|
||||
<NetworkTabView
|
||||
kind={activeTab}
|
||||
config={config}
|
||||
statusByName={liveStatusByName}
|
||||
onCreateClick={() => openCreate(activeTab)}
|
||||
onEdit={(idx) => openEdit(activeTab, idx)}
|
||||
onDelete={(idx) => handleDelete(activeTab, idx)}
|
||||
@@ -237,7 +259,7 @@ function HeaderBar({ selectedUin, dirty, saveStatus, onSave, activeTab, onCreate
|
||||
UIN {selectedUin}
|
||||
</code>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{saveStatus && (
|
||||
<span
|
||||
className={cn(
|
||||
@@ -281,7 +303,7 @@ interface TabStripProps {
|
||||
|
||||
function TabStrip({ activeTab, onChange, counts }: TabStripProps) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1 border-b">
|
||||
<div className="flex gap-1 overflow-x-auto border-b [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{ALL_TABS.map((key) => {
|
||||
const label = key === 'general' ? '通用设置' : NETWORK_TABS[key].title;
|
||||
const count = key === 'general' ? null : counts[key];
|
||||
@@ -292,7 +314,7 @@ function TabStrip({ activeTab, onChange, counts }: TabStripProps) {
|
||||
type="button"
|
||||
onClick={() => onChange(key)}
|
||||
className={cn(
|
||||
'group relative inline-flex items-center gap-1.5 px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
'group relative inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
@@ -333,6 +355,7 @@ function countMap(networks: OneBotNetworks): Record<NetworkKind, number> {
|
||||
interface NetworkTabViewProps {
|
||||
kind: NetworkKind;
|
||||
config: OneBotConfig;
|
||||
statusByName: Map<string, AdapterStatus>;
|
||||
onCreateClick: () => void;
|
||||
onEdit: (index: number) => void;
|
||||
onDelete: (index: number) => void;
|
||||
@@ -342,6 +365,7 @@ interface NetworkTabViewProps {
|
||||
function NetworkTabView({
|
||||
kind,
|
||||
config,
|
||||
statusByName,
|
||||
onCreateClick,
|
||||
onEdit,
|
||||
onDelete,
|
||||
@@ -390,6 +414,7 @@ function NetworkTabView({
|
||||
item={item}
|
||||
summary={summarize(item)}
|
||||
duplicateName={duplicate}
|
||||
liveStatus={statusByName.get(item.name)}
|
||||
onToggleEnabled={(v) => onToggleEnabled(idx, v)}
|
||||
onEdit={() => onEdit(idx)}
|
||||
onDelete={() => onDelete(idx)}
|
||||
|
||||
@@ -21,6 +21,13 @@ const levelClass: Record<LogLevel, string> = {
|
||||
|
||||
const LEVELS: LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
/** Show a locale time when the backend sends an ISO timestamp (it does);
|
||||
* fall back to the raw string otherwise so we never render "Invalid Date". */
|
||||
function formatTime(t: string): string {
|
||||
const d = new Date(t);
|
||||
return Number.isNaN(d.getTime()) ? t : d.toLocaleTimeString();
|
||||
}
|
||||
|
||||
export function LogsPage() {
|
||||
const api = useApi();
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
@@ -205,16 +212,19 @@ export function LogsPage() {
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.12 }}
|
||||
className="flex gap-2 whitespace-pre-wrap px-3 py-0.5 leading-5 hover:bg-accent/30"
|
||||
className="flex flex-col gap-0.5 px-3 py-1 leading-5 hover:bg-accent/30 sm:flex-row sm:gap-2 sm:py-0.5"
|
||||
>
|
||||
<span className="shrink-0 text-muted-foreground tabular-nums">
|
||||
{new Date(log.time).toLocaleTimeString()}
|
||||
</span>
|
||||
<span className={cn('w-14 shrink-0 font-semibold', levelClass[log.level])}>
|
||||
{log.level.toUpperCase()}
|
||||
</span>
|
||||
<span className="w-28 shrink-0 truncate text-muted-foreground">[{log.scope}]</span>
|
||||
<span className="break-all">{log.message}</span>
|
||||
{/* Meta drops to its own line on phones so the message gets
|
||||
the full width instead of a ~40px column that breaks
|
||||
every few characters. On sm+ it's the dense single row. */}
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<span className="shrink-0 text-muted-foreground tabular-nums">{formatTime(log.time)}</span>
|
||||
<span className={cn('shrink-0 font-semibold sm:w-14', levelClass[log.level])}>
|
||||
{log.level.toUpperCase()}
|
||||
</span>
|
||||
<span className="min-w-0 truncate text-muted-foreground sm:w-28">[{log.scope}]</span>
|
||||
</div>
|
||||
<span className="min-w-0 whitespace-pre-wrap break-all">{log.message}</span>
|
||||
</motion.div>
|
||||
))
|
||||
)}
|
||||
|
||||
@@ -1,51 +1,32 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import {
|
||||
Activity,
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
ArrowRight,
|
||||
Bell,
|
||||
Cable,
|
||||
Cpu,
|
||||
Eye,
|
||||
Loader2,
|
||||
MemoryStick,
|
||||
MonitorCog,
|
||||
PlugZap,
|
||||
RefreshCw,
|
||||
Server,
|
||||
Unplug,
|
||||
Users,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { ProcessProbeDialog } from '@/components/process-probe-dialog';
|
||||
import { cn, formatBytes, formatUptime } from '@/lib/utils';
|
||||
import type { HookProcessInfo } from '@/types';
|
||||
import type { AppPath } from '@/router';
|
||||
import type { AccountConnections, AdapterStatus, AdapterStatusLevel, LogEntry } from '@/types';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { useAppState } from '@/contexts/AppStateContext';
|
||||
import { useSession } from '@/contexts/SessionContext';
|
||||
|
||||
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
|
||||
available: '可加载',
|
||||
loading: '加载中',
|
||||
connecting: '等待连接',
|
||||
loaded: '等待登录',
|
||||
online: '已在线',
|
||||
error: '错误',
|
||||
disconnected: '已断开',
|
||||
};
|
||||
|
||||
function processBadgeVariant(status: HookProcessInfo['status']) {
|
||||
if (status === 'online') return 'success' as const;
|
||||
if (status === 'error') return 'destructive' as const;
|
||||
if (status === 'disconnected') return 'destructive' as const;
|
||||
if (status === 'loading' || status === 'connecting' || status === 'loaded') return 'default' as const;
|
||||
return 'secondary' as const;
|
||||
}
|
||||
|
||||
function qqAvatarUrl(uin: string) {
|
||||
return `/avatar/${encodeURIComponent(uin)}`;
|
||||
}
|
||||
@@ -56,44 +37,48 @@ function StatTile({
|
||||
value,
|
||||
subtext,
|
||||
accent = false,
|
||||
to,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
value: React.ReactNode;
|
||||
subtext?: React.ReactNode;
|
||||
accent?: boolean;
|
||||
/** When set, the whole tile becomes a link to this route. */
|
||||
to?: AppPath;
|
||||
}) {
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<CardContent className="flex items-center gap-3 p-4">
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-10 shrink-0 items-center justify-center rounded-xl',
|
||||
accent ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary'
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{label}</p>
|
||||
<div className="mt-0.5 truncate text-base font-semibold tabular-nums">{value}</div>
|
||||
{subtext && <p className="mt-0.5 truncate text-[11px] text-muted-foreground">{subtext}</p>}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
const body = (
|
||||
<CardContent className="flex items-center gap-3 p-4">
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-10 shrink-0 items-center justify-center rounded-xl',
|
||||
accent ? 'bg-primary text-primary-foreground' : 'bg-primary/10 text-primary'
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{label}</p>
|
||||
<div className="mt-0.5 truncate text-base font-semibold tabular-nums">{value}</div>
|
||||
{subtext && <p className="mt-0.5 truncate text-[11px] text-muted-foreground">{subtext}</p>}
|
||||
</div>
|
||||
{to && <ArrowRight className="size-4 shrink-0 text-muted-foreground/60" />}
|
||||
</CardContent>
|
||||
);
|
||||
|
||||
if (to) {
|
||||
return (
|
||||
<Link to={to} className="block rounded-xl outline-none">
|
||||
<Card className="overflow-hidden transition-colors hover:border-primary/40 hover:bg-accent/30">{body}</Card>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
return <Card className="overflow-hidden">{body}</Card>;
|
||||
}
|
||||
|
||||
export function OverviewPage() {
|
||||
const { qqList, processList, systemInfo, processOps, refreshProcesses, refreshSystem } =
|
||||
useAppState();
|
||||
const { qqList, processList, systemInfo, connections, refreshSystem } = useAppState();
|
||||
const { status } = useSession();
|
||||
const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps;
|
||||
const [confirm, setConfirm] = useState<
|
||||
| { kind: 'load' | 'unload'; pid: number; name: string }
|
||||
| null
|
||||
>(null);
|
||||
const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null);
|
||||
|
||||
// Lightweight tick to refresh "uptime" pretty-print every 30s
|
||||
const [, force] = useState(0);
|
||||
@@ -103,11 +88,14 @@ export function OverviewPage() {
|
||||
}, []);
|
||||
|
||||
const online = status === '已连接';
|
||||
// Read-only injection health for the dashboard. Control lives on /processes.
|
||||
const onlineProcs = processList.filter((p) => p.status === 'online').length;
|
||||
const loadableProcs = processList.filter((p) => !p.injected).length;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* Top stats */}
|
||||
<div className="grid grid-cols-2 gap-3 sm:gap-4 md:grid-cols-4">
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 lg:grid-cols-5">
|
||||
<StatTile
|
||||
icon={<Activity className="size-5" />}
|
||||
label="服务状态"
|
||||
@@ -121,6 +109,13 @@ export function OverviewPage() {
|
||||
value={qqList.length}
|
||||
subtext={`已接入 ${qqList.length} 个会话`}
|
||||
/>
|
||||
<StatTile
|
||||
icon={<PlugZap className="size-5" />}
|
||||
label="进程注入"
|
||||
value={`${onlineProcs} 在线`}
|
||||
subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`}
|
||||
to="/processes"
|
||||
/>
|
||||
<StatTile
|
||||
icon={<Server className="size-5" />}
|
||||
label="主机名"
|
||||
@@ -135,6 +130,35 @@ export function OverviewPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* First-run nudge: nothing online yet → point at the injection page. */}
|
||||
{qqList.length === 0 && (
|
||||
<motion.div initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }}>
|
||||
<Link
|
||||
to="/processes"
|
||||
className="flex items-center gap-3 rounded-xl border border-primary/30 bg-primary/5 px-4 py-3 transition-colors hover:bg-primary/10"
|
||||
>
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary">
|
||||
<PlugZap className="size-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium">
|
||||
{loadableProcs > 0 ? `检测到 ${loadableProcs} 个可加载 QQ 进程` : '尚未接入任何账号'}
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
前往「进程注入」加载 QQ,登录后会自动接入 OneBot 流程。
|
||||
</p>
|
||||
</div>
|
||||
<ArrowRight className="size-4 shrink-0 text-primary" />
|
||||
</Link>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Operational health — connection status + recent alerts (side by side on wide screens) */}
|
||||
<div className="grid gap-6 xl:grid-cols-2">
|
||||
<ConnectionsCard connections={connections} />
|
||||
<RecentAlertsCard />
|
||||
</div>
|
||||
|
||||
{/* System metrics */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
||||
@@ -240,147 +264,6 @@ export function OverviewPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* QQ Processes */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
||||
<div>
|
||||
<CardTitle>QQ 进程</CardTitle>
|
||||
<CardDescription>
|
||||
加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={refreshProcesses}>
|
||||
<RefreshCw className="size-3.5" /> 刷新
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{processActionStatus && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="mb-3 rounded-md border border-primary/20 bg-primary/5 px-3 py-2 text-xs text-primary"
|
||||
>
|
||||
{processActionStatus}
|
||||
</motion.div>
|
||||
)}
|
||||
{processList.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
|
||||
<Cpu className="size-7" strokeWidth={1.5} />
|
||||
<p className="text-sm">未检测到可加载 QQ 主进程</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
|
||||
{processList.map((proc, idx) => {
|
||||
const op = statusOf(proc.pid);
|
||||
const loading = op === 'load' || proc.status === 'loading';
|
||||
const unloading = op === 'unload';
|
||||
const refreshing = op === 'refresh';
|
||||
const busy = op != null || proc.status === 'loading';
|
||||
const isOnline = proc.status === 'online';
|
||||
const canUnload = proc.injected;
|
||||
// Refresh is meaningful whenever a hook may exist (so the user
|
||||
// can re-check the pipe and trigger a reconnect on demand).
|
||||
const showRefresh = proc.injected || proc.status === 'connecting' || proc.status === 'disconnected';
|
||||
return (
|
||||
<motion.div
|
||||
key={proc.pid}
|
||||
initial={{ opacity: 0, y: 6 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.03 + idx * 0.025, duration: 0.22 }}
|
||||
className="flex items-center gap-3 rounded-lg border bg-card/50 p-3"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-10 shrink-0 items-center justify-center rounded-lg',
|
||||
isOnline
|
||||
? 'bg-success/15 text-success'
|
||||
: proc.status === 'error'
|
||||
? 'bg-destructive/15 text-destructive'
|
||||
: 'bg-primary/10 text-primary'
|
||||
)}
|
||||
>
|
||||
{isOnline ? (
|
||||
<CheckCircle2 className="size-5" />
|
||||
) : proc.status === 'error' ? (
|
||||
<AlertCircle className="size-5" />
|
||||
) : (
|
||||
<Cpu className="size-5" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-semibold">{proc.name || 'QQ.exe'}</span>
|
||||
<Badge variant={processBadgeVariant(proc.status)}>{processStatusLabel[proc.status]}</Badge>
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground tabular-nums">
|
||||
PID {proc.pid}
|
||||
{proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''}
|
||||
</div>
|
||||
{proc.path && (
|
||||
<div className="truncate text-[11px] text-muted-foreground/80" title={proc.path}>
|
||||
{proc.path}
|
||||
</div>
|
||||
)}
|
||||
{proc.error && (
|
||||
<div className="mt-0.5 truncate text-[11px] text-destructive" title={proc.error}>
|
||||
{proc.error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => setProbeDialog({ pid: proc.pid, name: proc.name || `PID ${proc.pid}` })}
|
||||
>
|
||||
<Eye className="size-3.5" /> 探测登录
|
||||
</Button>
|
||||
{showRefresh && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
aria-label={`刷新进程 ${proc.pid} 管道状态`}
|
||||
title="刷新管道状态 / 重连"
|
||||
onClick={() => refresh(proc.pid)}
|
||||
className="size-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{refreshing ? (
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="size-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant={canUnload ? 'outline' : 'default'}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
setConfirm({
|
||||
kind: canUnload ? 'unload' : 'load',
|
||||
pid: proc.pid,
|
||||
name: proc.name || `PID ${proc.pid}`,
|
||||
})
|
||||
}
|
||||
className={cn(
|
||||
canUnload && 'text-destructive hover:bg-destructive/10 hover:text-destructive'
|
||||
)}
|
||||
>
|
||||
{(loading || unloading) && <Loader2 className="size-3.5 animate-spin" />}
|
||||
{!loading && !unloading && canUnload && <Unplug className="size-3.5" />}
|
||||
{canUnload ? (unloading ? '卸载中' : '卸载') : loading ? '加载中' : '加载'}
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Online accounts */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -395,7 +278,7 @@ export function OverviewPage() {
|
||||
</div>
|
||||
) : (
|
||||
<ScrollArea className="max-h-[420px]" viewportClassName="[&>div]:!block">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
|
||||
{qqList.map((q, idx) => (
|
||||
<motion.div
|
||||
key={q.uin}
|
||||
@@ -421,35 +304,160 @@ export function OverviewPage() {
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!confirm}
|
||||
onOpenChange={(o) => !o && setConfirm(null)}
|
||||
title={confirm?.kind === 'unload' ? '确认卸载 SnowLuma?' : '确认加载 SnowLuma?'}
|
||||
description={
|
||||
confirm
|
||||
? confirm.kind === 'unload'
|
||||
? `将从进程 ${confirm.name} 卸载 SnowLuma 注入,可能导致当前会话断开。`
|
||||
: `将向进程 ${confirm.name} 注入 SnowLuma,并开始监听登录状态。`
|
||||
: ''
|
||||
}
|
||||
confirmText={confirm?.kind === 'unload' ? '卸载' : '加载'}
|
||||
destructive={confirm?.kind === 'unload'}
|
||||
onConfirm={async () => {
|
||||
if (!confirm) return;
|
||||
if (confirm.kind === 'unload') await unload(confirm.pid);
|
||||
else await load(confirm.pid);
|
||||
}}
|
||||
/>
|
||||
|
||||
{probeDialog && (
|
||||
<ProcessProbeDialog
|
||||
pid={probeDialog.pid}
|
||||
processName={probeDialog.name}
|
||||
open={!!probeDialog}
|
||||
onOpenChange={(open) => !open && setProbeDialog(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── connection health ───────────────
|
||||
|
||||
const CONN_STATUS_STYLE: Record<AdapterStatusLevel, string> = {
|
||||
ok: 'bg-success/10 text-success',
|
||||
warn: 'bg-warning/10 text-warning',
|
||||
down: 'bg-destructive/10 text-destructive',
|
||||
disabled: 'bg-muted text-muted-foreground',
|
||||
};
|
||||
const CONN_STATUS_LABEL: Record<AdapterStatusLevel, string> = {
|
||||
ok: '正常',
|
||||
warn: '注意',
|
||||
down: '异常',
|
||||
disabled: '未启用',
|
||||
};
|
||||
const ADAPTER_KIND_LABEL: Record<AdapterStatus['kind'], string> = {
|
||||
httpServer: 'HTTP 服务端',
|
||||
httpClient: 'HTTP 上报',
|
||||
wsServer: 'WS 服务端',
|
||||
wsClient: 'WS 客户端',
|
||||
};
|
||||
|
||||
function ConnectionsCard({ connections }: { connections: AccountConnections[] }) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Cable className="size-4 text-primary" /> OneBot 连接
|
||||
</CardTitle>
|
||||
<CardDescription>各账号协议端点的实时连接状态</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{connections.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
|
||||
<Cable className="size-7" strokeWidth={1.5} />
|
||||
<p className="text-sm">暂无已接入的账号实例</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{connections.map((acc) => (
|
||||
<div key={acc.uin} className="flex flex-col gap-2">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-sm font-semibold">{acc.nickname || acc.uin}</span>
|
||||
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{acc.uin}</span>
|
||||
</div>
|
||||
{acc.adapters.length === 0 ? (
|
||||
<p className="rounded-md border border-dashed px-3 py-2 text-[11px] text-muted-foreground">
|
||||
未配置任何协议端点
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{acc.adapters.map((a) => (
|
||||
<div key={a.name} className="flex items-center gap-2 rounded-lg border bg-card/40 px-3 py-2">
|
||||
<span
|
||||
className={cn(
|
||||
'shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium',
|
||||
CONN_STATUS_STYLE[a.status],
|
||||
)}
|
||||
>
|
||||
{CONN_STATUS_LABEL[a.status]}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="truncate text-sm font-medium">{a.name}</span>
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground">{ADAPTER_KIND_LABEL[a.kind]}</span>
|
||||
</div>
|
||||
<div className="truncate text-[11px] text-muted-foreground">{a.detail}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── recent alerts ───────────────
|
||||
|
||||
function alertClock(t: string): string {
|
||||
const d = new Date(t);
|
||||
return Number.isNaN(d.getTime()) ? t : d.toLocaleTimeString();
|
||||
}
|
||||
|
||||
function RecentAlertsCard() {
|
||||
const api = useApi();
|
||||
const [alerts, setAlerts] = useState<LogEntry[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
api.logs
|
||||
.list(200)
|
||||
.then((list) => {
|
||||
if (!active) return;
|
||||
setAlerts(list.filter((l) => l.level === 'warn' || l.level === 'error').slice(-5));
|
||||
})
|
||||
.catch(() => { /* ignore */ });
|
||||
const stop = api.logs.stream({
|
||||
onLine: (entry) => {
|
||||
if (entry.level !== 'warn' && entry.level !== 'error') return;
|
||||
setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-5));
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
stop();
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Bell className="size-4 text-primary" /> 最近告警
|
||||
</CardTitle>
|
||||
<CardDescription>最近的 warn / error 级别日志</CardDescription>
|
||||
</div>
|
||||
<Link
|
||||
to="/logs"
|
||||
className="inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
查看日志 <ArrowRight className="size-3" />
|
||||
</Link>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{alerts.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-10 text-muted-foreground">
|
||||
<Bell className="size-7" strokeWidth={1.5} />
|
||||
<p className="text-sm">暂无告警</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1 font-mono text-[11px]">
|
||||
{alerts.map((a) => (
|
||||
<div key={a.id} className="flex gap-2 rounded px-2 py-1 hover:bg-accent/30">
|
||||
<span className="shrink-0 text-muted-foreground tabular-nums">{alertClock(a.time)}</span>
|
||||
<span className={cn('shrink-0 font-semibold', a.level === 'error' ? 'text-destructive' : 'text-warning')}>
|
||||
{a.level.toUpperCase()}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate" title={a.message}>
|
||||
[{a.scope}] {a.message}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
222
packages/webui/src/components/pages/processes-page.tsx
Normal file
222
packages/webui/src/components/pages/processes-page.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
import { useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { AlertCircle, CheckCircle2, Cpu, Eye, Loader2, RefreshCw, Unplug } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { ProcessProbeDialog } from '@/components/process-probe-dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { HookProcessInfo } from '@/types';
|
||||
import { useAppState } from '@/contexts/AppStateContext';
|
||||
|
||||
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
|
||||
available: '可加载',
|
||||
loading: '加载中',
|
||||
connecting: '等待连接',
|
||||
loaded: '等待登录',
|
||||
online: '已在线',
|
||||
error: '错误',
|
||||
disconnected: '已断开',
|
||||
};
|
||||
|
||||
function processBadgeVariant(status: HookProcessInfo['status']) {
|
||||
if (status === 'online') return 'success' as const;
|
||||
if (status === 'error') return 'destructive' as const;
|
||||
if (status === 'disconnected') return 'destructive' as const;
|
||||
if (status === 'loading' || status === 'connecting' || status === 'loaded') return 'default' as const;
|
||||
return 'secondary' as const;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process / injection control surface. Split out of the overview page so the
|
||||
* homepage stays a read-only monitoring dashboard. State (processList,
|
||||
* processOps) is owned by AppLayout and read from context, so this page needs
|
||||
* no plumbing of its own; the layout keeps polling and the unload-failed alert
|
||||
* regardless of which page is mounted.
|
||||
*/
|
||||
export function ProcessesPage() {
|
||||
const { processList, processOps, refreshProcesses } = useAppState();
|
||||
const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps;
|
||||
const [confirm, setConfirm] = useState<{ kind: 'load' | 'unload'; pid: number; name: string } | null>(null);
|
||||
const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
|
||||
<div>
|
||||
<CardTitle>进程注入</CardTitle>
|
||||
<CardDescription>加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程</CardDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={refreshProcesses}>
|
||||
<RefreshCw className="size-3.5" /> 刷新
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{processActionStatus && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="mb-3 rounded-md border border-primary/20 bg-primary/5 px-3 py-2 text-xs text-primary"
|
||||
>
|
||||
{processActionStatus}
|
||||
</motion.div>
|
||||
)}
|
||||
{processList.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed py-16 text-muted-foreground">
|
||||
<Cpu className="size-7" strokeWidth={1.5} />
|
||||
<p className="text-sm">未检测到可加载 QQ 主进程</p>
|
||||
<p className="text-[11px] text-muted-foreground/80">请确认 QQ 已启动后点击右上角刷新</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2 2xl:grid-cols-3">
|
||||
{processList.map((proc, idx) => {
|
||||
const op = statusOf(proc.pid);
|
||||
const loading = op === 'load' || proc.status === 'loading';
|
||||
const unloading = op === 'unload';
|
||||
const refreshing = op === 'refresh';
|
||||
const busy = op != null || proc.status === 'loading';
|
||||
const isOnline = proc.status === 'online';
|
||||
const canUnload = proc.injected;
|
||||
// Refresh is meaningful whenever a hook may exist (so the user
|
||||
// can re-check the pipe and trigger a reconnect on demand).
|
||||
const showRefresh = proc.injected || proc.status === 'connecting' || proc.status === 'disconnected';
|
||||
return (
|
||||
<motion.div
|
||||
key={proc.pid}
|
||||
initial={{ opacity: 0, y: 6 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.03 + idx * 0.025, duration: 0.22 }}
|
||||
className="flex flex-col gap-3 rounded-lg border bg-card/50 p-3 sm:flex-row sm:items-center"
|
||||
>
|
||||
{/* icon + info stay horizontal; on phones the actions drop to
|
||||
a second row so name / PID / path get the full width
|
||||
instead of collapsing to "Q..". */}
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<div
|
||||
className={cn(
|
||||
'flex size-10 shrink-0 items-center justify-center rounded-lg',
|
||||
isOnline
|
||||
? 'bg-success/15 text-success'
|
||||
: proc.status === 'error'
|
||||
? 'bg-destructive/15 text-destructive'
|
||||
: 'bg-primary/10 text-primary'
|
||||
)}
|
||||
>
|
||||
{isOnline ? (
|
||||
<CheckCircle2 className="size-5" />
|
||||
) : proc.status === 'error' ? (
|
||||
<AlertCircle className="size-5" />
|
||||
) : (
|
||||
<Cpu className="size-5" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 truncate text-sm font-semibold">{proc.name || 'QQ.exe'}</span>
|
||||
<Badge variant={processBadgeVariant(proc.status)} className="shrink-0 whitespace-nowrap">
|
||||
{processStatusLabel[proc.status]}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground tabular-nums">
|
||||
PID {proc.pid}
|
||||
{proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''}
|
||||
</div>
|
||||
{proc.path && (
|
||||
<div className="truncate text-[11px] text-muted-foreground/80" title={proc.path}>
|
||||
{proc.path}
|
||||
</div>
|
||||
)}
|
||||
{proc.error && (
|
||||
<div className="mt-0.5 truncate text-[11px] text-destructive" title={proc.error}>
|
||||
{proc.error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => setProbeDialog({ pid: proc.pid, name: proc.name || `PID ${proc.pid}` })}
|
||||
>
|
||||
<Eye className="size-3.5" /> 探测登录
|
||||
</Button>
|
||||
{showRefresh && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
aria-label={`刷新进程 ${proc.pid} 管道状态`}
|
||||
title="刷新管道状态 / 重连"
|
||||
onClick={() => refresh(proc.pid)}
|
||||
className="size-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{refreshing ? (
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="size-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant={canUnload ? 'outline' : 'default'}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
setConfirm({
|
||||
kind: canUnload ? 'unload' : 'load',
|
||||
pid: proc.pid,
|
||||
name: proc.name || `PID ${proc.pid}`,
|
||||
})
|
||||
}
|
||||
className={cn(
|
||||
canUnload && 'text-destructive hover:bg-destructive/10 hover:text-destructive'
|
||||
)}
|
||||
>
|
||||
{(loading || unloading) && <Loader2 className="size-3.5 animate-spin" />}
|
||||
{!loading && !unloading && canUnload && <Unplug className="size-3.5" />}
|
||||
{canUnload ? (unloading ? '卸载中' : '卸载') : loading ? '加载中' : '加载'}
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!confirm}
|
||||
onOpenChange={(o) => !o && setConfirm(null)}
|
||||
title={confirm?.kind === 'unload' ? '确认卸载 SnowLuma?' : '确认加载 SnowLuma?'}
|
||||
description={
|
||||
confirm
|
||||
? confirm.kind === 'unload'
|
||||
? `将从进程 ${confirm.name} 卸载 SnowLuma 注入,可能导致当前会话断开。`
|
||||
: `将向进程 ${confirm.name} 注入 SnowLuma,并开始监听登录状态。`
|
||||
: ''
|
||||
}
|
||||
confirmText={confirm?.kind === 'unload' ? '卸载' : '加载'}
|
||||
destructive={confirm?.kind === 'unload'}
|
||||
onConfirm={async () => {
|
||||
if (!confirm) return;
|
||||
if (confirm.kind === 'unload') await unload(confirm.pid);
|
||||
else await load(confirm.pid);
|
||||
}}
|
||||
/>
|
||||
|
||||
{probeDialog && (
|
||||
<ProcessProbeDialog
|
||||
pid={probeDialog.pid}
|
||||
processName={probeDialog.name}
|
||||
open={!!probeDialog}
|
||||
onOpenChange={(open) => !open && setProbeDialog(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Check, KeyRound, Loader2, Monitor, Moon, Sun } from 'lucide-react';
|
||||
import { Bug, Check, ExternalLink, Github, Info, KeyRound, Monitor, Moon, Palette, RefreshCw, ShieldCheck, Star, Sun, Tag } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -14,8 +14,7 @@ import {
|
||||
type Density,
|
||||
type ThemeMode,
|
||||
} from '@/contexts/ThemeContext';
|
||||
import { ChangePasswordPage } from '@/components/pages/change-password-page';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { ChangePasswordDialog } from '@/components/change-password-dialog';
|
||||
import { useAppState } from '@/contexts/AppStateContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -30,233 +29,354 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[]
|
||||
{ value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' },
|
||||
];
|
||||
|
||||
type SettingsTab = 'appearance' | 'data' | 'account' | 'about';
|
||||
|
||||
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
|
||||
{ key: 'appearance', label: '外观', icon: Palette },
|
||||
{ key: 'data', label: '数据刷新', icon: RefreshCw },
|
||||
{ key: 'account', label: '账号安全', icon: ShieldCheck },
|
||||
{ key: 'about', label: '关于', icon: Info },
|
||||
];
|
||||
|
||||
export function SettingsPage() {
|
||||
const api = useApi();
|
||||
const { onLogout } = useAppState();
|
||||
const {
|
||||
mode, setMode,
|
||||
accent, setAccent,
|
||||
radius, setRadius,
|
||||
density, setDensity,
|
||||
pollInterval, setPollInterval,
|
||||
} = useTheme();
|
||||
|
||||
const [showChangePwd, setShowChangePwd] = useState(false);
|
||||
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
|
||||
|
||||
if (showChangePwd) {
|
||||
return (
|
||||
<ChangePasswordPage
|
||||
forced={false}
|
||||
checkStrength={(p) => api.checkPasswordStrength(p)}
|
||||
submit={(o, n) => api.changePassword(o, n)}
|
||||
onSuccess={() => {
|
||||
setShowChangePwd(false);
|
||||
setPwdSavedAt(Date.now());
|
||||
}}
|
||||
onCancel={() => setShowChangePwd(false)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const [tab, setTab] = useState<SettingsTab>('appearance');
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* Appearance */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>外观</CardTitle>
|
||||
<CardDescription>调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-6">
|
||||
{/* Mode */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>显示模式</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{MODE_OPTIONS.map((opt) => {
|
||||
const Icon = opt.icon;
|
||||
const active = mode === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setMode(opt.value)}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-4" />
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-5">
|
||||
<MiniTabs tab={tab} onChange={setTab} />
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Accent color */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>强调色</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ACCENTS.map((spec) => {
|
||||
const active = accent === spec.id;
|
||||
return (
|
||||
<button
|
||||
key={spec.id}
|
||||
type="button"
|
||||
onClick={() => setAccent(spec.id as AccentColor)}
|
||||
title={spec.label}
|
||||
aria-label={spec.label}
|
||||
className={cn(
|
||||
'group relative flex h-9 w-9 items-center justify-center rounded-full border transition-transform cursor-pointer hover:scale-105',
|
||||
active ? 'border-foreground/30 ring-2 ring-primary' : 'border-border',
|
||||
)}
|
||||
style={{ backgroundColor: spec.swatch }}
|
||||
>
|
||||
{active && (
|
||||
<motion.span
|
||||
initial={{ scale: 0.4, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
className="text-white drop-shadow-sm"
|
||||
>
|
||||
<Check className="size-4" strokeWidth={3} />
|
||||
</motion.span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">当前:{ACCENTS.find((a) => a.id === accent)?.label}</p>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Radius */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>圆角</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{RADIUS_OPTIONS.map((opt) => {
|
||||
const active = Math.abs(radius - opt.value) < 1e-6;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setRadius(opt.value)}
|
||||
className={cn(
|
||||
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
style={{ borderRadius: `${opt.value}rem` }}
|
||||
>
|
||||
{opt.label}({opt.value}rem)
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Density */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>显示密度</Label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{DENSITY_OPTIONS.map((opt) => {
|
||||
const active = density === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setDensity(opt.value)}
|
||||
className={cn(
|
||||
'flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<span className="text-sm font-medium">{opt.label}</span>
|
||||
<span className="text-[11px] text-muted-foreground">{opt.description}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Behavior */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>数据刷新</CardTitle>
|
||||
<CardDescription>控制总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>轮询间隔</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{POLL_INTERVAL_OPTIONS.map((opt) => {
|
||||
const active = pollInterval === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setPollInterval(opt.value)}
|
||||
className={cn(
|
||||
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">当前生效值:{pollInterval === 0 ? '已暂停轮询' : `${pollInterval} 毫秒`}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Account */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>账号安全</CardTitle>
|
||||
<CardDescription>WebUI 仅有 admin 一个账号,密码会以 scrypt 哈希形式持久化到 config/webui.json。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowChangePwd(true)}
|
||||
className="w-fit"
|
||||
>
|
||||
<KeyRound className="size-4" />
|
||||
修改访问密码
|
||||
</Button>
|
||||
{pwdSavedAt && (
|
||||
<span className="text-[11px] text-success">
|
||||
密码已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。
|
||||
</span>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-medium">退出登录</p>
|
||||
<p className="mt-1 text-[11px] text-muted-foreground">立即清除当前浏览器的会话令牌。</p>
|
||||
<Button variant="ghost" onClick={onLogout} className="mt-2 text-destructive hover:text-destructive">
|
||||
<Loader2 className="size-4 hidden" />
|
||||
退出登录
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{tab === 'appearance' && <AppearancePanel />}
|
||||
{tab === 'data' && <DataPanel />}
|
||||
{tab === 'account' && <AccountPanel />}
|
||||
{tab === 'about' && <AboutPanel />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── mini tab strip ───────────────
|
||||
|
||||
function MiniTabs({ tab, onChange }: { tab: SettingsTab; onChange: (t: SettingsTab) => void }) {
|
||||
return (
|
||||
<div className="inline-flex w-fit items-center gap-1 rounded-lg border bg-muted/40 p-1">
|
||||
{TABS.map((t) => {
|
||||
const Icon = t.icon;
|
||||
const active = tab === t.key;
|
||||
return (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
onClick={() => onChange(t.key)}
|
||||
className={cn(
|
||||
'relative inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm transition-colors cursor-pointer',
|
||||
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{active && (
|
||||
<motion.span
|
||||
layoutId="settings-tab-pill"
|
||||
className="absolute inset-0 rounded-md bg-background shadow-sm"
|
||||
transition={{ type: 'spring', stiffness: 350, damping: 30 }}
|
||||
/>
|
||||
)}
|
||||
<span className="relative z-10 inline-flex items-center gap-1.5">
|
||||
<Icon className="size-4" />
|
||||
{t.label}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── 外观 ───────────────
|
||||
|
||||
function AppearancePanel() {
|
||||
const { mode, setMode, accent, setAccent, radius, setRadius, density, setDensity } = useTheme();
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>外观</CardTitle>
|
||||
<CardDescription>调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-6">
|
||||
{/* Mode */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>显示模式</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{MODE_OPTIONS.map((opt) => {
|
||||
const Icon = opt.icon;
|
||||
const active = mode === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setMode(opt.value)}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-4" />
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Accent color */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>强调色</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ACCENTS.map((spec) => {
|
||||
const active = accent === spec.id;
|
||||
return (
|
||||
<button
|
||||
key={spec.id}
|
||||
type="button"
|
||||
onClick={() => setAccent(spec.id as AccentColor)}
|
||||
title={spec.label}
|
||||
aria-label={spec.label}
|
||||
className={cn(
|
||||
'group relative flex h-9 w-9 items-center justify-center rounded-full border transition-transform cursor-pointer hover:scale-105',
|
||||
active ? 'border-foreground/30 ring-2 ring-primary' : 'border-border',
|
||||
)}
|
||||
style={{ backgroundColor: spec.swatch }}
|
||||
>
|
||||
{active && (
|
||||
<motion.span
|
||||
initial={{ scale: 0.4, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
className="text-white drop-shadow-sm"
|
||||
>
|
||||
<Check className="size-4" strokeWidth={3} />
|
||||
</motion.span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">当前:{ACCENTS.find((a) => a.id === accent)?.label}</p>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Radius */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>圆角</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{RADIUS_OPTIONS.map((opt) => {
|
||||
const active = Math.abs(radius - opt.value) < 1e-6;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setRadius(opt.value)}
|
||||
className={cn(
|
||||
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
style={{ borderRadius: `${opt.value}rem` }}
|
||||
>
|
||||
{opt.label}({opt.value}rem)
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Density */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>显示密度</Label>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{DENSITY_OPTIONS.map((opt) => {
|
||||
const active = density === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setDensity(opt.value)}
|
||||
className={cn(
|
||||
'flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors cursor-pointer',
|
||||
active ? 'border-primary bg-primary/10' : 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<span className="text-sm font-medium">{opt.label}</span>
|
||||
<span className="text-[11px] text-muted-foreground">{opt.description}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── 数据刷新 ───────────────
|
||||
|
||||
function DataPanel() {
|
||||
const { pollInterval, setPollInterval } = useTheme();
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>数据刷新</CardTitle>
|
||||
<CardDescription>控制总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>轮询间隔</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{POLL_INTERVAL_OPTIONS.map((opt) => {
|
||||
const active = pollInterval === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setPollInterval(opt.value)}
|
||||
className={cn(
|
||||
'rounded-md border px-3 py-2 text-sm transition-colors cursor-pointer',
|
||||
active
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-border bg-background hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
当前生效值:{pollInterval === 0 ? '已暂停轮询' : `${pollInterval} 毫秒`}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── 账号安全 ───────────────
|
||||
|
||||
function AccountPanel() {
|
||||
const { onLogout } = useAppState();
|
||||
const [showChangePwd, setShowChangePwd] = useState(false);
|
||||
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>账号安全</CardTitle>
|
||||
<CardDescription>WebUI 仅有 admin 一个账号,密码会以 scrypt 哈希形式持久化到 config/webui.json。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<Button variant="outline" onClick={() => setShowChangePwd(true)} className="w-fit">
|
||||
<KeyRound className="size-4" />
|
||||
修改访问密码
|
||||
</Button>
|
||||
{pwdSavedAt && (
|
||||
<span className="text-[11px] text-success">
|
||||
密码已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。
|
||||
</span>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-medium">退出登录</p>
|
||||
<p className="mt-1 text-[11px] text-muted-foreground">立即清除当前浏览器的会话令牌。</p>
|
||||
<Button variant="ghost" onClick={onLogout} className="mt-2 text-destructive hover:text-destructive">
|
||||
退出登录
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<ChangePasswordDialog
|
||||
open={showChangePwd}
|
||||
onOpenChange={setShowChangePwd}
|
||||
onSuccess={() => setPwdSavedAt(Date.now())}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── 关于 ───────────────
|
||||
|
||||
const REPO_URL = 'https://github.com/SnowLuma/SnowLuma';
|
||||
|
||||
function AboutPanel() {
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<CardContent className="flex flex-col items-center gap-6 px-6 py-8 text-center sm:px-8">
|
||||
{/* brand hero */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10, scale: 0.96 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={{ type: 'spring', stiffness: 260, damping: 22 }}
|
||||
className="flex flex-col items-center gap-3"
|
||||
>
|
||||
<div className="relative">
|
||||
<div aria-hidden className="absolute inset-0 -z-10 scale-125 rounded-full bg-primary/20 blur-2xl" />
|
||||
<img src="/logo.png" alt="SnowLuma" className="size-20 object-contain drop-shadow-sm" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-2xl font-semibold tracking-tight">SnowLuma</span>
|
||||
<span className="rounded-full border border-primary/30 bg-primary/10 px-2 py-0.5 font-mono text-[11px] text-primary tabular-nums">
|
||||
v{__APP_VERSION__}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">Next Remote Protocol Framework · 下一代远程协议框架</p>
|
||||
</motion.div>
|
||||
|
||||
<p className="max-w-md text-[13px] leading-relaxed text-muted-foreground">
|
||||
以轻量注入驱动 QQ NT,对外提供标准 OneBot v11 接口,让机器人一次部署、长期稳定运行。
|
||||
</p>
|
||||
|
||||
{/* Star CTA */}
|
||||
<div className="flex w-full max-w-sm flex-col items-center gap-2 rounded-xl border bg-gradient-to-b from-primary/[0.07] to-transparent p-5">
|
||||
<Star className="size-6 fill-primary/20 text-primary" />
|
||||
<p className="text-sm font-medium">喜欢 SnowLuma?点个 Star 支持一下</p>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
开源不易,你的 ⭐ 是我们持续维护的最大动力。
|
||||
</p>
|
||||
<Button asChild className="mt-1 w-full">
|
||||
<a href={REPO_URL} target="_blank" rel="noreferrer noopener">
|
||||
<Github className="size-4" />
|
||||
去 GitHub 点 Star
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* secondary links */}
|
||||
<div className="flex flex-wrap items-center justify-center gap-x-5 gap-y-2 text-[12px]">
|
||||
<AboutLink href={REPO_URL} icon={Github}>仓库</AboutLink>
|
||||
<AboutLink href={`${REPO_URL}/releases`} icon={Tag}>发行版</AboutLink>
|
||||
<AboutLink href={`${REPO_URL}/issues`} icon={Bug}>反馈问题</AboutLink>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function AboutLink({ href, icon: Icon, children }: { href: string; icon: typeof Sun; children: ReactNode }) {
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="inline-flex items-center gap-1.5 text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<Icon className="size-3.5" />
|
||||
{children}
|
||||
<ExternalLink className="size-3 opacity-50" />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
95
packages/webui/src/components/pages/status-screens.tsx
Normal file
95
packages/webui/src/components/pages/status-screens.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { AlertTriangle, Compass, Home, RotateCw } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Tone = 'primary' | 'destructive';
|
||||
|
||||
function StatusShell({
|
||||
tone,
|
||||
icon,
|
||||
code,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
}: {
|
||||
tone: Tone;
|
||||
icon: ReactNode;
|
||||
code?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-h-[60vh] w-full flex-col items-center justify-center px-4 text-center">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
|
||||
className="flex w-full max-w-md flex-col items-center"
|
||||
>
|
||||
<div
|
||||
className={
|
||||
tone === 'destructive'
|
||||
? 'flex size-14 items-center justify-center rounded-2xl bg-destructive/10 ring-1 ring-destructive/20'
|
||||
: 'flex size-14 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20'
|
||||
}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
{code && (
|
||||
<span className="mt-4 font-mono text-4xl font-bold tracking-tight tabular-nums text-muted-foreground/60">
|
||||
{code}
|
||||
</span>
|
||||
)}
|
||||
<h1 className="mt-2 text-xl font-semibold tracking-tight">{title}</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{description}</p>
|
||||
<div className="mt-6 flex flex-wrap items-center justify-center gap-2">{children}</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Rendered by the router for any unmatched path. */
|
||||
export function NotFoundPage() {
|
||||
return (
|
||||
<StatusShell
|
||||
tone="primary"
|
||||
icon={<Compass className="size-7 text-primary" strokeWidth={1.75} />}
|
||||
code="404"
|
||||
title="页面不存在"
|
||||
description="你访问的地址没有对应的页面,可能链接已失效或输入有误。"
|
||||
>
|
||||
<Button onClick={() => window.location.assign('/')}>
|
||||
<Home className="size-4" /> 返回首页
|
||||
</Button>
|
||||
</StatusShell>
|
||||
);
|
||||
}
|
||||
|
||||
/** Rendered by the router when a route component throws while rendering. */
|
||||
export function ErrorPage({ error, reset }: { error?: Error; reset?: () => void }) {
|
||||
const message = error?.message?.trim();
|
||||
return (
|
||||
<StatusShell
|
||||
tone="destructive"
|
||||
icon={<AlertTriangle className="size-7 text-destructive" strokeWidth={1.75} />}
|
||||
title="页面出错了"
|
||||
description="渲染该页面时发生了意外错误。可以重试,或返回首页继续操作。"
|
||||
>
|
||||
{reset && (
|
||||
<Button variant="outline" onClick={reset}>
|
||||
<RotateCw className="size-4" /> 重试
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => window.location.assign('/')}>
|
||||
<Home className="size-4" /> 返回首页
|
||||
</Button>
|
||||
{message && (
|
||||
<pre className="mt-3 max-h-32 w-full overflow-auto rounded-md border bg-muted/40 px-3 py-2 text-left text-[11px] leading-relaxed text-muted-foreground whitespace-pre-wrap">
|
||||
{message}
|
||||
</pre>
|
||||
)}
|
||||
</StatusShell>
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,11 @@ const DialogContent = React.forwardRef<
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border bg-card p-6 shadow-lg outline-none',
|
||||
// `w-[calc(100vw-2rem)]` keeps a 1rem gutter on every side on small
|
||||
// phones (plain `w-full` made the dialog touch both edges). Callers
|
||||
// only ever override `max-w-*` (the desktop cap), so the width floor
|
||||
// here survives those overrides — width and max-width are distinct.
|
||||
'fixed left-1/2 top-1/2 z-50 grid w-[calc(100vw_-_2rem)] max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border bg-card p-6 shadow-lg outline-none',
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
className
|
||||
|
||||
@@ -63,4 +63,29 @@ const SheetContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Co
|
||||
);
|
||||
SheetContent.displayName = 'SheetContent';
|
||||
|
||||
export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetPortal, SheetOverlay };
|
||||
const SheetTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title ref={ref} className={cn('text-lg font-semibold tracking-tight', className)} {...props} />
|
||||
));
|
||||
SheetTitle.displayName = 'SheetTitle';
|
||||
|
||||
const SheetDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
));
|
||||
SheetDescription.displayName = 'SheetDescription';
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetPortal,
|
||||
SheetOverlay,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
};
|
||||
|
||||
35
packages/webui/src/components/ui/toggle-switch.tsx
Normal file
35
packages/webui/src/components/ui/toggle-switch.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import { motion } from 'motion/react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ToggleSwitchProps {
|
||||
value: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
ariaLabel: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/** Small animated on/off switch (`role="switch"`). Shared across the config
|
||||
* surfaces — node enable toggle, built-in command toggles, etc. */
|
||||
export function ToggleSwitch({ value, onChange, ariaLabel, disabled }: ToggleSwitchProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={value ? 'true' : 'false'}
|
||||
aria-label={ariaLabel}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(!value)}
|
||||
className={cn(
|
||||
'relative inline-flex h-6 w-11 shrink-0 items-center rounded-full border transition-colors',
|
||||
disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
|
||||
value ? 'border-primary bg-primary' : 'border-input bg-muted',
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
className="inline-block size-4 rounded-full bg-background shadow-sm"
|
||||
animate={{ x: value ? 22 : 4 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createContext, useContext, type ReactNode } from 'react';
|
||||
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
|
||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo } from '@/types';
|
||||
import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
|
||||
|
||||
/**
|
||||
@@ -12,11 +12,13 @@ export interface AppStateValue {
|
||||
qqList: QQInfo[];
|
||||
processList: HookProcessInfo[];
|
||||
systemInfo: SystemInfo | null;
|
||||
connections: AccountConnections[];
|
||||
selectedUin: string | null;
|
||||
setSelectedUin: (uin: string | null) => void;
|
||||
processOps: HookProcessOps;
|
||||
refreshProcesses: () => void;
|
||||
refreshSystem: () => void;
|
||||
refreshConnections: () => void;
|
||||
/** Triggered from the topbar logout button. */
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,13 @@ export interface UseOneBotInstanceConfig {
|
||||
pendingSwitchUin: string | null;
|
||||
confirmSwitch: () => void;
|
||||
cancelSwitch: () => void;
|
||||
save: () => Promise<void>;
|
||||
/**
|
||||
* Persist to the backend. Pass an explicit config to save it directly —
|
||||
* the node dialog / enable-toggle / delete persist their freshly-computed
|
||||
* config in the same tick, before React has flushed `setConfig`, so they
|
||||
* can't rely on the (still-stale) closed-over `config`.
|
||||
*/
|
||||
save: (override?: OneBotConfig) => Promise<void>;
|
||||
saveStatus: string;
|
||||
}
|
||||
|
||||
@@ -117,11 +123,12 @@ export function useOneBotInstanceConfig(
|
||||
}, CLEAR_SAVE_STATUS_MS);
|
||||
}, []);
|
||||
|
||||
const save = useCallback(async () => {
|
||||
if (!selectedUin || !config) return;
|
||||
const save = useCallback(async (override?: OneBotConfig) => {
|
||||
const target = override ?? config;
|
||||
if (!selectedUin || !target) return;
|
||||
setSaveStatus('保存中...');
|
||||
try {
|
||||
const serverView = await api.config.save(selectedUin, config);
|
||||
const serverView = await api.config.save(selectedUin, target);
|
||||
setConfigState(serverView);
|
||||
setSavedSnapshot(JSON.stringify(serverView));
|
||||
setSaveStatus('保存成功');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types';
|
||||
import type { AccountConnections, HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types';
|
||||
import type { PasswordRule } from '@/components/pages/change-password-page';
|
||||
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
||||
import {
|
||||
@@ -222,6 +222,10 @@ class HttpApiClient implements ApiClient {
|
||||
return this.getJson<SystemInfo>('/api/system');
|
||||
}
|
||||
|
||||
connections(): Promise<AccountConnections[]> {
|
||||
return this.getJson<{ list: AccountConnections[] }>('/api/connections').then((d) => d.list ?? []);
|
||||
}
|
||||
|
||||
// ---------- SSE ----------
|
||||
|
||||
private openLogStream(options: LogsStreamOptions): () => void {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
AccountConnections,
|
||||
HookProcessInfo,
|
||||
LogEntry,
|
||||
LogLevel,
|
||||
@@ -50,6 +51,8 @@ export interface ApiClient {
|
||||
// ---- system ----
|
||||
qqList(): Promise<QQInfo[]>;
|
||||
system(): Promise<SystemInfo>;
|
||||
/** Live OneBot adapter health per account. */
|
||||
connections(): Promise<AccountConnections[]>;
|
||||
|
||||
// ---- hook processes ----
|
||||
processes: {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user