Merge upstream/dev into feat/onebot
This commit is contained in:
commit
0d40a03f28
122 files changed
+7842
-1099
No files matched your search
@@ -0,0 +1,119 @@
|
||||
name: Bug 反馈
|
||||
description: 报告一个可复现的问题
|
||||
title: "[Bug] "
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
感谢花时间反馈 Bug。请尽量填全以下信息,方便我们定位问题。
|
||||
在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有相同问题。
|
||||
|
||||
- type: checkboxes
|
||||
id: preflight
|
||||
attributes:
|
||||
label: 提交前检查
|
||||
options:
|
||||
- label: 我已搜索过 Issues,确认没有重复的反馈
|
||||
required: true
|
||||
- label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: snowluma-version
|
||||
attributes:
|
||||
label: SnowLuma 版本
|
||||
description: 启动日志首行或 `package.json` 里的版本号
|
||||
placeholder: "例如 1.8.5"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: adapter
|
||||
attributes:
|
||||
label: 出问题的适配器
|
||||
description: 可多选
|
||||
multiple: true
|
||||
options:
|
||||
- WebSocket Server
|
||||
- WebSocket Client
|
||||
- HTTP Server
|
||||
- HTTP Post
|
||||
- WebUI
|
||||
- Bridge / Core(协议层)
|
||||
- 其他 / 不确定
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: os
|
||||
attributes:
|
||||
label: 操作系统
|
||||
placeholder: "例如 Windows 11 23H2 / macOS 14.5 / Ubuntu 22.04"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: node-version
|
||||
attributes:
|
||||
label: Node.js 版本
|
||||
description: '`node -v` 的输出。如果使用预构建包可填"预构建包"'
|
||||
placeholder: "例如 v20.11.0 或 预构建包"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: qq-version
|
||||
attributes:
|
||||
label: QQ 客户端版本
|
||||
description: QQ NT 客户端的版本号
|
||||
placeholder: "例如 9.9.15-29722"
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: 问题描述
|
||||
description: 简要说明发生了什么
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: reproduce
|
||||
attributes:
|
||||
label: 复现步骤
|
||||
description: 详细列出如何触发这个问题
|
||||
placeholder: |
|
||||
1. 启动 SnowLuma 并登录账号 ...
|
||||
2. 通过 HTTP Server 调用 `send_group_msg` ...
|
||||
3. 观察到 ...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: 期望行为
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: 实际行为
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 相关日志 / 错误堆栈
|
||||
description: |
|
||||
粘贴控制台日志、SSE 实时日志或错误堆栈。
|
||||
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
|
||||
render: shell
|
||||
|
||||
- type: textarea
|
||||
id: extra
|
||||
attributes:
|
||||
label: 补充信息
|
||||
description: 配置片段(脱敏后)、截图、相关 Issue / PR 链接等
|
||||
@@ -0,0 +1,11 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: QQ 群
|
||||
url: https://qm.qq.com/q/g3UMLpWALe
|
||||
about: 日常使用问题、快速交流可以先来 QQ 群
|
||||
- name: Telegram
|
||||
url: https://t.me/napcatqq
|
||||
about: 海外用户交流频道
|
||||
- name: Releases
|
||||
url: https://github.com/SnowLuma/SnowLuma/releases
|
||||
about: 在反馈 Bug 前,请先确认已使用最新发布版本
|
||||
@@ -0,0 +1,76 @@
|
||||
name: 功能请求
|
||||
description: 提议一个新功能或对现有功能的增强
|
||||
title: "[Feature] "
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
感谢您的建议。在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有类似提案。
|
||||
|
||||
- type: checkboxes
|
||||
id: preflight
|
||||
attributes:
|
||||
label: 提交前检查
|
||||
options:
|
||||
- label: 我已搜索过 Issues,确认没有重复的提案
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: scope
|
||||
attributes:
|
||||
label: 涉及范围
|
||||
multiple: true
|
||||
options:
|
||||
- OneBot 协议 / 消息段
|
||||
- WebSocket Server / Client 适配器
|
||||
- HTTP Server / Post 适配器
|
||||
- WebUI 管理面板
|
||||
- SDK (`@snowluma/sdk`)
|
||||
- UI 组件 (`@snowluma/ui`)
|
||||
- Bridge / Core(协议层)
|
||||
- 构建 / 发布流程
|
||||
- 文档
|
||||
- 其他
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: 需求场景 / 当前痛点
|
||||
description: 这个功能要解决什么问题?目前是如何变通处理的?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: 期望方案
|
||||
description: 您希望它如何工作?如果是 API 改动,建议给出示例输入 / 输出
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: 已考虑的替代方案
|
||||
description: 还想过哪些其他实现路径,为什么放弃
|
||||
|
||||
- type: textarea
|
||||
id: references
|
||||
attributes:
|
||||
label: 参考链接
|
||||
description: 例如 OneBot 规范条目、其他实现的对应特性、相关 Issue / PR
|
||||
placeholder: |
|
||||
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
|
||||
- 相关讨论: #xxx
|
||||
|
||||
- type: checkboxes
|
||||
id: willingness
|
||||
attributes:
|
||||
label: 您是否愿意提交 PR 来实现这个功能?
|
||||
options:
|
||||
- label: 愿意,且需要维护者讨论方案后再动手
|
||||
- label: 愿意,已有大致实现思路
|
||||
- label: 暂时只提建议
|
||||
@@ -0,0 +1,103 @@
|
||||
name: Publish UI to npm
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/ui/**'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'tsconfig.base.json'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: ui-npm-publish-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Build and publish UI
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Type check UI
|
||||
run: pnpm --filter @snowluma/ui typecheck
|
||||
|
||||
- name: Build UI
|
||||
run: pnpm --filter @snowluma/ui build
|
||||
|
||||
- name: Check npm package version
|
||||
id: npm
|
||||
working-directory: packages/ui
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
|
||||
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
|
||||
|
||||
{
|
||||
echo "package_name=${package_name}"
|
||||
echo "package_version=${package_version}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
|
||||
echo "already_published=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
|
||||
else
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Publish UI to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/ui
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
shell: bash
|
||||
run: |
|
||||
{
|
||||
echo "## UI npm publish"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -1,22 +1,130 @@
|
||||
# ❄️ SnowLuma
|
||||
> Next Remote Protocol Framework.
|
||||
<h1 align="center">❄️ SnowLuma</h1>
|
||||
|
||||
<p align="center">
|
||||
<i>Next Remote Protocol Framework.</i>
|
||||
</p>
|
||||
|
||||
## 关于项目
|
||||
项目处于开发初期,仅支持部分功能,高速迭代中,随时可能出现破坏性更新。
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases">Releases</a> ·
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/issues">Issues</a> ·
|
||||
<a href="https://qm.qq.com/q/g3UMLpWALe">QQ 群</a> ·
|
||||
<a href="https://t.me/napcatqq">Telegram</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## 简介
|
||||
|
||||
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
|
||||
|
||||
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
|
||||
|
||||
## 特性
|
||||
|
||||
- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。
|
||||
- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。
|
||||
- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。
|
||||
- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。
|
||||
- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。
|
||||
- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。
|
||||
|
||||
## 快速开始
|
||||
|
||||
下载预构建发布包:
|
||||
|
||||
```bash
|
||||
# 从 Releases 下载 zip,解压到任意目录
|
||||
./launcher.bat # Windows
|
||||
```
|
||||
|
||||
或从源码开发:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
cd SnowLuma
|
||||
pnpm install
|
||||
pnpm build
|
||||
pnpm start
|
||||
```
|
||||
|
||||
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
|
||||
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
|
||||
|
||||
## 工作区
|
||||
|
||||
本仓库使用 pnpm monorepo 管理,各包职责如下:
|
||||
|
||||
| 包 | 说明 |
|
||||
| --- | --- |
|
||||
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
|
||||
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
|
||||
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
|
||||
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
|
||||
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
|
||||
| [`webui`](packages/webui) | Web 管理面板前端。 |
|
||||
|
||||
## 架构
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A([QQ 客户端])
|
||||
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
|
||||
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
|
||||
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
|
||||
E([WS / HTTP / WebUI])
|
||||
|
||||
A --> B --> C --> D --> E
|
||||
```
|
||||
|
||||
## 文档
|
||||
|
||||
- [路线图](RoadMap.md)
|
||||
- [贡献指南](CONTRIBUTING.md)
|
||||
- [行为准则](CODE_OF_CONDUCT.md)
|
||||
|
||||
## 开发命令
|
||||
|
||||
```bash
|
||||
pnpm dev # 启动 core dev server
|
||||
pnpm dev:web # 启动 webui dev server
|
||||
pnpm test # 运行 core 测试
|
||||
pnpm typecheck # 全仓库 type check
|
||||
pnpm build:all # 构建 core + sdk + webui
|
||||
```
|
||||
|
||||
## 鸣谢
|
||||
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
|
||||
|
||||
[NapCatQQ](https://github.com/NapNeko/NapCatQQ) - Scaner/Packet
|
||||
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
|
||||
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
|
||||
|
||||
## 辅助编程
|
||||
## 贡献者
|
||||
|
||||
推荐 Opus4.6 + Gemini3.1pro 对本项目辅助开发
|
||||
感谢每一位为 SnowLuma 提交过代码的伙伴。
|
||||
|
||||
本项目大量使用Ai技术。
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
|
||||
</a>
|
||||
|
||||
## 加入我们
|
||||
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
## Star 趋势
|
||||
|
||||
[SnowLuma-TG](https://t.me/napcatqq)
|
||||
<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)
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"$schema": "./qq.schema.json",
|
||||
"version": 1,
|
||||
"updatedAt": "2026-05-16T00:00:00Z",
|
||||
"policy": {
|
||||
"allowUnknown": true,
|
||||
"warnUnknown": true
|
||||
},
|
||||
"knownGoodVersions": [],
|
||||
"knownBadVersions": [],
|
||||
"minVersion": null,
|
||||
"notes": [
|
||||
"QQ 兼容性 manifest — Desktop 启动时拉 https://raw.githubusercontent.com/SnowLuma/SnowLuma/main/compat/qq.json 校验本地 QQ 版本",
|
||||
"policy.allowUnknown = true: 任何不在 knownBadVersions 里的版本都允许(理论上所有 QQ 新版本都可用)",
|
||||
"knownBadVersions: 列在这里的版本 Desktop 会拒绝注入,弹出引导让用户切版本",
|
||||
"minVersion: 设为 SemVer 字符串则更早的版本会被拒",
|
||||
"知道某个版本会破坏 Hook 后把它加进 knownBadVersions,加 reason 字段说明"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "SnowLuma QQ compatibility manifest",
|
||||
"type": "object",
|
||||
"required": ["version", "policy", "knownGoodVersions", "knownBadVersions"],
|
||||
"properties": {
|
||||
"$schema": { "type": "string" },
|
||||
"version": { "type": "integer", "const": 1 },
|
||||
"updatedAt": { "type": "string", "format": "date-time" },
|
||||
"policy": {
|
||||
"type": "object",
|
||||
"required": ["allowUnknown"],
|
||||
"properties": {
|
||||
"allowUnknown": {
|
||||
"type": "boolean",
|
||||
"description": "若 true,未在 known* 中列出的版本视为允许;若 false,需明确出现在 knownGoodVersions"
|
||||
},
|
||||
"warnUnknown": {
|
||||
"type": "boolean",
|
||||
"description": "未列出的版本启动时是否弹警告"
|
||||
}
|
||||
}
|
||||
},
|
||||
"knownGoodVersions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["version"],
|
||||
"properties": {
|
||||
"version": { "type": "string", "description": "QQ 版本号字符串,如 '9.9.20.123'" },
|
||||
"note": { "type": "string" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"knownBadVersions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["version"],
|
||||
"properties": {
|
||||
"version": { "type": "string" },
|
||||
"reason": { "type": "string" },
|
||||
"fixedInDesktopVersion": { "type": "string" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"minVersion": {
|
||||
"type": ["string", "null"],
|
||||
"description": "最低支持版本(SemVer),null = 不限"
|
||||
},
|
||||
"notes": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.8.1",
|
||||
"version": "1.8.5",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.8.1",
|
||||
"version": "1.8.5",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -66,6 +66,9 @@ export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<St
|
||||
request: {
|
||||
schema: OidbStrangerStatusReqSchema,
|
||||
value: { uin, key: [{ key: 27372 }] },
|
||||
// Same UIN-form flag fetchUserProfile sets — without it newer
|
||||
// QQ NT rejects with `[oidb] one of uid/openid is invaild`.
|
||||
isUid: true,
|
||||
},
|
||||
response: { schema: OidbStrangerStatusRespSchema },
|
||||
});
|
||||
|
||||
@@ -28,12 +28,23 @@ const forwardResCache = new Map<string, ForwardNodePayload[]>();
|
||||
async function buildForwardPushBody(
|
||||
bridge: Bridge,
|
||||
node: ForwardNodePayload,
|
||||
groupId?: number,
|
||||
userUid?: string,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
|
||||
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
|
||||
|
||||
const nickname = node.nickname.trim() || String(fromUin);
|
||||
const elems = await buildSendElems(node.elements);
|
||||
// image/record/video upload inside a forward node must be scoped to the
|
||||
// forward's recipient: group → groupId, private → recipient uid.
|
||||
// Without this the OIDB upload (0x11c4/0x11c5) has no scene and the
|
||||
// element builder throws "private image target uid is missing".
|
||||
const sendCtx = groupId !== undefined
|
||||
? { bridge, groupId }
|
||||
: userUid
|
||||
? { bridge, userUid }
|
||||
: { bridge };
|
||||
const elems = await buildSendElems(node.elements, sendCtx);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
|
||||
const seq = Math.floor(Math.random() * 9000000) + 1000000;
|
||||
@@ -62,12 +73,32 @@ async function buildForwardPushBody(
|
||||
};
|
||||
}
|
||||
|
||||
export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number): Promise<string> {
|
||||
export async function uploadForwardNodes(
|
||||
bridge: Bridge,
|
||||
nodes: ForwardNodePayload[],
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<string> {
|
||||
if (!Array.isArray(nodes) || nodes.length === 0) {
|
||||
throw new Error('forward nodes are required');
|
||||
}
|
||||
|
||||
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node)));
|
||||
// For a private forward to `userId`, any image/record/video inside a node
|
||||
// needs the recipient's uid as upload scene. Resolve it once up-front,
|
||||
// and only when at least one node actually contains media (saves an RPC
|
||||
// for text-only forwards).
|
||||
let userUid: string | undefined;
|
||||
if (groupId === undefined && userId !== undefined && userId > 0) {
|
||||
const hasMedia = nodes.some(node => node.elements.some(
|
||||
e => e.type === 'image' || e.type === 'record' || e.type === 'video',
|
||||
));
|
||||
if (hasMedia) {
|
||||
const resolved = await bridge.resolveUserUid(userId);
|
||||
if (resolved) userUid = resolved;
|
||||
}
|
||||
}
|
||||
|
||||
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId, userUid)));
|
||||
const longMsgResult = protoEncode({
|
||||
action: [
|
||||
{
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { Bridge } from '../bridge';
|
||||
import { protoEncode } from '../../protobuf/decode';
|
||||
import { runOidb } from '../bridge-oidb';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
|
||||
import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
|
||||
import {
|
||||
OidbGroupFileCountViewReqSchema,
|
||||
OidbGroupFileCountViewRespSchema,
|
||||
@@ -288,7 +288,9 @@ export async function uploadGroupFile(
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const loaded = await loadBinarySource(source, 'file');
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('group file is empty');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
@@ -366,7 +368,9 @@ export async function uploadPrivateFile(
|
||||
name = '',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const loaded = await loadBinarySource(source, 'file');
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('private file is empty');
|
||||
|
||||
const targetUid = await bridge.resolveUserUid(userId);
|
||||
|
||||
@@ -103,6 +103,19 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
|
||||
// The config flags ask QQ which per-group fields to include in the
|
||||
// response. Asking for everything looks innocent on small accounts
|
||||
// but on ~200+ groups it makes the QQ NT process write a payload
|
||||
// large enough to blow the named-pipe write buffer — we then read
|
||||
// EPIPE and the whole session dies. See issue #42.
|
||||
//
|
||||
// The user-verified safe combination: keep `config1.*` mostly on
|
||||
// (the response decoder pulls groupOwner / memberMax / memberCount /
|
||||
// groupName / description / question / announcement from this
|
||||
// group), but turn off the costly groups of bools that never map
|
||||
// back to a decoded field:
|
||||
// - config1.field5002, field5003 (expansive 5xxx-range descriptors)
|
||||
// - all of config2 (auxiliary per-group blob the decoder ignores)
|
||||
const allTrue = true;
|
||||
const body = {
|
||||
config: {
|
||||
@@ -114,11 +127,11 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
|
||||
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
|
||||
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
|
||||
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
|
||||
field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue,
|
||||
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
|
||||
},
|
||||
config2: {
|
||||
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
|
||||
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
|
||||
field1: false, field2: false, field3: false, field4: false,
|
||||
field5: false, field6: false, field7: false, field8: false,
|
||||
},
|
||||
config3: { field5: allTrue, field6: allTrue },
|
||||
},
|
||||
@@ -208,16 +221,23 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
|
||||
|
||||
export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<UserProfileInfo> {
|
||||
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
|
||||
// Only `uin` and `keys` — see OidbUserInfoRequestSchema for why
|
||||
// sending field 2 makes the server reject the request.
|
||||
const body = {
|
||||
uin,
|
||||
field2: 0,
|
||||
keys: keys.map(k => ({ key: k })),
|
||||
};
|
||||
|
||||
// Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the
|
||||
// name is historical, the wire semantic is "this is the UIN-form
|
||||
// variant of the call"). Without it newer QQ NT versions take the
|
||||
// UID-form validation path, find neither uid nor openid in the body
|
||||
// and bounce the request with `[oidb] one of uid/openid is invaild`.
|
||||
// Matches Lagrange.Core's FetchStrangerByUin (Reserved = 1).
|
||||
const resp = await runOidb<any>(bridge, {
|
||||
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
|
||||
oidbCmd: 0xFE1, subCmd: 2,
|
||||
request: { schema: OidbUserInfoRequestSchema, value: body },
|
||||
request: { schema: OidbUserInfoRequestSchema, value: body, isUid: true },
|
||||
response: { schema: OidbUserInfoResponseSchema },
|
||||
});
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ export interface BridgeInterface {
|
||||
likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<any>;
|
||||
|
||||
// ─── Forward ───
|
||||
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string>;
|
||||
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string>;
|
||||
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
|
||||
|
||||
// ─── Message ops ───
|
||||
|
||||
@@ -20,10 +20,16 @@ export interface OidbCall<TResp = void> {
|
||||
schema: ProtoSchema;
|
||||
value: any;
|
||||
/**
|
||||
* Sets the OIDB envelope `reserved` field to 1 when true. A handful
|
||||
* of commands (group/friend list, rkey download) operate on
|
||||
* UID-keyed data and require this flag — the wire format is
|
||||
* otherwise identical.
|
||||
* Sets the OIDB envelope `reserved` field to 1 when true.
|
||||
*
|
||||
* The name is historical and misleading: empirically (see Lagrange
|
||||
* FetchStrangerByUin vs FetchStrangerByUid, fetchGroupList, our own
|
||||
* highway uploads) the `reserved = 1` flag indicates the UIN-form
|
||||
* variant of an OIDB call — it tells newer QQ NT to translate the
|
||||
* UIN in the body to an internal UID rather than running the
|
||||
* UID-form validator that expects a uid/openid string in the body.
|
||||
*
|
||||
* Omit (default false) for genuinely UID-keyed calls.
|
||||
*/
|
||||
isUid?: boolean;
|
||||
};
|
||||
|
||||
@@ -461,7 +461,7 @@ export class Bridge implements BridgeInterface {
|
||||
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
|
||||
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
|
||||
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivateVideoUrlByNode_(this, node); }
|
||||
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId); }
|
||||
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId, userId); }
|
||||
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
|
||||
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
|
||||
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }
|
||||
|
||||
@@ -37,19 +37,43 @@ function makeFaceElem(faceId: number): ProtoElem {
|
||||
};
|
||||
}
|
||||
|
||||
function makeMentionElem(element: MessageElement): ProtoElem {
|
||||
function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string {
|
||||
if (!ctx || !targetUin) return '';
|
||||
if (ctx.groupId !== undefined) {
|
||||
const member = ctx.bridge.identity.findGroupMember(ctx.groupId, targetUin);
|
||||
return member?.card?.trim() || member?.nickname?.trim() || '';
|
||||
}
|
||||
const friend = ctx.bridge.identity.findFriend(targetUin);
|
||||
return friend?.remark?.trim() || friend?.nickname?.trim() || '';
|
||||
}
|
||||
|
||||
function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem {
|
||||
const mentionAll = element.uid === 'all' || element.targetUin === 0;
|
||||
const targetUin = element.targetUin ?? 0;
|
||||
|
||||
const extra = protoEncode({
|
||||
type: mentionAll ? 1 : 2,
|
||||
uin: mentionAll ? 0 : (element.targetUin ?? 0),
|
||||
uin: mentionAll ? 0 : targetUin,
|
||||
field5: 0,
|
||||
uid: mentionAll ? 'all' : (element.uid ?? ''),
|
||||
}, MentionExtraSendSchema);
|
||||
|
||||
// Prefer an explicit display string from the caller; otherwise look the
|
||||
// target up in the roster so QQ renders `@昵称` instead of `@QQ号`.
|
||||
// Falls back to the bare uin when the roster doesn't know them yet.
|
||||
let str = element.text;
|
||||
if (!str) {
|
||||
if (mentionAll) {
|
||||
str = '@全体成员 ';
|
||||
} else {
|
||||
const name = resolveMentionDisplay(ctx, targetUin);
|
||||
str = name ? `@${name} ` : `@${targetUin} `;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
text: {
|
||||
str: element.text || (mentionAll ? '@全体成员 ' : `@${element.targetUin} `),
|
||||
str,
|
||||
pbReserve: extra,
|
||||
} as any,
|
||||
};
|
||||
@@ -260,7 +284,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
||||
break;
|
||||
|
||||
case 'at':
|
||||
result.push(makeMentionElem(elem));
|
||||
result.push(makeMentionElem(elem, ctx));
|
||||
break;
|
||||
|
||||
case 'reply':
|
||||
|
||||
@@ -230,6 +230,22 @@ export interface FriendAddEvent extends QQEvent {
|
||||
userUin: number;
|
||||
}
|
||||
|
||||
export interface GroupMsgEmojiLikeEvent extends QQEvent {
|
||||
kind: 'group_msg_emoji_like';
|
||||
groupId: number;
|
||||
operatorUin: number;
|
||||
operatorUid: string;
|
||||
/** Sequence of the message that was reacted to (server-assigned msg_seq). */
|
||||
msgSeq: number;
|
||||
/** Emoji ID. QQ system faces are short numeric strings; market faces
|
||||
* are alphanumeric. We keep the wire string verbatim. */
|
||||
emojiId: string;
|
||||
/** Multiplicity of the reaction event. Usually 1. */
|
||||
count: number;
|
||||
/** True when the reaction is being added; false when removed. */
|
||||
isAdd: boolean;
|
||||
}
|
||||
|
||||
export type QQEventVariant =
|
||||
| FriendMessage
|
||||
| GroupMessage
|
||||
@@ -246,4 +262,5 @@ export type QQEventVariant =
|
||||
| GroupPokeEvent
|
||||
| GroupEssenceEvent
|
||||
| GroupFileUploadEvent
|
||||
| FriendAddEvent;
|
||||
| FriendAddEvent
|
||||
| GroupMsgEmojiLikeEvent;
|
||||
@@ -129,10 +129,31 @@ export function buildHighwayExtend(
|
||||
|
||||
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.createConnection({ host, port }, () => resolve(socket));
|
||||
let settled = false;
|
||||
const onTimeout = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
reject(new Error('TCP connect timeout'));
|
||||
};
|
||||
const onError = (err: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(err);
|
||||
};
|
||||
const socket = net.createConnection({ host, port }, () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
// Drop the connect-only listeners so subsequent IO errors / idle
|
||||
// timeouts don't try to reject this already-resolved promise.
|
||||
socket.setTimeout(0);
|
||||
socket.removeListener('timeout', onTimeout);
|
||||
socket.removeListener('error', onError);
|
||||
resolve(socket);
|
||||
});
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); });
|
||||
socket.on('error', reject);
|
||||
socket.once('timeout', onTimeout);
|
||||
socket.once('error', onError);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -148,8 +169,21 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
let headerEnd = -1;
|
||||
let contentLength = 0;
|
||||
let totalNeeded = 0;
|
||||
let settled = false;
|
||||
|
||||
const checkComplete = () => {
|
||||
const detach = () => {
|
||||
socket.off('data', onData);
|
||||
socket.off('error', onError);
|
||||
socket.off('close', onClose);
|
||||
};
|
||||
const finish = (fn: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
detach();
|
||||
fn();
|
||||
};
|
||||
const onData = (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd < 0) {
|
||||
const idx = buf.indexOf('\r\n\r\n');
|
||||
@@ -162,19 +196,19 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
}
|
||||
}
|
||||
if (headerEnd >= 0 && buf.length >= totalNeeded) {
|
||||
socket.removeAllListeners('data');
|
||||
socket.removeAllListeners('error');
|
||||
resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)));
|
||||
finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))));
|
||||
}
|
||||
};
|
||||
|
||||
socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); });
|
||||
socket.on('error', reject);
|
||||
socket.on('close', () => {
|
||||
const onError = (err: Error) => finish(() => reject(err));
|
||||
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'));
|
||||
});
|
||||
|
||||
socket.on('data', onData);
|
||||
socket.on('error', onError);
|
||||
socket.on('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { MessageElement } from '../events';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
|
||||
import {
|
||||
finalizeMediaMsgInfo,
|
||||
@@ -16,6 +17,14 @@ import {
|
||||
} from './pipeline';
|
||||
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
|
||||
|
||||
const moduleLog = createLogger('Highway.Image');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
interface ImageData {
|
||||
/** Empty when the caller is forwarding from cached fingerprints. */
|
||||
bytes: Uint8Array;
|
||||
@@ -106,7 +115,13 @@ export async function uploadImageMsgInfo(
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const image = await loadImage(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
image.fileSize,
|
||||
image.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
|
||||
@@ -25,6 +25,9 @@ import {
|
||||
NTV2UploadRichMediaRespSchema,
|
||||
} from '../proto/highway';
|
||||
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const moduleLog = createLogger('Highway');
|
||||
|
||||
// ─────────────── public types ───────────────
|
||||
|
||||
@@ -123,6 +126,11 @@ export function hexToBytes(hex: string): Uint8Array {
|
||||
export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
|
||||
const label = params.label ?? 'media';
|
||||
const raw = bridge.identity?.uin;
|
||||
const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
const log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
// Build the full body once. Pulling this in here means each format file
|
||||
// only specifies the seven fields that actually vary.
|
||||
@@ -184,6 +192,7 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
return session;
|
||||
};
|
||||
|
||||
let didPut = false;
|
||||
for (const sub of uploads) {
|
||||
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
|
||||
const uKey = target?.uKey ?? '';
|
||||
@@ -203,7 +212,15 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
|
||||
sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both
|
||||
sub.subFileIndex ?? 0,
|
||||
);
|
||||
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
|
||||
const t0 = Date.now();
|
||||
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
}
|
||||
|
||||
if (!didPut) {
|
||||
log.debug('%s fast-upload hit (server already had bytes)', label);
|
||||
}
|
||||
|
||||
return upload;
|
||||
|
||||
@@ -22,7 +22,13 @@ import {
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
|
||||
const log = createLogger('Ptt');
|
||||
const moduleLog = createLogger('Highway.Ptt');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_PTT_CMD_ID = 1007;
|
||||
export const GROUP_PTT_CMD_ID = 1008;
|
||||
@@ -105,7 +111,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
|
||||
const silk = await encodeSilk(inputPath, tempDir);
|
||||
if (silk.converted) {
|
||||
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
|
||||
log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
|
||||
}
|
||||
|
||||
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
|
||||
@@ -141,8 +147,15 @@ export async function uploadPttMsgInfo(
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const tempDir = defaultPttTempDir();
|
||||
const ptt = await loadPtt(element, tempDir);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds',
|
||||
ptt.fileSize,
|
||||
ptt.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid),
|
||||
ptt.duration);
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [{
|
||||
source: 'top',
|
||||
|
||||
@@ -11,6 +11,20 @@ export interface LoadedBinary {
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default cap on a single binary load issued through this helper. Callers
|
||||
* that route here (image / voice via base64+HTTP, group/private file
|
||||
* uploads, avatar) get bounded reads. Not all callers route through here
|
||||
* — in particular `video-upload.stageVideoSource` reads local-video files
|
||||
* directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private
|
||||
* file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's
|
||||
* file protocol legitimately supports up to 4 GiB.
|
||||
*/
|
||||
const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
|
||||
/** Hard ceiling QQ's file protocol supports — used by group/private files. */
|
||||
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
const FETCH_TIMEOUT_MS = 60_000;
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
@@ -54,24 +68,74 @@ export function resolveLocalFilePath(source: string): string | null {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
|
||||
export async function loadBinarySource(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
|
||||
): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
if (/^base64:\/\//i.test(source)) {
|
||||
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
|
||||
const bytes = Buffer.from(source.slice(9), 'base64');
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName: '' };
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const resp = await fetch(source);
|
||||
const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
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}`);
|
||||
}
|
||||
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 new Error(`${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 filePath = resolveLocalFilePath(source);
|
||||
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
|
||||
|
||||
const stat = fs.statSync(filePath);
|
||||
if (stat.size > maxBytes) {
|
||||
throw new Error(`${resourceName} too large: ${stat.size} > ${maxBytes}`);
|
||||
}
|
||||
const bytes = fs.readFileSync(filePath);
|
||||
const fileName = path.basename(filePath);
|
||||
return { bytes, fileName };
|
||||
@@ -183,7 +247,12 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
if (offset + 4 > bytes.length) break;
|
||||
const segLen = readBE16(bytes, offset + 2);
|
||||
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
|
||||
if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) {
|
||||
// Real SOF markers: 0xC0..0xCF EXCEPT 0xC4 (DHT), 0xC8 (JPG), 0xCC
|
||||
// (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT
|
||||
// and friends, then misread Huffman table bytes as image dimensions.
|
||||
const isSof = marker >= 0xC0 && marker <= 0xCF
|
||||
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
|
||||
if (isSof && segLen >= 7 && offset + 9 <= bytes.length) {
|
||||
height = readBE16(bytes, offset + 5);
|
||||
width = readBE16(bytes, offset + 7);
|
||||
return { format: 1000, width, height };
|
||||
|
||||
@@ -29,7 +29,13 @@ import {
|
||||
type MediaSubFileUpload,
|
||||
} from './pipeline';
|
||||
|
||||
const log = createLogger('Video');
|
||||
const moduleLog = createLogger('Highway.Video');
|
||||
|
||||
function loggerFor(bridge: Bridge) {
|
||||
const raw = bridge.identity?.uin;
|
||||
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
|
||||
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
}
|
||||
|
||||
export const PRIVATE_VIDEO_CMD_ID = 1001;
|
||||
export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
|
||||
@@ -280,6 +286,14 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
|
||||
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (local && fs.existsSync(local)) {
|
||||
// Pre-check on disk size BEFORE reading bytes into memory. The later
|
||||
// `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only
|
||||
// run after we'd already allocated the entire file (so a 10 GiB
|
||||
// local path still OOMs us before the check fires).
|
||||
const stat = fs.statSync(local);
|
||||
if (stat.size > MAX_VIDEO_SIZE) {
|
||||
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
|
||||
}
|
||||
return {
|
||||
bytes: new Uint8Array(fs.readFileSync(local)),
|
||||
filePath: local,
|
||||
@@ -287,7 +301,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
|
||||
};
|
||||
}
|
||||
|
||||
const loaded = await loadBinarySource(source, 'video');
|
||||
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE);
|
||||
const fileName = element.fileName || loaded.fileName || '';
|
||||
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
|
||||
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
|
||||
@@ -315,7 +329,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
try {
|
||||
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
|
||||
} catch (err) {
|
||||
log.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
|
||||
moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,7 +343,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
|
||||
thumbBytes = new Uint8Array(info.image);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
|
||||
moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,7 +389,7 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
|
||||
const staged = await stageVideoSource(element, tempDir, cleanups);
|
||||
if (staged.bytes.length === 0) throw new Error('video file is empty');
|
||||
if (staged.bytes.length > MAX_VIDEO_SIZE) {
|
||||
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB`);
|
||||
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
|
||||
}
|
||||
|
||||
const hashes = computeHashes(staged.bytes);
|
||||
@@ -422,7 +436,13 @@ export async function uploadVideoMsgInfo(
|
||||
targetIdOrUid: string | number,
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const video = await loadVideo(element);
|
||||
log.debug('uploading %d bytes md5=%s... → %s %s',
|
||||
video.fileSize,
|
||||
video.md5Hex.slice(0, 8),
|
||||
isGroup ? 'group' : 'c2c',
|
||||
String(targetIdOrUid));
|
||||
try {
|
||||
const uploads: MediaSubFileUpload[] = [
|
||||
{
|
||||
@@ -487,11 +507,17 @@ export async function uploadVideoMsgInfo(
|
||||
subFileType: 100,
|
||||
},
|
||||
],
|
||||
// Scene tag the NTV2 upload registers under. image-upload and
|
||||
// ptt-upload both differentiate (group=2, c2c=1); video was
|
||||
// hardcoded to the group value, which contributed to the c2c
|
||||
// send-back rejection (PbSendMsg result=79).
|
||||
compatQmsgSceneType: isGroup ? 2 : 1,
|
||||
// Hardcoded 2 even on c2c (matches NapCat). Image/PTT use
|
||||
// `isGroup ? 2 : 1` because their legacy compat elements differ
|
||||
// per scene (notOnlineImage vs customFace; ptt c2c vs group),
|
||||
// but the legacy `videoFile` element has no scene split — its
|
||||
// fromChatType/toChatType live inside the element itself — so
|
||||
// the server generates a single group-shaped compat payload
|
||||
// regardless. Setting 1 here makes the server emit a c2c-scene
|
||||
// shaped compat blob that old QQ clients fail to resolve,
|
||||
// showing the message as "视频已过期" on those receivers while
|
||||
// new clients (which only read the commonElem) display fine.
|
||||
compatQmsgSceneType: 2,
|
||||
extBizInfo: {
|
||||
pic: { bizType: 0, textSummary: 'Nya~' },
|
||||
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
|
||||
|
||||
@@ -6,9 +6,9 @@ import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
UserProfileInfo, GroupRequestInfo,
|
||||
} from './qq-info';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('Identity');
|
||||
const moduleLogger = createLogger('Identity');
|
||||
|
||||
/**
|
||||
* Hooks Identity uses when its read methods miss every cache layer. Wired in
|
||||
@@ -112,9 +112,14 @@ export class IdentityService {
|
||||
private readonly db: DatabaseSync | null;
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(uin: string, dbPath: string | null) {
|
||||
this.uin_ = uin;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLogger.child({ uin: uinNum })
|
||||
: moduleLogger;
|
||||
|
||||
if (!dbPath) {
|
||||
this.db = null;
|
||||
@@ -440,6 +445,13 @@ export class IdentityService {
|
||||
const normalizedUid = normalizeUid(uid);
|
||||
const normalizedUin = normalizeUin(uin);
|
||||
if (!normalizedUid || normalizedUin === null) return;
|
||||
// Drop any stale mapping for the old partner first; otherwise the two
|
||||
// maps disagree (`findUinByUid(oldUid) -> uin` while
|
||||
// `findUidByUin(uin) -> newUid`) after a uid/uin re-binding.
|
||||
const oldUid = this.uidByUin.get(normalizedUin);
|
||||
if (oldUid && oldUid !== normalizedUid) this.uinByUid.delete(oldUid);
|
||||
const oldUin = this.uinByUid.get(normalizedUid);
|
||||
if (oldUin !== undefined && oldUin !== normalizedUin) this.uidByUin.delete(oldUin);
|
||||
this.uinByUid.set(normalizedUid, normalizedUin);
|
||||
this.uidByUin.set(normalizedUin, normalizedUid);
|
||||
}
|
||||
@@ -833,7 +845,7 @@ export class IdentityService {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
this.log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ import { Event0x210SubType } from '../enums';
|
||||
import {
|
||||
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
|
||||
} from '../helpers';
|
||||
import { createLogger } from '../../../utils/logger';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x210SubType) {
|
||||
@@ -21,6 +24,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
|
||||
case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx);
|
||||
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
|
||||
}
|
||||
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches
|
||||
// to GroupMute (12) / GroupRecall (17) / GroupGreyTip (20) / GroupEssence (21).
|
||||
// to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) /
|
||||
// GroupGreyTip (20) / GroupEssence (21).
|
||||
|
||||
import { protoDecode } from '../../../protobuf/decode';
|
||||
import {
|
||||
GroupMuteSchema, NotifyMessageBodySchema,
|
||||
GroupMuteSchema, NotifyMessageBodySchema, GroupReactNotifySchema,
|
||||
} from '../../proto/notify';
|
||||
import type {
|
||||
GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent,
|
||||
GroupMsgEmojiLikeEvent,
|
||||
QQEventVariant,
|
||||
} from '../../events';
|
||||
import type { MsgPushDecoder } from '../registry';
|
||||
@@ -16,14 +18,19 @@ import {
|
||||
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
|
||||
unwrapGroupNotifyPayload,
|
||||
} from '../helpers';
|
||||
import { createLogger } from '../../../utils/logger';
|
||||
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
|
||||
switch (ctx.head.subType as Event0x2DCSubType) {
|
||||
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
|
||||
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
|
||||
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
|
||||
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
|
||||
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
|
||||
}
|
||||
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
|
||||
return [];
|
||||
};
|
||||
|
||||
@@ -104,3 +111,51 @@ function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
|
||||
// Magic prefix QQ prepends to the GroupReactNotify payload inside
|
||||
// body.msgContent for Event0x2DC subType=16. Same value NapCat strips
|
||||
// (see api/group.ts: `msgContent?.slice(7)`).
|
||||
const GROUP_REACT_PREFIX_BYTES = 7;
|
||||
// Discriminator on GroupReactNotify.field13 — same subType is reused
|
||||
// for other notify variants, only 35 means "emoji react". Anything
|
||||
// else falls through to MsgPush.Unknown for protocol-drift visibility.
|
||||
const GROUP_REACT_DISCRIMINATOR = 35;
|
||||
|
||||
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
|
||||
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
|
||||
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
|
||||
const notify = protoDecode(payload, GroupReactNotifySchema);
|
||||
if (!notify) return [];
|
||||
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
|
||||
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
|
||||
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
|
||||
return [];
|
||||
}
|
||||
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
|
||||
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
|
||||
if (!content) return [];
|
||||
|
||||
const groupId = Number(notify.groupUin ?? 0n);
|
||||
const operatorUid = content.operatorUid ?? '';
|
||||
const emojiId = content.code ?? '';
|
||||
const count = content.count ?? 1;
|
||||
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
|
||||
// removed. Older payloads occasionally omit it; default to "add"
|
||||
// since most clients can only generate add events.
|
||||
const isAdd = (content.type ?? 1) === 1;
|
||||
const msgSeq = Number(target?.seq ?? 0n);
|
||||
|
||||
const ev: GroupMsgEmojiLikeEvent = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: ctx.head.timestamp,
|
||||
selfUin: ctx.selfUin,
|
||||
groupId,
|
||||
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin),
|
||||
operatorUid,
|
||||
msgSeq,
|
||||
emojiId,
|
||||
count,
|
||||
isAdd,
|
||||
};
|
||||
return [ev];
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export enum PkgType {
|
||||
|
||||
export enum Event0x2DCSubType {
|
||||
GroupMuteNotice = 12,
|
||||
GroupMsgEmojiLikeNotice = 16,
|
||||
GroupRecallNotice = 17,
|
||||
GroupGreyTipNotice = 20,
|
||||
GroupEssenceNotice = 21,
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { MsgPushContext } from './context';
|
||||
import type { PkgType } from './enums';
|
||||
|
||||
const log = createLogger('MsgPush');
|
||||
const unknownLog = createLogger('MsgPush.Unknown');
|
||||
|
||||
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
|
||||
|
||||
@@ -27,7 +28,13 @@ export class MsgPushRegistry {
|
||||
|
||||
decode(ctx: MsgPushContext): QQEventVariant[] {
|
||||
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
|
||||
if (!decoder) return [];
|
||||
if (!decoder) {
|
||||
// Unrecognized PkgType: either we don't care about this notify, or
|
||||
// the QQ NT client added a new variant. Surface at debug so a
|
||||
// protocol change can be spotted without spamming production logs.
|
||||
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
return decoder(ctx);
|
||||
} catch (e) {
|
||||
|
||||
@@ -20,10 +20,23 @@ import type { PacketInfo } from '../protocol/types';
|
||||
import type { QQEventVariant } from './events';
|
||||
import type { IdentityService } from './identity-service';
|
||||
import type { BridgeEventBus } from './event-bus';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { formatEvent } from '../utils/event-format';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const eventLog = createLogger('Event');
|
||||
const moduleLog = createLogger('Bridge');
|
||||
const moduleEventLog = createLogger('Event');
|
||||
|
||||
// Notice kinds that get logged as a warning (operationally important
|
||||
// state changes that an operator probably wants to see at default
|
||||
// info level). Everything else falls through to info.
|
||||
const WARN_EVENT_KINDS = new Set([
|
||||
'group_recall',
|
||||
'friend_recall',
|
||||
'group_member_leave',
|
||||
'group_mute',
|
||||
'friend_request',
|
||||
'group_invite',
|
||||
]);
|
||||
|
||||
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
|
||||
|
||||
@@ -43,8 +56,18 @@ export interface PacketPipelineDeps {
|
||||
export class IncomingPacketPipeline {
|
||||
private cmdHandlers_ = new Map<string, CmdParser[]>();
|
||||
private memberRefreshTasks_ = new Map<number, Promise<void>>();
|
||||
private readonly log: Logger;
|
||||
private readonly eventLog: Logger;
|
||||
|
||||
constructor(private readonly deps: PacketPipelineDeps) {}
|
||||
constructor(private readonly deps: PacketPipelineDeps) {
|
||||
// Tag every line we emit with this Bridge's UIN so per-account file
|
||||
// routing works. Unparseable uin (shouldn't happen) falls back to
|
||||
// the module-level logger so we still log, just without the slot.
|
||||
const uinNum = Number.parseInt(deps.identity.uin, 10);
|
||||
const bind = Number.isFinite(uinNum) && uinNum > 0 ? { uin: uinNum } : null;
|
||||
this.log = bind ? moduleLog.child(bind) : moduleLog;
|
||||
this.eventLog = bind ? moduleEventLog.child(bind) : moduleEventLog;
|
||||
}
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
const arr = this.cmdHandlers_.get(cmd) ?? [];
|
||||
@@ -65,15 +88,18 @@ export class IncomingPacketPipeline {
|
||||
const events = handler(pkt, this.deps.identity);
|
||||
for (const event of events) {
|
||||
if (this.needsPreDispatchIdentityRefresh(event)) {
|
||||
void this.dispatchAfterIdentityRefresh(event);
|
||||
void this.dispatchAfterIdentityRefresh(event).catch((err) => {
|
||||
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
} else {
|
||||
this.handleSideEffects(event);
|
||||
printEvent(event);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
this.log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,12 +119,12 @@ export class IncomingPacketPipeline {
|
||||
try {
|
||||
refreshed = await this.prepareGroupMemberJoinIdentity(event);
|
||||
} catch (e) {
|
||||
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
|
||||
this.log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
|
||||
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
this.handleSideEffects(event, refreshed);
|
||||
printEvent(event);
|
||||
printEvent(this.eventLog, this.deps.identity, event);
|
||||
this.emit(event);
|
||||
}
|
||||
|
||||
@@ -166,9 +192,9 @@ export class IncomingPacketPipeline {
|
||||
const task = (async () => {
|
||||
try {
|
||||
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
|
||||
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
|
||||
} catch (e) {
|
||||
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||
this.log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
|
||||
groupId, reason, e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
this.memberRefreshTasks_.delete(groupId);
|
||||
@@ -226,50 +252,16 @@ export class IncomingPacketPipeline {
|
||||
}
|
||||
}
|
||||
|
||||
function formatEventUser(uin: number, uid?: string): string {
|
||||
if (uin > 0) return String(uin);
|
||||
return uid || '未知用户';
|
||||
}
|
||||
|
||||
function printEvent(event: QQEventVariant): void {
|
||||
switch (event.kind) {
|
||||
case 'group_message':
|
||||
case 'friend_message':
|
||||
case 'temp_message':
|
||||
// Message logging is handled by OneBot layer with message ID
|
||||
break;
|
||||
case 'group_recall':
|
||||
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
|
||||
break;
|
||||
case 'friend_recall':
|
||||
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
|
||||
break;
|
||||
case 'group_member_join':
|
||||
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
|
||||
break;
|
||||
case 'group_member_leave':
|
||||
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
|
||||
break;
|
||||
case 'group_mute':
|
||||
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
|
||||
break;
|
||||
case 'group_admin':
|
||||
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
|
||||
break;
|
||||
case 'friend_poke':
|
||||
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
|
||||
break;
|
||||
case 'group_poke':
|
||||
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
|
||||
break;
|
||||
case 'friend_request':
|
||||
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
|
||||
break;
|
||||
case 'group_invite':
|
||||
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
|
||||
break;
|
||||
case 'group_essence':
|
||||
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
|
||||
break;
|
||||
function printEvent(log: Logger, identity: IdentityService, event: QQEventVariant): void {
|
||||
// Message-class events (group/friend/temp message) get rendered by the
|
||||
// OneBot layer's logReceivedMessage — its output already includes the
|
||||
// assigned message ID, which the raw packet doesn't have. Returning
|
||||
// null here is the formatter's signal to skip.
|
||||
const message = formatEvent(identity, event);
|
||||
if (!message) return;
|
||||
if (WARN_EVENT_KINDS.has(event.kind)) {
|
||||
log.warn('%s', message);
|
||||
} else {
|
||||
log.info('%s', message);
|
||||
}
|
||||
}
|
||||
@@ -205,3 +205,41 @@ export const NotifyMessageBodySchema = {
|
||||
msgSequence: { field: 37, type: 'uint32' as const },
|
||||
field39: { field: 39, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// ─── Event0x2DC subType=16: GroupMsgEmojiLike ──────────────────────────────
|
||||
//
|
||||
// QQ pushes a Group message emoji reaction (someone tapped an emoji on a
|
||||
// message in a group). The payload nesting matches NapCat's transformer
|
||||
// (packet/transformer/proto/message/message.ts → GroupReactNotify); the
|
||||
// outermost message is preceded by a 7-byte prefix that must be stripped
|
||||
// before decoding (see the call site).
|
||||
|
||||
export const GroupReactionDataInnerDataTargetSchema = {
|
||||
seq: { field: 1, type: 'uint64' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataContentSchema = {
|
||||
code: { field: 1, type: 'string' as const },
|
||||
count: { field: 3, type: 'uint32' as const },
|
||||
operatorUid: { field: 4, type: 'string' as const },
|
||||
type: { field: 5, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataInnerDataSchema = {
|
||||
groupReactionTarget: { field: 2, type: 'message' as const, schema: GroupReactionDataInnerDataTargetSchema },
|
||||
groupReactionDataContent: { field: 3, type: 'message' as const, schema: GroupReactionDataContentSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataInnerSchema = {
|
||||
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerDataSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactionDataSchema = {
|
||||
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerSchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const GroupReactNotifySchema = {
|
||||
groupUin: { field: 4, type: 'uint64' as const },
|
||||
field13: { field: 13, type: 'uint32' as const },
|
||||
groupReactionData: { field: 44, type: 'message' as const, schema: GroupReactionDataSchema },
|
||||
} satisfies ProtoSchema;
|
||||
@@ -190,10 +190,14 @@ export const OidbUserInfoKeySchema = {
|
||||
key: { field: 1, type: 'uint32' as const },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
// Field 2 USED to be `field2: uint32 = 0`, but newer QQ NT versions
|
||||
// reinterpret field 2 as `uid: string` / `openid: string` and reject
|
||||
// the request with "one of uid/openid is invaild" when a varint 0
|
||||
// shows up there. NapCat's schema (Oidb.0XFE1_2.ts) only emits `uin`
|
||||
// and `key[]`, so we match that exactly.
|
||||
export const OidbUserInfoRequestSchema = {
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
field2: { field: 2, type: 'uint32' as const },
|
||||
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
|
||||
uin: { field: 1, type: 'uint32' as const },
|
||||
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
|
||||
} satisfies ProtoSchema;
|
||||
|
||||
export const OidbTwoNumberSchema = {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
// 定义接口返回类型
|
||||
export interface GroupEssenceMsgRet {
|
||||
@@ -39,6 +42,8 @@ export async function getGroupEssenceMsg(
|
||||
);
|
||||
return ret.retcode === 0 ? ret : undefined;
|
||||
} catch (e) {
|
||||
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
|
||||
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export enum WebHonorType {
|
||||
TALKATIVE = 'talkative',
|
||||
@@ -43,7 +46,8 @@ export async function getHonorListWebAPI(cookieObject: Record<string, string>, g
|
||||
description: item?.desc,
|
||||
}));
|
||||
} catch (e) {
|
||||
// console.error(e);
|
||||
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
|
||||
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { RequestUtil, cookieToString } from './request-util';
|
||||
import https from 'node:https';
|
||||
// import { readFileSync } from 'node:fs';
|
||||
// import * as console from "node:console";
|
||||
import { createLogger } from '../../utils/logger';
|
||||
|
||||
const log = createLogger('Bridge.Web');
|
||||
|
||||
export interface SetNoticeRetSuccess {
|
||||
ec?: number;
|
||||
@@ -112,6 +113,7 @@ export async function setGroupNoticeWebAPI(
|
||||
);
|
||||
return ret;
|
||||
} catch (e) {
|
||||
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -158,7 +160,8 @@ export async function getGroupNoticeWebAPI(
|
||||
);
|
||||
// console.log(JSON.stringify(ret, null, 2));
|
||||
return ret?.ec === 0 ? ret : undefined;
|
||||
} catch {
|
||||
} catch (e) {
|
||||
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -215,11 +218,15 @@ export async function uploadGroupNoticeImage(
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', () => resolve(undefined));
|
||||
req.on('error', (err) => {
|
||||
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
|
||||
resolve(undefined);
|
||||
});
|
||||
req.write(body);
|
||||
req.end();
|
||||
});
|
||||
} catch {
|
||||
} catch (e) {
|
||||
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -260,7 +267,8 @@ export async function deleteGroupNotice(
|
||||
false
|
||||
);
|
||||
return ret?.ec === 0;
|
||||
} catch {
|
||||
} catch (e) {
|
||||
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -21,26 +21,45 @@ export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const loaded = tryLoadRuntimeConfig();
|
||||
let normalized: RuntimeConfig;
|
||||
if (!loaded) {
|
||||
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
|
||||
return { ...DEFAULT_RUNTIME_CONFIG };
|
||||
normalized = { ...DEFAULT_RUNTIME_CONFIG };
|
||||
} else {
|
||||
normalized = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
|
||||
};
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
}
|
||||
|
||||
const normalized: RuntimeConfig = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
|
||||
};
|
||||
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
// SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without
|
||||
// rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop)
|
||||
// pick a free port per-launch while CLI/Docker users continue to drive
|
||||
// it from runtime.json.
|
||||
const envPort = envPortOverride();
|
||||
if (envPort !== undefined) {
|
||||
normalized = { ...normalized, webuiPort: envPort };
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function envPortOverride(): number | undefined {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
if (!raw || typeof raw !== 'string') return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
|
||||
|
||||
@@ -14,8 +14,13 @@ export type HookSessionDeps = {
|
||||
};
|
||||
makeClient: (pid: number) => QqHookClient;
|
||||
/** Sync fast-path check used by load() to skip re-injection when a
|
||||
* prior SnowLuma run left a working pipe behind. */
|
||||
pipeWatcher: { isPipeLive: (pid: number) => boolean };
|
||||
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
|
||||
* fresh poll — used after unload to dodge the up-to-1500ms cache
|
||||
* staleness that would otherwise false-flag a successful unload. */
|
||||
pipeWatcher: {
|
||||
isPipeLive: (pid: number) => boolean;
|
||||
tickNow?: () => Promise<void>;
|
||||
};
|
||||
/** Sink for parsed packets. Called with the BridgeManager-shaped
|
||||
* PacketInfo for every packet received while logged in. If omitted,
|
||||
* packets are dropped (useful in unit tests that don't care). */
|
||||
@@ -254,7 +259,11 @@ export class HookSession extends EventEmitter {
|
||||
this._uin = '0';
|
||||
|
||||
// Verify the unload took: if the pipe is still up the DLL is still
|
||||
// resident. Drop back to 'connecting' and let the watcher reconnect.
|
||||
// resident. The cached snapshot is up to 1500ms stale and we just
|
||||
// changed the world, so force a fresh poll first — otherwise even
|
||||
// a successful unload reads as "pipe still live" until the next
|
||||
// background tick runs and we'd report a spurious failure.
|
||||
await this.pipeWatcher.tickNow?.();
|
||||
if (this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
|
||||
this.setStatus('connecting', this._error);
|
||||
|
||||
@@ -444,7 +444,18 @@ export class QqHookClient extends EventEmitter {
|
||||
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
|
||||
await this.connect();
|
||||
|
||||
const requestId = this.nextRequestId++ >>> 0;
|
||||
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would
|
||||
// misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the
|
||||
// postfix increment loses precision before the shift), letting two
|
||||
// distinct requests collide on the same id. Skip 0 because zero is
|
||||
// used as a sentinel by the wire protocol.
|
||||
let requestId = this.nextRequestId;
|
||||
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
|
||||
requestId = (requestId + 1) >>> 0;
|
||||
if (requestId === 0) requestId = 1;
|
||||
}
|
||||
this.nextRequestId = (requestId + 1) >>> 0;
|
||||
if (this.nextRequestId === 0) this.nextRequestId = 1;
|
||||
const payload = encodeFrame({
|
||||
op: PipeOp.sendRequest,
|
||||
requestId,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { OneBotManager } from './onebot/manager';
|
||||
import { loadRuntimeConfig } from './common/runtime';
|
||||
import { createLogger } from './utils/logger';
|
||||
import { closeLogger, createLogger } from './utils/logger';
|
||||
import { HookManager } from './hook/hook-manager';
|
||||
|
||||
const runtimeConfig = loadRuntimeConfig();
|
||||
@@ -38,13 +38,17 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Graceful shutdown
|
||||
process.on('SIGINT', () => {
|
||||
log.warn('Shutting down...');
|
||||
// Graceful shutdown: dispose managers, await log flush, then exit.
|
||||
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
|
||||
const shutdown = (signal: string) => async () => {
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
oneBotManager.dispose();
|
||||
hookManager.dispose();
|
||||
await closeLogger();
|
||||
process.exit(0);
|
||||
});
|
||||
};
|
||||
process.on('SIGINT', shutdown('SIGINT'));
|
||||
process.on('SIGTERM', shutdown('SIGTERM'));
|
||||
}
|
||||
|
||||
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
|
||||
@@ -57,7 +61,8 @@ function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
|
||||
return fromConfig === true;
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
main().catch(async (error) => {
|
||||
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
await closeLogger();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -3,6 +3,62 @@ import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
|
||||
import type { ForwardPreviewMeta } from '../modules/message-actions';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
// Bounded download for the OneBot `download_file` action. An authenticated
|
||||
// client could otherwise hand us a multi-GB URL (or chunked response with
|
||||
// no Content-Length) and OOM the bot — `await response.arrayBuffer()`
|
||||
// happily allocates the whole payload before any size check fires.
|
||||
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
|
||||
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
|
||||
|
||||
async function fetchDownloadFile(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
maxBytes: number,
|
||||
timeoutMs: number,
|
||||
): Promise<Buffer> {
|
||||
const response = await fetch(url, {
|
||||
headers,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (!response.ok) throw new Error(`download failed: HTTP ${response.status}`);
|
||||
|
||||
const declared = Number(response.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw new Error(`download too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`download too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// Stream so a server that omits / understates Content-Length can't make
|
||||
// us buffer past maxBytes — abort the read as soon as the running total
|
||||
// crosses the cap.
|
||||
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 new Error(`download too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
return Buffer.concat(chunks, total);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull NapCat-compatible forward preview overrides off a send_*_forward_msg
|
||||
* payload. All four fields are optional — when omitted, the module layer
|
||||
@@ -157,8 +213,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
|
||||
if (!meta || !meta.isGroup) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message');
|
||||
}
|
||||
@@ -167,8 +221,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
|
||||
}
|
||||
|
||||
|
||||
await ctx.bridge.markGroupMsgAsRead(groupId, meta.sequence);
|
||||
await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
@@ -180,8 +233,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
|
||||
if (!meta || meta.isGroup) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message');
|
||||
}
|
||||
@@ -190,8 +241,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session');
|
||||
}
|
||||
|
||||
|
||||
await ctx.bridge.markPrivateMsgAsRead(userId, meta.sequence);
|
||||
await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
@@ -205,15 +255,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
|
||||
|
||||
if (targetId && targetId !== meta.targetId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session');
|
||||
}
|
||||
|
||||
if (meta.isGroup) {
|
||||
await ctx.bridge.markGroupMsgAsRead(targetId, meta.sequence);
|
||||
await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence);
|
||||
} else {
|
||||
await ctx.bridge.markPrivateMsgAsRead(targetId, meta.sequence);
|
||||
await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence);
|
||||
}
|
||||
return okResponse();
|
||||
});
|
||||
@@ -310,7 +359,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
|
||||
const result = await ctx.sendForwardMsg(messages);
|
||||
// Group and private forwards live in different resId namespaces
|
||||
// (see bridge/actions/forward.ts: type=3+groupUin vs type=1+selfUid).
|
||||
// Passing groupId through is what makes the resulting resId usable
|
||||
// when the caller later sends it into the same group.
|
||||
const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined);
|
||||
const data: Record<string, unknown> = {
|
||||
res_id: result.forwardId,
|
||||
forward_id: result.forwardId,
|
||||
@@ -320,10 +373,13 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
return okResponse(data as any);
|
||||
});
|
||||
|
||||
// Kept for backward compat with clients that follow the historical
|
||||
// gocqhttp/NapCat docs misspelling; same semantics as upload_forward_msg.
|
||||
h.registerAction('upload_foward_msg', async (params) => {
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
const result = await ctx.sendForwardMsg(messages);
|
||||
const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined);
|
||||
return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 });
|
||||
});
|
||||
|
||||
@@ -482,17 +538,23 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
|
||||
h.registerAction('set_friend_remark', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const remark = asString(params.remark) ?? '';
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
await ctx.bridge.setFriendRemark(userId, remark);
|
||||
// remark must be explicitly provided. Falling back to '' on a missing
|
||||
// field would silently CLEAR the operator's existing remark.
|
||||
if (params.remark === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)');
|
||||
}
|
||||
await ctx.bridge.setFriendRemark(userId, asString(params.remark));
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_remark', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const remark = asString(params.remark) ?? '';
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.setGroupRemark(groupId, remark);
|
||||
if (params.remark === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)');
|
||||
}
|
||||
await ctx.bridge.setGroupRemark(groupId, asString(params.remark));
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
@@ -545,26 +607,55 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
const fs = await import('fs');
|
||||
const pathMod = await import('path');
|
||||
const cryptoMod = await import('crypto');
|
||||
const tempDir = pathMod.join('data', 'downloads');
|
||||
const tempDir = pathMod.resolve('data', 'downloads');
|
||||
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
let filePath: string;
|
||||
// Sanitize file name: strip any path components, reject anything that
|
||||
// resolves outside `tempDir`. Without this guard, `name = "../../config/onebot_x.json"`
|
||||
// would let an authenticated OneBot client overwrite arbitrary files
|
||||
// (config / dist / node_modules) under the working directory.
|
||||
const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => {
|
||||
const raw = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex');
|
||||
const safeName = pathMod.basename(raw);
|
||||
if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) return null;
|
||||
const resolved = pathMod.resolve(tempDir, safeName);
|
||||
const rel = pathMod.relative(tempDir, resolved);
|
||||
if (rel.startsWith('..') || pathMod.isAbsolute(rel)) return null;
|
||||
return resolved;
|
||||
};
|
||||
|
||||
let buf: Buffer;
|
||||
if (base64) {
|
||||
const buf = Buffer.from(base64, 'base64');
|
||||
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
|
||||
filePath = pathMod.join(tempDir, fileName);
|
||||
fs.writeFileSync(filePath, buf);
|
||||
// Every 4 base64 chars decode to at most 3 bytes. Reject before
|
||||
// `Buffer.from` allocates anything to avoid OOM on a giant payload
|
||||
// that wouldn't pass the post-decode check anyway.
|
||||
const upperBound = Math.floor((base64.length * 3) / 4);
|
||||
if (upperBound > DOWNLOAD_FILE_MAX_BYTES) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
|
||||
}
|
||||
buf = Buffer.from(base64, 'base64');
|
||||
if (buf.length > DOWNLOAD_FILE_MAX_BYTES) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
|
||||
}
|
||||
} else {
|
||||
const response = await fetch(url!, {
|
||||
headers: parseDownloadHeaders(params.headers),
|
||||
});
|
||||
if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`);
|
||||
const buf = Buffer.from(await response.arrayBuffer());
|
||||
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
|
||||
filePath = pathMod.join(tempDir, fileName);
|
||||
fs.writeFileSync(filePath, buf);
|
||||
try {
|
||||
buf = await fetchDownloadFile(
|
||||
url!,
|
||||
parseDownloadHeaders(params.headers),
|
||||
DOWNLOAD_FILE_MAX_BYTES,
|
||||
DOWNLOAD_FILE_TIMEOUT_MS,
|
||||
);
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
return okResponse({ file: pathMod.resolve(filePath) });
|
||||
|
||||
const safe = resolveSafePath(name, buf);
|
||||
if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name');
|
||||
// Async write so we don't block the event loop on a GiB-class download
|
||||
// (the prior `writeFileSync` stalled every other bot action while it ran).
|
||||
await fs.promises.writeFile(safe, buf);
|
||||
return okResponse({ file: safe });
|
||||
});
|
||||
|
||||
h.registerAction('set_qq_profile', async (params) => {
|
||||
|
||||
@@ -2,6 +2,10 @@ import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import type { ForwardPreviewMeta } from './modules/message-actions';
|
||||
import type { BridgeInterface } from '../bridge/bridge-interface';
|
||||
import { RETCODE, failedResponse } from './types';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { summarizeParams } from '../utils/log-summary';
|
||||
|
||||
const moduleLog = createLogger('Bridge.Action');
|
||||
|
||||
import { register as registerInfo } from './actions/info';
|
||||
import { register as registerMessage } from './actions/message';
|
||||
@@ -92,7 +96,7 @@ export interface ApiActionContext {
|
||||
getDownloadRKeys: () => Promise<JsonObject[]>;
|
||||
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
|
||||
sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>;
|
||||
sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>;
|
||||
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
|
||||
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
|
||||
// Extended NapCat-compatible
|
||||
@@ -131,8 +135,10 @@ type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiRespon
|
||||
|
||||
export class ApiHandler {
|
||||
private readonly handlers = new Map<string, ActionHandler>();
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(context: ApiActionContext) {
|
||||
constructor(context: ApiActionContext, uin?: number) {
|
||||
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
registerInfo(this, context);
|
||||
registerMessage(this, context);
|
||||
registerFriend(this, context);
|
||||
@@ -151,12 +157,25 @@ export class ApiHandler {
|
||||
async handle(action: string, params: JsonObject): Promise<import('./types').ApiResponse> {
|
||||
const handler = this.handlers.get(action);
|
||||
if (!handler) {
|
||||
this.log.debug('unknown action %s', action);
|
||||
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
|
||||
}
|
||||
|
||||
// Entry log goes to file always (debug); console only when level is
|
||||
// dialed down to debug. Caller-perspective summary lets the operator
|
||||
// grep "what did the bot get asked to do" without scraping wire logs.
|
||||
this.log.debug('%s params=%s', action, summarizeParams(params));
|
||||
|
||||
try {
|
||||
return await handler(params);
|
||||
} catch (error) {
|
||||
// Action failures are almost always param-shape problems coming
|
||||
// from the OneBot client; warn (not error) is the right level so
|
||||
// the log file stays a useful signal of real internal faults.
|
||||
this.log.warn('%s failed: %s\n%s',
|
||||
action,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
error instanceof Error ? (error.stack ?? '') : '');
|
||||
const message = error instanceof Error ? error.message : 'internal error';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import type {
|
||||
HttpClientNetwork,
|
||||
HttpServerNetwork,
|
||||
@@ -13,6 +14,8 @@ import type {
|
||||
WsServerNetwork,
|
||||
} from './types';
|
||||
|
||||
const log = createLogger('OneBot.Config');
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
|
||||
@@ -50,7 +53,18 @@ function generateAccessToken(): string {
|
||||
return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url');
|
||||
}
|
||||
|
||||
export function loadOneBotConfig(uin: string): OneBotConfig {
|
||||
export interface LoadOneBotConfigOptions {
|
||||
/**
|
||||
* Persist the normalized config to disk when the file is missing or was
|
||||
* in legacy format. Default `false` so accidental call sites (read-only
|
||||
* GETs in particular) don't generate fresh access tokens, race on
|
||||
* concurrent writes, or surprise the operator with materialized files.
|
||||
* Pass `true` from boot / explicit POST handlers.
|
||||
*/
|
||||
persistDefaults?: boolean;
|
||||
}
|
||||
|
||||
export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = {}): OneBotConfig {
|
||||
ensureConfigDir();
|
||||
|
||||
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||
@@ -65,12 +79,11 @@ export function loadOneBotConfig(uin: string): OneBotConfig {
|
||||
if (globalRaw) sources.push(globalRaw);
|
||||
if (perUinRaw) sources.push(perUinRaw);
|
||||
|
||||
const config = fromJson(sources);
|
||||
const config = fromJson(sources, !perUinRaw && !globalRaw);
|
||||
|
||||
// Persist normalized form whenever the file is missing OR was in legacy
|
||||
// format, so downstream code can rely on the unified shape on disk.
|
||||
const shouldSave = !perUinRaw || legacy;
|
||||
if (shouldSave) saveOneBotConfig(uin, config);
|
||||
if (options.persistDefaults && (!perUinRaw || legacy)) {
|
||||
saveOneBotConfig(uin, config);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
@@ -148,7 +161,7 @@ function wsClientToJson(n: WsClientNetwork): JsonObject {
|
||||
return out;
|
||||
}
|
||||
|
||||
function fromJson(sources: JsonObject[]): OneBotConfig {
|
||||
function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
|
||||
// Legacy top-level scalars are pulled DOWN into each adapter on the first
|
||||
// load: the on-disk schema has no globals anymore, every adapter is
|
||||
// self-describing. We compute the legacy fallbacks here so that adapters
|
||||
@@ -175,8 +188,11 @@ function fromJson(sources: JsonObject[]): OneBotConfig {
|
||||
const wsServers = collectByName<WsServerNetwork>(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults));
|
||||
const wsClients = collectByName<WsClientNetwork>(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults));
|
||||
|
||||
// Seed defaults if all four arrays are empty (brand-new install).
|
||||
// Seed defaults ONLY for a brand-new install (no source files at all).
|
||||
// If the operator deliberately emptied every adapter, respect that and
|
||||
// do NOT silently revive default 0.0.0.0 listeners.
|
||||
if (
|
||||
freshInstall &&
|
||||
httpServers.length === 0 &&
|
||||
httpClients.length === 0 &&
|
||||
wsServers.length === 0 &&
|
||||
@@ -354,7 +370,8 @@ function tryLoadJson(filePath: string): JsonObject | null {
|
||||
const raw = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
log.warn('config file %s is corrupt and will be ignored: %s', filePath, err instanceof Error ? err.message : String(err));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -364,20 +381,6 @@ function saveJson(filePath: string, json: JsonObject): void {
|
||||
fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
function deepClone(obj: JsonObject): JsonObject {
|
||||
return JSON.parse(JSON.stringify(obj)) as JsonObject;
|
||||
}
|
||||
|
||||
function deepMerge(base: JsonObject, override: JsonObject): void {
|
||||
for (const [key, value] of Object.entries(override)) {
|
||||
if (isObject(base[key]) && isObject(value)) {
|
||||
deepMerge(base[key] as JsonObject, value);
|
||||
} else {
|
||||
base[key] = value as never;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
convertGroupFileUpload,
|
||||
convertGroupMemberJoin,
|
||||
convertGroupMemberLeave,
|
||||
convertGroupMsgEmojiLike,
|
||||
convertGroupMute,
|
||||
convertGroupPoke,
|
||||
convertGroupRecall,
|
||||
@@ -98,6 +99,7 @@ export async function convertEvent(
|
||||
case 'group_essence': return convertGroupEssence(ctx, event);
|
||||
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
|
||||
case 'friend_add': return convertFriendAdd(ctx, event);
|
||||
case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event);
|
||||
|
||||
// Requests.
|
||||
case 'friend_request': return convertFriendRequest(ctx, event);
|
||||
|
||||
@@ -21,6 +21,7 @@ type GroupPoke = Extract<QQEventVariant, { kind: 'group_poke' }>;
|
||||
type GroupEssence = Extract<QQEventVariant, { kind: 'group_essence' }>;
|
||||
type GroupFileUpload = Extract<QQEventVariant, { kind: 'group_file_upload' }>;
|
||||
type FriendAdd = Extract<QQEventVariant, { kind: 'friend_add' }>;
|
||||
type GroupMsgEmojiLike = Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>;
|
||||
|
||||
export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject {
|
||||
return {
|
||||
@@ -187,3 +188,32 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO
|
||||
user_id: event.userUin,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Group message emoji reaction notice. Matches the gocqhttp / NapCat
|
||||
* extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot
|
||||
* v11 standard has no slot for reactions and that's what every
|
||||
* downstream framework keys off.
|
||||
*/
|
||||
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
|
||||
// Reconstruct the OneBot message_id we originally minted for the
|
||||
// reacted-to message. hashMessageIdInt32 is deterministic so the ID
|
||||
// matches whatever the client received at receive-time, even when
|
||||
// the message has fallen out of our store.
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_msg_emoji_like',
|
||||
sub_type: event.isAdd ? 'add' : 'remove',
|
||||
group_id: event.groupId,
|
||||
user_id: event.operatorUin,
|
||||
operator_id: event.operatorUin,
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
likes: [{ emoji_id: event.emojiId, count: event.count }],
|
||||
};
|
||||
}
|
||||
@@ -73,6 +73,7 @@ const NOTICE_KINDS = [
|
||||
'group_essence',
|
||||
'group_file_upload',
|
||||
'friend_add',
|
||||
'group_msg_emoji_like',
|
||||
] as const satisfies readonly QQEventVariant['kind'][];
|
||||
|
||||
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
|
||||
|
||||
@@ -158,7 +158,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
getDownloadRKeys: () => getDownloadRKeys(bridge),
|
||||
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
|
||||
sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta),
|
||||
sendForwardMsg: (messages) => uploadForwardMessage(ref, messages),
|
||||
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
|
||||
getForwardMsg: (resId) => getForwardMessage(ref, resId),
|
||||
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
|
||||
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
|
||||
|
||||
@@ -10,7 +10,7 @@ import { RKeyCache } from './instance-rkey';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { JsonObject, MessageMeta, OneBotConfig, NetworkBase } from './types';
|
||||
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types';
|
||||
import {
|
||||
OneBotNetworkManager,
|
||||
WsServerAdapter,
|
||||
@@ -19,9 +19,10 @@ import {
|
||||
HttpPostAdapter,
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '../utils/event-format';
|
||||
|
||||
const log = createLogger('Event');
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
export class OneBotInstance {
|
||||
readonly uin: string;
|
||||
@@ -40,12 +41,17 @@ export class OneBotInstance {
|
||||
private online = true;
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private static readonly HEARTBEAT_INTERVAL = 30000;
|
||||
private readonly log: Logger;
|
||||
|
||||
get nickname(): string { return this.bridge.identity.nickname; }
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
this.rkeyCache = new RKeyCache();
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
|
||||
@@ -85,10 +91,12 @@ export class OneBotInstance {
|
||||
};
|
||||
this.ctx = ctx;
|
||||
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx));
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
|
||||
this.networkManager = new OneBotNetworkManager();
|
||||
this.installAdaptersFromConfig(config);
|
||||
void this.networkManager.openAll();
|
||||
void this.networkManager.openAll().catch((err) => {
|
||||
this.log.warn('openAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
|
||||
this.startHeartbeat();
|
||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||
@@ -99,7 +107,9 @@ export class OneBotInstance {
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
void this.applyConfigDiff(config);
|
||||
void this.applyConfigDiff(config).catch((err) => {
|
||||
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
@@ -107,7 +117,9 @@ export class OneBotInstance {
|
||||
this.stopHeartbeat();
|
||||
this.disposeEventPipeline?.();
|
||||
this.disposeEventPipeline = null;
|
||||
void this.networkManager.closeAll();
|
||||
void this.networkManager.closeAll().catch((err) => {
|
||||
this.log.warn('closeAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
this.messageStore.close();
|
||||
this.mediaStore.close();
|
||||
}
|
||||
@@ -136,8 +148,12 @@ export class OneBotInstance {
|
||||
this.cacheMessageEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// NetworkManager builds the dispatch payload once and fans out to every
|
||||
// active adapter in parallel via Promise.allSettled.
|
||||
void this.networkManager.emitEvent(event);
|
||||
// active adapter in parallel via Promise.allSettled — per-adapter errors
|
||||
// are already isolated, so the outer promise should never reject. The
|
||||
// .catch is a belt-and-suspenders guard against future refactors.
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private buildNetworkContext(): NetworkAdapterContext {
|
||||
@@ -206,7 +222,7 @@ export class OneBotInstance {
|
||||
try {
|
||||
await existing.reload(net as never);
|
||||
} catch (err) {
|
||||
log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else if (net.enabled !== false) {
|
||||
const factory = factories.get(name);
|
||||
@@ -224,56 +240,56 @@ export class OneBotInstance {
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
const isGroup = event.message_type === 'group';
|
||||
|
||||
// Build message preview
|
||||
const parts: string[] = [];
|
||||
const idStr = `ID:${messageId}`;
|
||||
const selfTag = isSelf ? '[自身] ' : '';
|
||||
const identity = this.bridge.identity;
|
||||
|
||||
// Walk the segment array once: render via the shared formatter for
|
||||
// non-reply segments, and resolve `reply` segments through the
|
||||
// message store so the chain reference becomes legible
|
||||
// ("[回复 <user>: <body>...]" instead of "[回复:1234567890]").
|
||||
const renderedParts: string[] = [];
|
||||
const message = event.message;
|
||||
|
||||
if (Array.isArray(message)) {
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const type = String(seg.type ?? '');
|
||||
const data: Record<string, unknown> = (
|
||||
typeof seg.data === 'object' && seg.data !== null && !Array.isArray(seg.data)
|
||||
) ? seg.data : {};
|
||||
|
||||
if (type === 'text' && data.text) {
|
||||
const text = String(data.text);
|
||||
const preview = text.length > 50 ? text.substring(0, 50) + '...' : text;
|
||||
parts.push(preview);
|
||||
} else if (type === 'image') {
|
||||
parts.push('[图片]');
|
||||
} else if (type === 'face') {
|
||||
parts.push('[表情]');
|
||||
} else if (type === 'at') {
|
||||
parts.push(`@${data.qq || ''}`);
|
||||
} else if (type === 'reply') {
|
||||
parts.push(`[回复:${data.id || ''}]`);
|
||||
} else if (type === 'record') {
|
||||
parts.push('[语音]');
|
||||
} else if (type === 'video') {
|
||||
parts.push('[视频]');
|
||||
const type = String((seg as JsonObject).type ?? '');
|
||||
const data = (typeof (seg as JsonObject).data === 'object' && (seg as JsonObject).data !== null && !Array.isArray((seg as JsonObject).data))
|
||||
? (seg as JsonObject).data as Record<string, unknown>
|
||||
: {};
|
||||
if (type === 'reply') {
|
||||
const replyId = toInt(data.id);
|
||||
renderedParts.push(formatReply(this.messageStore, identity, replyId));
|
||||
} else {
|
||||
parts.push(`[${type}]`);
|
||||
renderedParts.push(formatMessageSegments([seg as JsonValue]));
|
||||
}
|
||||
}
|
||||
} else if (typeof message === 'string') {
|
||||
renderedParts.push(formatMessageSegments(message));
|
||||
}
|
||||
|
||||
const content = parts.join(' ').trim() || '[空消息]';
|
||||
const idStr = `ID:${messageId}`;
|
||||
const selfTag = isSelf ? '[自身] ' : '';
|
||||
|
||||
const content = renderedParts.join(' ').trim() || '[空消息]';
|
||||
|
||||
if (isGroup) {
|
||||
const groupId = toInt(event.group_id);
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = event.sender as any;
|
||||
const nickname = sender?.card || sender?.nickname || String(userId);
|
||||
log.success(`${selfTag}群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.card as string) || (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, groupId, userId);
|
||||
this.log.success(`${selfTag}群 ${formatGroup(identity, groupId)} | ${userPart}: ${idStr} ${content}`);
|
||||
} else {
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = event.sender as any;
|
||||
const nickname = sender?.nickname || String(userId);
|
||||
log.success(`${selfTag}私聊 ${nickname}(${userId}): ${idStr} ${content}`);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, undefined, userId);
|
||||
this.log.success(`${selfTag}私聊 ${userPart}: ${idStr} ${content}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ export class OneBotManager {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return false;
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
instance.reloadConfig(config);
|
||||
log.info('configuration reloaded: UIN=%s', uin);
|
||||
return true;
|
||||
@@ -51,7 +51,7 @@ export class OneBotManager {
|
||||
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
|
||||
if (this.instances.has(uin)) return;
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
const instance = new OneBotInstance(uin, bridge, config);
|
||||
|
||||
const activePid = bridge.activePid;
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
import type { MessageElement } from '../bridge/events';
|
||||
import type { JsonValue, JsonObject } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('MsgParser');
|
||||
|
||||
export interface ParseMessageOptions {
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||
@@ -16,6 +19,19 @@ export interface ParseMessageOptions {
|
||||
|
||||
const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
|
||||
|
||||
/**
|
||||
* Best-effort base-10 integer coercion. Falls back to `fallback` (default 0)
|
||||
* when the input can't be parsed as a finite integer — `parseInt('abc')`
|
||||
* is `NaN`, which silently turns into `0`/`null` further down the wire
|
||||
* pipeline and produces undebuggable protocol-level failures.
|
||||
*/
|
||||
function intOr(value: unknown, fallback = 0): number {
|
||||
if (value === undefined || value === null) return fallback;
|
||||
if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback;
|
||||
const n = parseInt(String(value), 10);
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
}
|
||||
|
||||
function parseCQParams(raw: string): Record<string, string> {
|
||||
const params: Record<string, string> = {};
|
||||
if (!raw) return params;
|
||||
@@ -33,9 +49,12 @@ function parseCQParams(raw: string): Record<string, string> {
|
||||
}
|
||||
|
||||
function cqUnescape(text: string): string {
|
||||
// Order matters: `&` MUST be last so that, e.g., `&#91;` keeps
|
||||
// the literal `[` instead of decoding twice into `[`.
|
||||
return text
|
||||
.replace(/[/g, '[')
|
||||
.replace(/]/g, ']')
|
||||
.replace(/,/g, ',')
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
|
||||
@@ -88,7 +107,8 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
return text ? { type: 'text', text } : null;
|
||||
}
|
||||
case 'face': {
|
||||
const id = parseInt(String(data.id ?? '0'), 10);
|
||||
const id = intOr(data.id, -1);
|
||||
if (id < 0) return null;
|
||||
return { type: 'face', faceId: id };
|
||||
}
|
||||
case 'at': {
|
||||
@@ -96,7 +116,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
if (qq === 'all') {
|
||||
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
|
||||
}
|
||||
const uin = parseInt(qq, 10);
|
||||
const uin = intOr(qq, 0);
|
||||
if (uin <= 0) return null;
|
||||
|
||||
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
|
||||
@@ -105,16 +125,17 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'at',
|
||||
targetUin: uin,
|
||||
uid: uid || undefined,
|
||||
text: name ? `@${name} ` : `@${uin} `,
|
||||
};
|
||||
// Leave `text` undefined when the caller didn't supply a display
|
||||
// name. The element-builder then resolves it from the group roster
|
||||
// (so QQ renders `@昵称` instead of `@QQ号`).
|
||||
const element: MessageElement = { type: 'at', targetUin: uin };
|
||||
if (uid) element.uid = uid;
|
||||
if (name) element.text = `@${name} `;
|
||||
return element;
|
||||
}
|
||||
case 'reply': {
|
||||
const id = parseInt(String(data.id ?? '0'), 10);
|
||||
if (!Number.isInteger(id) || id === 0) return null;
|
||||
const id = intOr(data.id, 0);
|
||||
if (id === 0) return null;
|
||||
|
||||
if (options?.resolveReplySequence) {
|
||||
const resolved = options.resolveReplySequence(id);
|
||||
@@ -147,7 +168,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
type: 'image',
|
||||
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
|
||||
flash: data.type === 'flash',
|
||||
subType: parseInt(String(data.subType ?? '0'), 10),
|
||||
subType: intOr(data.subType, 0),
|
||||
summary: data.summary ? String(data.summary) : undefined,
|
||||
};
|
||||
}
|
||||
@@ -178,13 +199,13 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
return {
|
||||
type: 'xml',
|
||||
text: String(data.data ?? ''),
|
||||
subType: parseInt(String(data.id ?? '0'), 10),
|
||||
subType: intOr(data.id, 0),
|
||||
};
|
||||
}
|
||||
case 'poke': {
|
||||
return {
|
||||
type: 'poke',
|
||||
faceId: parseInt(String(data.type ?? data.id ?? '0'), 10),
|
||||
faceId: intOr(data.type ?? data.id, 0),
|
||||
};
|
||||
}
|
||||
case 'forward': {
|
||||
@@ -196,11 +217,10 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
case 'node': {
|
||||
// Fake forward node segment — store the raw data for later processing
|
||||
// The content field may be a segment array, a single segment, or a CQ string
|
||||
const uin = String(data.user_id ?? data.uin ?? '0');
|
||||
const name = String(data.nickname ?? data.name ?? '');
|
||||
return {
|
||||
type: 'node',
|
||||
targetUin: parseInt(uin, 10) || 0,
|
||||
targetUin: intOr(data.user_id ?? data.uin, 0),
|
||||
text: name,
|
||||
// Raw content is stored as JSON string in resId for later processing
|
||||
resId: JSON.stringify(data.content ?? ''),
|
||||
@@ -254,7 +274,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
const musicJson = await resp.text();
|
||||
return { type: 'json', text: musicJson };
|
||||
} catch (e) {
|
||||
console.warn(`[MsgParser] music sign failed: ${e}, falling back to local card`);
|
||||
log.warn('music sign failed: %s, falling back to local card', e instanceof Error ? e.message : String(e));
|
||||
// Fallback: build a basic card locally
|
||||
const title = String(data.title ?? 'Music');
|
||||
const jsonData = JSON.stringify({
|
||||
|
||||
@@ -99,10 +99,32 @@ export async function sendPrivateMessage(
|
||||
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
// Prefer the cached event (it carries the REAL sender). When only
|
||||
// meta exists — typically because the message we're replying to was
|
||||
// sent by the bot itself and never round-tripped through dispatch
|
||||
// (reportSelfMessage off / no message_sent event) — fall back to
|
||||
// selfId. The previous code used `meta.targetId` here, which is the
|
||||
// conversation PEER and shows the wrong "回复 @某人" in QQ for any
|
||||
// self-reply.
|
||||
const event = ref.messageStore.findEvent(replyMessageId);
|
||||
if (event) {
|
||||
const senderUin = typeof event.user_id === 'number'
|
||||
? event.user_id
|
||||
: parseInt(String(event.user_id || '0'), 10);
|
||||
const time = typeof event.time === 'number'
|
||||
? event.time
|
||||
: parseInt(String(event.time || '0'), 10);
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
return {
|
||||
senderUin,
|
||||
time,
|
||||
random: meta?.random ?? 0,
|
||||
};
|
||||
}
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
if (meta) {
|
||||
return {
|
||||
senderUin: meta.targetId,
|
||||
senderUin: ref.selfId,
|
||||
time: meta.timestamp,
|
||||
random: meta.random,
|
||||
};
|
||||
@@ -219,7 +241,10 @@ export async function sendPrivateForwardMessage(
|
||||
meta?: ForwardPreviewMeta,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages);
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
|
||||
// userId is plumbed through so inner image/record/video can be uploaded
|
||||
// under the recipient's scene (otherwise the OIDB private-image upload
|
||||
// has no target uid and the element builder bails).
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes, undefined, userId);
|
||||
const previewElement = buildForwardPreviewElement(forwardId, nodes, false, meta);
|
||||
const receipt = await ref.bridge.sendPrivateMessage(userId, [previewElement]);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||
@@ -240,9 +265,12 @@ export async function sendPrivateForwardMessage(
|
||||
export async function uploadForwardMessage(
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
groupId?: number,
|
||||
): Promise<{ forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages);
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
|
||||
// groupId controls the resId namespace (group vs private). Without it,
|
||||
// a resId minted here is unusable when later sent into a group.
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
|
||||
return { forwardId };
|
||||
}
|
||||
|
||||
|
||||
@@ -9,11 +9,20 @@ export async function handleGroupAddRequest(
|
||||
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
|
||||
const parts = flag.split(':');
|
||||
if (parts.length < 3) throw new Error('invalid group request flag');
|
||||
const requestType = parts[0];
|
||||
const groupId = parseInt(parts[1], 10);
|
||||
const targetUid = parts.slice(2).join(':');
|
||||
if (!groupId) throw new Error('invalid group_id in flag');
|
||||
if (!targetUid) throw new Error('invalid request target in flag');
|
||||
|
||||
const requests = await bridge.fetchGroupRequests();
|
||||
const matching = requests.find(r => r.groupId === groupId);
|
||||
const matching = requests.find((r) => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
if (requestType === 'add') return r.targetUid === targetUid;
|
||||
if (requestType === 'invite') return r.invitorUid === targetUid;
|
||||
return false;
|
||||
}) || requests.find(r => r.groupId === groupId);
|
||||
|
||||
if (!matching) {
|
||||
throw new Error('matching group request not found');
|
||||
}
|
||||
|
||||
@@ -10,21 +10,24 @@ import {
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { executeQuickOperation } from './quick-operation';
|
||||
|
||||
const log = createLogger('OneBot.POST');
|
||||
const moduleLog = createLogger('OneBot.POST');
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private signature_: string;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.signature_ = bindingSignature(config);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
@@ -74,7 +77,9 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
if (!this.isEnabled) return;
|
||||
const json = pickDispatchJson(payload, this.options);
|
||||
if (json === null) return;
|
||||
void this.postEvent(json, event);
|
||||
void this.postEvent(json, event).catch((err) => {
|
||||
this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private async postEvent(payload: string, event: JsonObject): Promise<void> {
|
||||
@@ -106,11 +111,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.isEnabled) {
|
||||
log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,7 +126,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
if (!operation || typeof operation !== 'object') return;
|
||||
await executeQuickOperation(event, operation, this.ctx.api);
|
||||
} catch (error) {
|
||||
log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
this.log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,14 +12,21 @@ import {
|
||||
} from 'http';
|
||||
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.HTTP');
|
||||
const moduleLog = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
// HTTP server never receives events — `isActive` purely tracks the
|
||||
@@ -81,7 +88,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
this.server = server;
|
||||
|
||||
server.on('listening', () => {
|
||||
log.success(
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
@@ -90,7 +97,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
);
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
|
||||
@@ -136,19 +143,61 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
} else if (req.method === 'POST') {
|
||||
const bodyContent = await readRequestBody(req);
|
||||
if (bodyContent.trim()) {
|
||||
try {
|
||||
const parsedBody = JSON.parse(bodyContent);
|
||||
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
|
||||
if (parsedBody.action && !action) action = String(parsedBody.action);
|
||||
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
|
||||
params = parsedBody.params as Record<string, unknown>;
|
||||
} else {
|
||||
params = parsedBody as Record<string, unknown>;
|
||||
const contentType = req.headers['content-type'] ?? '';
|
||||
if (contentType.includes('application/x-www-form-urlencoded')) {
|
||||
const parsed = new URLSearchParams(bodyContent);
|
||||
parsed.forEach((value, key) => {
|
||||
try {
|
||||
params[key] = JSON.parse(value);
|
||||
} catch {
|
||||
params[key] = value;
|
||||
}
|
||||
echo = parsedBody.echo;
|
||||
});
|
||||
if (params.action && !action) {
|
||||
action = String(params.action);
|
||||
delete params.action;
|
||||
}
|
||||
} catch {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||||
if (params.echo !== undefined) {
|
||||
echo = params.echo;
|
||||
delete params.echo;
|
||||
}
|
||||
} else if (contentType.includes('application/json') || !contentType) {
|
||||
try {
|
||||
const parsedBody = JSON.parse(bodyContent);
|
||||
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
|
||||
if (parsedBody.action && !action) action = String(parsedBody.action);
|
||||
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
|
||||
params = parsedBody.params as Record<string, unknown>;
|
||||
} else {
|
||||
params = parsedBody as Record<string, unknown>;
|
||||
}
|
||||
echo = parsedBody.echo;
|
||||
}
|
||||
} catch {
|
||||
if (contentType.includes('application/json')) {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||||
return;
|
||||
}
|
||||
// 无 content-type,JSON 失败则 fallback 到 urlencoded
|
||||
const parsed = new URLSearchParams(bodyContent);
|
||||
parsed.forEach((value, key) => {
|
||||
try {
|
||||
params[key] = JSON.parse(value);
|
||||
} catch {
|
||||
params[key] = value;
|
||||
}
|
||||
});
|
||||
if (params.action && !action) {
|
||||
action = String(params.action);
|
||||
delete params.action;
|
||||
}
|
||||
if (params.echo !== undefined) {
|
||||
echo = params.echo;
|
||||
delete params.echo;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -200,4 +249,4 @@ function writeJson(res: ServerResponse, statusCode: number, data: unknown): void
|
||||
res.statusCode = statusCode;
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.end(JSON.stringify(data));
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,7 @@ import type { WebSocket } from '@snowluma/websocket';
|
||||
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
|
||||
export function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) return true;
|
||||
const rawAuth = request.headers.authorization;
|
||||
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
|
||||
const auth = request.headers.authorization ?? '';
|
||||
if (auth === `Bearer ${token}`) return true;
|
||||
try {
|
||||
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
|
||||
|
||||
@@ -13,11 +13,11 @@ import {
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.WS-Client');
|
||||
const moduleLog = createLogger('OneBot.WS-Client');
|
||||
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
|
||||
|
||||
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
@@ -26,11 +26,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
private explicitlyClosed = false;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.role = config.role ?? 'Universal';
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
@@ -111,12 +114,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
this.socket = socket;
|
||||
|
||||
socket.on('open', () => {
|
||||
log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
});
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, raw);
|
||||
void this.handleApiMessage(socket, raw).catch((err) => {
|
||||
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
@@ -126,7 +131,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
});
|
||||
|
||||
socket.on('error', (err: Error) => {
|
||||
log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -14,11 +14,11 @@ import {
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, parseRequestPath, rawDataToString, safeClose, safeSend, normalizePath } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.WS-Server');
|
||||
const moduleLog = createLogger('OneBot.WS-Server');
|
||||
|
||||
interface ForwardConn {
|
||||
socket: WebSocket;
|
||||
@@ -30,10 +30,13 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
@@ -114,7 +117,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
this.wss = wss;
|
||||
|
||||
wss.on('listening', () => {
|
||||
log.success(
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
@@ -124,7 +127,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
});
|
||||
|
||||
wss.on('error', (err: Error) => {
|
||||
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
|
||||
@@ -145,7 +148,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
});
|
||||
socket.on('close', () => this.connections.delete(socket));
|
||||
socket.on('error', (err: Error) => {
|
||||
log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
if (role === 'Event' || role === 'Universal') {
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// Identity-aware, one-line readable rendering for log output.
|
||||
//
|
||||
// Two layers consume this:
|
||||
// - bridge/packet-pipeline.ts → notice events (recall / join / poke / …)
|
||||
// - onebot/instance.ts → received-message log
|
||||
//
|
||||
// All formatters are defensive: any field lookup that throws falls
|
||||
// back to the raw numeric form, so a malformed event or stale
|
||||
// Identity cache never crashes the logger. Cache misses simply
|
||||
// degrade to the previous "just print the uin / groupId" output.
|
||||
|
||||
import type { IdentityService } from '../bridge/identity-service';
|
||||
import type { QQEventVariant } from '../bridge/events';
|
||||
import type { MessageStore } from '../onebot/message-store';
|
||||
import type { JsonObject, JsonValue } from '../onebot/types';
|
||||
|
||||
const MAX_TEXT_PREVIEW = 50;
|
||||
const MAX_REPLY_BODY_PREVIEW = 30;
|
||||
|
||||
/** "[群名(12345)]" if known, else "12345" (or "0" if missing). */
|
||||
export function formatGroup(identity: IdentityService, groupId: number): string {
|
||||
if (!groupId || groupId <= 0) return String(groupId || 0);
|
||||
try {
|
||||
const g = identity.findGroup(groupId);
|
||||
const name = g?.groupName?.trim();
|
||||
return name ? `[${name}(${groupId})]` : String(groupId);
|
||||
} catch {
|
||||
return String(groupId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "[card-or-nick(uin)]" when the uin is in the group-member or friend
|
||||
* roster; falls back to the bare uin string. When only a uid is known
|
||||
* (no uin yet) the uid is returned as-is so the line still references
|
||||
* someone — better than logging "0".
|
||||
*/
|
||||
export function formatUser(
|
||||
identity: IdentityService,
|
||||
groupId: number | undefined,
|
||||
uin: number,
|
||||
uid?: string,
|
||||
): string {
|
||||
try {
|
||||
if (!uin || uin <= 0) return uid ? uid : '0';
|
||||
if (groupId !== undefined && groupId > 0) {
|
||||
const member = identity.findGroupMember(groupId, uin);
|
||||
const name = member?.card?.trim() || member?.nickname?.trim();
|
||||
if (name) return `[${name}(${uin})]`;
|
||||
}
|
||||
const friend = identity.findFriend(uin);
|
||||
const fname = friend?.remark?.trim() || friend?.nickname?.trim();
|
||||
if (fname) return `[${fname}(${uin})]`;
|
||||
return String(uin);
|
||||
} catch {
|
||||
return String(uin);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line preview of an OneBot-shape message (array of segments or
|
||||
* raw string). Element rendering matches the existing logReceivedMessage
|
||||
* vocabulary so this is a drop-in replacement, with a few additions
|
||||
* (json / xml / markdown / forward / poke / file).
|
||||
*/
|
||||
export function formatMessageSegments(message: JsonValue): string {
|
||||
try {
|
||||
if (typeof message === 'string') {
|
||||
return truncate(message, MAX_TEXT_PREVIEW) || '[空消息]';
|
||||
}
|
||||
if (!Array.isArray(message)) return '[空消息]';
|
||||
const parts: string[] = [];
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const obj = seg as JsonObject;
|
||||
const type = String(obj.type ?? '');
|
||||
const data = (typeof obj.data === 'object' && obj.data !== null && !Array.isArray(obj.data))
|
||||
? obj.data as Record<string, unknown>
|
||||
: {};
|
||||
parts.push(renderSegment(type, data));
|
||||
}
|
||||
return parts.join(' ').trim() || '[空消息]';
|
||||
} catch {
|
||||
return '[消息渲染异常]';
|
||||
}
|
||||
}
|
||||
|
||||
function renderSegment(type: string, data: Record<string, unknown>): string {
|
||||
switch (type) {
|
||||
case 'text': return truncate(String(data.text ?? ''), MAX_TEXT_PREVIEW);
|
||||
case 'image': return '[图片]';
|
||||
case 'face': return '[表情]';
|
||||
case 'mface': return data.text ? `[${String(data.text)}]` : '[表情]';
|
||||
case 'at': return data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`;
|
||||
case 'reply': return `[回复:${data.id ?? ''}]`;
|
||||
case 'record': return '[语音]';
|
||||
case 'video': return '[视频]';
|
||||
case 'file': return data.file ? `[文件:${truncate(String(data.file), 20)}]` : '[文件]';
|
||||
case 'json': return '[JSON]';
|
||||
case 'xml': return '[XML]';
|
||||
case 'markdown': return '[Markdown]';
|
||||
case 'forward': return '[聊天记录]';
|
||||
case 'poke': return '[戳一戳]';
|
||||
default: return `[${type}]`;
|
||||
}
|
||||
}
|
||||
|
||||
function truncate(s: string, max: number): string {
|
||||
return s.length > max ? `${s.slice(0, max)}...` : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a `reply` segment's referenced message and return a short
|
||||
* "[回复 user: body...]" string. On miss (older than store retention,
|
||||
* never seen, lookup throws) falls back to "[回复:<id>]" so the chain
|
||||
* reference is at least preserved.
|
||||
*
|
||||
* Deliberately one level deep — we don't recurse into the reply's own
|
||||
* reply. Long chains aren't worth the runtime cost in the hot path,
|
||||
* and a 1-level peek catches 90% of real-world "what's this referring
|
||||
* to" questions.
|
||||
*/
|
||||
export function formatReply(
|
||||
messageStore: MessageStore,
|
||||
identity: IdentityService,
|
||||
replyId: number,
|
||||
): string {
|
||||
try {
|
||||
if (!replyId) return '[回复:0]';
|
||||
const event = messageStore.findEvent(replyId);
|
||||
if (!event) return `[回复:${replyId}]`;
|
||||
const isGroup = event.message_type === 'group';
|
||||
const uin = toIntOrZero(event.user_id);
|
||||
const groupId = isGroup ? toIntOrZero(event.group_id) : undefined;
|
||||
|
||||
// Prefer cache; if cache miss, use the sender fields baked into the
|
||||
// stored event itself (those came from the original receive path
|
||||
// when the roster was warm).
|
||||
let userPart = formatUser(identity, groupId, uin);
|
||||
if (userPart === String(uin) && uin > 0) {
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const fallback = ((sender.card as string) || (sender.nickname as string) || '').trim();
|
||||
if (fallback) userPart = `[${fallback}(${uin})]`;
|
||||
}
|
||||
|
||||
const body = truncate(formatMessageSegments(event.message as JsonValue), MAX_REPLY_BODY_PREVIEW);
|
||||
return `[回复 ${userPart}: ${body}]`;
|
||||
} catch {
|
||||
return `[回复:${replyId}]`;
|
||||
}
|
||||
}
|
||||
|
||||
function toIntOrZero(v: unknown): number {
|
||||
if (typeof v === 'number' && Number.isFinite(v)) return v;
|
||||
if (typeof v === 'string') {
|
||||
const n = Number.parseInt(v, 10);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Readable one-line rendering of a notice-class QQEventVariant. Returns
|
||||
* null for kinds the OneBot layer's message log already renders
|
||||
* (group_message / friend_message / temp_message / group_file_upload /
|
||||
* friend_add — those have richer dedicated paths).
|
||||
*/
|
||||
export function formatEvent(identity: IdentityService, event: QQEventVariant): string | null {
|
||||
try {
|
||||
switch (event.kind) {
|
||||
case 'group_message':
|
||||
case 'friend_message':
|
||||
case 'temp_message':
|
||||
case 'group_file_upload':
|
||||
case 'friend_add':
|
||||
return null;
|
||||
case 'group_recall':
|
||||
return `群撤回 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.authorUin)} 被 ${formatUser(identity, event.groupId, event.operatorUin)} 撤回`;
|
||||
case 'friend_recall':
|
||||
return `私聊撤回 ${formatUser(identity, undefined, event.userUin)} 撤回了消息`;
|
||||
case 'group_member_join':
|
||||
return `入群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} 加入 ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_member_leave':
|
||||
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${event.isKick ? '被踢出' : '退出'} ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_mute':
|
||||
return `禁言 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.duration}秒`;
|
||||
case 'group_admin':
|
||||
return `管理 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.set ? '+' : '-'}管理员`;
|
||||
case 'friend_poke':
|
||||
return `戳一戳 ${formatUser(identity, undefined, event.userUin)} -> ${formatUser(identity, undefined, event.targetUin)}`;
|
||||
case 'group_poke':
|
||||
return `群戳 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} -> ${formatUser(identity, event.groupId, event.targetUin)}`;
|
||||
case 'friend_request':
|
||||
return `好友请求 ${formatUser(identity, undefined, event.fromUin)}: ${event.message}`;
|
||||
case 'group_invite':
|
||||
return `群邀请 ${formatUser(identity, undefined, event.fromUin)} -> ${formatGroup(identity, event.groupId)}`;
|
||||
case 'group_essence':
|
||||
return `精华 ${formatGroup(identity, event.groupId)} | ${event.set ? '+' : '-'}精华`;
|
||||
case 'group_msg_emoji_like':
|
||||
return `表情回应 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.operatorUin, event.operatorUid)} ${event.isAdd ? '+' : '-'}[${event.emojiId}] msgSeq=${event.msgSeq}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
// File transport for the SnowLuma logger.
|
||||
//
|
||||
// Writes plain text (ANSI stripped) to:
|
||||
// <SNOWLUMA_LOG_DIR>/snowluma-YYYY-MM-DD.log (shared, all UINs)
|
||||
// <SNOWLUMA_LOG_DIR>/<uin>/snowluma-YYYY-MM-DD.log (per-account)
|
||||
//
|
||||
// Both pathways use the same daily rotation + per-file size cap. When the
|
||||
// cap is hit the in-flight file is closed and writes continue in
|
||||
// snowluma-YYYY-MM-DD.1.log, .2.log, ...
|
||||
// at the same date. Files older than the retain window are unlinked on
|
||||
// startup and on each day rollover.
|
||||
//
|
||||
// Disabled via SNOWLUMA_LOG_FILE=0. Per-UIN sub-files are additionally
|
||||
// gated by SNOWLUMA_LOG_PER_UIN=0 (still keeps the shared file). Any I/O
|
||||
// failure during init or write degrades silently to console-only — we
|
||||
// deliberately do NOT use the logger from inside this module to avoid
|
||||
// recursion.
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const DEFAULT_DIR = 'logs';
|
||||
const DEFAULT_MAX_MB = 50;
|
||||
const DEFAULT_RETAIN_DAYS = 7;
|
||||
const FILE_PREFIX = 'snowluma-';
|
||||
const FILE_SUFFIX = '.log';
|
||||
const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/;
|
||||
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
|
||||
// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit
|
||||
// multi-line records (stack traces), ESC is stripped through ANSI_RE.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g;
|
||||
|
||||
function parsePositiveInt(v: string | undefined, dflt: number): number {
|
||||
if (!v) return dflt;
|
||||
const n = Number.parseInt(v, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : dflt;
|
||||
}
|
||||
|
||||
function todayString(d: Date = new Date()): string {
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
function dateOf(s: string): Date {
|
||||
const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10));
|
||||
return new Date(y!, m! - 1, d!);
|
||||
}
|
||||
|
||||
function stripAnsi(line: string): string {
|
||||
return line.replace(ANSI_RE, '').replace(CTRL_RE, '');
|
||||
}
|
||||
|
||||
interface OpenFile {
|
||||
stream: fs.WriteStream;
|
||||
bytes: number;
|
||||
date: string;
|
||||
splitIndex: number;
|
||||
path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns one output directory: keeps at most one open WriteStream, handles
|
||||
* daily rollover, per-file size cap, and retention cleanup. The shared
|
||||
* top-level dir uses one of these; each per-UIN sub-dir gets its own.
|
||||
*/
|
||||
class FileWriter {
|
||||
private disabled = false;
|
||||
private file: OpenFile | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly dir: string,
|
||||
private readonly maxBytes: number,
|
||||
private readonly retainDays: number,
|
||||
) {
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
} catch (err) {
|
||||
this.disabled = true;
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
get isDisabled(): boolean {
|
||||
return this.disabled;
|
||||
}
|
||||
|
||||
get currentPath(): string | null {
|
||||
return this.file?.path ?? null;
|
||||
}
|
||||
|
||||
write(data: string, bytes: number): void {
|
||||
if (this.disabled) return;
|
||||
const today = todayString();
|
||||
this.ensureForToday(today);
|
||||
if (!this.file) return;
|
||||
|
||||
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
|
||||
this.rotateBySize();
|
||||
if (!this.file) return;
|
||||
}
|
||||
|
||||
this.file.stream.write(data);
|
||||
this.file.bytes += bytes;
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
const f = this.file;
|
||||
this.file = null;
|
||||
if (!f) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
f.stream.end(() => resolve());
|
||||
} catch {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ensureForToday(today: string): void {
|
||||
if (this.file && this.file.date === today) return;
|
||||
|
||||
if (this.file) {
|
||||
try {
|
||||
this.file.stream.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
this.file = null;
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
// Resume from the highest existing split index for today (so two
|
||||
// process starts on the same day share files / don't clobber).
|
||||
let idx = 0;
|
||||
while (fs.existsSync(this.pathFor(today, idx + 1))) idx++;
|
||||
this.file = this.openFile(today, idx);
|
||||
}
|
||||
|
||||
private rotateBySize(): void {
|
||||
if (!this.file) return;
|
||||
const date = this.file.date;
|
||||
try {
|
||||
this.file.stream.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
let next = this.file.splitIndex + 1;
|
||||
while (fs.existsSync(this.pathFor(date, next))) next++;
|
||||
this.file = this.openFile(date, next);
|
||||
}
|
||||
|
||||
private openFile(date: string, splitIndex: number): OpenFile | null {
|
||||
const p = this.pathFor(date, splitIndex);
|
||||
try {
|
||||
let bytes = 0;
|
||||
try {
|
||||
bytes = fs.statSync(p).size;
|
||||
} catch {
|
||||
/* file doesn't exist yet */
|
||||
}
|
||||
const stream = fs.createWriteStream(p, { flags: 'a' });
|
||||
stream.on('error', (err) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`[logger] file write error on ${p}: ${err.message}`);
|
||||
});
|
||||
return { stream, bytes, date, splitIndex, path: p };
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private pathFor(date: string, splitIndex: number): string {
|
||||
const tail = splitIndex > 0 ? `.${splitIndex}` : '';
|
||||
return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`);
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = fs.readdirSync(this.dir);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const retainMs = this.retainDays * 24 * 60 * 60 * 1000;
|
||||
const cutoff = Date.now() - retainMs;
|
||||
for (const name of entries) {
|
||||
const m = FILE_RE.exec(name);
|
||||
if (!m) continue;
|
||||
const dateStr = m[1]!;
|
||||
if (dateOf(dateStr).getTime() < cutoff) {
|
||||
try {
|
||||
fs.unlinkSync(path.join(this.dir, name));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class FileTransport {
|
||||
private readonly dir: string;
|
||||
private readonly maxBytes: number;
|
||||
private readonly retainDays: number;
|
||||
private readonly enabled: boolean;
|
||||
private readonly perUinEnabled: boolean;
|
||||
private shared: FileWriter | null = null;
|
||||
private perUin = new Map<number, FileWriter>();
|
||||
|
||||
constructor() {
|
||||
this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR;
|
||||
this.maxBytes =
|
||||
parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024;
|
||||
this.retainDays = parsePositiveInt(
|
||||
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
DEFAULT_RETAIN_DAYS,
|
||||
);
|
||||
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
|
||||
this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0';
|
||||
|
||||
if (this.enabled) {
|
||||
const w = new FileWriter(this.dir, this.maxBytes, this.retainDays);
|
||||
this.shared = w.isDisabled ? null : w;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when no file output will happen (env disable or init failure). */
|
||||
get isDisabled(): boolean {
|
||||
return !this.shared;
|
||||
}
|
||||
|
||||
/** Current shared-file path (or null if disabled / not yet opened). */
|
||||
get currentPath(): string | null {
|
||||
return this.shared?.currentPath ?? null;
|
||||
}
|
||||
|
||||
/** Path of the per-UIN file for the given UIN, if open. */
|
||||
perUinPath(uin: number): string | null {
|
||||
return this.perUin.get(uin)?.currentPath ?? null;
|
||||
}
|
||||
|
||||
write(line: string, uin?: number): void {
|
||||
if (!this.shared) return;
|
||||
const data = stripAnsi(line) + '\n';
|
||||
const bytes = Buffer.byteLength(data, 'utf8');
|
||||
|
||||
this.shared.write(data, bytes);
|
||||
|
||||
if (uin !== undefined && this.perUinEnabled) {
|
||||
let w = this.perUin.get(uin);
|
||||
if (!w) {
|
||||
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays);
|
||||
if (w.isDisabled) return;
|
||||
this.perUin.set(uin, w);
|
||||
}
|
||||
w.write(data, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const closes: Promise<void>[] = [];
|
||||
if (this.shared) closes.push(this.shared.close());
|
||||
for (const w of this.perUin.values()) closes.push(w.close());
|
||||
this.shared = null;
|
||||
this.perUin.clear();
|
||||
await Promise.all(closes);
|
||||
}
|
||||
}
|
||||
|
||||
let singleton: FileTransport | null = null;
|
||||
|
||||
export function getFileTransport(): FileTransport {
|
||||
if (!singleton) singleton = new FileTransport();
|
||||
return singleton;
|
||||
}
|
||||
|
||||
/** Reset state between tests. Closes all active file handles. */
|
||||
export async function _resetFileTransportForTesting(): Promise<void> {
|
||||
if (singleton) await singleton.close();
|
||||
singleton = null;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Compact one-line param summary for log output.
|
||||
//
|
||||
// OneBot action params can include large message arrays / nested
|
||||
// payloads that would blow the line width to multiple kilobytes if we
|
||||
// JSON.stringify them naively. This helper produces a flat
|
||||
// `k1=v1 k2=v2 ...` rendering with per-field truncation and a hard
|
||||
// total cap, designed to be grep-friendly without flooding the log
|
||||
// file.
|
||||
|
||||
const MAX_FIELD = 40;
|
||||
const MAX_TOTAL = 200;
|
||||
|
||||
function valueRepr(v: unknown): string {
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) return `[len=${v.length}]`;
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a params object as a single line for logging. Skips deep
|
||||
* traversal: nested objects collapse to `{...}`, arrays to `[len=N]`.
|
||||
* Strings are quoted; long ones are truncated with an ellipsis.
|
||||
*
|
||||
* Output is capped at MAX_TOTAL chars; on overflow the tail is
|
||||
* replaced with `...` so the next field doesn't get half-rendered.
|
||||
*/
|
||||
export function summarizeParams(params: unknown): string {
|
||||
if (params === null || params === undefined) return '{}';
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
|
||||
}
|
||||
if (Array.isArray(params)) return `[len=${params.length}]`;
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v)}`;
|
||||
// +1 accounts for the separating space we'd insert when joining.
|
||||
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
|
||||
out.push('...');
|
||||
break;
|
||||
}
|
||||
out.push(entry);
|
||||
total += entry.length + (out.length > 1 ? 1 : 0);
|
||||
}
|
||||
return out.join(' ');
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
@@ -7,14 +8,26 @@ export interface LogEntry {
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogOptions {
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// Fixed-width slot for the UIN tag in rendered output so the [Scope]
|
||||
// column stays vertically aligned across lines with and without a UIN.
|
||||
// Width covers `[1234567890]` (12 chars); anything longer just won't pad.
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
debug: 10,
|
||||
info: 20,
|
||||
@@ -55,10 +68,32 @@ function resolveMinLevel(): LogLevel {
|
||||
return 'info';
|
||||
}
|
||||
|
||||
const MIN_LEVEL = resolveMinLevel();
|
||||
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
|
||||
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
|
||||
// Only governs console + ring buffer + subscribers; the file
|
||||
// transport always sees debug-and-up regardless.
|
||||
let currentLevel: LogLevel = resolveMinLevel();
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[MIN_LEVEL];
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the console / subscriber level at runtime. Invalid input is
|
||||
* a no-op (returns false). File transport is unaffected — it always
|
||||
* sees every level so post-mortems remain useful.
|
||||
*/
|
||||
export function setLogLevel(level: string): boolean {
|
||||
const lower = String(level).toLowerCase();
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
}
|
||||
|
||||
function useColor(): boolean {
|
||||
@@ -78,43 +113,72 @@ function currentTime(): string {
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, scope: string, args: unknown[]): string {
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
const message = format(...args);
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} [${scope}] ${message}`;
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${scope}]`);
|
||||
return `${cTs} ${cLabel} ${cScope} ${message}`;
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
|
||||
}
|
||||
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
if (!shouldLog(level)) return;
|
||||
// Console / subscriber level filter. File output is debug-and-up always;
|
||||
// see log-file-transport.ts.
|
||||
const passesConsole = shouldLog(level);
|
||||
const message = format(...args);
|
||||
const line = render(level, options.scope, args);
|
||||
const line = render(level, options, args);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
message,
|
||||
line,
|
||||
};
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. ESC (0x1B) is preserved so the
|
||||
// ANSI color sequences emitted by render() actually reach the terminal.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
stream.write(line.replace(/[\x00-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
|
||||
if (passesConsole) {
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// File transport always sees every level (debug-and-up) for post-mortem
|
||||
// value; ANSI stripping happens inside the transport. UIN routes the
|
||||
// line to its per-account sub-file in addition to the shared one.
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush and close the underlying log file. Call from shutdown hooks
|
||||
* (SIGINT / SIGTERM / uncaughtException) so the WriteStream's internal
|
||||
* buffer makes it to disk. Returns a promise that resolves once the OS
|
||||
* has finalized the write.
|
||||
*/
|
||||
export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
@@ -135,15 +199,33 @@ export interface Logger {
|
||||
success: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number; [k: string]: unknown }) => Logger;
|
||||
}
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createLogger(scope: string): Logger {
|
||||
const options: LogOptions = { scope };
|
||||
return {
|
||||
debug: (...args: unknown[]) => emit('debug', options, args),
|
||||
info: (...args: unknown[]) => emit('info', options, args),
|
||||
success: (...args: unknown[]) => emit('success', options, args),
|
||||
warn: (...args: unknown[]) => emit('warn', options, args),
|
||||
error: (...args: unknown[]) => emit('error', options, args),
|
||||
};
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('WebUI.Auth');
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const WEBUI_CONFIG_PATH = path.join(CONFIG_DIR, 'webui.json');
|
||||
@@ -21,6 +24,16 @@ export function isDevAuthMode(): boolean {
|
||||
return process.env.SNOWLUMA_DEV_MODE === '1';
|
||||
}
|
||||
|
||||
function envBootstrapPassword(): string | null {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
|
||||
if (!raw || typeof raw !== 'string') return null;
|
||||
// Minimum sanity: avoid accidental empty / 1-char seeds. Strength
|
||||
// rules still don't apply because we want trusted launchers to be
|
||||
// able to pick a high-entropy random secret (e.g. base64(16)).
|
||||
if (raw.length < 8) return null;
|
||||
return raw;
|
||||
}
|
||||
|
||||
export interface WebuiAuthState {
|
||||
passwordHash: string; // hex
|
||||
passwordSalt: string; // hex
|
||||
@@ -84,6 +97,16 @@ function generateInitialState(initialPassword: string): WebuiAuthState {
|
||||
};
|
||||
}
|
||||
|
||||
function backupCorruptConfig(): void {
|
||||
try {
|
||||
const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`;
|
||||
fs.renameSync(WEBUI_CONFIG_PATH, dest);
|
||||
log.warn('previous webui.json moved to %s', dest);
|
||||
} catch (err) {
|
||||
log.warn('failed to back up corrupt webui.json: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(state: WebuiAuthState): void {
|
||||
ensureConfigDir();
|
||||
const tmp = WEBUI_CONFIG_PATH + '.tmp';
|
||||
@@ -128,12 +151,50 @@ export class WebuiAuth {
|
||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (isValidState(parsed)) {
|
||||
if (parsed.mustChangePassword) {
|
||||
// Previous start generated a bootstrap password but the operator
|
||||
// never completed the forced-change flow. The plaintext is gone
|
||||
// (only the hash is on disk, and the log line from last run may
|
||||
// be lost), so rotate to a fresh CSPRNG password they can see.
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
log.warn('previous bootstrap password was never rotated; regenerated a new one');
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
return new WebuiAuth(parsed, null, false);
|
||||
}
|
||||
} catch {
|
||||
/* fallthrough — regenerate */
|
||||
log.error('webui.json schema invalid; backing up and regenerating credentials');
|
||||
backupCorruptConfig();
|
||||
} catch (err) {
|
||||
log.error(
|
||||
'webui.json is corrupt and will be regenerated; the previous file is backed up: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
backupCorruptConfig();
|
||||
}
|
||||
}
|
||||
// SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD lets a trusted launcher seed the
|
||||
// password on first run instead of having to scrape it from logs.
|
||||
// Effect: write webui.json with the env-provided password, hashed,
|
||||
// and mustChangePassword=false. Only honoured when there is NO existing
|
||||
// webui.json — once persisted, password changes happen via the UI.
|
||||
const envPassword = envBootstrapPassword();
|
||||
if (envPassword !== null) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(envPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
atomicWrite(state);
|
||||
log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD');
|
||||
return new WebuiAuth(state, null, false);
|
||||
}
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Resolve the request's "real" client IP for per-IP rate limiting.
|
||||
//
|
||||
// Threat model:
|
||||
// - By default we ONLY trust the TCP socket peer. `X-Forwarded-For` and
|
||||
// `X-Real-IP` are client-controllable, so honoring them lets any
|
||||
// client rotate the header to escape the 5-attempts/15-min login
|
||||
// lockout.
|
||||
// - Operators who actually run behind a reverse proxy (nginx, Caddy,
|
||||
// a SaaS CDN) need a way to opt back into the real client IP. The
|
||||
// `SNOWLUMA_WEBUI_TRUST_PROXY` env var lets them say "when the
|
||||
// immediate TCP peer is THIS, treat the headers as authoritative".
|
||||
//
|
||||
// Supported values for SNOWLUMA_WEBUI_TRUST_PROXY:
|
||||
// - unset / empty — default; ignore headers, use socket peer
|
||||
// - "loopback" — trust headers when the socket peer is 127.0.0.1
|
||||
// or ::1 (typical for nginx/Caddy on the same host)
|
||||
// - "1" / "true" / — trust headers from any peer (only safe behind a
|
||||
// "all" trusted SaaS CDN that strips client-set headers)
|
||||
// - comma-separated — trust headers when the socket peer matches one
|
||||
// IP list of these IPs (reverse proxy on another machine)
|
||||
//
|
||||
// When trusted, we prefer X-Real-IP (a single value the reverse proxy
|
||||
// overwrites unconditionally) and fall back to the first hop of
|
||||
// X-Forwarded-For. We never parse the FULL XFF chain — if the proxy
|
||||
// chain isn't fully trusted, the leftmost value can still be spoofed
|
||||
// by the original client, and a single-tier proxy is the only setup
|
||||
// this app realistically sees.
|
||||
|
||||
import type { Context } from 'hono';
|
||||
import { getConnInfo } from '@hono/node-server/conninfo';
|
||||
|
||||
export type TrustProxyMode =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'loopback' }
|
||||
| { kind: 'all' }
|
||||
| { kind: 'ip-list'; ips: Set<string> };
|
||||
|
||||
export function parseTrustProxy(raw: string | undefined): TrustProxyMode {
|
||||
const value = raw?.trim().toLowerCase() ?? '';
|
||||
if (!value) return { kind: 'none' };
|
||||
if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' };
|
||||
if (value === 'loopback') return { kind: 'loopback' };
|
||||
const ips = new Set(
|
||||
value.split(',').map((s) => s.trim()).filter(Boolean),
|
||||
);
|
||||
if (ips.size === 0) return { kind: 'none' };
|
||||
return { kind: 'ip-list', ips };
|
||||
}
|
||||
|
||||
export function describeTrustProxy(mode: TrustProxyMode): string {
|
||||
switch (mode.kind) {
|
||||
case 'none': return 'socket peer (default)';
|
||||
case 'all': return 'X-Real-IP / X-Forwarded-For from any peer';
|
||||
case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
|
||||
case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
|
||||
}
|
||||
}
|
||||
|
||||
function isLoopback(ip: string): boolean {
|
||||
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
|
||||
}
|
||||
|
||||
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
|
||||
switch (mode.kind) {
|
||||
case 'none': return false;
|
||||
case 'all': return true;
|
||||
case 'loopback': return isLoopback(socketIp);
|
||||
case 'ip-list': return mode.ips.has(socketIp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the right "client IP" for rate-limit keying.
|
||||
*
|
||||
* Exposed as a pure function over a small dependency surface so the
|
||||
* unit tests can fabricate request shapes without spinning up a server.
|
||||
*/
|
||||
export function pickClientIp(
|
||||
c: Pick<Context, 'req'>,
|
||||
mode: TrustProxyMode,
|
||||
getSocketIp: () => string,
|
||||
): string {
|
||||
const socketIp = (() => {
|
||||
try { return getSocketIp() || '127.0.0.1'; }
|
||||
catch { return '127.0.0.1'; }
|
||||
})();
|
||||
|
||||
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
|
||||
|
||||
const realIp = c.req.header('x-real-ip')?.trim();
|
||||
if (realIp) return realIp;
|
||||
const xff = c.req.header('x-forwarded-for');
|
||||
if (xff) {
|
||||
const first = xff.split(',')[0].trim();
|
||||
if (first) return first;
|
||||
}
|
||||
return socketIp;
|
||||
}
|
||||
|
||||
/** Convenience binding for the live server: read socket via getConnInfo. */
|
||||
export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string {
|
||||
return (c) => pickClientIp(c, mode, () => {
|
||||
try { return getConnInfo(c).remote.address ?? '127.0.0.1'; }
|
||||
catch { return '127.0.0.1'; }
|
||||
});
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
import { serve } from '@hono/node-server';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import { Hono } from 'hono';
|
||||
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
|
||||
import { Hono, type Context } from 'hono';
|
||||
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '../utils/logger';
|
||||
import { randomBytes } from 'crypto';
|
||||
import type { OneBotManager } from '../onebot/manager';
|
||||
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
||||
import type { OneBotConfig } from '../onebot/types';
|
||||
import type { HookManager } from '../hook/hook-manager';
|
||||
import type { HookManager, HookProcessInfo } from '../hook/hook-manager';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
@@ -40,6 +41,14 @@ const MUST_CHANGE_ALLOWLIST = new Set([
|
||||
'/api/logout',
|
||||
]);
|
||||
|
||||
// Endpoints that may authenticate via `?token=` query parameter. Only the
|
||||
// SSE log stream is here because EventSource cannot set custom headers; all
|
||||
// other endpoints MUST use the Authorization header so tokens never leak
|
||||
// into access logs / Referer / browser history.
|
||||
const TOKEN_QUERY_ALLOWLIST = new Set([
|
||||
'/api/logs/stream',
|
||||
]);
|
||||
|
||||
// uin = QQ number; 5–12 digits. Used to construct config file paths,
|
||||
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
|
||||
const UIN_REGEX = /^\d{5,12}$/;
|
||||
@@ -51,11 +60,19 @@ function purgeExpiredTokens() {
|
||||
for (const [token, info] of sessionTokens) {
|
||||
if (now > info.expiresAt) sessionTokens.delete(token);
|
||||
}
|
||||
for (const [ip, attempt] of loginAttempts) {
|
||||
if (now > attempt.resetAt) loginAttempts.delete(ip);
|
||||
}
|
||||
}
|
||||
|
||||
function getClientIp(req: Request): string {
|
||||
return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1';
|
||||
}
|
||||
/**
|
||||
* Resolve the client IP for per-IP rate limiting. Default is the TCP
|
||||
* socket peer (cannot be spoofed by the client). Operators behind a
|
||||
* reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env
|
||||
* var; see `./client-ip.ts` for the accepted values.
|
||||
*/
|
||||
const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY);
|
||||
const getClientIp = makeClientIpResolver(trustProxyMode);
|
||||
|
||||
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
|
||||
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
|
||||
@@ -81,14 +98,44 @@ export async function initWebUI(
|
||||
log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword);
|
||||
log.warn('dev mode skips config/webui.json and password rotation');
|
||||
} else if (initialPassword) {
|
||||
log.info('════════════════════════════════════════════════════════════════');
|
||||
log.info(' ★ WebUI 初始登录凭据 / Initial WebUI Credentials ★');
|
||||
log.info(' 请立即登录并修改密码 —— 关闭程序后此密码无法找回。');
|
||||
log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。');
|
||||
log.info(' Log in and change the password now; it will not be shown again.');
|
||||
log.info('────────────────────────────────────────────────────────────────');
|
||||
log.info('initial credentials: user=admin password=%s', initialPassword);
|
||||
log.info('password change required after first login');
|
||||
log.info('════════════════════════════════════════════════════════════════');
|
||||
} else if (auth.mustChangePassword()) {
|
||||
log.warn('password change is still required');
|
||||
}
|
||||
log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode));
|
||||
if (trustProxyMode.kind === 'all') {
|
||||
log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For');
|
||||
}
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
// ─── Anti-indexing ───────────────────────────────────────────────────────
|
||||
// The WebUI is an admin surface that has no business showing up in
|
||||
// search results — even the login page leaks the existence of a
|
||||
// SnowLuma instance to anyone scanning the IP. Three overlapping
|
||||
// signals: a hard X-Robots-Tag on every response, a robots.txt for
|
||||
// crawlers that read it before pages, and a <meta robots> in the
|
||||
// SPA shell for the case where a proxy strips headers.
|
||||
app.use('*', async (c, next) => {
|
||||
await next();
|
||||
c.res.headers.set(
|
||||
'X-Robots-Tag',
|
||||
'noindex, nofollow, noarchive, nosnippet, noimageindex',
|
||||
);
|
||||
});
|
||||
|
||||
app.get('/robots.txt', (c) => {
|
||||
c.res.headers.set('Content-Type', 'text/plain; charset=utf-8');
|
||||
return c.body('User-agent: *\nDisallow: /\n');
|
||||
});
|
||||
|
||||
// ─── Auth middleware ─────────────────────────────────────────────────────
|
||||
app.use('/api/*', async (c, next) => {
|
||||
const reqPath = c.req.path;
|
||||
@@ -96,11 +143,10 @@ export async function initWebUI(
|
||||
|
||||
const authHeader = c.req.header('Authorization');
|
||||
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
|
||||
const queryToken = c.req.query('token') ?? '';
|
||||
const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : '';
|
||||
const token = bearerToken || queryToken;
|
||||
if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
|
||||
|
||||
purgeExpiredTokens();
|
||||
const info = sessionTokens.get(token);
|
||||
if (!info || Date.now() > info.expiresAt) {
|
||||
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
|
||||
@@ -114,9 +160,14 @@ export async function initWebUI(
|
||||
await next();
|
||||
});
|
||||
|
||||
// Periodic janitor — keeps sessionTokens / loginAttempts from growing
|
||||
// unbounded and replaces the per-request O(n) sweep we used to do.
|
||||
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
|
||||
tokenJanitor.unref?.();
|
||||
|
||||
// ─── Login ───────────────────────────────────────────────────────────────
|
||||
app.post('/api/login', async (c) => {
|
||||
const ip = getClientIp(c.req.raw);
|
||||
const ip = getClientIp(c);
|
||||
const now = Date.now();
|
||||
const attempt = loginAttempts.get(ip);
|
||||
if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) {
|
||||
@@ -140,7 +191,6 @@ export async function initWebUI(
|
||||
}
|
||||
|
||||
loginAttempts.delete(ip);
|
||||
purgeExpiredTokens();
|
||||
const token = randomBytes(32).toString('hex');
|
||||
const mustChange = auth.mustChangePassword();
|
||||
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
|
||||
@@ -196,20 +246,15 @@ export async function initWebUI(
|
||||
try {
|
||||
auth.setPassword(newPassword);
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 400);
|
||||
log.warn('change password failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '密码修改失败' }, 400);
|
||||
}
|
||||
// Invalidate all other sessions; current keeps but loses must-change flag.
|
||||
const currentToken = c.get('sessionToken' as never) as string | undefined;
|
||||
for (const [tok, info] of sessionTokens) {
|
||||
if (tok === currentToken) {
|
||||
info.mustChangePassword = false;
|
||||
sessionTokens.set(tok, info);
|
||||
} else {
|
||||
sessionTokens.delete(tok);
|
||||
}
|
||||
}
|
||||
log.info('password updated');
|
||||
return c.json({ success: true });
|
||||
// Invalidate every session, including the current one. If the old
|
||||
// password was compromised, the attacker may already hold the current
|
||||
// token; rotating credentials must rotate sessions too.
|
||||
sessionTokens.clear();
|
||||
log.info('password updated; all sessions invalidated');
|
||||
return c.json({ success: true, requireRelogin: true });
|
||||
});
|
||||
|
||||
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
|
||||
@@ -315,27 +360,53 @@ export async function initWebUI(
|
||||
return c.json({ list: getRecentLogs(limit) });
|
||||
});
|
||||
|
||||
app.get('/api/logs/level', (c) => {
|
||||
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
|
||||
});
|
||||
|
||||
app.post('/api/logs/level', async (c) => {
|
||||
const body = await c.req.json().catch(() => null) as { level?: unknown } | null;
|
||||
const next = typeof body?.level === 'string' ? body.level : '';
|
||||
if (!setLogLevel(next)) {
|
||||
return c.json({ message: `invalid level: ${next}`, levels: [...LOG_LEVELS] }, 400);
|
||||
}
|
||||
log.info('console log level set to %s via WebUI', getLogLevel());
|
||||
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
|
||||
});
|
||||
|
||||
app.get('/api/logs/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
let heartbeat: NodeJS.Timeout | undefined;
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
unsubscribe?.();
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const safeEnqueue = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try {
|
||||
controller.enqueue(chunk);
|
||||
} catch {
|
||||
// The peer dropped between abort and the next enqueue —
|
||||
// treat as end-of-stream so we don't leak listeners.
|
||||
teardown();
|
||||
}
|
||||
};
|
||||
const send = (event: unknown) => {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
};
|
||||
send({ type: 'ready' });
|
||||
const unsubscribe = subscribeLogs((entry) => send(entry));
|
||||
const heartbeat = setInterval(() => {
|
||||
controller.enqueue(encoder.encode(': heartbeat\n\n'));
|
||||
unsubscribe = subscribeLogs((entry) => send(entry));
|
||||
heartbeat = setInterval(() => {
|
||||
safeEnqueue(encoder.encode(': heartbeat\n\n'));
|
||||
}, 15000);
|
||||
c.req.raw.signal.addEventListener('abort', () => {
|
||||
clearInterval(heartbeat);
|
||||
unsubscribe();
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
});
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
@@ -356,62 +427,43 @@ export async function initWebUI(
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/processes/:pid/load', async (c) => {
|
||||
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||
const pid = Number(c.req.param('pid'));
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
const processInfo = await hookManager.loadProcess(pid);
|
||||
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/processes/:pid/unload', async (c) => {
|
||||
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||
const pid = Number(c.req.param('pid'));
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
const processInfo = await hookManager.unloadProcess(pid);
|
||||
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/processes/:pid/refresh', async (c) => {
|
||||
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||
const pid = Number(c.req.param('pid'));
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
const processInfo = await hookManager.refreshProcess(pid);
|
||||
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
|
||||
}
|
||||
});
|
||||
// Per-process action handler. The three routes below differ only in
|
||||
// which HookManager method they call.
|
||||
const MAX_PID = 4_194_304;
|
||||
function processAction(label: string, action: (pid: number) => Promise<HookProcessInfo>) {
|
||||
return async (c: Context) => {
|
||||
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||
const pid = Number(c.req.param('pid'));
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
const processInfo = await action(pid);
|
||||
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||
} catch (err) {
|
||||
log.warn('%s pid=%d failed: %s', label, pid, err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '操作失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
};
|
||||
}
|
||||
app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid)));
|
||||
app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid)));
|
||||
app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid)));
|
||||
|
||||
app.get('/api/config/:uin', (c) => {
|
||||
const uin = c.req.param('uin');
|
||||
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
|
||||
// Read-only: never write defaults to disk on a GET. The persisted
|
||||
// file is created when manager.onSessionStarted boots an instance
|
||||
// or when the operator POSTs from this very endpoint.
|
||||
const config = loadOneBotConfig(uin);
|
||||
return c.json({
|
||||
...config,
|
||||
config,
|
||||
});
|
||||
return c.json({ config });
|
||||
});
|
||||
|
||||
app.post('/api/config/:uin', async (c) => {
|
||||
const uin = c.req.param('uin');
|
||||
if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400);
|
||||
try {
|
||||
const uin = c.req.param('uin');
|
||||
if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400);
|
||||
const body = (await c.req.json()) as OneBotConfig;
|
||||
saveOneBotConfig(uin, body);
|
||||
const reloaded = oneBotManager.reloadConfig(uin);
|
||||
@@ -422,7 +474,8 @@ export async function initWebUI(
|
||||
message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。',
|
||||
});
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: String(err) }, 400);
|
||||
log.warn('save config for uin=%s failed: %s', uin, err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '配置保存失败,请检查服务器日志' }, 400);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ vi.mock('../../src/bridge/highway/utils', () => ({
|
||||
})),
|
||||
computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })),
|
||||
computeMd5: vi.fn(() => new Uint8Array(16)),
|
||||
FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024,
|
||||
}));
|
||||
|
||||
import * as oidb from '../../src/bridge/bridge-oidb';
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
// Tests for ApiHandler's central dispatch logging.
|
||||
// Verifies that every action call emits a debug entry line, failures
|
||||
// fold into a warn line with stack, and unknown actions are surfaced.
|
||||
// Also covers the summarizeParams helper used to keep the entry log
|
||||
// from blowing the line width.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { ApiHandler } from '../src/onebot/api-handler';
|
||||
import { subscribeLogs, type LogEntry } from '../src/utils/logger';
|
||||
import { summarizeParams } from '../src/utils/log-summary';
|
||||
|
||||
// Minimal context — we never reach the real action handlers; we
|
||||
// register our own via registerAction.
|
||||
function emptyContext(): any {
|
||||
return {
|
||||
bridge: {},
|
||||
getLoginInfo: () => ({ userId: 0, nickname: '' }),
|
||||
isOnline: () => true,
|
||||
getMessage: () => null,
|
||||
getMessageMeta: () => null,
|
||||
sendPrivateMessage: async () => ({ messageId: 0 }),
|
||||
sendGroupMessage: async () => ({ messageId: 0 }),
|
||||
deleteMessage: async () => {},
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
getFriendList: async () => [],
|
||||
getImageInfo: async () => null,
|
||||
getRecordInfo: async () => null,
|
||||
};
|
||||
}
|
||||
|
||||
let captured: LogEntry[];
|
||||
let unsub: () => void;
|
||||
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.SNOWLUMA_LOG_LEVEL = 'debug';
|
||||
captured = [];
|
||||
unsub = subscribeLogs((e) => captured.push(e));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
unsub();
|
||||
if (savedLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_LEVEL = savedLogLevel;
|
||||
});
|
||||
|
||||
describe('summarizeParams', () => {
|
||||
it('renders flat scalar fields as k=v pairs', () => {
|
||||
const out = summarizeParams({ group_id: 12345, auto_escape: false, foo: 'bar' });
|
||||
expect(out).toBe('group_id=12345 auto_escape=false foo="bar"');
|
||||
});
|
||||
|
||||
it('truncates long string values with an ellipsis', () => {
|
||||
const long = 'x'.repeat(80);
|
||||
const out = summarizeParams({ s: long });
|
||||
expect(out).toMatch(/^s="x{40}\.\.\."$/);
|
||||
});
|
||||
|
||||
it('collapses arrays and nested objects rather than dumping them', () => {
|
||||
const out = summarizeParams({ messages: [1, 2, 3, 4], meta: { a: 1, b: 2 } });
|
||||
expect(out).toBe('messages=[len=4] meta={...}');
|
||||
});
|
||||
|
||||
it('caps the total line and tags the cut with ellipsis', () => {
|
||||
const params: Record<string, number> = {};
|
||||
for (let i = 0; i < 30; i++) params[`field_with_some_padding_${i}`] = i;
|
||||
const out = summarizeParams(params);
|
||||
expect(out.length).toBeLessThan(220);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
});
|
||||
|
||||
it('handles null / undefined inputs gracefully', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ApiHandler dispatch logging', () => {
|
||||
it('emits a debug entry under [Bridge.Action] when an action is called', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('echo', async () => ({ status: 'ok', retcode: 0, data: null }));
|
||||
|
||||
await handler.handle('echo', { group_id: 67890, message: [1, 2, 3] });
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.uin).toBe(12345);
|
||||
expect(entry!.message).toContain('echo');
|
||||
expect(entry!.message).toContain('group_id=67890');
|
||||
expect(entry!.message).toContain('message=[len=3]');
|
||||
});
|
||||
|
||||
it('emits a warn line with the error stack when the handler throws', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 12345);
|
||||
handler.registerAction('boom', async () => {
|
||||
throw new Error('kapow');
|
||||
});
|
||||
|
||||
const result = await handler.handle('boom', {});
|
||||
expect(result.status).toBe('failed');
|
||||
|
||||
const warn = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'warn');
|
||||
expect(warn).toBeDefined();
|
||||
expect(warn!.message).toContain('boom');
|
||||
expect(warn!.message).toContain('kapow');
|
||||
// stack contains the test file path; just check that something stack-shaped is appended
|
||||
expect(warn!.message).toMatch(/at\s+/);
|
||||
});
|
||||
|
||||
it('logs unknown actions at debug level', async () => {
|
||||
const handler = new ApiHandler(emptyContext(), 99);
|
||||
await handler.handle('not_a_real_action', {});
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.message.includes('unknown action'));
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.level).toBe('debug');
|
||||
});
|
||||
|
||||
it('falls back to the module-level logger (no uin slot) when uin is omitted', async () => {
|
||||
const handler = new ApiHandler(emptyContext());
|
||||
handler.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: null }));
|
||||
|
||||
await handler.handle('ping', {});
|
||||
|
||||
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.uin).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -45,7 +45,7 @@ describe('loadOneBotConfig', () => {
|
||||
|
||||
it('creates and persists default config when none exists', () => {
|
||||
const uin = '10001';
|
||||
const config = loadOneBotConfig(uin);
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
expect(config.networks.httpServers).toHaveLength(1);
|
||||
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'));
|
||||
@@ -74,7 +74,7 @@ describe('loadOneBotConfig', () => {
|
||||
};
|
||||
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify(legacy), 'utf8');
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
expect(config.networks.httpServers).toHaveLength(1);
|
||||
expect(config.networks.httpServers[0].port).toBe(3100);
|
||||
expect(config.networks.httpServers[0].accessToken).toBe('tok');
|
||||
@@ -128,6 +128,34 @@ describe('loadOneBotConfig', () => {
|
||||
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
|
||||
});
|
||||
|
||||
it('does not write to disk by default (read-only contract)', () => {
|
||||
const uin = '10006';
|
||||
const cfgPath = path.join(tempDir, 'config', `onebot_${uin}.json`);
|
||||
|
||||
// Default call must not materialize the file or mint a fresh access token.
|
||||
const config = loadOneBotConfig(uin);
|
||||
expect(config.networks.httpServers).toHaveLength(1);
|
||||
expect(fs.existsSync(cfgPath)).toBe(false);
|
||||
|
||||
// Explicit opt-in still writes.
|
||||
loadOneBotConfig(uin, { persistDefaults: true });
|
||||
expect(fs.existsSync(cfgPath)).toBe(true);
|
||||
});
|
||||
|
||||
it('respects an operator-emptied adapter list instead of seeding defaults back', () => {
|
||||
const uin = '10007';
|
||||
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: [] },
|
||||
musicSignUrl: '',
|
||||
}), 'utf8');
|
||||
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
expect(config.networks.httpServers).toEqual([]);
|
||||
expect(config.networks.wsServers).toEqual([]);
|
||||
});
|
||||
|
||||
it('migrates legacy lowercase WsRole values into canonical uppercase form', () => {
|
||||
const uin = '10005';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
// Tests for utils/event-format.ts.
|
||||
//
|
||||
// Each formatter is defensive about cache misses / malformed input —
|
||||
// these tests cover both the happy paths (resolves names from
|
||||
// Identity / MessageStore) and the degraded paths (falls back to the
|
||||
// raw uin / groupId without crashing).
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
formatEvent,
|
||||
formatGroup,
|
||||
formatMessageSegments,
|
||||
formatReply,
|
||||
formatUser,
|
||||
} from '../src/utils/event-format';
|
||||
import type { QQEventVariant } from '../src/bridge/events';
|
||||
|
||||
// ─── Test fakes (just the find* surface event-format uses) ───
|
||||
|
||||
function fakeIdentity(opts: {
|
||||
groups?: Record<number, { groupName: string }>;
|
||||
members?: Record<string, { uin: number; card?: string; nickname?: string }>;
|
||||
friends?: Record<number, { uin: number; nickname?: string; remark?: string }>;
|
||||
} = {}): any {
|
||||
return {
|
||||
findGroup: (gid: number) => opts.groups?.[gid] ?? null,
|
||||
findGroupMember: (gid: number, uin: number) => opts.members?.[`${gid}/${uin}`] ?? null,
|
||||
findFriend: (uin: number) => opts.friends?.[uin] ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function fakeMessageStore(events: Record<number, Record<string, unknown>>): any {
|
||||
return {
|
||||
findEvent: (id: number) => events[id] ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
describe('formatGroup', () => {
|
||||
it('renders [groupName(id)] when the group is in cache', () => {
|
||||
const id = fakeIdentity({ groups: { 123: { groupName: 'TestGroup' } } });
|
||||
expect(formatGroup(id, 123)).toBe('[TestGroup(123)]');
|
||||
});
|
||||
|
||||
it('falls back to bare id on cache miss', () => {
|
||||
const id = fakeIdentity();
|
||||
expect(formatGroup(id, 123)).toBe('123');
|
||||
});
|
||||
|
||||
it('handles 0 / missing group id without crashing', () => {
|
||||
const id = fakeIdentity();
|
||||
expect(formatGroup(id, 0)).toBe('0');
|
||||
});
|
||||
|
||||
it('falls back to bare id if findGroup throws', () => {
|
||||
const id = { findGroup: () => { throw new Error('db dead'); } } as any;
|
||||
expect(formatGroup(id, 123)).toBe('123');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatUser', () => {
|
||||
it('prefers group-member card over nickname', () => {
|
||||
const id = fakeIdentity({ members: { '1/100': { uin: 100, card: 'Card', nickname: 'Nick' } } });
|
||||
expect(formatUser(id, 1, 100)).toBe('[Card(100)]');
|
||||
});
|
||||
|
||||
it('falls back to nickname when card is empty', () => {
|
||||
const id = fakeIdentity({ members: { '1/100': { uin: 100, card: '', nickname: 'Nick' } } });
|
||||
expect(formatUser(id, 1, 100)).toBe('[Nick(100)]');
|
||||
});
|
||||
|
||||
it('falls back to friend list when not a group member', () => {
|
||||
const id = fakeIdentity({ friends: { 100: { uin: 100, nickname: 'FriendNick' } } });
|
||||
expect(formatUser(id, undefined, 100)).toBe('[FriendNick(100)]');
|
||||
});
|
||||
|
||||
it('prefers friend remark over nickname', () => {
|
||||
const id = fakeIdentity({ friends: { 100: { uin: 100, nickname: 'A', remark: 'B' } } });
|
||||
expect(formatUser(id, undefined, 100)).toBe('[B(100)]');
|
||||
});
|
||||
|
||||
it('falls back to uin on full cache miss', () => {
|
||||
const id = fakeIdentity();
|
||||
expect(formatUser(id, 1, 100)).toBe('100');
|
||||
});
|
||||
|
||||
it('falls back to uid when only uid is available', () => {
|
||||
const id = fakeIdentity();
|
||||
expect(formatUser(id, undefined, 0, 'u_abc')).toBe('u_abc');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatMessageSegments', () => {
|
||||
it('renders text segments and truncates beyond 50 chars', () => {
|
||||
const long = 'a'.repeat(80);
|
||||
expect(formatMessageSegments([{ type: 'text', data: { text: long } }]))
|
||||
.toBe(`${'a'.repeat(50)}...`);
|
||||
});
|
||||
|
||||
it('handles known media types and at/reply', () => {
|
||||
const out = formatMessageSegments([
|
||||
{ type: 'text', data: { text: 'hi' } },
|
||||
{ type: 'image', data: {} },
|
||||
{ type: 'at', data: { qq: 12345 } },
|
||||
{ type: 'at', data: { qq: 'all' } },
|
||||
{ type: 'reply', data: { id: 999 } },
|
||||
{ type: 'face', data: {} },
|
||||
{ type: 'video', data: {} },
|
||||
{ type: 'record', data: {} },
|
||||
]);
|
||||
expect(out).toBe('hi [图片] @12345 @全体成员 [回复:999] [表情] [视频] [语音]');
|
||||
});
|
||||
|
||||
it('renders unknown segment types as [type]', () => {
|
||||
expect(formatMessageSegments([{ type: 'something_new', data: {} }]))
|
||||
.toBe('[something_new]');
|
||||
});
|
||||
|
||||
it('renders a string message as text (truncated)', () => {
|
||||
expect(formatMessageSegments('hello')).toBe('hello');
|
||||
expect(formatMessageSegments('a'.repeat(60))).toBe(`${'a'.repeat(50)}...`);
|
||||
});
|
||||
|
||||
it('returns [空消息] for empty arrays / non-array / null', () => {
|
||||
expect(formatMessageSegments([])).toBe('[空消息]');
|
||||
expect(formatMessageSegments(null as any)).toBe('[空消息]');
|
||||
expect(formatMessageSegments({} as any)).toBe('[空消息]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatReply', () => {
|
||||
it('renders the resolved sender + body preview when the original is in the store', () => {
|
||||
const store = fakeMessageStore({
|
||||
42: {
|
||||
message_type: 'group',
|
||||
group_id: 1,
|
||||
user_id: 100,
|
||||
sender: { card: 'OrigSender' },
|
||||
message: [{ type: 'text', data: { text: '早安' } }],
|
||||
},
|
||||
});
|
||||
const id = fakeIdentity({ members: { '1/100': { uin: 100, card: 'OrigSender' } } });
|
||||
expect(formatReply(store, id, 42)).toBe('[回复 [OrigSender(100)]: 早安]');
|
||||
});
|
||||
|
||||
it('falls back to [回复:<id>] when the original is missing', () => {
|
||||
const store = fakeMessageStore({});
|
||||
const id = fakeIdentity();
|
||||
expect(formatReply(store, id, 9999)).toBe('[回复:9999]');
|
||||
});
|
||||
|
||||
it('uses the sender baked into the stored event when cache misses', () => {
|
||||
const store = fakeMessageStore({
|
||||
42: {
|
||||
message_type: 'private',
|
||||
user_id: 100,
|
||||
sender: { nickname: 'StoredNick' },
|
||||
message: [{ type: 'text', data: { text: 'hi' } }],
|
||||
},
|
||||
});
|
||||
const id = fakeIdentity(); // no cache
|
||||
expect(formatReply(store, id, 42)).toBe('[回复 [StoredNick(100)]: hi]');
|
||||
});
|
||||
|
||||
it('truncates the body preview to 30 chars', () => {
|
||||
const store = fakeMessageStore({
|
||||
42: {
|
||||
message_type: 'private',
|
||||
user_id: 100,
|
||||
sender: { nickname: 'X' },
|
||||
message: [{ type: 'text', data: { text: 'a'.repeat(80) } }],
|
||||
},
|
||||
});
|
||||
const id = fakeIdentity();
|
||||
const out = formatReply(store, id, 42);
|
||||
// Inner text gets truncated to 50 by formatMessageSegments, then to 30 here
|
||||
expect(out).toContain('...');
|
||||
expect(out.length).toBeLessThan(80);
|
||||
});
|
||||
|
||||
it('returns the fallback when findEvent throws', () => {
|
||||
const store = { findEvent: () => { throw new Error('store dead'); } } as any;
|
||||
const id = fakeIdentity();
|
||||
expect(formatReply(store, id, 42)).toBe('[回复:42]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatEvent', () => {
|
||||
const id = fakeIdentity({
|
||||
groups: { 1: { groupName: 'Grp' } },
|
||||
members: {
|
||||
'1/100': { uin: 100, card: 'Alice' },
|
||||
'1/200': { uin: 200, card: 'Bob' },
|
||||
'1/300': { uin: 300, nickname: 'Carol' },
|
||||
},
|
||||
friends: {
|
||||
500: { uin: 500, nickname: 'FriendA' },
|
||||
600: { uin: 600, nickname: 'FriendB' },
|
||||
},
|
||||
});
|
||||
|
||||
it('returns null for kinds rendered elsewhere', () => {
|
||||
expect(formatEvent(id, { kind: 'group_message' } as QQEventVariant)).toBeNull();
|
||||
expect(formatEvent(id, { kind: 'friend_message' } as QQEventVariant)).toBeNull();
|
||||
expect(formatEvent(id, { kind: 'temp_message' } as QQEventVariant)).toBeNull();
|
||||
});
|
||||
|
||||
it('renders group_recall with all three name slots', () => {
|
||||
expect(formatEvent(id, {
|
||||
kind: 'group_recall',
|
||||
groupId: 1, authorUin: 100, operatorUin: 200,
|
||||
} as QQEventVariant))
|
||||
.toBe('群撤回 [Grp(1)] | [Alice(100)] 被 [Bob(200)] 撤回');
|
||||
});
|
||||
|
||||
it('renders group_member_join with group name and joiner', () => {
|
||||
expect(formatEvent(id, {
|
||||
kind: 'group_member_join',
|
||||
groupId: 1, userUin: 300, userUid: '',
|
||||
} as QQEventVariant))
|
||||
.toBe('入群 [Carol(300)] 加入 [Grp(1)]');
|
||||
});
|
||||
|
||||
it('renders group_poke with both endpoints', () => {
|
||||
expect(formatEvent(id, {
|
||||
kind: 'group_poke',
|
||||
groupId: 1, userUin: 100, targetUin: 200,
|
||||
} as QQEventVariant))
|
||||
.toBe('群戳 [Grp(1)] | [Alice(100)] -> [Bob(200)]');
|
||||
});
|
||||
|
||||
it('renders friend_poke without group context', () => {
|
||||
expect(formatEvent(id, {
|
||||
kind: 'friend_poke',
|
||||
userUin: 500, targetUin: 600,
|
||||
} as QQEventVariant))
|
||||
.toBe('戳一戳 [FriendA(500)] -> [FriendB(600)]');
|
||||
});
|
||||
|
||||
it('degrades to numeric IDs when nothing is cached', () => {
|
||||
const empty = fakeIdentity();
|
||||
expect(formatEvent(empty, {
|
||||
kind: 'group_recall',
|
||||
groupId: 1, authorUin: 100, operatorUin: 200,
|
||||
} as QQEventVariant))
|
||||
.toBe('群撤回 1 | 100 被 200 撤回');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
// Tests for the Event0x2DC subType=16 (GroupMsgEmojiLike) end-to-end:
|
||||
// - decoder strips the 7-byte prefix and decodes GroupReactNotify
|
||||
// - field13==35 yields a GroupMsgEmojiLikeEvent
|
||||
// - field13!=35 surfaces under MsgPush.Unknown and emits nothing
|
||||
// - converter shape matches the gocqhttp / NapCat extension layout
|
||||
// - formatEvent prints something readable in the [Event] log
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { protoEncode } from '../src/protobuf/decode';
|
||||
import { GroupReactNotifySchema } from '../src/bridge/proto/notify';
|
||||
import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc';
|
||||
import type { MsgPushContext } from '../src/bridge/msg-push/context';
|
||||
import { IdentityService } from '../src/bridge/identity-service';
|
||||
import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '../src/bridge/events';
|
||||
import { convertGroupMsgEmojiLike } from '../src/onebot/event-converter/to-notice';
|
||||
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/onebot/message-id';
|
||||
import { formatEvent } from '../src/utils/event-format';
|
||||
import { subscribeLogs, type LogEntry } from '../src/utils/logger';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
const GROUP_ID = 123456789;
|
||||
|
||||
function makeIdentity(): IdentityService {
|
||||
return IdentityService.memory(SELF_UIN);
|
||||
}
|
||||
|
||||
/** Build the raw bytes QQ would push into ctx.content for subType=16:
|
||||
* a 7-byte magic prefix followed by an encoded GroupReactNotify. */
|
||||
function buildReactContent(notify: Record<string, unknown>): Uint8Array {
|
||||
const prefix = new Uint8Array([0, 0, 0, 0, 0, 0, 0]);
|
||||
const body = protoEncode(notify as never, GroupReactNotifySchema);
|
||||
const out = new Uint8Array(prefix.length + body.length);
|
||||
out.set(prefix, 0);
|
||||
out.set(body, prefix.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext {
|
||||
return {
|
||||
head: { msgType: 732, subType: 16, sequence: 0, timestamp: 1735000000, msgId: 0 },
|
||||
fromUin: 0,
|
||||
fromUid: '',
|
||||
selfUin: Number(SELF_UIN),
|
||||
content,
|
||||
body: undefined,
|
||||
responseHead: undefined,
|
||||
identity,
|
||||
};
|
||||
}
|
||||
|
||||
describe('decodeEvent0x2DC subType=16 — GroupMsgEmojiLike', () => {
|
||||
it('decodes a field13=35 react add into a GroupMsgEmojiLikeEvent', () => {
|
||||
const content = buildReactContent({
|
||||
groupUin: BigInt(GROUP_ID),
|
||||
field13: 35,
|
||||
groupReactionData: {
|
||||
data: {
|
||||
data: {
|
||||
groupReactionTarget: { seq: 4242n },
|
||||
groupReactionDataContent: {
|
||||
code: '76',
|
||||
count: 1,
|
||||
operatorUid: 'u_operator_xxx',
|
||||
type: 1, // add
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
|
||||
expect(event).toBeDefined();
|
||||
expect(event.kind).toBe('group_msg_emoji_like');
|
||||
expect(event.groupId).toBe(GROUP_ID);
|
||||
expect(event.operatorUid).toBe('u_operator_xxx');
|
||||
expect(event.emojiId).toBe('76');
|
||||
expect(event.msgSeq).toBe(4242);
|
||||
expect(event.count).toBe(1);
|
||||
expect(event.isAdd).toBe(true);
|
||||
});
|
||||
|
||||
it('decodes type=2 as react remove (isAdd=false)', () => {
|
||||
const content = buildReactContent({
|
||||
groupUin: BigInt(GROUP_ID),
|
||||
field13: 35,
|
||||
groupReactionData: {
|
||||
data: {
|
||||
data: {
|
||||
groupReactionTarget: { seq: 1n },
|
||||
groupReactionDataContent: {
|
||||
code: '⭐',
|
||||
count: 1,
|
||||
operatorUid: 'u_x',
|
||||
type: 2,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
|
||||
expect(event.isAdd).toBe(false);
|
||||
expect(event.emojiId).toBe('⭐');
|
||||
});
|
||||
|
||||
it('drops the packet and logs to MsgPush.Unknown when field13 is not 35', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
|
||||
const content = buildReactContent({
|
||||
groupUin: BigInt(GROUP_ID),
|
||||
field13: 99, // not 35
|
||||
groupReactionData: {
|
||||
data: { data: { groupReactionDataContent: { code: 'x', operatorUid: 'u_y' } } },
|
||||
},
|
||||
});
|
||||
|
||||
const result = decodeEvent0x2DC(makeCtx(content));
|
||||
unsub();
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
const unknown = captured.find((e) =>
|
||||
e.scope === 'MsgPush.Unknown' && /field13=99/.test(e.message));
|
||||
expect(unknown).toBeDefined();
|
||||
});
|
||||
|
||||
it('returns empty when content is shorter than the prefix length', () => {
|
||||
const tooShort = new Uint8Array([1, 2, 3]); // < 7 bytes
|
||||
expect(decodeEvent0x2DC(makeCtx(tooShort))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertGroupMsgEmojiLike — OneBot notice shape', () => {
|
||||
const baseEvent: GroupMsgEmojiLikeEvent = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: 1735000000,
|
||||
selfUin: 10001,
|
||||
groupId: 123456789,
|
||||
operatorUin: 99999,
|
||||
operatorUid: 'u_x',
|
||||
msgSeq: 4242,
|
||||
emojiId: '76',
|
||||
count: 1,
|
||||
isAdd: true,
|
||||
};
|
||||
|
||||
// Real production wiring puts a hashMessageIdInt32-based resolver
|
||||
// on the ctx; mirror that so message_id is the same value the
|
||||
// bot would have minted for the original message.
|
||||
const ctx = {
|
||||
selfId: 10001,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: (_isGroup: boolean, sessionId: number, sequence: number, eventName: string) =>
|
||||
hashMessageIdInt32(sequence, sessionId, eventName),
|
||||
mediaSegmentSink: null,
|
||||
} as never;
|
||||
|
||||
it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', () => {
|
||||
const out = convertGroupMsgEmojiLike(ctx, baseEvent);
|
||||
expect(out.post_type).toBe('notice');
|
||||
expect(out.notice_type).toBe('group_msg_emoji_like');
|
||||
expect(out.sub_type).toBe('add');
|
||||
expect(out.group_id).toBe(123456789);
|
||||
expect(out.user_id).toBe(99999);
|
||||
expect(out.operator_id).toBe(99999);
|
||||
expect(out.message_seq).toBe(4242);
|
||||
expect(out.message_id).toBe(hashMessageIdInt32(4242, 123456789, GROUP_MESSAGE_EVENT));
|
||||
expect(out.likes).toEqual([{ emoji_id: '76', count: 1 }]);
|
||||
});
|
||||
|
||||
it('flips sub_type to remove when isAdd is false', () => {
|
||||
const out = convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false });
|
||||
expect(out.sub_type).toBe('remove');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatEvent — group_msg_emoji_like', () => {
|
||||
let savedLevel: string | undefined;
|
||||
beforeEach(() => { savedLevel = process.env.SNOWLUMA_LOG_LEVEL; });
|
||||
afterEach(() => {
|
||||
if (savedLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_LEVEL = savedLevel;
|
||||
});
|
||||
|
||||
it('renders a one-line summary with group, operator and emoji id', () => {
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.rememberGroups([{
|
||||
groupId: GROUP_ID, groupName: 'TestGroup', remark: '',
|
||||
memberCount: 1, memberMax: 500, members: new Map(),
|
||||
}]);
|
||||
identity.rememberGroupMembers(GROUP_ID, [{
|
||||
uin: 99999, uid: 'u_x', nickname: 'Alice', card: '',
|
||||
role: 'member', level: 0, title: '',
|
||||
joinTime: 0, lastSentTime: 0, shutUpTime: 0,
|
||||
}]);
|
||||
|
||||
const event: QQEventVariant = {
|
||||
kind: 'group_msg_emoji_like',
|
||||
time: 0, selfUin: Number(SELF_UIN),
|
||||
groupId: GROUP_ID,
|
||||
operatorUin: 99999, operatorUid: 'u_x',
|
||||
msgSeq: 100, emojiId: '76', count: 1, isAdd: true,
|
||||
};
|
||||
|
||||
const line = formatEvent(identity, event);
|
||||
expect(line).toBeDefined();
|
||||
expect(line).toContain('TestGroup');
|
||||
expect(line).toContain('Alice');
|
||||
expect(line).toContain('[76]');
|
||||
expect(line).toContain('msgSeq=100');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils';
|
||||
|
||||
describe('highway source paths', () => {
|
||||
@@ -26,3 +26,76 @@ describe('highway source paths', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadBinarySource maxBytes enforcement', () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('rejects HTTP downloads larger than maxBytes via streaming, even without Content-Length', async () => {
|
||||
// Streamed chunk-encoded response: no Content-Length, totals > cap.
|
||||
const chunkSize = 4 * 1024;
|
||||
const totalChunks = 16;
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
for (let i = 0; i < totalChunks; i++) controller.enqueue(new Uint8Array(chunkSize));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
globalThis.fetch = vi.fn(async () => new Response(stream, {
|
||||
status: 200,
|
||||
headers: { /* no content-length */ },
|
||||
})) as typeof fetch;
|
||||
|
||||
// Cap below total: 16*4096 = 65536, cap 32 KiB → should throw mid-stream.
|
||||
await expect(
|
||||
loadBinarySource('https://example.test/big.bin', 'test', 32 * 1024),
|
||||
).rejects.toThrow(/too large/);
|
||||
});
|
||||
|
||||
it('rejects HTTP downloads when Content-Length already exceeds maxBytes', async () => {
|
||||
globalThis.fetch = vi.fn(async () => new Response(new Uint8Array(0), {
|
||||
status: 200,
|
||||
headers: { 'content-length': String(10 * 1024 * 1024) },
|
||||
})) as typeof fetch;
|
||||
|
||||
await expect(
|
||||
loadBinarySource('https://example.test/big.bin', 'test', 1024),
|
||||
).rejects.toThrow(/too large: 10485760/);
|
||||
});
|
||||
|
||||
it('accepts a streamed download that fits inside maxBytes', async () => {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
controller.enqueue(new Uint8Array([4, 5]));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
globalThis.fetch = vi.fn(async () => new Response(stream, { status: 200 })) as typeof fetch;
|
||||
|
||||
const loaded = await loadBinarySource('https://example.test/small.bin', 'test', 1024);
|
||||
expect(Array.from(loaded.bytes)).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('rejects oversized local files via fs.stat before reading them', async () => {
|
||||
const filePath = path.join(os.tmpdir(), `snowluma-binary-cap-${process.pid}-${Date.now()}.bin`);
|
||||
fs.writeFileSync(filePath, Buffer.alloc(128));
|
||||
try {
|
||||
await expect(
|
||||
loadBinarySource(filePath, 'test', 64),
|
||||
).rejects.toThrow(/too large: 128 > 64/);
|
||||
} finally {
|
||||
try { fs.unlinkSync(filePath); } catch { /* ignore */ }
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects oversized base64 payloads', async () => {
|
||||
const big = Buffer.alloc(128).toString('base64');
|
||||
await expect(
|
||||
loadBinarySource(`base64://${big}`, 'test', 64),
|
||||
).rejects.toThrow(/too large: 128 > 64/);
|
||||
});
|
||||
});
|
||||
@@ -254,6 +254,34 @@ describe('HookSession — unload', () => {
|
||||
expect(info.status).toBe('connecting');
|
||||
expect(info.error).toContain('命名管道仍然存在');
|
||||
});
|
||||
|
||||
it('forces a fresh tick before verifying so a stale snapshot does not false-flag a successful unload', async () => {
|
||||
// Reproduces the Windows-WebUI bug: PipeWatcher's cached snapshot is
|
||||
// up to 1500ms stale, so right after a successful native unload the
|
||||
// pre-fix code would read isPipeLive() == true and report failure
|
||||
// even though the DLL is gone. With the fix, tickNow() refreshes
|
||||
// the snapshot first and verification correctly sees the pipe down.
|
||||
const pid = 5555;
|
||||
let pipeLive = true; // initial cached state: pipe is live
|
||||
const tickNow = vi.fn(async () => { pipeLive = false; }); // OS poll says: gone now
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => new FakeClient() as unknown as QqHookClient,
|
||||
pipeWatcher: { isPipeLive: () => pipeLive, tickNow },
|
||||
});
|
||||
await session.load();
|
||||
pipeLive = true; // ensure the pre-check snapshot says "live"
|
||||
|
||||
const info = await session.unload();
|
||||
|
||||
expect(tickNow).toHaveBeenCalledOnce();
|
||||
expect(info.status).toBe('available');
|
||||
expect(info.error).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — serialization', () => {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// Tests for HTTP server adapter content-type parsing (POST body).
|
||||
// Covers: application/x-www-form-urlencoded, application/json,
|
||||
// no content-type fallback, and unsupported content-type rejection.
|
||||
|
||||
import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest';
|
||||
import http from 'http';
|
||||
import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter';
|
||||
import type { NetworkAdapterContext } from '../src/onebot/network/adapter';
|
||||
import type { HttpServerNetwork } from '../src/onebot/types';
|
||||
|
||||
// ─── Helpers ───
|
||||
|
||||
function fakeCtx(handleFn: (action: string, params: Record<string, unknown>) => unknown): NetworkAdapterContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
api: {
|
||||
handle: vi.fn(async (action: string, params: Record<string, unknown>) => {
|
||||
const data = handleFn(action, params);
|
||||
return { status: 'ok', retcode: 0, data };
|
||||
}),
|
||||
} as any,
|
||||
buildLifecycleEvent: vi.fn(() => ({})),
|
||||
buildHeartbeatEvent: vi.fn(() => ({})),
|
||||
};
|
||||
}
|
||||
|
||||
function post(port: number, path: string, body: string, headers: Record<string, string> = {}): Promise<{ status: number; body: any }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request({ hostname: '127.0.0.1', port, path, method: 'POST', headers }, (res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (c) => chunks.push(c));
|
||||
res.on('end', () => {
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
try {
|
||||
resolve({ status: res.statusCode!, body: JSON.parse(raw) });
|
||||
} catch {
|
||||
resolve({ status: res.statusCode!, body: raw });
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end(body);
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Tests ───
|
||||
|
||||
describe('HttpServerAdapter content-type parsing', () => {
|
||||
let adapter: HttpServerAdapter;
|
||||
let handleFn: ReturnType<typeof vi.fn<(action: string, params: Record<string, unknown>) => unknown>>;
|
||||
const PORT = 19876;
|
||||
|
||||
beforeAll(async () => {
|
||||
handleFn = vi.fn((_action: string, params: Record<string, unknown>) => params);
|
||||
const ctx = fakeCtx(handleFn);
|
||||
const config: HttpServerNetwork = { name: 'test-http', port: PORT, enabled: true, messageFormat: 'array', reportSelfMessage: false };
|
||||
adapter = new HttpServerAdapter('test-http', config, ctx);
|
||||
adapter.open();
|
||||
// Wait for server to be listening
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
adapter.close();
|
||||
});
|
||||
|
||||
it('should parse application/json body', async () => {
|
||||
const res = await post(PORT, '/send_message', JSON.stringify({ params: { group_id: 123, message: 'hi' } }), {
|
||||
'content-type': 'application/json',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('ok');
|
||||
expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 123, message: 'hi' });
|
||||
});
|
||||
|
||||
it('should parse application/x-www-form-urlencoded body', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'group_id=456&message=hello';
|
||||
const res = await post(PORT, '/send_message', body, {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe('ok');
|
||||
expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 456, message: 'hello' });
|
||||
});
|
||||
|
||||
it('should JSON-parse values in urlencoded body', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'user_id=789&data={"nested":true}';
|
||||
const res = await post(PORT, '/get_info', body, {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(handleFn).toHaveBeenCalledWith('get_info', { user_id: 789, data: { nested: true } });
|
||||
});
|
||||
|
||||
it('should extract action from urlencoded body when path has no action', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'action=get_status&key=value';
|
||||
const res = await post(PORT, '/', body, {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(handleFn).toHaveBeenCalledWith('get_status', { key: 'value' });
|
||||
});
|
||||
|
||||
it('should extract echo from urlencoded body', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'action=test_action&echo=12345&foo=bar';
|
||||
const res = await post(PORT, '/', body, {
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.echo).toBe(12345);
|
||||
expect(handleFn).toHaveBeenCalledWith('test_action', { foo: 'bar' });
|
||||
});
|
||||
|
||||
it('should reject unsupported content-type with 400', async () => {
|
||||
const res = await post(PORT, '/send_message', '<xml></xml>', {
|
||||
'content-type': 'application/xml',
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.wording).toContain('unsupported content-type');
|
||||
});
|
||||
|
||||
it('should reject invalid JSON with explicit application/json content-type', async () => {
|
||||
const res = await post(PORT, '/send_message', 'not-json{{{', {
|
||||
'content-type': 'application/json',
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.wording).toContain('invalid json');
|
||||
});
|
||||
|
||||
it('should fallback to urlencoded when no content-type and body is not valid JSON', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = 'action=fallback_action¶m1=value1';
|
||||
const res = await post(PORT, '/', body, {});
|
||||
expect(res.status).toBe(200);
|
||||
expect(handleFn).toHaveBeenCalledWith('fallback_action', { param1: 'value1' });
|
||||
});
|
||||
|
||||
it('should parse JSON when no content-type and body is valid JSON', async () => {
|
||||
handleFn.mockClear();
|
||||
const body = JSON.stringify({ action: 'json_action', params: { x: 1 } });
|
||||
const res = await post(PORT, '/', body, {});
|
||||
expect(res.status).toBe(200);
|
||||
expect(handleFn).toHaveBeenCalledWith('json_action', { x: 1 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
// Tests for the file transport that backs the SnowLuma logger.
|
||||
// Each test gets its own tmp dir and a fresh FileTransport so env / state
|
||||
// from one test never bleeds into another.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { FileTransport } from '../src/utils/log-file-transport';
|
||||
|
||||
let tmpDir: string;
|
||||
const ENV_KEYS = [
|
||||
'SNOWLUMA_LOG_FILE',
|
||||
'SNOWLUMA_LOG_DIR',
|
||||
'SNOWLUMA_LOG_MAX_MB',
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
] as const;
|
||||
const savedEnv: Record<string, string | undefined> = {};
|
||||
|
||||
function setEnv(env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>): void {
|
||||
for (const [k, v] of Object.entries(env)) {
|
||||
if (v === undefined) delete process.env[k];
|
||||
else process.env[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
function listLogFiles(dir: string): string[] {
|
||||
return fs.readdirSync(dir).filter((f) => f.endsWith('.log')).sort();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const k of ENV_KEYS) savedEnv[k] = process.env[k];
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-log-'));
|
||||
setEnv({
|
||||
SNOWLUMA_LOG_DIR: tmpDir,
|
||||
SNOWLUMA_LOG_FILE: '1',
|
||||
SNOWLUMA_LOG_MAX_MB: '1',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '7',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const k of ENV_KEYS) {
|
||||
if (savedEnv[k] === undefined) delete process.env[k];
|
||||
else process.env[k] = savedEnv[k];
|
||||
}
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('FileTransport', () => {
|
||||
it('creates today\'s file and writes a single line', async () => {
|
||||
const t = new FileTransport();
|
||||
t.write('hello world');
|
||||
await t.close();
|
||||
|
||||
const files = listLogFiles(tmpDir);
|
||||
expect(files).toHaveLength(1);
|
||||
expect(files[0]).toMatch(/^snowluma-\d{4}-\d{2}-\d{2}\.log$/);
|
||||
expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8')).toBe('hello world\n');
|
||||
});
|
||||
|
||||
it('strips ANSI color escapes and ASCII control chars before writing', async () => {
|
||||
const t = new FileTransport();
|
||||
t.write('\x1b[36mINFO\x1b[0m \x07[Bridge] msg');
|
||||
await t.close();
|
||||
|
||||
const [file] = listLogFiles(tmpDir);
|
||||
expect(fs.readFileSync(path.join(tmpDir, file!), 'utf8')).toBe('INFO [Bridge] msg\n');
|
||||
});
|
||||
|
||||
it('rolls into a .1 file when the current file exceeds the size cap', async () => {
|
||||
// 1MB cap from beforeEach. Write ~2 MB to force a single rotation.
|
||||
const t = new FileTransport();
|
||||
const oneKB = 'x'.repeat(1023); // +1 byte newline = 1024
|
||||
for (let i = 0; i < 2048; i++) t.write(oneKB);
|
||||
await t.close();
|
||||
|
||||
const files = listLogFiles(tmpDir);
|
||||
expect(files.length).toBeGreaterThanOrEqual(2);
|
||||
const base = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.log$/.test(f));
|
||||
const split = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.1\.log$/.test(f));
|
||||
expect(base).toBeDefined();
|
||||
expect(split).toBeDefined();
|
||||
});
|
||||
|
||||
it('opens a new file when the day rolls over mid-process', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0));
|
||||
const t = new FileTransport();
|
||||
t.write('day-one line');
|
||||
vi.setSystemTime(new Date(2026, 4, 19, 0, 0, 1));
|
||||
t.write('day-two line');
|
||||
await t.close();
|
||||
|
||||
const files = listLogFiles(tmpDir);
|
||||
expect(files).toContain('snowluma-2026-05-18.log');
|
||||
expect(files).toContain('snowluma-2026-05-19.log');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8'))
|
||||
.toContain('day-one line');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8'))
|
||||
.toContain('day-two line');
|
||||
});
|
||||
|
||||
it('deletes files older than the retention window on startup', async () => {
|
||||
const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log');
|
||||
fs.writeFileSync(stalePath, 'stale\n');
|
||||
const t = new FileTransport();
|
||||
t.write('fresh');
|
||||
await t.close();
|
||||
|
||||
expect(fs.existsSync(stalePath)).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps files inside the retention window', async () => {
|
||||
const recent = new Date();
|
||||
recent.setDate(recent.getDate() - 2);
|
||||
const recentName = `snowluma-${recent.getFullYear()}-${String(recent.getMonth() + 1).padStart(2, '0')}-${String(recent.getDate()).padStart(2, '0')}.log`;
|
||||
const recentPath = path.join(tmpDir, recentName);
|
||||
fs.writeFileSync(recentPath, 'recent\n');
|
||||
|
||||
const t = new FileTransport();
|
||||
await t.close();
|
||||
|
||||
expect(fs.existsSync(recentPath)).toBe(true);
|
||||
});
|
||||
|
||||
it('SNOWLUMA_LOG_FILE=0 suppresses all file output', async () => {
|
||||
setEnv({ SNOWLUMA_LOG_FILE: '0' });
|
||||
const t = new FileTransport();
|
||||
t.write('should not be written');
|
||||
await t.close();
|
||||
|
||||
expect(t.isDisabled).toBe(true);
|
||||
expect(listLogFiles(tmpDir)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('appends to the existing today file across restarts', async () => {
|
||||
const a = new FileTransport();
|
||||
a.write('before restart');
|
||||
await a.close();
|
||||
|
||||
const b = new FileTransport();
|
||||
b.write('after restart');
|
||||
await b.close();
|
||||
|
||||
const files = listLogFiles(tmpDir);
|
||||
expect(files).toHaveLength(1);
|
||||
expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8'))
|
||||
.toBe('before restart\nafter restart\n');
|
||||
});
|
||||
|
||||
it('exposes the current file path while open', () => {
|
||||
const t = new FileTransport();
|
||||
t.write('x');
|
||||
expect(t.currentPath).not.toBeNull();
|
||||
expect(t.currentPath!).toMatch(/snowluma-\d{4}-\d{2}-\d{2}\.log$/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
// Tests for the core logger API:
|
||||
// - createLogger() output shape (scope rendering)
|
||||
// - .child({ uin }) derivation and the [UIN] slot in the rendered line
|
||||
// - LogEntry.uin propagation to subscribers
|
||||
// - File transport per-UIN fan-out (and the SNOWLUMA_LOG_PER_UIN=0 gate)
|
||||
//
|
||||
// We exercise the file transport via its real fs paths against tmpdirs
|
||||
// so the test catches integration regressions, not just unit shape.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createLogger, getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '../src/utils/logger';
|
||||
import { _resetFileTransportForTesting } from '../src/utils/log-file-transport';
|
||||
|
||||
let tmpDir: string;
|
||||
const ENV_KEYS = [
|
||||
'SNOWLUMA_LOG_FILE',
|
||||
'SNOWLUMA_LOG_PER_UIN',
|
||||
'SNOWLUMA_LOG_DIR',
|
||||
'SNOWLUMA_LOG_MAX_MB',
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
'SNOWLUMA_LOG_LEVEL',
|
||||
'NO_COLOR',
|
||||
] as const;
|
||||
const savedEnv: Record<string, string | undefined> = {};
|
||||
|
||||
function setEnv(env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>): void {
|
||||
for (const [k, v] of Object.entries(env)) {
|
||||
if (v === undefined) delete process.env[k];
|
||||
else process.env[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
for (const k of ENV_KEYS) savedEnv[k] = process.env[k];
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-logger-'));
|
||||
setEnv({
|
||||
SNOWLUMA_LOG_DIR: tmpDir,
|
||||
SNOWLUMA_LOG_FILE: '1',
|
||||
SNOWLUMA_LOG_PER_UIN: '1',
|
||||
SNOWLUMA_LOG_MAX_MB: '5',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '7',
|
||||
NO_COLOR: '1',
|
||||
});
|
||||
await _resetFileTransportForTesting();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await _resetFileTransportForTesting();
|
||||
for (const k of ENV_KEYS) {
|
||||
if (savedEnv[k] === undefined) delete process.env[k];
|
||||
else process.env[k] = savedEnv[k];
|
||||
}
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('createLogger', () => {
|
||||
it('renders [Scope] with the empty UIN slot when no child binding', async () => {
|
||||
const log = createLogger('Bridge');
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
log.info('hello');
|
||||
unsub();
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
const entry = captured[0]!;
|
||||
expect(entry.scope).toBe('Bridge');
|
||||
expect(entry.uin).toBeUndefined();
|
||||
// Plain-text line shape (NO_COLOR=1):
|
||||
// HH:MM:SS · INFO_ · _<12 blank uin slot>_ · [Bridge] · msg
|
||||
// where · = single separator space inside the template literal.
|
||||
const tail = entry.line.slice(9); // drop "HH:MM:SS "
|
||||
expect(tail).toBe(`INFO ${' '.repeat(12)} [Bridge] hello`);
|
||||
});
|
||||
|
||||
it('child({ uin }) derives a logger that stamps the [UIN] slot', async () => {
|
||||
const log = createLogger('Bridge').child({ uin: 12345 });
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
log.info('via child');
|
||||
unsub();
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
const entry = captured[0]!;
|
||||
expect(entry.uin).toBe(12345);
|
||||
expect(entry.scope).toBe('Bridge');
|
||||
// "[12345]" is 7 chars; padEnd to 12 leaves 5 trailing spaces inside
|
||||
// the slot, then 1 separator space before "[Bridge]".
|
||||
const tail = entry.line.slice(9);
|
||||
expect(tail).toBe(`INFO [12345] [Bridge] via child`);
|
||||
});
|
||||
|
||||
it('child() does not mutate the parent logger', async () => {
|
||||
const parent = createLogger('Bridge');
|
||||
const childA = parent.child({ uin: 100 });
|
||||
const childB = parent.child({ uin: 200 });
|
||||
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
parent.info('parent');
|
||||
childA.info('a');
|
||||
childB.info('b');
|
||||
unsub();
|
||||
|
||||
expect(captured.map((e) => e.uin)).toEqual([undefined, 100, 200]);
|
||||
});
|
||||
|
||||
it('child() can be chained; later uin wins, earlier meta is preserved', async () => {
|
||||
const log = createLogger('Bridge').child({ uin: 100, foo: 'first' }).child({ bar: 'second' });
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
log.info('chained');
|
||||
unsub();
|
||||
|
||||
// uin from first child survives through the second (which only sets bar)
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]!.uin).toBe(100);
|
||||
});
|
||||
|
||||
it('writes the per-UIN sub-file in addition to the shared file', async () => {
|
||||
const log = createLogger('Bridge').child({ uin: 67890 });
|
||||
log.info('to file');
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const sharedFiles = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log'));
|
||||
expect(sharedFiles).toHaveLength(1);
|
||||
const sharedPath = path.join(tmpDir, sharedFiles[0]!);
|
||||
expect(fs.readFileSync(sharedPath, 'utf8')).toContain('[67890]');
|
||||
|
||||
const uinSubDir = path.join(tmpDir, '67890');
|
||||
expect(fs.existsSync(uinSubDir)).toBe(true);
|
||||
const uinFiles = fs.readdirSync(uinSubDir).filter((f) => f.endsWith('.log'));
|
||||
expect(uinFiles).toHaveLength(1);
|
||||
expect(fs.readFileSync(path.join(uinSubDir, uinFiles[0]!), 'utf8'))
|
||||
.toContain('to file');
|
||||
});
|
||||
|
||||
it('lines without uin go only to the shared file', async () => {
|
||||
const log = createLogger('App');
|
||||
log.info('no uin here');
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const shared = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log'));
|
||||
expect(shared).toHaveLength(1);
|
||||
// No numeric sub-dirs should have been created.
|
||||
const subDirs = fs.readdirSync(tmpDir, { withFileTypes: true })
|
||||
.filter((d) => d.isDirectory())
|
||||
.map((d) => d.name);
|
||||
expect(subDirs).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('SNOWLUMA_LOG_PER_UIN=0 suppresses the per-UIN sub-file but keeps the shared one', async () => {
|
||||
setEnv({ SNOWLUMA_LOG_PER_UIN: '0' });
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const log = createLogger('Bridge').child({ uin: 9999 });
|
||||
log.info('one line');
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
expect(fs.existsSync(path.join(tmpDir, '9999'))).toBe(false);
|
||||
const shared = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log'));
|
||||
expect(shared).toHaveLength(1);
|
||||
expect(fs.readFileSync(path.join(tmpDir, shared[0]!), 'utf8'))
|
||||
.toContain('one line');
|
||||
});
|
||||
|
||||
it('SNOWLUMA_LOG_FILE=0 also suppresses per-UIN files', async () => {
|
||||
setEnv({ SNOWLUMA_LOG_FILE: '0' });
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const log = createLogger('Bridge').child({ uin: 1 });
|
||||
log.info('hi');
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
const entries = fs.readdirSync(tmpDir);
|
||||
expect(entries).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setLogLevel / getLogLevel — runtime level toggle', () => {
|
||||
// Each test restores whatever level was active going in so the suite
|
||||
// ordering can't bleed state between specs.
|
||||
let saved: ReturnType<typeof getLogLevel>;
|
||||
beforeEach(() => { saved = getLogLevel(); });
|
||||
afterEach(() => { setLogLevel(saved); });
|
||||
|
||||
it('setLogLevel updates getLogLevel for valid input', () => {
|
||||
expect(setLogLevel('warn')).toBe(true);
|
||||
expect(getLogLevel()).toBe('warn');
|
||||
expect(setLogLevel('debug')).toBe(true);
|
||||
expect(getLogLevel()).toBe('debug');
|
||||
});
|
||||
|
||||
it('setLogLevel rejects unknown values without mutating state', () => {
|
||||
setLogLevel('info');
|
||||
expect(setLogLevel('nonsense')).toBe(false);
|
||||
expect(getLogLevel()).toBe('info');
|
||||
expect(setLogLevel('')).toBe(false);
|
||||
expect(setLogLevel('Verbose')).toBe(false);
|
||||
});
|
||||
|
||||
it('setLogLevel is case-insensitive', () => {
|
||||
expect(setLogLevel('WARN')).toBe(true);
|
||||
expect(getLogLevel()).toBe('warn');
|
||||
});
|
||||
|
||||
it('changes which entries reach the ring buffer / subscribers', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsub = subscribeLogs((e) => captured.push(e));
|
||||
const log = createLogger('LevelTest');
|
||||
|
||||
setLogLevel('warn');
|
||||
log.debug('hidden-debug');
|
||||
log.info('hidden-info');
|
||||
log.warn('visible-warn');
|
||||
log.error('visible-error');
|
||||
|
||||
unsub();
|
||||
|
||||
const messages = captured
|
||||
.filter((e) => e.scope === 'LevelTest')
|
||||
.map((e) => e.message);
|
||||
expect(messages).toEqual(['visible-warn', 'visible-error']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
// Tests for the new PR5 observability log lines:
|
||||
// - [Highway.Image] entry log on uploadImageMsgInfo
|
||||
// - [Highway] fast-upload hit when OIDB returns no uKey
|
||||
// - [Highway] OIDB-requires-bytes + PUT-done with elapsed ms
|
||||
// - [MsgPush.Unknown] unrecognized PkgType
|
||||
// - [MsgPush.Unknown] wrapper decoder unknown subType
|
||||
//
|
||||
// Highway transport is mocked the same way pipeline.test.ts does it so
|
||||
// runNtv2Upload exercises real OIDB encode/decode but skips actual
|
||||
// network I/O.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { subscribeLogs, type LogEntry } from '../src/utils/logger';
|
||||
|
||||
vi.mock('../src/bridge/highway/highway-client', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
|
||||
PRIVATE_IMAGE_CMD_ID: 1003,
|
||||
GROUP_IMAGE_CMD_ID: 1004,
|
||||
}));
|
||||
|
||||
import {
|
||||
runNtv2Upload,
|
||||
type MediaSubFileUpload,
|
||||
} from '../src/bridge/highway/pipeline';
|
||||
import { protoEncode } from '../src/protobuf/decode';
|
||||
import { makeOidbBaseSchema } from '../src/bridge/proto/oidb';
|
||||
import {
|
||||
NTV2UploadRichMediaRespSchema,
|
||||
} from '../src/bridge/proto/highway';
|
||||
import { MsgPushRegistry } from '../src/bridge/msg-push/registry';
|
||||
import type { MsgPushContext } from '../src/bridge/msg-push/context';
|
||||
import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc';
|
||||
|
||||
function encodeOidbResponse(body: unknown): Buffer {
|
||||
const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema);
|
||||
return Buffer.from(protoEncode({
|
||||
command: 0x11C4, subCommand: 100, errorCode: 0,
|
||||
body: body as Record<string, unknown>,
|
||||
errorMsg: '', reserved: 1,
|
||||
}, baseSchema));
|
||||
}
|
||||
|
||||
function fakeBridge(responseData: Buffer, uin = '12345'): any {
|
||||
return {
|
||||
identity: { uin },
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
let captured: LogEntry[];
|
||||
let unsub: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
captured = [];
|
||||
unsub = subscribeLogs((e) => captured.push(e));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
unsub();
|
||||
});
|
||||
|
||||
describe('PR5 — highway pipeline logging', () => {
|
||||
it('logs fast-upload hit when the server returns no uKey', async () => {
|
||||
// upload.uKey absent → no PUT performed.
|
||||
const bridge = fakeBridge(encodeOidbResponse({
|
||||
upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } },
|
||||
}));
|
||||
|
||||
const params = {
|
||||
bridge,
|
||||
isGroup: true,
|
||||
targetIdOrUid: 67890,
|
||||
oidbCmd: 0x11C4,
|
||||
serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100',
|
||||
requestId: 1,
|
||||
businessType: 1,
|
||||
uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }],
|
||||
compatQmsgSceneType: 2,
|
||||
extBizInfo: { pic: {} },
|
||||
uploads: [{
|
||||
source: 'top',
|
||||
cmdId: 1004,
|
||||
bytes: new Uint8Array([1, 2, 3]),
|
||||
md5: new Uint8Array(16),
|
||||
sha1: new Uint8Array(20),
|
||||
}] as MediaSubFileUpload[],
|
||||
label: 'image',
|
||||
};
|
||||
|
||||
await runNtv2Upload(params);
|
||||
|
||||
const hit = captured.find((e) =>
|
||||
e.scope === 'Highway' && e.message.includes('fast-upload hit'));
|
||||
expect(hit).toBeDefined();
|
||||
expect(hit!.uin).toBe(12345);
|
||||
});
|
||||
|
||||
it('logs OIDB-requires-bytes and PUT-done with elapsed ms when uKey is present', async () => {
|
||||
const bridge = fakeBridge(encodeOidbResponse({
|
||||
upload: {
|
||||
uKey: 'server-needs-bytes-please',
|
||||
ipv4s: [{ ipv4: '1.2.3.4', port: 80 }],
|
||||
msgInfo: { msgInfoBody: [], extBizInfo: {} },
|
||||
},
|
||||
}));
|
||||
|
||||
const params = {
|
||||
bridge,
|
||||
isGroup: true,
|
||||
targetIdOrUid: 67890,
|
||||
oidbCmd: 0x11C4,
|
||||
serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100',
|
||||
requestId: 1,
|
||||
businessType: 1,
|
||||
uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }],
|
||||
compatQmsgSceneType: 2,
|
||||
extBizInfo: { pic: {} },
|
||||
uploads: [{
|
||||
source: 'top',
|
||||
cmdId: 1004,
|
||||
bytes: new Uint8Array(1024),
|
||||
md5: new Uint8Array(16),
|
||||
sha1: new Uint8Array(20),
|
||||
}] as MediaSubFileUpload[],
|
||||
label: 'image',
|
||||
};
|
||||
|
||||
await runNtv2Upload(params);
|
||||
|
||||
const requiresBytes = captured.find((e) =>
|
||||
e.scope === 'Highway' && e.message.includes('OIDB requires bytes'));
|
||||
const putDone = captured.find((e) =>
|
||||
e.scope === 'Highway' && /PUT done in \d+ms/.test(e.message));
|
||||
|
||||
expect(requiresBytes).toBeDefined();
|
||||
expect(putDone).toBeDefined();
|
||||
|
||||
const fastHit = captured.find((e) =>
|
||||
e.scope === 'Highway' && e.message.includes('fast-upload hit'));
|
||||
expect(fastHit).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PR5 — MsgPush unknown dispatch logging', () => {
|
||||
it('logs an unknown PkgType under [MsgPush.Unknown]', () => {
|
||||
const reg = new MsgPushRegistry();
|
||||
// No decoders registered → any pkgType is unknown.
|
||||
const ctx = {
|
||||
head: { msgType: 9999, subType: 0, timestamp: 0 },
|
||||
content: new Uint8Array(0),
|
||||
identity: {} as any,
|
||||
fromUin: 0,
|
||||
selfUin: 0,
|
||||
} as unknown as MsgPushContext;
|
||||
|
||||
reg.decode(ctx);
|
||||
|
||||
const entry = captured.find((e) =>
|
||||
e.scope === 'MsgPush.Unknown' && e.message.includes('PkgType=9999'));
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.level).toBe('debug');
|
||||
});
|
||||
|
||||
it('logs an unknown wrapper subType under [MsgPush.Unknown] (Event0x2DC)', () => {
|
||||
const ctx = {
|
||||
head: { msgType: 732, subType: 999, timestamp: 0 },
|
||||
content: new Uint8Array(0),
|
||||
identity: {} as any,
|
||||
fromUin: 0,
|
||||
selfUin: 0,
|
||||
} as unknown as MsgPushContext;
|
||||
|
||||
decodeEvent0x2DC(ctx);
|
||||
|
||||
const entry = captured.find((e) =>
|
||||
e.scope === 'MsgPush.Unknown' && /Event0x2DC unknown subType=999/.test(e.message));
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry!.level).toBe('debug');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { handleGroupAddRequest } from '../../src/onebot/modules/request-actions';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type { GroupRequestInfo } from '../../src/bridge/qq-info';
|
||||
|
||||
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
|
||||
return new Proxy(overrides as BridgeInterface, {
|
||||
get(target, prop) {
|
||||
if (prop in target) return (target as any)[prop];
|
||||
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function fakeRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
|
||||
return {
|
||||
groupId: 999,
|
||||
groupName: 'g',
|
||||
targetUid: 'u_t',
|
||||
targetUin: 5555,
|
||||
targetName: 'target',
|
||||
invitorUid: 'u_i',
|
||||
invitorUin: 7777,
|
||||
invitorName: 'inviter',
|
||||
operatorUid: 'u_o',
|
||||
operatorUin: 8888,
|
||||
operatorName: 'op',
|
||||
sequence: 42,
|
||||
state: 1,
|
||||
eventType: 7,
|
||||
comment: 'pls',
|
||||
filtered: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
|
||||
it('matches add requests by groupId and targetUid', async () => {
|
||||
const setGroupAddRequest = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async () => [
|
||||
fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, eventType: 7, filtered: false }),
|
||||
]),
|
||||
setGroupAddRequest: setGroupAddRequest as any,
|
||||
});
|
||||
|
||||
await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok');
|
||||
|
||||
expect(setGroupAddRequest).toHaveBeenCalledOnce();
|
||||
expect(setGroupAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false);
|
||||
});
|
||||
|
||||
it('matches invite requests by groupId and invitorUid', async () => {
|
||||
const setGroupAddRequest = vi.fn(async () => {});
|
||||
const bridge = fakeBridge({
|
||||
fetchGroupRequests: vi.fn(async () => [
|
||||
fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }),
|
||||
]),
|
||||
setGroupAddRequest: setGroupAddRequest as any,
|
||||
});
|
||||
|
||||
await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no');
|
||||
|
||||
expect(setGroupAddRequest).toHaveBeenCalledOnce();
|
||||
expect(setGroupAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
describeTrustProxy,
|
||||
parseTrustProxy,
|
||||
pickClientIp,
|
||||
type TrustProxyMode,
|
||||
} from '../src/webui/client-ip';
|
||||
|
||||
function mockCtx(headers: Record<string, string> = {}) {
|
||||
return {
|
||||
req: {
|
||||
header: (name: string) => headers[name.toLowerCase()],
|
||||
},
|
||||
} as unknown as Parameters<typeof pickClientIp>[0];
|
||||
}
|
||||
|
||||
describe('parseTrustProxy', () => {
|
||||
it('treats empty / unset as none (safe default)', () => {
|
||||
expect(parseTrustProxy(undefined)).toEqual({ kind: 'none' });
|
||||
expect(parseTrustProxy('')).toEqual({ kind: 'none' });
|
||||
expect(parseTrustProxy(' ')).toEqual({ kind: 'none' });
|
||||
});
|
||||
|
||||
it('recognises "1" / "true" / "all" as full trust', () => {
|
||||
expect(parseTrustProxy('1')).toEqual({ kind: 'all' });
|
||||
expect(parseTrustProxy('true')).toEqual({ kind: 'all' });
|
||||
expect(parseTrustProxy('ALL')).toEqual({ kind: 'all' });
|
||||
});
|
||||
|
||||
it('recognises "loopback" case-insensitively', () => {
|
||||
expect(parseTrustProxy('Loopback')).toEqual({ kind: 'loopback' });
|
||||
});
|
||||
|
||||
it('parses a comma-separated IP list', () => {
|
||||
const mode = parseTrustProxy('10.0.0.1, 192.168.1.5, ');
|
||||
expect(mode.kind).toBe('ip-list');
|
||||
if (mode.kind !== 'ip-list') throw new Error('unreachable');
|
||||
expect([...mode.ips].sort()).toEqual(['10.0.0.1', '192.168.1.5']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pickClientIp', () => {
|
||||
const xff = { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' };
|
||||
const realIp = { 'x-real-ip': '203.0.113.42' };
|
||||
const both = { ...xff, ...realIp };
|
||||
|
||||
it('returns socket peer and IGNORES headers when trust=none (default)', () => {
|
||||
const mode: TrustProxyMode = { kind: 'none' };
|
||||
expect(pickClientIp(mockCtx(both), mode, () => '198.51.100.9')).toBe('198.51.100.9');
|
||||
});
|
||||
|
||||
it('honors X-Real-IP first, then XFF first hop, when trust=all', () => {
|
||||
const mode: TrustProxyMode = { kind: 'all' };
|
||||
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('203.0.113.42');
|
||||
expect(pickClientIp(mockCtx(xff), mode, () => '10.0.0.1')).toBe('203.0.113.7');
|
||||
});
|
||||
|
||||
it('falls back to socket peer when trust=all but no headers present', () => {
|
||||
const mode: TrustProxyMode = { kind: 'all' };
|
||||
expect(pickClientIp(mockCtx({}), mode, () => '10.0.0.1')).toBe('10.0.0.1');
|
||||
});
|
||||
|
||||
it('trust=loopback honors headers only when socket is loopback', () => {
|
||||
const mode: TrustProxyMode = { kind: 'loopback' };
|
||||
expect(pickClientIp(mockCtx(both), mode, () => '127.0.0.1')).toBe('203.0.113.42');
|
||||
expect(pickClientIp(mockCtx(both), mode, () => '::1')).toBe('203.0.113.42');
|
||||
expect(pickClientIp(mockCtx(both), mode, () => '::ffff:127.0.0.1')).toBe('203.0.113.42');
|
||||
// Non-loopback peer → headers ignored, socket wins.
|
||||
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('10.0.0.1');
|
||||
});
|
||||
|
||||
it('trust=ip-list honors headers only when socket is in the list', () => {
|
||||
const mode: TrustProxyMode = { kind: 'ip-list', ips: new Set(['10.0.0.1', '10.0.0.2']) };
|
||||
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.2')).toBe('203.0.113.42');
|
||||
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.9')).toBe('10.0.0.9');
|
||||
});
|
||||
|
||||
it('survives a socket resolver that throws', () => {
|
||||
const mode: TrustProxyMode = { kind: 'none' };
|
||||
expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); })).toBe('127.0.0.1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('describeTrustProxy', () => {
|
||||
it('renders each mode in a recognisable form for the boot log', () => {
|
||||
expect(describeTrustProxy({ kind: 'none' })).toContain('socket peer');
|
||||
expect(describeTrustProxy({ kind: 'all' })).toContain('any peer');
|
||||
expect(describeTrustProxy({ kind: 'loopback' })).toContain('loopback');
|
||||
expect(describeTrustProxy({ kind: 'ip-list', ips: new Set(['10.0.0.1']) }))
|
||||
.toContain('10.0.0.1');
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,18 @@ export default defineConfig({
|
||||
},
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node'
|
||||
environment: 'node',
|
||||
// Suppress the logger's file transport during tests so the suite
|
||||
// doesn't litter cwd with logs/snowluma-*.log files. Tests that
|
||||
// explicitly cover file output set their own SNOWLUMA_LOG_FILE='1'
|
||||
// + SNOWLUMA_LOG_DIR=<tmp>.
|
||||
//
|
||||
// Run at debug level so tests asserting on debug-level log entries
|
||||
// (e.g. action dispatch entry lines) actually see them via the
|
||||
// ring buffer / subscribers, which sit behind the console-level gate.
|
||||
env: {
|
||||
SNOWLUMA_LOG_FILE: '0',
|
||||
SNOWLUMA_LOG_LEVEL: 'debug'
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/runtime",
|
||||
"version": "1.8.1",
|
||||
"version": "1.8.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"version": "1.8.1",
|
||||
"version": "1.8.5",
|
||||
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"name": "@snowluma/ui",
|
||||
"author": {
|
||||
"name": "MotricSeven",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"version": "1.8.5",
|
||||
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
"ui",
|
||||
"shadcn",
|
||||
"tailwind",
|
||||
"react"
|
||||
],
|
||||
"homepage": "https://github.com/SnowLuma/SnowLuma#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/SnowLuma/SnowLuma/issues"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/SnowLuma/SnowLuma.git",
|
||||
"directory": "packages/ui"
|
||||
},
|
||||
"license": "UNLICENSED",
|
||||
"type": "module",
|
||||
"sideEffects": [
|
||||
"**/*.css"
|
||||
],
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./styles/theme.css": "./src/styles/theme.css",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"src/styles"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "node -e \"const fs = require('node:fs'); fs.rmSync('dist', { recursive: true, force: true })\"",
|
||||
"prebuild": "pnpm run clean",
|
||||
"build": "tsup",
|
||||
"dev": "tsup --watch",
|
||||
"prepack": "pnpm run build",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-alert-dialog": "^1.1.7",
|
||||
"@radix-ui/react-checkbox": "^1.1.5",
|
||||
"@radix-ui/react-dialog": "^1.1.7",
|
||||
"@radix-ui/react-label": "^2.1.3",
|
||||
"@radix-ui/react-popover": "^1.1.7",
|
||||
"@radix-ui/react-scroll-area": "^1.2.4",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.3",
|
||||
"@radix-ui/react-slot": "^1.1.3",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-tooltip": "^1.1.9",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.469.0",
|
||||
"sonner": "^2.0.6",
|
||||
"tailwind-merge": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"react": "^19.2.5",
|
||||
"react-dom": "^19.2.5",
|
||||
"tsup": "^8.5.0",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import * as React from 'react';
|
||||
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';
|
||||
import { cn } from '../lib/cn';
|
||||
import { buttonVariants } from './button';
|
||||
|
||||
const AlertDialog = AlertDialogPrimitive.Root;
|
||||
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
|
||||
const AlertDialogPortal = AlertDialogPrimitive.Portal;
|
||||
|
||||
const AlertDialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-background/60 backdrop-blur-sm',
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDialogOverlay.displayName = 'AlertDialogOverlay';
|
||||
|
||||
const AlertDialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-1/2 top-1/2 z-50 grid w-[calc(100%-2rem)] max-w-lg grid-cols-[minmax(0,1fr)] -translate-x-1/2 -translate-y-1/2 gap-5 rounded-2xl border border-border bg-popover p-6 text-popover-foreground shadow-xl ring-1 ring-foreground/5',
|
||||
'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,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
));
|
||||
AlertDialogContent.displayName = 'AlertDialogContent';
|
||||
|
||||
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col gap-1.5 text-left', className)} {...props} />
|
||||
);
|
||||
|
||||
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)} {...props} />
|
||||
);
|
||||
|
||||
const AlertDialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Title ref={ref} className={cn('text-base font-semibold leading-tight tracking-tight', className)} {...props} />
|
||||
));
|
||||
AlertDialogTitle.displayName = 'AlertDialogTitle';
|
||||
|
||||
const AlertDialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Description ref={ref} className={cn('text-sm leading-relaxed text-muted-foreground', className)} {...props} />
|
||||
));
|
||||
AlertDialogDescription.displayName = 'AlertDialogDescription';
|
||||
|
||||
const AlertDialogAction = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
|
||||
));
|
||||
AlertDialogAction.displayName = 'AlertDialogAction';
|
||||
|
||||
const AlertDialogCancel = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Cancel ref={ref} className={cn(buttonVariants({ variant: 'outline' }), 'mt-0', className)} {...props} />
|
||||
));
|
||||
AlertDialogCancel.displayName = 'AlertDialogCancel';
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
interface AvatarProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
size?: number;
|
||||
}
|
||||
|
||||
const Avatar = React.forwardRef<HTMLDivElement, AvatarProps>(
|
||||
({ className, size = 36, style, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn('relative inline-flex shrink-0 overflow-hidden rounded-full bg-muted', className)}
|
||||
style={{ width: size, height: size, ...style }}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
Avatar.displayName = 'Avatar';
|
||||
|
||||
const AvatarImage = React.forwardRef<HTMLImageElement, React.ImgHTMLAttributes<HTMLImageElement>>(
|
||||
({ className, alt = '', ...props }, ref) => (
|
||||
<img
|
||||
ref={ref}
|
||||
alt={alt}
|
||||
className={cn('aspect-square size-full object-cover', className)}
|
||||
referrerPolicy="no-referrer"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
AvatarImage.displayName = 'AvatarImage';
|
||||
|
||||
const AvatarFallback = React.forwardRef<HTMLSpanElement, React.HTMLAttributes<HTMLSpanElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<span
|
||||
ref={ref}
|
||||
className={cn('flex size-full items-center justify-center bg-muted text-xs font-medium text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
AvatarFallback.displayName = 'AvatarFallback';
|
||||
|
||||
export { Avatar, AvatarImage, AvatarFallback };
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
export const badgeVariants = cva(
|
||||
'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium leading-none transition-colors',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary/15 text-primary',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground',
|
||||
destructive: 'border-transparent bg-destructive/15 text-destructive',
|
||||
success: 'border-transparent bg-success/15 text-success',
|
||||
warning: 'border-transparent bg-warning/15 text-warning',
|
||||
info: 'border-transparent bg-info/15 text-info',
|
||||
outline: 'border-border bg-card text-foreground',
|
||||
soft: 'border-transparent bg-muted text-muted-foreground',
|
||||
},
|
||||
size: {
|
||||
default: 'px-2 py-0.5 text-[11px]',
|
||||
sm: 'px-1.5 py-px text-[10px]',
|
||||
lg: 'px-2.5 py-1 text-xs',
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: 'default', size: 'default' },
|
||||
},
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLSpanElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
export function Badge({ className, variant, size, ...props }: BadgeProps) {
|
||||
return <span className={cn(badgeVariants({ variant, size }), className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
export const buttonVariants = cva(
|
||||
[
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium",
|
||||
"transition-[color,background-color,border-color,box-shadow,transform] duration-150 ease-out",
|
||||
"disabled:pointer-events-none disabled:opacity-50",
|
||||
"[&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0",
|
||||
"outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring",
|
||||
"active:translate-y-px cursor-pointer",
|
||||
].join(' '),
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 active:bg-primary/95',
|
||||
destructive:
|
||||
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90 active:bg-destructive/95',
|
||||
outline:
|
||||
'border border-border bg-card text-foreground shadow-xs hover:bg-accent hover:text-accent-foreground hover:border-border/80',
|
||||
secondary: 'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80',
|
||||
ghost: 'text-foreground hover:bg-accent hover:text-accent-foreground',
|
||||
link: 'text-primary underline-offset-4 hover:underline shadow-none',
|
||||
success: 'bg-success text-success-foreground shadow-sm hover:bg-success/90',
|
||||
warning: 'bg-warning text-warning-foreground shadow-sm hover:bg-warning/90',
|
||||
},
|
||||
size: {
|
||||
default: 'h-9 px-4 py-2',
|
||||
sm: 'h-8 rounded-md px-3 text-xs',
|
||||
lg: 'h-10 rounded-lg px-6',
|
||||
icon: 'size-9 rounded-lg',
|
||||
'icon-sm': 'size-8 rounded-md',
|
||||
'icon-xs': 'size-7 rounded-md',
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: 'default', size: 'default' },
|
||||
},
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
return <Comp className={cn(buttonVariants({ variant, size }), className)} ref={ref} {...props} />;
|
||||
},
|
||||
);
|
||||
Button.displayName = 'Button';
|
||||
@@ -0,0 +1,50 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn('rounded-xl border border-border bg-card text-card-foreground shadow-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
Card.displayName = 'Card';
|
||||
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex flex-col gap-1.5 p-5', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardHeader.displayName = 'CardHeader';
|
||||
|
||||
const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('text-base font-semibold leading-tight tracking-tight', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardTitle.displayName = 'CardTitle';
|
||||
|
||||
const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('text-sm leading-relaxed text-muted-foreground', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardDescription.displayName = 'CardDescription';
|
||||
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('p-5 pt-0', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardContent.displayName = 'CardContent';
|
||||
|
||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex items-center gap-2 p-5 pt-0', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardFooter.displayName = 'CardFooter';
|
||||
|
||||
export { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter };
|
||||
@@ -0,0 +1,30 @@
|
||||
import * as React from 'react';
|
||||
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
|
||||
import { Check, Minus } from 'lucide-react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Checkbox = React.forwardRef<
|
||||
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CheckboxPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'peer size-4 shrink-0 rounded-[5px] border border-border bg-card shadow-xs transition-colors',
|
||||
'hover:border-border/80',
|
||||
'focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground data-[state=checked]:border-primary',
|
||||
'data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground data-[state=indeterminate]:border-primary',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator className="flex items-center justify-center text-current">
|
||||
{props.checked === 'indeterminate' ? <Minus className="size-3" /> : <Check className="size-3" />}
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
));
|
||||
Checkbox.displayName = 'Checkbox';
|
||||
|
||||
export { Checkbox };
|
||||
@@ -0,0 +1,102 @@
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { X } from 'lucide-react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Dialog = DialogPrimitive.Root;
|
||||
const DialogTrigger = DialogPrimitive.Trigger;
|
||||
const DialogPortal = DialogPrimitive.Portal;
|
||||
const DialogClose = DialogPrimitive.Close;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-background/60 backdrop-blur-sm',
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogOverlay.displayName = 'DialogOverlay';
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { showClose?: boolean }
|
||||
>(({ className, children, showClose = true, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
// grid-cols-[minmax(0,1fr)] keeps wide children (long select text,
|
||||
// file paths, etc.) from blowing past the dialog's max-w-lg by
|
||||
// forcing the implicit grid track's `min-width: auto` to 0.
|
||||
'fixed left-1/2 top-1/2 z-50 grid w-[calc(100%-2rem)] max-w-lg grid-cols-[minmax(0,1fr)] -translate-x-1/2 -translate-y-1/2 gap-5 rounded-2xl border border-border bg-popover p-6 text-popover-foreground shadow-xl ring-1 ring-foreground/5',
|
||||
'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',
|
||||
'data-[state=open]:slide-in-from-top-2',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showClose && (
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 inline-flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-80 transition hover:bg-muted hover:opacity-100 focus:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40">
|
||||
<X className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
DialogContent.displayName = 'DialogContent';
|
||||
|
||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col gap-1.5 text-left', className)} {...props} />
|
||||
);
|
||||
|
||||
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)} {...props} />
|
||||
);
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn('text-base font-semibold leading-tight tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = 'DialogTitle';
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm leading-relaxed text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogDescription.displayName = 'DialogDescription';
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogTrigger,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
interface EmptyStateProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'title'> {
|
||||
icon?: React.ReactNode;
|
||||
title: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
action?: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic "nothing here yet" placeholder. Used by Bot list, search-with-no-
|
||||
* results, log filters that filtered everything out, etc.
|
||||
*/
|
||||
export function EmptyState({ icon, title, description, action, className, ...props }: EmptyStateProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-border bg-card/40 px-6 py-12 text-center',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{icon && (
|
||||
<div className="flex size-12 items-center justify-center rounded-full bg-muted text-muted-foreground">
|
||||
{icon}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium text-foreground">{title}</h3>
|
||||
{description && <p className="text-xs leading-relaxed text-muted-foreground">{description}</p>}
|
||||
</div>
|
||||
{action && <div className="pt-1">{action}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
|
||||
({ className, type, ...props }, ref) => (
|
||||
<input
|
||||
type={type}
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex h-9 w-full min-w-0 rounded-lg border border-border bg-card px-3 py-1 text-sm text-foreground shadow-xs transition-[color,box-shadow,border-color,background-color] outline-none',
|
||||
'file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium',
|
||||
'placeholder:text-muted-foreground',
|
||||
'hover:border-border/80',
|
||||
'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'aria-invalid:border-destructive aria-invalid:ring-destructive/20',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
Input.displayName = 'Input';
|
||||
|
||||
export { Input };
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
/** Small inline keyboard-key label, e.g. `<Kbd>⌘K</Kbd>`. */
|
||||
export const Kbd = React.forwardRef<HTMLElement, React.HTMLAttributes<HTMLElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<kbd
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex h-5 min-w-[1.25rem] items-center justify-center rounded border border-border bg-muted px-1 font-mono text-[10px] font-medium text-muted-foreground',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
Kbd.displayName = 'Kbd';
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as React from 'react';
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn('text-xs font-medium leading-none text-muted-foreground select-none', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Label.displayName = 'Label';
|
||||
|
||||
export { Label };
|
||||
@@ -0,0 +1,31 @@
|
||||
import * as React from 'react';
|
||||
import * as PopoverPrimitive from '@radix-ui/react-popover';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Popover = PopoverPrimitive.Root;
|
||||
const PopoverTrigger = PopoverPrimitive.Trigger;
|
||||
const PopoverAnchor = PopoverPrimitive.Anchor;
|
||||
|
||||
const PopoverContent = React.forwardRef<
|
||||
React.ElementRef<typeof PopoverPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
|
||||
>(({ className, align = 'center', sideOffset = 6, ...props }, ref) => (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
ref={ref}
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'z-50 w-72 rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-xl ring-1 ring-foreground/5 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',
|
||||
'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
));
|
||||
PopoverContent.displayName = 'PopoverContent';
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent };
|
||||
@@ -0,0 +1,54 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
interface ProgressProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
value?: number;
|
||||
indicatorClassName?: string;
|
||||
/**
|
||||
* When true, the bar shows an animated marquee instead of a fixed
|
||||
* width — useful when we know a job is running but don't yet know
|
||||
* the total size (e.g. a download whose Content-Length is unknown).
|
||||
*/
|
||||
indeterminate?: boolean;
|
||||
}
|
||||
|
||||
const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
|
||||
({ className, value = 0, indicatorClassName, indeterminate = false, ...props }, ref) => {
|
||||
const clamped = Math.max(0, Math.min(100, value));
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
role="progressbar"
|
||||
aria-valuenow={indeterminate ? undefined : clamped}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
className={cn(
|
||||
'relative h-2 w-full overflow-hidden rounded-full bg-muted',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{indeterminate ? (
|
||||
<div
|
||||
className={cn(
|
||||
'absolute inset-y-0 left-0 w-1/3 rounded-full bg-primary',
|
||||
'animate-[progress-marquee_1.4s_ease-in-out_infinite]',
|
||||
indicatorClassName,
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className={cn(
|
||||
'h-full rounded-full bg-primary transition-[width] duration-200 ease-out',
|
||||
indicatorClassName,
|
||||
)}
|
||||
style={{ width: `${clamped}%` }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
Progress.displayName = 'Progress';
|
||||
|
||||
export { Progress };
|
||||
@@ -0,0 +1,50 @@
|
||||
import * as React from 'react';
|
||||
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
interface ScrollAreaProps extends React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> {
|
||||
viewportClassName?: string;
|
||||
}
|
||||
|
||||
const ScrollArea = React.forwardRef<React.ElementRef<typeof ScrollAreaPrimitive.Root>, ScrollAreaProps>(
|
||||
({ className, children, viewportClassName, type = 'hover', ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.Root
|
||||
ref={ref}
|
||||
type={type}
|
||||
className={cn('relative overflow-hidden', className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
className={cn('size-full rounded-[inherit] [&>div]:!block', viewportClassName)}
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
),
|
||||
);
|
||||
ScrollArea.displayName = 'ScrollArea';
|
||||
|
||||
const ScrollBar = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
>(({ className, orientation = 'vertical', ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
ref={ref}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
'flex touch-none select-none p-0.5 transition-colors',
|
||||
orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent',
|
||||
orientation === 'horizontal' && 'h-2.5 w-full flex-col border-t border-t-transparent',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border transition-colors hover:bg-muted-foreground/50" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
));
|
||||
ScrollBar.displayName = 'ScrollBar';
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
@@ -0,0 +1,158 @@
|
||||
import * as React from 'react';
|
||||
import * as SelectPrimitive from '@radix-ui/react-select';
|
||||
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Select = SelectPrimitive.Root;
|
||||
const SelectGroup = SelectPrimitive.Group;
|
||||
const SelectValue = SelectPrimitive.Value;
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'group flex h-9 w-full min-w-0 items-center justify-between gap-2 rounded-lg border border-border bg-card px-3 py-1 text-sm shadow-xs outline-none transition-[color,box-shadow,background-color,border-color]',
|
||||
'hover:border-border/80 hover:bg-card/70',
|
||||
'placeholder:text-muted-foreground',
|
||||
'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
|
||||
'data-[state=open]:border-ring data-[state=open]:ring-[3px] data-[state=open]:ring-ring/40',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'data-[placeholder]:text-muted-foreground',
|
||||
// Selected text mustn't push the chevron out of the trigger.
|
||||
'[&>span:not([data-radix-select-icon])]:flex-1 [&>span:not([data-radix-select-icon])]:min-w-0 [&>span:not([data-radix-select-icon])]:truncate [&>span:not([data-radix-select-icon])]:text-left',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild data-radix-select-icon>
|
||||
<ChevronDown className="size-4 shrink-0 opacity-60 transition-transform group-data-[state=open]:rotate-180" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
));
|
||||
SelectTrigger.displayName = 'SelectTrigger';
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn('flex cursor-default items-center justify-center py-1 text-muted-foreground', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
));
|
||||
SelectScrollUpButton.displayName = 'SelectScrollUpButton';
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn('flex cursor-default items-center justify-center py-1 text-muted-foreground', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
));
|
||||
SelectScrollDownButton.displayName = 'SelectScrollDownButton';
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = 'popper', ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
position={position}
|
||||
sideOffset={4}
|
||||
className={cn(
|
||||
// Solid popover surface — explicit bg + ring for visibility against any background.
|
||||
'relative z-50 max-h-(--radix-select-content-available-height) min-w-(--radix-select-trigger-width) overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-xl ring-1 ring-foreground/5',
|
||||
'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',
|
||||
position === 'popper' &&
|
||||
'data-[side=bottom]:translate-y-1 data-[side=top]:-translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
'p-1',
|
||||
position === 'popper' &&
|
||||
'h-(--radix-select-trigger-height) w-full min-w-(--radix-select-trigger-width)',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
));
|
||||
SelectContent.displayName = 'SelectContent';
|
||||
|
||||
const SelectLabel = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn('px-2 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectLabel.displayName = 'SelectLabel';
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex w-full cursor-default select-none items-center gap-2 rounded-md py-1.5 pl-2 pr-8 text-sm outline-none transition-colors',
|
||||
'focus:bg-accent focus:text-accent-foreground',
|
||||
'data-[state=checked]:font-medium',
|
||||
'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex size-3.5 items-center justify-center text-primary">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
));
|
||||
SelectItem.displayName = 'SelectItem';
|
||||
|
||||
const SelectSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator ref={ref} className={cn('-mx-1 my-1 h-px bg-border', className)} {...props} />
|
||||
));
|
||||
SelectSeparator.displayName = 'SelectSeparator';
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as React from 'react';
|
||||
import * as SeparatorPrimitive from '@radix-ui/react-separator';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Separator = React.forwardRef<
|
||||
React.ElementRef<typeof SeparatorPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||
>(({ className, orientation = 'horizontal', decorative = true, ...props }, ref) => (
|
||||
<SeparatorPrimitive.Root
|
||||
ref={ref}
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
'shrink-0 bg-border',
|
||||
orientation === 'horizontal' ? 'h-px w-full' : 'h-full w-px',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Separator.displayName = 'Separator';
|
||||
|
||||
export { Separator };
|
||||
@@ -0,0 +1,66 @@
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { X } from 'lucide-react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Sheet = DialogPrimitive.Root;
|
||||
const SheetTrigger = DialogPrimitive.Trigger;
|
||||
const SheetClose = DialogPrimitive.Close;
|
||||
const SheetPortal = DialogPrimitive.Portal;
|
||||
|
||||
const SheetOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SheetOverlay.displayName = 'SheetOverlay';
|
||||
|
||||
const sheetVariants = cva(
|
||||
'fixed z-50 gap-4 bg-card p-0 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500 outline-none',
|
||||
{
|
||||
variants: {
|
||||
side: {
|
||||
top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top',
|
||||
bottom: 'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom',
|
||||
left: 'inset-y-0 left-0 h-full w-3/4 max-w-xs border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm',
|
||||
right: 'inset-y-0 right-0 h-full w-3/4 max-w-xs border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm',
|
||||
},
|
||||
},
|
||||
defaultVariants: { side: 'right' },
|
||||
}
|
||||
);
|
||||
|
||||
interface SheetContentProps
|
||||
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>,
|
||||
VariantProps<typeof sheetVariants> {
|
||||
showClose?: boolean;
|
||||
}
|
||||
|
||||
const SheetContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Content>, SheetContentProps>(
|
||||
({ side = 'right', className, children, showClose = true, ...props }, ref) => (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<DialogPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
|
||||
{children}
|
||||
{showClose && (
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none cursor-pointer">
|
||||
<X className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</SheetPortal>
|
||||
)
|
||||
);
|
||||
SheetContent.displayName = 'SheetContent';
|
||||
|
||||
export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetPortal, SheetOverlay };
|
||||
@@ -0,0 +1,6 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
export function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn('animate-pulse rounded-md bg-muted', className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
/**
|
||||
* A semantic colored status dot — drop-in replacement for ad-hoc emoji
|
||||
* (🟢 / 🟡 / 🔴) so we keep visual rhythm with the rest of the Lucide
|
||||
* iconography. `pulse` adds a soft halo for the "active" state.
|
||||
*/
|
||||
const dotVariants = cva('inline-block shrink-0 rounded-full', {
|
||||
variants: {
|
||||
tone: {
|
||||
success: 'bg-success',
|
||||
warning: 'bg-warning',
|
||||
destructive: 'bg-destructive',
|
||||
info: 'bg-info',
|
||||
muted: 'bg-muted-foreground/50',
|
||||
primary: 'bg-primary',
|
||||
},
|
||||
size: {
|
||||
xs: 'size-1.5',
|
||||
sm: 'size-2',
|
||||
md: 'size-2.5',
|
||||
lg: 'size-3',
|
||||
},
|
||||
},
|
||||
defaultVariants: { tone: 'muted', size: 'sm' },
|
||||
});
|
||||
|
||||
export interface StatusDotProps
|
||||
extends React.HTMLAttributes<HTMLSpanElement>,
|
||||
VariantProps<typeof dotVariants> {
|
||||
pulse?: boolean;
|
||||
}
|
||||
|
||||
export function StatusDot({ className, tone, size, pulse, ...props }: StatusDotProps) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'relative inline-flex items-center justify-center',
|
||||
pulse && 'before:absolute before:inset-0 before:rounded-full before:bg-current before:opacity-30 before:animate-ping',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className={cn(dotVariants({ tone, size }), 'relative')} aria-hidden />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as React from 'react';
|
||||
import * as SwitchPrimitive from '@radix-ui/react-switch';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Switch = React.forwardRef<
|
||||
React.ElementRef<typeof SwitchPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-border shadow-inner transition-colors',
|
||||
'focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
// Checked: filled with primary
|
||||
'data-[state=checked]:bg-primary data-[state=checked]:border-primary',
|
||||
// Unchecked: visible track that contrasts with both surface modes
|
||||
'data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-muted-foreground/25',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
className={cn(
|
||||
'pointer-events-none block size-4 rounded-full shadow-md ring-0 transition-transform',
|
||||
// Thumb always uses card surface so it pops against the track in both states.
|
||||
'bg-card dark:bg-foreground/95',
|
||||
'data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0',
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
));
|
||||
Switch.displayName = 'Switch';
|
||||
|
||||
export { Switch };
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user