Compare commits

..
47 Commits
Author SHA1 Message Date
手瓜一十雪 890d032794 Add streaming file upload and download actions
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Introduces new OneBot actions for streaming file upload and download, including chunked file transfer with memory/disk management and SHA256 verification. Adds CleanStreamTempFile, DownloadFileStream, UploadFileStream, and TestStreamDownload actions, updates action routing and network adapters to support streaming via HTTP and WebSocket, and provides Python test scripts for concurrent upload testing.
2025-09-16 23:24:00 +08:00
837951602 66f30e1ebf 找不到类型时显式报错 (#1256) 2025-09-16 17:19:59 +08:00
MliKiowa ada614d007 Fix link for QQ Group#2 in README
Updated the link for QQ Group#2 in the README.
2025-09-13 17:23:21 +08:00
MliKiowa ea3ab7f13f Fix QQ Group links in README.md 2025-09-13 17:22:53 +08:00
MliKiowa a5e4c24de3 Revise README for clarity and additional resources
Updated README with links to documentation and community guidelines.
2025-09-13 17:20:07 +08:00
Mlikiowa bcc7d25b64 release: v4.8.113 2025-09-13 05:51:02 +00:00
手瓜一十雪 aae676fdc7 Update default host and token length in config
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
Changed the default host to '0.0.0.0' and increased the default token length from 8 to 12 characters in WebUiConfigSchema. Also removed unused getDefaultHost import and made minor formatting adjustments.
2025-09-13 13:49:18 +08:00
Mlikiowa 0e9aa43476 release: v4.8.112 2025-09-12 14:15:08 +00:00
时瑾 b2ff556aa6 fix: 更新默认主机地址获取逻辑,支持Docker环境
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
2025-09-12 21:56:12 +08:00
Mlikiowa 69c5b78678 release: v4.8.111 2025-09-12 11:19:26 +00:00
时瑾 8be7f74e9f fix: 移除 defaultToken 字段,彻底移除硬编码的默认密码,采用全随机密码
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
2025-09-12 18:50:21 +08:00
时瑾 a05150ebe1 fix(dos): 修复红红的ci 2025-09-12 15:36:30 +08:00
Mlikiowa 5e6b607ded release: v4.8.110 2025-09-11 05:15:29 +00:00
时瑾 df2dabfe76 refactor: 将默认密码相关逻辑重构为后端处理 (#1247)
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
* refactor: 将默认密码相关逻辑重构为后端处理

* refactor: 日志路由进行脱敏,生成随机密码使用node:crypto.randomBytes

* feat: 更新密码功能增强,添加新密码强度验证和旧密码检查

* feat: 给文件管理添加WebUI配置文件的脱敏处理和验证逻辑

* refactor: 优化网络显示卡片按钮样式和行为,调整按钮属性以提升用户体验

* feat: 增强路径处理逻辑,添加安全验证以防止路径遍历攻击

* feat: 增强文件路径处理逻辑,添加安全验证以防止路径遍历攻击,并优化查询参数提取

* feat: CodeQL不认可 受不了
2025-09-11 13:13:00 +08:00
手瓜一十雪 5e032fcc6a upate: package 2025-09-08 16:16:38 +08:00
Mlikiowa 44200a2208 release: v4.8.109 2025-09-08 08:11:05 +00:00
手瓜一十雪 e39bb05f01 fix: 多层解析
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
2025-09-08 16:05:10 +08:00
手瓜一十雪 677731dd70 Add qq-chat-exporter to recommended tools
Included qq-chat-exporter, a NapCat-based message export tool, in the list of recommended related projects in the README.
2025-09-07 15:20:17 +08:00
Mlikiowa fa8e6f2c59 release: v4.8.108 2025-09-07 05:57:27 +00:00
手瓜一十雪 509b23ff04 Update Telegram link in About page
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
Changed the Telegram href in the About page from MelodicMoonlight to napcatqq to reflect the correct contact or channel.
2025-09-07 13:54:44 +08:00
Mlikiowa cf1765f5a4 release: v4.8.107 2025-09-07 05:48:15 +00:00
手瓜一十雪 c541c7e257 Update Telegram link in README
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
Changed the Telegram badge and link from MelodicMoonlight to napcatqq for accuracy.
2025-09-07 13:47:23 +08:00
手瓜一十雪 298b8b71c8 Log WebUI panel URL on server start
Adds logging of the WebUI user panel URL with localhost address when the server starts. Also adjusts QQ login callback invocation in OneBot adapter for improved login flow.
2025-09-07 13:29:37 +08:00
手瓜一十雪 5c120a8231 Add WebUI token update and callback handling
Introduces callback mechanisms for WebUI token changes and QQ login status updates. The WebUI token is now updated and communicated via a callback after login, and related runtime and type definitions are extended to support these features. Also sets a static default token value in the config schema.
2025-09-06 18:15:35 +08:00
手瓜一十雪 88ee8f89fe Comment out documentation links in README
The section containing links to documentation and Telegram has been commented out in the README.md. This may be for temporary removal or future revision.
2025-09-06 13:13:14 +08:00
Mlikiowa 12b8130372 release: v4.8.106 2025-09-06 03:53:33 +00:00
手瓜一十雪 58332dad24 feat: 支持禁用webui 速率配置 禁用外网访问 禁用webui
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
2025-09-06 11:53:04 +08:00
手瓜一十雪 e97f3e1283 feat: 进一步提高密码安全性 2025-09-06 11:42:12 +08:00
手瓜一十雪 e406dca7ae feat: 禁止默认密码 2025-09-06 11:41:06 +08:00
手瓜一十雪 e4c1807f76 feat: 安全性提升 2025-09-06 11:32:09 +08:00
手瓜一十雪 f4412bb086 feat: 安全性提升 2025-09-06 11:23:09 +08:00
手瓜一十雪 27af8e52ac feat: 安全性提升 2025-09-06 10:49:29 +08:00
手瓜一十雪 4c9a220300 Add README for example plugin
Introduces installation instructions for the example plugin, detailing how to place the build output in the appropriate plugins directory.
2025-09-02 22:54:44 +08:00
手瓜一十雪 1fe822cd20 Update import paths and remove plugin tsconfig
Changed import paths in example-plugin to use alias '@' instead of relative paths. Deleted the example-plugin/tsconfig.json file, likely consolidating TypeScript configuration or relying on a root config.
2025-09-02 22:48:01 +08:00
手瓜一十雪 0ab8d025bf Declare config property in OB11PluginMangerAdapter
Adds an explicit declaration for the 'config' property in the OB11PluginMangerAdapter class to improve type safety and clarity.
2025-09-02 22:42:09 +08:00
Mlikiowa a0f3d66607 release: v4.8.105 2025-09-02 14:33:33 +00:00
手瓜一十雪 06e7c3363a Add quick_reply support to message parsing
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Introduces the quick_reply boolean option to message history schema and message parsing logic. Updates relevant functions to handle quick_reply, allowing for conditional behavior during message reply and segment parsing.
2025-09-02 22:33:05 +08:00
手瓜一十雪 4d200de6b7 Refactor packet client and update message history actions
Replaced LRUCache with Map for callback and event management in packet clients, and standardized callback hash usage. Updated GetFriendMsgHistory and GetGroupMsgHistory actions to use snake_case for payload keys. Modified OneBotMsgApi to support disabling URL retrieval for ptt elements via a new parameter.
2025-09-02 22:24:53 +08:00
手瓜一十雪 6200097f7c Add resource health management and enhance message parsing
Introduces a ResourceManager for health checking and retry logic in src/common/health.ts. Updates OneBot message parsing to support disabling URL fetching and multi-message parsing via new payload options. File, image, video, and ptt URL retrievals now use resource health management for improved reliability. Also refactors packet API to allow configurable timeout for FetchRkey.
#1220
2025-09-02 21:19:49 +08:00
手瓜一十雪 c7af0384fb Add plugin manager and example plugin system
Introduces a plugin manager (OB11PluginMangerAdapter) for dynamic plugin loading, initialization, and event handling. Adds an example plugin with configuration files and updates related code to support plugin directory detection and loading. Refactors plugin adapter logic for extensibility and modularity.
2025-09-02 20:42:54 +08:00
Mlikiowa dc87615bd6 release: v4.8.104 2025-09-02 08:32:22 +00:00
手瓜一十雪 ff2cfcee97 Add appid and offset entries for new versions
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
Added appid and qua mappings for versions 3.2.19-39038 and 9.9.21-39038 in appid.json. Updated offset.json with send/recv offsets for these new versions and architectures (x64, arm64).
2025-09-02 16:31:24 +08:00
手瓜一十雪 f3c07ed8fc Add timeout parameter to file and packet API methods
Introduces an optional timeout parameter (defaulting to 20000ms) to various file and packet API methods for improved control over request duration. Updates all relevant method calls and internal usages to support the new timeout argument, including OneBot message API calls with a shorter timeout for file, video, and ptt URL retrieval.
2025-09-02 09:54:42 +08:00
手瓜一十雪 7ab44dcb34 Refactor video thumbnail generation logic
Moved video thumbnail generation to occur before custom thumbnail copying, ensuring fallback to default thumbnail only if video info retrieval fails. Also reordered rkeyManager URLs for consistency.
2025-09-02 09:35:56 +08:00
Mlikiowa aa6699d06e release: v4.8.103 2025-08-31 13:32:47 +00:00
手瓜一十雪 3cb51a17a6 Add new appid and offset entries for version 38960
Build Release / check-version (push) Canceled after 0s
Build Release / Build-LiteLoader (push) Canceled after 0s
Build Release / Build-Shell (push) Canceled after 0s
Build Release / release-napcat (push) Canceled after 0s
Build Release / build-docker (push) Canceled after 0s
Build Action / Build-LiteLoader (push) Canceled after 0s
Build Action / Build-Shell (push) Canceled after 0s
Updated appid.json and offset.json to include new entries for versions 3.2.19-38960 and 9.9.21-38960, supporting both x64 and arm64 architectures.
2025-08-31 21:32:15 +08:00
Mlikiowa 994e8ced3e release: v4.8.102 2025-08-26 06:59:25 +00:00
77 changed files with 3813 additions and 386 deletions

No files matched your search

+6 -1
View File
@@ -9,4 +9,9 @@
"css.customData": [
".vscode/tailwindcss.json"
],
}
"editor.formatOnPaste": false,
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "never"
},
}
+8 -3
View File
@@ -33,6 +33,7 @@ _Modern protocol-side framework implemented based on NTQQ._
**首次使用**请务必查看如下文档看使用教程
> 项目非盈利,对接问题/基础问题/下层框架问题 请自行搜索解决,本项目社区不提供此类解答。
## Link
| Docs | [![Github.IO](https://img.shields.io/badge/docs%20on-Github.IO-orange)](https://napneko.github.io/) | [![Cloudflare.Worker](https://img.shields.io/badge/docs%20on-Cloudflare.Worker-black)](https://doc.napneko.icu/) | [![Cloudflare.HKServer](https://img.shields.io/badge/docs%20on-Cloudflare.HKServer-informational)](https://napcat.napneko.icu/) |
@@ -41,12 +42,14 @@ _Modern protocol-side framework implemented based on NTQQ._
| Docs | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.cyou/) | [![NapCat.Wiki](https://img.shields.io/badge/docs%20on-NapCat.Wiki-red)](https://www.napcat.wiki) |
|:-:|:-:|:-:|:-:|
| QQ Group | [![QQ Group#4](https://img.shields.io/badge/QQ%20Group%234-Join-blue)](https://qm.qq.com/q/CMmPbGw0jA) | [![QQ Group#3](https://img.shields.io/badge/QQ%20Group%233-Join-blue)](https://qm.qq.com/q/8zJMLjqy2Y) | [![QQ Group#2](https://img.shields.io/badge/QQ%20Group%232-Join-blue)](https://qm.qq.com/q/HaRcfrHpUk) | [![QQ Group#1](https://img.shields.io/badge/QQ%20Group%231-Join-blue)](https://qm.qq.com/q/I6LU87a0Yq) |
| QQ Group | [![QQ Group#4](https://img.shields.io/badge/QQ%20Group%234-Join-blue)](https://qm.qq.com/q/CMmPbGw0jA) | [![QQ Group#3](https://img.shields.io/badge/QQ%20Group%233-Join-blue)](https://qm.qq.com/q/8zJMLjqy2Y) | [![QQ Group#2](https://img.shields.io/badge/QQ%20Group%232-Join-blue)](https://qm.qq.com/q/CMmPbGw0jA) | [![QQ Group#1](https://img.shields.io/badge/QQ%20Group%231-Join-blue)](https://qm.qq.com/q/I6LU87a0Yq) |
|:-:|:-:|:-:|:-:|:-:|
| Telegram | [![Telegram](https://img.shields.io/badge/Telegram-MelodicMoonlight-blue)](https://t.me/MelodicMoonlight) |
| Telegram | [![Telegram](https://img.shields.io/badge/Telegram-napcatqq-blue)](https://t.me/napcatqq) |
|:-:|:-:|
> 请不要在其余社区提及本项目(包括其余协议端/相关应用端项目)引发争论,如有建议到达官方交流群讨论或PR。
## Thanks
+ [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
@@ -54,7 +57,9 @@ _Modern protocol-side framework implemented based on NTQQ._
+ [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美适配本项目的LLM Bot框架 在此推荐一下
+ [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一只赛博群友 麦麦 Bot框架 在此推荐一下
+ [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基于NapCat的消息导出工具 在此推荐一下
+ 不过最最重要的 还是需要感谢屏幕前的你哦~
---
+5 -5
View File
@@ -1,9 +1,9 @@
{
"name": "qq-chat",
"version": "9.9.19-34740",
"verHash": "f31348f2",
"linuxVersion": "3.2.17-34740",
"linuxVerHash": "5aa2d8d6",
"verHash": "cc326038",
"version": "9.9.21-39038",
"linuxVersion": "3.2.19-39038",
"linuxVerHash": "c773cdf7",
"private": true,
"description": "QQ",
"productName": "QQ",
@@ -17,7 +17,7 @@
"qd": "externals/devtools/cli/index.js"
},
"main": "./loadNapCat.js",
"buildVersion": "34740",
"buildVersion": "39038",
"isPureShell": true,
"isByteCodeShell": true,
"platform": "win32",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "NapCatQQ",
"slug": "NapCat.Framework",
"description": "高性能的 OneBot 11 协议实现",
"version": "4.8.101",
"version": "4.8.113",
"icon": "./logo.png",
"authors": [
{
@@ -62,24 +62,39 @@ const NetworkDisplayCard = <T extends keyof NetworkType>({
<ButtonGroup
fullWidth
isDisabled={editing}
radius="full"
radius="sm"
size="sm"
variant="shadow"
variant="flat"
>
<Button color="warning" startContent={<FiEdit3 />} onPress={onEdit}>
<Button
color="warning"
startContent={<FiEdit3 size={16} />}
onPress={onEdit}
>
编辑
</Button>
<Button
color={debug ? 'success' : 'default'}
startContent={<CgDebug />}
color={debug ? 'secondary' : 'success'}
variant="flat"
startContent={
<CgDebug
style={{
width: '16px',
height: '16px',
minWidth: '16px',
minHeight: '16px'
}}
/>
}
onPress={handleEnableDebug}
>
{debug ? '关闭调试' : '开启调试'}
</Button>
<Button
color="primary"
startContent={<MdDeleteForever />}
className="bg-danger/20 text-danger hover:bg-danger/30 transition-colors"
variant="flat"
startContent={<MdDeleteForever size={16} />}
onPress={handleDelete}
>
删除
@@ -170,3 +170,11 @@ const GenericForm = <T extends keyof NetworkConfigType>({
}
export default GenericForm
export function random_token(length: number) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%^&*()-_=+[]{}|;:,.<>?'
let result = ''
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}
@@ -1,4 +1,4 @@
import GenericForm from './generic_form'
import GenericForm, { random_token } from './generic_form'
import type { Field } from './generic_form'
export interface HTTPClientFormProps {
@@ -20,7 +20,7 @@ const HTTPClientForm: React.FC<HTTPClientFormProps> = ({
url: 'http://localhost:8080',
reportSelfMessage: false,
messagePostFormat: 'array',
token: '',
token: random_token(16),
debug: false
}
@@ -1,4 +1,4 @@
import GenericForm from './generic_form'
import GenericForm, { random_token } from './generic_form'
import type { Field } from './generic_form'
export interface HTTPServerFormProps {
@@ -17,12 +17,12 @@ const HTTPServerForm: React.FC<HTTPServerFormProps> = ({
const defaultValues: HTTPServerFormType[0] = {
enable: false,
name: '',
host: '0.0.0.0',
host: '127.0.0.1',
port: 3000,
enableCors: true,
enableWebsocket: true,
messagePostFormat: 'array',
token: '',
token: random_token(16),
debug: false
}
@@ -1,4 +1,4 @@
import GenericForm from './generic_form'
import GenericForm, { random_token } from './generic_form'
import type { Field } from './generic_form'
export interface HTTPServerSSEFormProps {
@@ -19,12 +19,12 @@ const HTTPServerSSEForm: React.FC<HTTPServerSSEFormProps> = ({
const defaultValues: HTTPServerSSEFormType[0] = {
enable: false,
name: '',
host: '0.0.0.0',
host: '127.0.0.1',
port: 3000,
enableCors: true,
enableWebsocket: true,
messagePostFormat: 'array',
token: '',
token: random_token(16),
debug: false,
reportSelfMessage: false
}
@@ -1,4 +1,4 @@
import GenericForm from './generic_form'
import GenericForm, { random_token } from './generic_form'
import type { Field } from './generic_form'
export interface WebsocketClientFormProps {
@@ -22,7 +22,7 @@ const WebsocketClientForm: React.FC<WebsocketClientFormProps> = ({
url: 'ws://localhost:8082',
reportSelfMessage: false,
messagePostFormat: 'array',
token: '',
token: random_token(16),
debug: false,
heartInterval: 30000,
reconnectInterval: 30000
@@ -1,4 +1,4 @@
import GenericForm from './generic_form'
import GenericForm, { random_token } from './generic_form'
import type { Field } from './generic_form'
export interface WebsocketServerFormProps {
@@ -19,12 +19,12 @@ const WebsocketServerForm: React.FC<WebsocketServerFormProps> = ({
const defaultValues: WebsocketServerFormType[0] = {
enable: false,
name: '',
host: '0.0.0.0',
host: '127.0.0.1',
port: 3001,
reportSelfMessage: false,
enableForcePushEvent: true,
messagePostFormat: 'array',
token: '',
token: random_token(16),
debug: false,
heartInterval: 30000
}
+51 -7
View File
@@ -33,13 +33,6 @@ export default class WebUIManager {
return data.data
}
public static async checkUsingDefaultToken() {
const { data } = await serverRequest.get<ServerResponse<boolean>>(
'/auth/check_using_default_token'
)
return data.data
}
public static async proxy<T>(url = '') {
const data = await serverRequest.get<ServerResponse<string>>(
'/base/proxy?url=' + encodeURIComponent(url)
@@ -152,4 +145,55 @@ export default class WebUIManager {
return eventSource
}
// 获取WebUI基础配置
public static async getWebUIConfig() {
const { data } = await serverRequest.get<ServerResponse<WebUIConfig>>(
'/WebUIConfig/GetConfig'
)
return data.data
}
// 更新WebUI基础配置
public static async updateWebUIConfig(config: Partial<WebUIConfig>) {
const { data } = await serverRequest.post<ServerResponse<boolean>>(
'/WebUIConfig/UpdateConfig',
config
)
return data.data
}
// 获取是否禁用WebUI
public static async getDisableWebUI() {
const { data } = await serverRequest.get<ServerResponse<boolean>>(
'/WebUIConfig/GetDisableWebUI'
)
return data.data
}
// 更新是否禁用WebUI
public static async updateDisableWebUI(disable: boolean) {
const { data } = await serverRequest.post<ServerResponse<boolean>>(
'/WebUIConfig/UpdateDisableWebUI',
{ disable }
)
return data.data
}
// 获取是否禁用非局域网访问
public static async getDisableNonLANAccess() {
const { data } = await serverRequest.get<ServerResponse<boolean>>(
'/WebUIConfig/GetDisableNonLANAccess'
)
return data.data
}
// 更新是否禁用非局域网访问
public static async updateDisableNonLANAccess(disable: boolean) {
const { data } = await serverRequest.post<ServerResponse<boolean>>(
'/WebUIConfig/UpdateDisableNonLANAccess',
{ disable }
)
return data.data
}
}
+1 -1
View File
@@ -155,7 +155,7 @@ export default function AboutPage() {
shadow="sm"
isPressable
isExternal
href="https://t.me/MelodicMoonlight"
href="https://t.me/napcatqq"
>
<CardBody className="flex-row items-center gap-2">
<span className="p-2 rounded-small bg-primary-50 text-primary-500">
@@ -14,8 +14,9 @@ const ChangePasswordCard = () => {
const {
control,
handleSubmit: handleWebuiSubmit,
formState: { isSubmitting },
reset
formState: { isSubmitting, errors },
reset,
watch
} = useForm<{
oldToken: string
newToken: string
@@ -29,9 +30,14 @@ const ChangePasswordCard = () => {
const navigate = useNavigate()
const [_, setToken] = useLocalStorage(key.token, '')
// 监听旧密码的值
const oldTokenValue = watch('oldToken')
const onSubmit = handleWebuiSubmit(async (data) => {
try {
// 使用正常密码更新流程
await WebUIManager.changePassword(data.oldToken, data.newToken)
toast.success('修改成功')
setToken('')
localStorage.removeItem(key.token)
@@ -45,30 +51,75 @@ const ChangePasswordCard = () => {
return (
<>
<title>修改密码 - NapCat WebUI</title>
<Controller
control={control}
name="oldToken"
rules={{
required: '旧密码不能为空',
validate: (value) => {
if (!value || value.trim().length === 0) {
return '旧密码不能为空'
}
return true
}
}}
render={({ field }) => (
<Input
{...field}
label="旧密码"
placeholder="请输入旧密码"
type="password"
isRequired
isInvalid={!!errors.oldToken}
errorMessage={errors.oldToken?.message}
/>
)}
/>
<Controller
control={control}
name="newToken"
rules={{
required: '新密码不能为空',
minLength: {
value: 6,
message: '新密码至少需要6个字符'
},
validate: (value) => {
if (!value || value.trim().length === 0) {
return '新密码不能为空'
}
if (value.trim().length !== value.length) {
return '新密码不能包含前后空格'
}
if (value === oldTokenValue) {
return '新密码不能与旧密码相同'
}
// 检查是否包含字母
if (!/[a-zA-Z]/.test(value)) {
return '新密码必须包含字母'
}
// 检查是否包含数字
if (!/[0-9]/.test(value)) {
return '新密码必须包含数字'
}
return true
}
}}
render={({ field }) => (
<Input
{...field}
label="新密码"
placeholder="请输入新密码"
placeholder="至少6位,包含字母和数字"
type="password"
isRequired
isInvalid={!!errors.newToken}
errorMessage={errors.newToken?.message}
/>
)}
/>
<SaveButtons
onSubmit={onSubmit}
reset={reset}
@@ -7,6 +7,7 @@ import { useNavigate, useSearchParams } from 'react-router-dom'
import ChangePasswordCard from './change_password'
import LoginConfigCard from './login'
import OneBotConfigCard from './onebot'
import ServerConfigCard from './server'
import ThemeConfigCard from './theme'
import WebUIConfigCard from './webui'
@@ -67,6 +68,11 @@ export default function ConfigPage() {
<OneBotConfigCard />
</ConfingPageItem>
</Tab>
<Tab title="服务器配置" key="server">
<ConfingPageItem>
<ServerConfigCard />
</ConfingPageItem>
</Tab>
<Tab title="WebUI配置" key="webui">
<ConfingPageItem>
<WebUIConfigCard />
@@ -0,0 +1,185 @@
import { Input } from '@heroui/input'
import { Switch } from '@heroui/switch'
import { useRequest } from 'ahooks'
import { useEffect } from 'react'
import { Controller, useForm } from 'react-hook-form'
import toast from 'react-hot-toast'
import SaveButtons from '@/components/button/save_buttons'
import PageLoading from '@/components/page_loading'
import WebUIManager from '@/controllers/webui_manager'
const ServerConfigCard = () => {
const {
data: configData,
loading: configLoading,
error: configError,
refreshAsync: refreshConfig
} = useRequest(WebUIManager.getWebUIConfig)
const {
control,
handleSubmit: handleConfigSubmit,
formState: { isSubmitting },
setValue: setConfigValue
} = useForm<{
host: string
port: number
loginRate: number
disableWebUI: boolean
disableNonLANAccess: boolean
}>({
defaultValues: {
host: '0.0.0.0',
port: 6099,
loginRate: 10,
disableWebUI: false,
disableNonLANAccess: false
}
})
const reset = () => {
if (configData) {
setConfigValue('host', configData.host)
setConfigValue('port', configData.port)
setConfigValue('loginRate', configData.loginRate)
setConfigValue('disableWebUI', configData.disableWebUI)
setConfigValue('disableNonLANAccess', configData.disableNonLANAccess)
}
}
const onSubmit = handleConfigSubmit(async (data) => {
try {
await WebUIManager.updateWebUIConfig(data)
toast.success('保存成功')
} catch (error) {
const msg = (error as Error).message
toast.error(`保存失败: ${msg}`)
}
})
const onRefresh = async () => {
try {
await refreshConfig()
toast.success('刷新成功')
} catch (error) {
const msg = (error as Error).message
toast.error(`刷新失败: ${msg}`)
}
}
useEffect(() => {
reset()
}, [configData])
if (configLoading) return <PageLoading loading={true} />
return (
<>
<title>服务器配置 - NapCat WebUI</title>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<div className="flex-shrink-0 w-full">服务器配置</div>
<Controller
control={control}
name="host"
render={({ field }) => (
<Input
{...field}
label="监听地址"
placeholder="请输入监听地址"
description="服务器监听的IP地址,0.0.0.0表示监听所有网卡"
isDisabled={!!configError}
errorMessage={configError ? '获取配置失败' : undefined}
/>
)}
/>
<Controller
control={control}
name="port"
render={({ field }) => (
<Input
{...field}
type="number"
value={field.value?.toString() || ''}
label="监听端口"
placeholder="请输入监听端口"
description="服务器监听的端口号,范围1-65535"
isDisabled={!!configError}
errorMessage={configError ? '获取配置失败' : undefined}
onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
/>
)}
/>
<Controller
control={control}
name="loginRate"
render={({ field }) => (
<Input
{...field}
type="number"
value={field.value?.toString() || ''}
label="登录速率限制"
placeholder="请输入登录速率限制"
description="每小时允许的登录尝试次数"
isDisabled={!!configError}
errorMessage={configError ? '获取配置失败' : undefined}
onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
/>
)}
/>
</div>
<div className="flex flex-col gap-2">
<div className="flex-shrink-0 w-full">安全配置</div>
<Controller
control={control}
name="disableWebUI"
render={({ field }) => (
<Switch
isSelected={field.value}
onValueChange={field.onChange}
isDisabled={!!configError}
>
<div className="flex flex-col">
<span>禁用WebUI</span>
<span className="text-sm text-default-400">
启用后将完全禁用WebUI服务,需要重启生效
</span>
</div>
</Switch>
)}
/>
<Controller
control={control}
name="disableNonLANAccess"
render={({ field }) => (
<Switch
isSelected={field.value}
onValueChange={field.onChange}
isDisabled={!!configError}
>
<div className="flex flex-col">
<span>禁用非局域网访问</span>
<span className="text-sm text-default-400">
启用后只允许局域网内的设备访问WebUI,提高安全性
</span>
</div>
</Switch>
)}
/>
</div>
</div>
<SaveButtons
onSubmit={onSubmit}
reset={reset}
isSubmitting={isSubmitting || configLoading}
refresh={onRefresh}
/>
</>
)
}
export default ServerConfigCard
+2 -33
View File
@@ -1,46 +1,15 @@
import { Spinner } from '@heroui/spinner'
import { AnimatePresence, motion } from 'motion/react'
import { Suspense, useEffect } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import { Suspense } from 'react'
import { Outlet, useLocation } from 'react-router-dom'
import useAuth from '@/hooks/auth'
import useDialog from '@/hooks/use-dialog'
import WebUIManager from '@/controllers/webui_manager'
import DefaultLayout from '@/layouts/default'
const CheckDefaultPassword = () => {
const { isAuth } = useAuth()
const dialog = useDialog()
const navigate = useNavigate()
const checkDefaultPassword = async () => {
const data = await WebUIManager.checkUsingDefaultToken()
if (data) {
dialog.confirm({
title: '修改默认密码',
content: '检测到当前密码为默认密码,请尽快修改密码。',
confirmText: '前往修改',
onConfirm: () => {
navigate('/config?tab=token')
}
})
}
}
useEffect(() => {
if (isAuth) {
checkDefaultPassword()
}
}, [isAuth])
return null
}
export default function IndexPage() {
const location = useLocation()
return (
<DefaultLayout>
<CheckDefaultPassword />
<Suspense
fallback={
<div className="flex justify-center px-10">
+58 -36
View File
@@ -25,7 +25,6 @@ export default function WebLoginPage() {
const [tokenValue, setTokenValue] = useState<string>(token || '')
const [isLoading, setIsLoading] = useState<boolean>(false)
const [, setLocalToken] = useLocalStorage<string>(key.token, '')
const onSubmit = async () => {
if (!tokenValue) {
toast.error('请输入token')
@@ -93,42 +92,65 @@ export default function WebLoginPage() {
</CardHeader>
<CardBody className="flex gap-5 py-5 px-5 md:px-10">
<Input
isClearable
type="password"
classNames={{
label: 'text-black/50 dark:text-white/90',
input: [
'bg-transparent',
'text-black/90 dark:text-white/90',
'placeholder:text-default-700/50 dark:placeholder:text-white/60'
],
innerWrapper: 'bg-transparent',
inputWrapper: [
'shadow-xl',
'bg-default-100/70',
'dark:bg-default/60',
'backdrop-blur-xl',
'backdrop-saturate-200',
'hover:bg-default-0/70',
'dark:hover:bg-default/70',
'group-data-[focus=true]:bg-default-100/50',
'dark:group-data-[focus=true]:bg-default/60',
'!cursor-text'
]
<form
onSubmit={(e) => {
e.preventDefault()
onSubmit()
}}
isDisabled={isLoading}
label="Token"
placeholder="请输入token"
radius="lg"
size="lg"
startContent={
<IoKeyOutline className="text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0" />
}
value={tokenValue}
onChange={(e) => setTokenValue(e.target.value)}
onClear={() => setTokenValue('')}
/>
>
{/* 隐藏的用户名字段,帮助浏览器识别登录表单 */}
<input
type="text"
name="username"
value="napcat-webui"
autoComplete="username"
className="absolute -left-[9999px] opacity-0 pointer-events-none"
readOnly
tabIndex={-1}
aria-label="Username"
/>
<Input
isClearable
type="password"
name="password"
autoComplete="current-password"
classNames={{
label: 'text-black/50 dark:text-white/90',
input: [
'bg-transparent',
'text-black/90 dark:text-white/90',
'placeholder:text-default-700/50 dark:placeholder:text-white/60'
],
innerWrapper: 'bg-transparent',
inputWrapper: [
'shadow-xl',
'bg-default-100/70',
'dark:bg-default/60',
'backdrop-blur-xl',
'backdrop-saturate-200',
'hover:bg-default-0/70',
'dark:hover:bg-default/70',
'group-data-[focus=true]:bg-default-100/50',
'dark:group-data-[focus=true]:bg-default/60',
'!cursor-text'
]
}}
isDisabled={isLoading}
label="Token"
placeholder="请输入token"
radius="lg"
size="lg"
startContent={
<IoKeyOutline className="text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0" />
}
value={tokenValue}
onChange={(e) => setTokenValue(e.target.value)}
onClear={() => setTokenValue('')}
/>
</form>
<div className="text-center text-small text-default-600 dark:text-default-400 px-2">
💡 提示:请从 NapCat 启动日志中查看登录密钥
</div>
<Button
className="mx-10 mt-10 text-lg py-7"
color="primary"
+8
View File
@@ -181,3 +181,11 @@ interface ThemeConfig {
dark: ThemeConfigItem
light: ThemeConfigItem
}
interface WebUIConfig {
host: string
port: number
loginRate: number
disableWebUI: boolean
disableNonLANAccess: boolean
}
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "napcat",
"private": true,
"type": "module",
"version": "4.8.101",
"version": "4.8.113",
"scripts": {
"build:universal": "npm run build:webui && vite build --mode universal || exit 1",
"build:framework": "npm run build:webui && vite build --mode framework || exit 1",
+328
View File
@@ -0,0 +1,328 @@
export interface ResourceConfig<T extends any[], R> {
/** 资源获取函数 */
resourceFn: (...args: T) => Promise<R>;
/** 失败后禁用时间(毫秒),默认 30 秒 */
disableTime?: number;
/** 最大重试次数,默认 3 次 */
maxRetries?: number;
/** 主动测试间隔(毫秒),默认 60 秒 */
healthCheckInterval?: number;
/** 最大健康检查失败次数,超过后永久禁用,默认 5 次 */
maxHealthCheckFailures?: number;
/** 资源名称(用于日志) */
name?: string;
/** 测试参数(用于健康检查) */
testArgs?: T;
/** 健康检查函数,如果提供则优先使用此函数进行健康检查 */
healthCheckFn?: (...args: T) => Promise<boolean>;
}
interface ResourceState<T extends any[], R> {
config: ResourceConfig<T, R>;
isEnabled: boolean;
disableUntil: number;
currentRetries: number;
healthCheckFailureCount: number;
isPermanentlyDisabled: boolean;
lastError?: Error;
lastHealthCheckTime: number;
registrationKey: string;
}
export class ResourceManager {
private resources = new Map<string, ResourceState<any, any>>();
private destroyed = false;
private healthCheckTimer?: NodeJS.Timeout;
private readonly HEALTH_CHECK_TASK_INTERVAL = 5000; // 5秒执行一次健康检查任务
constructor() {
this.startHealthCheckTask();
}
/**
* 注册资源(注册即调用,重复注册只实际注册一次)
*/
async register<T extends any[], R>(
key: string,
config: ResourceConfig<T, R>,
...args: T
): Promise<R> {
if (this.destroyed) {
throw new Error('ResourceManager has been destroyed');
}
const registrationKey = this.generateRegistrationKey(key, config);
// 检查是否已经注册
if (this.resources.has(key)) {
const existingState = this.resources.get(key)!;
// 如果是相同的配置,直接调用
if (existingState.registrationKey === registrationKey) {
return this.callResource<T, R>(key, ...args);
}
// 配置不同,清理旧的并重新注册
this.unregister(key);
}
// 创建新的资源状态
const state: ResourceState<T, R> = {
config: {
disableTime: 30000,
maxRetries: 3,
healthCheckInterval: 60000,
maxHealthCheckFailures: 5,
name: key,
...config
},
isEnabled: true,
disableUntil: 0,
currentRetries: 0,
healthCheckFailureCount: 0,
isPermanentlyDisabled: false,
lastHealthCheckTime: 0,
registrationKey
};
this.resources.set(key, state);
// 注册即调用
return await this.callResource<T, R>(key, ...args);
}
/**
* 调用资源
*/
async callResource<T extends any[], R>(key: string, ...args: T): Promise<R> {
const state = this.resources.get(key) as ResourceState<T, R> | undefined;
if (!state) {
throw new Error(`Resource ${key} not registered`);
}
if (state.isPermanentlyDisabled) {
throw new Error(`Resource ${key} is permanently disabled due to repeated health check failures`);
}
if (!this.isResourceAvailable(key)) {
const disableUntilDate = new Date(state.disableUntil).toISOString();
throw new Error(`Resource ${key} is currently disabled until ${disableUntilDate}`);
}
try {
const result = await state.config.resourceFn(...args);
this.onResourceSuccess(state);
return result;
} catch (error) {
this.onResourceFailure(state, error as Error);
throw error;
}
}
/**
* 检查资源是否可用
*/
isResourceAvailable(key: string): boolean {
const state = this.resources.get(key);
if (!state) {
return false;
}
if (state.isPermanentlyDisabled || !state.isEnabled) {
return false;
}
return Date.now() >= state.disableUntil;
}
/**
* 注销资源
*/
unregister(key: string): boolean {
return this.resources.delete(key);
}
/**
* 销毁管理器,清理所有资源
*/
destroy(): void {
if (this.destroyed) {
return;
}
this.stopHealthCheckTask();
this.resources.clear();
this.destroyed = true;
}
private generateRegistrationKey<T extends any[], R>(key: string, config: ResourceConfig<T, R>): string {
const configStr = JSON.stringify({
name: config.name,
disableTime: config.disableTime,
maxRetries: config.maxRetries,
healthCheckInterval: config.healthCheckInterval,
maxHealthCheckFailures: config.maxHealthCheckFailures,
functionStr: config.resourceFn.toString(),
healthCheckFnStr: config.healthCheckFn?.toString()
});
return `${key}_${this.simpleHash(configStr)}`;
}
private simpleHash(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash).toString(36);
}
private onResourceSuccess<T extends any[], R>(state: ResourceState<T, R>): void {
state.currentRetries = 0;
state.disableUntil = 0;
state.healthCheckFailureCount = 0;
state.lastError = undefined;
}
private onResourceFailure<T extends any[], R>(state: ResourceState<T, R>, error: Error): void {
state.currentRetries++;
state.lastError = error;
// 如果重试次数达到上限,禁用资源
if (state.currentRetries >= state.config.maxRetries!) {
state.disableUntil = Date.now() + state.config.disableTime!;
state.currentRetries = 0;
}
}
private startHealthCheckTask(): void {
if (this.healthCheckTimer) {
return;
}
this.healthCheckTimer = setInterval(() => {
this.runHealthCheckTask();
}, this.HEALTH_CHECK_TASK_INTERVAL);
}
private stopHealthCheckTask(): void {
if (this.healthCheckTimer) {
clearInterval(this.healthCheckTimer);
this.healthCheckTimer = undefined;
}
}
private async runHealthCheckTask(): Promise<void> {
if (this.destroyed) {
return;
}
const now = Date.now();
for (const [key, state] of this.resources) {
// 跳过永久禁用或可用的资源
if (state.isPermanentlyDisabled || this.isResourceAvailable(key)) {
continue;
}
// 跳过还在禁用期内的资源
if (now < state.disableUntil) {
continue;
}
// 检查是否需要进行健康检查(根据间隔时间)
const lastHealthCheck = state.lastHealthCheckTime || 0;
const healthCheckInterval = state.config.healthCheckInterval!;
if (now - lastHealthCheck < healthCheckInterval) {
continue;
}
// 执行健康检查
await this.performHealthCheck(state);
}
}
private async performHealthCheck<T extends any[], R>(state: ResourceState<T, R>): Promise<void> {
state.lastHealthCheckTime = Date.now();
try {
let healthCheckResult: boolean;
// 如果有专门的健康检查函数,使用它
if (state.config.healthCheckFn) {
const testArgs = state.config.testArgs || [] as unknown as T;
healthCheckResult = await state.config.healthCheckFn(...testArgs);
} else {
// 否则使用原始函数进行检查
const testArgs = state.config.testArgs || [] as unknown as T;
await state.config.resourceFn(...testArgs);
healthCheckResult = true;
}
if (healthCheckResult) {
// 健康检查成功,重新启用
state.isEnabled = true;
state.disableUntil = 0;
state.currentRetries = 0;
state.healthCheckFailureCount = 0;
state.lastError = undefined;
} else {
throw new Error('Health check function returned false');
}
} catch (error) {
// 健康检查失败,增加失败计数
state.healthCheckFailureCount++;
state.lastError = error as Error;
// 检查是否达到最大健康检查失败次数
if (state.healthCheckFailureCount >= state.config.maxHealthCheckFailures!) {
// 永久禁用资源
state.isPermanentlyDisabled = true;
state.disableUntil = 0;
} else {
// 继续禁用一段时间
state.disableUntil = Date.now() + state.config.disableTime!;
}
}
}
}
// 创建全局实例
export const resourceManager = new ResourceManager();
// 便捷函数
export async function registerResource<T extends any[], R>(
key: string,
config: ResourceConfig<T, R>,
...args: T
): Promise<R> {
return resourceManager.register(key, config, ...args);
}
// 使用示例:
/*
await registerResource(
'api-with-health-check',
{
resourceFn: async (id: string) => {
const response = await fetch(`https://api.example.com/data/${id}`);
return response.json();
},
healthCheckFn: async (id: string) => {
try {
const response = await fetch(`https://api.example.com/health`);
return response.ok;
} catch {
return false;
}
},
testArgs: ['health-check-id'],
healthCheckInterval: 30000,
maxHealthCheckFailures: 3
},
'user123'
);
*/
+2
View File
@@ -9,6 +9,7 @@ export class NapCatPathWrapper {
configPath: string;
cachePath: string;
staticPath: string;
pluginPath: string;
constructor(mainPath: string = dirname(fileURLToPath(import.meta.url))) {
this.binaryPath = mainPath;
@@ -24,6 +25,7 @@ export class NapCatPathWrapper {
this.logsPath = path.join(writePath, 'logs');
this.configPath = path.join(writePath, 'config');
this.pluginPath = path.join(writePath, 'plugins');//dynamic load
this.cachePath = path.join(writePath, 'cache');
this.staticPath = path.join(this.binaryPath, 'static');
if (!fs.existsSync(this.logsPath)) {
+1 -1
View File
@@ -1 +1 @@
export const napCatVersion = '4.8.101';
export const napCatVersion = '4.8.113';
+20 -21
View File
@@ -42,8 +42,8 @@ export class NTQQFileApi {
this.context = context;
this.core = core;
this.rkeyManager = new RkeyManager([
'https://secret-service.bietiaop.com/rkeys',
'http://ss.xingzhige.com/music_card/rkey',
'https://secret-service.bietiaop.com/rkeys',
],
this.context.logger
);
@@ -64,13 +64,13 @@ export class NTQQFileApi {
}
}
async getFileUrl(chatType: ChatType, peer: string, fileUUID?: string, file10MMd5?: string | undefined) {
async getFileUrl(chatType: ChatType, peer: string, fileUUID?: string, file10MMd5?: string | undefined,timeout: number = 20000) {
if (this.core.apis.PacketApi.packetStatus) {
try {
if (chatType === ChatType.KCHATTYPEGROUP && fileUUID) {
return this.core.apis.PacketApi.pkt.operation.GetGroupFileUrl(+peer, fileUUID);
return this.core.apis.PacketApi.pkt.operation.GetGroupFileUrl(+peer, fileUUID, timeout);
} else if (file10MMd5 && fileUUID) {
return this.core.apis.PacketApi.pkt.operation.GetPrivateFileUrl(peer, fileUUID, file10MMd5);
return this.core.apis.PacketApi.pkt.operation.GetPrivateFileUrl(peer, fileUUID, file10MMd5, timeout);
}
} catch (error) {
this.context.logger.logError('获取文件URL失败', (error as Error).message);
@@ -79,7 +79,7 @@ export class NTQQFileApi {
throw new Error('fileUUID or file10MMd5 is undefined');
}
async getPttUrl(peer: string, fileUUID?: string) {
async getPttUrl(peer: string, fileUUID?: string,timeout: number = 20000) {
if (this.core.apis.PacketApi.packetStatus && fileUUID) {
let appid = new NapProtoMsg(FileId).decode(Buffer.from(fileUUID.replaceAll('-', '+').replaceAll('_', '/'), 'base64')).appid;
try {
@@ -90,7 +90,7 @@ export class NTQQFileApi {
uploadTime: 0,
ttl: 0,
subType: 0,
});
}, timeout);
} else if (fileUUID) {
return this.core.apis.PacketApi.pkt.operation.GetPttUrl(peer, {
fileUuid: fileUUID,
@@ -98,7 +98,7 @@ export class NTQQFileApi {
uploadTime: 0,
ttl: 0,
subType: 0,
});
}, timeout);
}
} catch (error) {
this.context.logger.logError('获取文件URL失败', (error as Error).message);
@@ -107,7 +107,7 @@ export class NTQQFileApi {
throw new Error('packet cant get ptt url');
}
async getVideoUrlPacket(peer: string, fileUUID?: string) {
async getVideoUrlPacket(peer: string, fileUUID?: string,timeout: number = 20000) {
if (this.core.apis.PacketApi.packetStatus && fileUUID) {
let appid = new NapProtoMsg(FileId).decode(Buffer.from(fileUUID.replaceAll('-', '+').replaceAll('_', '/'), 'base64')).appid;
try {
@@ -118,7 +118,7 @@ export class NTQQFileApi {
uploadTime: 0,
ttl: 0,
subType: 0,
});
}, timeout);
} else if (fileUUID) {
return this.core.apis.PacketApi.pkt.operation.GetVideoUrl(peer, {
fileUuid: fileUUID,
@@ -126,7 +126,7 @@ export class NTQQFileApi {
uploadTime: 0,
ttl: 0,
subType: 0,
});
}, timeout);
}
} catch (error) {
this.context.logger.logError('获取文件URL失败', (error as Error).message);
@@ -260,23 +260,22 @@ export class NTQQFileApi {
const thumbDir = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`);
fs.mkdirSync(pathLib.dirname(thumbDir), { recursive: true });
const thumbPath = pathLib.join(pathLib.dirname(thumbDir), `${md5}_0.png`);
try {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
if (!fs.existsSync(thumbPath)) {
this.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
throw new Error('获取视频缩略图失败');
}
} catch (e) {
this.context.logger.logError('获取视频信息失败', e);
fs.writeFileSync(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
}
if (_diyThumbPath) {
try {
await this.copyFile(_diyThumbPath, thumbPath);
} catch (e) {
this.context.logger.logError('复制自定义缩略图失败', e);
}
} else {
try {
videoInfo = await FFmpegService.getVideoInfo(filePath, thumbPath);
if (!fs.existsSync(thumbPath)) {
this.context.logger.logError('获取视频缩略图失败', new Error('缩略图不存在'));
throw new Error('获取视频缩略图失败');
}
} catch (e) {
this.context.logger.logError('获取视频信息失败', e);
fs.writeFileSync(thumbPath, Buffer.from(defaultVideoThumbB64, 'base64'));
}
}
context.deleteAfterSentFiles.push(thumbPath);
const thumbSize = (await fsPromises.stat(thumbPath)).size;
+1 -1
View File
@@ -68,7 +68,7 @@ export class NTQQPacketApi {
this.pkt = new PacketClientSession(this.core);
await this.pkt.init(process.pid, table.recv, table.send);
try {
await this.pkt.operation.FetchRkey();
await this.pkt.operation.FetchRkey(1500);
} catch (error) {
this.logger.logError('测试Packet状态异常', error);
return false;
+16
View File
@@ -370,5 +370,21 @@
"9.9.21-38711": {
"appid": 537307655,
"qua": "V1_WIN_NQ_9.9.21_38626_GW_B"
},
"9.9.21-38960": {
"appid": 537313855,
"qua": "V1_WIN_NQ_9.9.21_38960_GW_B"
},
"3.2.19-38960": {
"appid": 537313891,
"qua": "V1_LNX_NQ_3.2.19_38960_GW_B"
},
"3.2.19-39038": {
"appid": 537313942,
"qua": "V1_LNX_NQ_3.2.19_39038_GW_B"
},
"9.9.21-39038": {
"appid": 537313906,
"qua": "V1_WIN_NQ_9.9.21_39038_GW_B"
}
}
+24
View File
@@ -486,5 +486,29 @@
"9.9.21-38711-x64": {
"send": "310A758",
"recv": "310DEFC"
},
"3.2.19-38960-x64": {
"send": "B3740E0",
"recv": "B377B60"
},
"9.9.21-38960-x64": {
"send": "313F7D8",
"recv": "3142F7C"
},
"3.2.19-38960-arm64": {
"send": "7B01D98",
"recv": "7B05728"
},
"3.2.19-39038-x64": {
"send": "B3759E0",
"recv": "B379460"
},
"3.2.19-39038-arm64": {
"send": "7B025C8",
"recv": "7B05F58"
},
"9.9.21-39038-x64": {
"send": "313FB58",
"recv": "31432FC"
}
}
+16 -22
View File
@@ -1,4 +1,3 @@
import { LRUCache } from '@/common/lru-cache';
import crypto, { createHash } from 'crypto';
import { OidbPacket, PacketHexStr } from '@/core/packet/transformer/base';
import { LogStack } from '@/core/packet/context/clientContext';
@@ -7,7 +6,6 @@ import { PacketLogger } from '@/core/packet/context/loggerContext';
export interface RecvPacket {
type: string, // 仅recv
trace_id_md5?: string,
data: RecvPacketData
}
@@ -30,7 +28,7 @@ function randText(len: number): string {
export abstract class IPacketClient {
protected readonly napcore: NapCoreContext;
protected readonly logger: PacketLogger;
protected readonly cb = new LRUCache<string, (json: RecvPacketData) => Promise<void>>(500); // trace_id-type callback
protected readonly cb = new Map<string, (json: RecvPacketData) => Promise<any> | any>(); // hash-type callback
logStack: LogStack;
available: boolean = false;
@@ -44,24 +42,21 @@ export abstract class IPacketClient {
abstract init(pid: number, recv: string, send: string): Promise<void>;
abstract sendCommandImpl(cmd: string, data: string, trace_id: string): void;
abstract sendCommandImpl(cmd: string, data: string, hash: string, timeout: number): void;
private async registerCallback(trace_id: string, type: string, callback: (json: RecvPacketData) => Promise<void>): Promise<void> {
this.cb.put(createHash('md5').update(trace_id).digest('hex') + type, callback);
}
private async sendCommand(cmd: string, data: string, trace_id: string, rsp: boolean = false, timeout: number = 20000, sendcb: (json: RecvPacketData) => void = () => {
private async sendCommand(cmd: string, data: string, trace_data: string, rsp: boolean = false, timeout: number = 20000, sendcb: (json: RecvPacketData) => void = () => {
}): Promise<RecvPacketData> {
return new Promise<RecvPacketData>((resolve, reject) => {
if (!this.available) {
reject(new Error('packetBackend 当前不可用!'));
}
let hash = createHash('md5').update(trace_data).digest('hex');
const timeoutHandle = setTimeout(() => {
reject(new Error(`sendCommand timed out after ${timeout} ms for ${cmd} with trace_id ${trace_id}`));
this.cb.delete(hash + 'send');
this.cb.delete(hash + 'recv');
reject(new Error(`sendCommand timed out after ${timeout} ms for ${cmd} with hash ${hash}`));
}, timeout);
this.registerCallback(trace_id, 'send', async (json: RecvPacketData) => {
this.cb.set(hash + 'send', async (json: RecvPacketData) => {
sendcb(json);
if (!rsp) {
clearTimeout(timeoutHandle);
@@ -70,25 +65,24 @@ export abstract class IPacketClient {
});
if (rsp) {
this.registerCallback(trace_id, 'recv', async (json: RecvPacketData) => {
this.cb.set(hash + 'recv', async (json: RecvPacketData) => {
clearTimeout(timeoutHandle);
resolve(json);
});
}
this.sendCommandImpl(cmd, data, trace_id);
this.sendCommandImpl(cmd, data, hash, timeout);
});
}
async sendPacket(cmd: string, data: PacketHexStr, rsp = false): Promise<RecvPacketData> {
async sendPacket(cmd: string, data: PacketHexStr, rsp = false, timeout = 20000): Promise<RecvPacketData> {
const md5 = crypto.createHash('md5').update(data).digest('hex');
const trace_id = (randText(4) + md5 + data).slice(0, data.length / 2);
return this.sendCommand(cmd, data, trace_id, rsp, 20000, async () => {
await this.napcore.sendSsoCmdReqByContend(cmd, trace_id);
const trace_data = (randText(4) + md5 + data).slice(0, data.length / 2);// trace_data
return this.sendCommand(cmd, data, trace_data, rsp, timeout, async () => {
await this.napcore.sendSsoCmdReqByContend(cmd, trace_data);
});
}
async sendOidbPacket(pkt: OidbPacket, rsp = false): Promise<RecvPacketData> {
return this.sendPacket(pkt.cmd, pkt.data, rsp);
async sendOidbPacket(pkt: OidbPacket, rsp = false, timeout = 20000): Promise<RecvPacketData> {
return this.sendPacket(pkt.cmd, pkt.data, rsp, timeout);
}
}
+19 -13
View File
@@ -4,7 +4,6 @@ import { fileURLToPath } from 'url';
import fs from 'fs';
import { IPacketClient } from '@/core/packet/client/baseClient';
import { constants } from 'node:os';
import { LRUCache } from '@/common/lru-cache';
import { LogStack } from '@/core/packet/context/clientContext';
import { NapCoreContext } from '@/core/packet/context/napCoreContext';
import { PacketLogger } from '@/core/packet/context/loggerContext';
@@ -18,7 +17,8 @@ export interface NativePacketExportType {
export class NativePacketClient extends IPacketClient {
private readonly supportedPlatforms = ['win32.x64', 'linux.x64', 'linux.arm64', 'darwin.x64', 'darwin.arm64'];
private readonly MoeHooExport: { exports: NativePacketExportType } = { exports: {} };
private readonly sendEvent = new LRUCache<number, string>(500); // seq->trace_id
private readonly sendEvent = new Map<number, string>(); // seq - hash
private readonly timeEvent = new Map<string, NodeJS.Timeout>(); // hash - timeout
constructor(napCore: NapCoreContext, logger: PacketLogger, logStack: LogStack) {
super(napCore, logger, logStack);
@@ -45,25 +45,31 @@ export class NativePacketClient extends IPacketClient {
process.dlopen(this.MoeHooExport, moehoo_path, constants.dlopen.RTLD_LAZY);
this.MoeHooExport.exports.InitHook?.(send, recv, (type: number, _uin: string, cmd: string, seq: number, hex_data: string) => {
const trace_id = createHash('md5').update(Buffer.from(hex_data, 'hex')).digest('hex');
if (type === 0 && this.cb.get(trace_id + 'recv')) {
const hash = createHash('md5').update(Buffer.from(hex_data, 'hex')).digest('hex');
if (type === 0 && this.cb.get(hash + 'recv')) {
//此时为send 提取seq
this.sendEvent.put(seq, trace_id);
this.sendEvent.set(seq, hash);
setTimeout(() => {
this.sendEvent.delete(seq);
this.timeEvent.delete(hash);
}, +(this.timeEvent.get(hash) ?? 20000));
//正式send完成 无recv v
//均无异常 v
}
if (type === 1 && this.sendEvent.get(seq)) {
//此时为recv 调用callback
const trace_id = this.sendEvent.get(seq);
const callback = this.cb.get(trace_id + 'recv');
// console.log('callback:', callback, trace_id);
const hash = this.sendEvent.get(seq);
const callback = this.cb.get(hash + 'recv');
callback?.({ seq, cmd, hex_data });
}
}, this.napcore.config.o3HookMode == 1);
this.available = true;
}
sendCommandImpl(cmd: string, data: string, trace_id: string): void {
const trace_id_md5 = createHash('md5').update(trace_id).digest('hex');
this.MoeHooExport.exports.SendPacket?.(cmd, data, trace_id_md5);
this.cb.get(trace_id_md5 + 'send')?.({ seq: 0, cmd, hex_data: '' });
sendCommandImpl(cmd: string, data: string, hash: string, timeout: number): void {
this.timeEvent.set(hash, setTimeout(() => {
this.timeEvent.delete(hash);//考虑情况为正式send都没进
}, timeout));
this.MoeHooExport.exports.SendPacket?.(cmd, data, hash);
this.cb.get(hash + 'send')?.({ seq: 0, cmd, hex_data: '' });
}
}
+2 -2
View File
@@ -73,8 +73,8 @@ export class PacketClientContext {
await this._client.init(pid, recv, send);
}
async sendOidbPacket<T extends boolean = false>(pkt: OidbPacket, rsp?: T): Promise<T extends true ? Buffer : void> {
const raw = await this._client.sendOidbPacket(pkt, rsp);
async sendOidbPacket<T extends boolean = false>(pkt: OidbPacket, rsp?: T, timeout?: number): Promise<T extends true ? Buffer : void> {
const raw = await this._client.sendOidbPacket(pkt, rsp, timeout);
return (rsp ? Buffer.from(raw.hex_data, 'hex') : undefined) as T extends true ? Buffer : void;
}
+16 -16
View File
@@ -38,9 +38,9 @@ export class PacketOperationContext {
const req = trans.SetGroupTodo.build(groupUin, msgSeq);
await this.context.client.sendOidbPacket(req, true);
}
async FetchRkey() {
async FetchRkey(timeout: number = 10000) {
const req = trans.FetchRkey.build();
const resp = await this.context.client.sendOidbPacket(req, true);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.FetchRkey.parse(resp);
return res.data.rkeyList;
}
@@ -122,37 +122,37 @@ export class PacketOperationContext {
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetPttUrl(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>) {
async GetPttUrl(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>,timeout: number = 20000) {
const req = trans.DownloadPtt.build(selfUid, node);
const resp = await this.context.client.sendOidbPacket(req, true);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadPtt.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetVideoUrl(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>) {
async GetVideoUrl(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>, timeout: number = 20000) {
const req = trans.DownloadVideo.build(selfUid, node);
const resp = await this.context.client.sendOidbPacket(req, true);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadVideo.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetGroupImageUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
async GetGroupImageUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>, timeout: number = 20000) {
const req = trans.DownloadGroupImage.build(groupUin, node);
const resp = await this.context.client.sendOidbPacket(req, true);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadImage.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetGroupPttUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
async GetGroupPttUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>, timeout: number = 20000) {
const req = trans.DownloadGroupPtt.build(groupUin, node);
const resp = await this.context.client.sendOidbPacket(req, true);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadImage.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
async GetGroupVideoUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
async GetGroupVideoUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>, timeout: number = 20000) {
const req = trans.DownloadGroupVideo.build(groupUin, node);
const resp = await this.context.client.sendOidbPacket(req, true);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadImage.parse(resp);
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
}
@@ -243,16 +243,16 @@ export class PacketOperationContext {
return res.rename.retCode;
}
async GetGroupFileUrl(groupUin: number, fileUUID: string) {
async GetGroupFileUrl(groupUin: number, fileUUID: string,timeout: number = 20000) {
const req = trans.DownloadGroupFile.build(groupUin, fileUUID);
const resp = await this.context.client.sendOidbPacket(req, true);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadGroupFile.parse(resp);
return `https://${res.download.downloadDns}/ftn_handler/${Buffer.from(res.download.downloadUrl).toString('hex')}/?fname=`;
}
async GetPrivateFileUrl(self_id: string, fileUUID: string, md5: string) {
async GetPrivateFileUrl(self_id: string, fileUUID: string, md5: string, timeout: number = 20000) {
const req = trans.DownloadPrivateFile.build(self_id, fileUUID, md5);
const resp = await this.context.client.sendOidbPacket(req, true);
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
const res = trans.DownloadPrivateFile.parse(resp);
return `http://${res.body?.result?.server}:${res.body?.result?.port}${res.body?.result?.url?.slice(8)}&isthumb=0`;
}
+3
View File
@@ -0,0 +1,3 @@
# Example Plugin
## Install
安装只需要将dist产物 `index.mjs` 目录放入 napcat根目录下`plugins/example`,如果没有这个目录请创建。
+12
View File
@@ -0,0 +1,12 @@
import { EventType } from "@/onebot/event/OneBotEvent";
import type { PluginModule } from "@/onebot/network/plugin-manger";
const plugin_init: PluginModule["plugin_init"] = async (_core, _obContext, _actions, _instance) => {
console.log(`[Plugin: example] 插件已初始化`);
}
const plugin_onmessage: PluginModule["plugin_onmessage"] = async (adapter, _core, _obCtx, event, actions, instance) => {
if (event.post_type === EventType.MESSAGE && event.raw_message.includes('ping')) {
await actions.get('send_group_msg')?.handle({ group_id: String(event.group_id), message: 'pong' }, adapter, instance.config);
}
}
export { plugin_init, plugin_onmessage };
+10
View File
@@ -0,0 +1,10 @@
{
"name": "advanced-plugin",
"version": "1.0.0",
"type": "module",
"main": "index.mjs",
"description": "一个高级的 NapCat 插件示例",
"scripts": {
"build": "vite build"
}
}
+30
View File
@@ -0,0 +1,30 @@
import { defineConfig } from 'vite';
import { resolve } from 'path';
import nodeResolve from '@rollup/plugin-node-resolve';
import { builtinModules } from 'module';
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
export default defineConfig({
resolve: {
conditions: ['node', 'default'],
alias: {
'@/core': resolve(__dirname, '../core'),
'@': resolve(__dirname, '../'),
},
},
build: {
sourcemap: false,
target: 'esnext',
minify: false,
lib: {
entry: 'index.ts',
formats: ['es'],
fileName: () => 'index.mjs',
},
rollupOptions: {
external: [...nodeModules],
},
},
plugins: [nodeResolve()],
});
+10 -8
View File
@@ -29,7 +29,9 @@ export class OB11Response {
return this.createResponse(null, 'failed', retcode, err, echo);
}
}
export interface OneBotRequestToolkit<T = unknown> {
send: (data: T) => Promise<void>;
}
export abstract class OneBotAction<PayloadType, ReturnDataType> {
actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown;
core: NapCatCore;
@@ -57,27 +59,27 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
return { valid: true };
}
public async handle(payload: PayloadType, adaptername: string, config: NetworkAdapterConfig): Promise<OB11Return<ReturnDataType | null>> {
public async handle(payload: PayloadType, adaptername: string, config: NetworkAdapterConfig, req: OneBotRequestToolkit = { send: async () => { } }, echo?: string): Promise<OB11Return<ReturnDataType | null>> {
const result = await this.check(payload);
if (!result.valid) {
return OB11Response.error(result.message, 400);
}
try {
const resData = await this._handle(payload, adaptername, config);
return OB11Response.ok(resData);
const resData = await this._handle(payload, adaptername, config, req);
return OB11Response.ok(resData, echo);
} catch (e: unknown) {
this.core.context.logger.logError('发生错误', e);
return OB11Response.error((e as Error).message.toString() || (e as Error)?.stack?.toString() || '未知错误,可能操作超时', 200);
return OB11Response.error((e as Error).message.toString() || (e as Error)?.stack?.toString() || '未知错误,可能操作超时', 200, echo);
}
}
public async websocketHandle(payload: PayloadType, echo: unknown, adaptername: string, config: NetworkAdapterConfig): Promise<OB11Return<ReturnDataType | null>> {
public async websocketHandle(payload: PayloadType, echo: unknown, adaptername: string, config: NetworkAdapterConfig, req: OneBotRequestToolkit = { send: async () => { } }): Promise<OB11Return<ReturnDataType | null>> {
const result = await this.check(payload);
if (!result.valid) {
return OB11Response.error(result.message, 1400, echo);
}
try {
const resData = await this._handle(payload, adaptername, config);
const resData = await this._handle(payload, adaptername, config, req);
return OB11Response.ok(resData, echo);
} catch (e: unknown) {
this.core.context.logger.logError('发生错误', e);
@@ -85,5 +87,5 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
}
}
abstract _handle(payload: PayloadType, adaptername: string, config: NetworkAdapterConfig): Promise<ReturnDataType>;
abstract _handle(payload: PayloadType, adaptername: string, config: NetworkAdapterConfig, req: OneBotRequestToolkit): Promise<ReturnDataType>;
}
+2 -2
View File
@@ -41,12 +41,12 @@ export class GetFileBase extends OneBotAction<GetFilePayload, GetFileResponse> {
let url = '';
if (mixElement?.picElement && rawMessage) {
const tempData =
await this.obContext.apis.MsgApi.rawToOb11Converters.picElement?.(mixElement?.picElement, rawMessage, mixElement, { parseMultMsg: false }) as OB11MessageImage | undefined;
await this.obContext.apis.MsgApi.rawToOb11Converters.picElement?.(mixElement?.picElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: true }) as OB11MessageImage | undefined;
url = tempData?.data.url ?? '';
}
if (mixElement?.videoElement && rawMessage) {
const tempData =
await this.obContext.apis.MsgApi.rawToOb11Converters.videoElement?.(mixElement?.videoElement, rawMessage, mixElement, { parseMultMsg: false }) as OB11MessageVideo | undefined;
await this.obContext.apis.MsgApi.rawToOb11Converters.videoElement?.(mixElement?.videoElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: true }) as OB11MessageVideo | undefined;
url = tempData?.data.url ?? '';
}
const res: GetFileResponse = {
+1 -1
View File
@@ -130,7 +130,7 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, {
throw new Error('消息不存在或已过期');
}
// 6. 解析消息内容
const resMsg = (await this.obContext.apis.MsgApi.parseMessageV2(singleMsg))?.arrayMsg;
const resMsg = (await this.obContext.apis.MsgApi.parseMessage(singleMsg, 'array', true));
const forwardContent = (resMsg?.message?.[0] as OB11MessageForward)?.data?.content;
if (forwardContent) {
@@ -14,7 +14,10 @@ const SchemaData = Type.Object({
user_id: Type.String(),
message_seq: Type.Optional(Type.String()),
count: Type.Number({ default: 20 }),
reverseOrder: Type.Boolean({ default: false })
reverseOrder: Type.Boolean({ default: false }),
disable_get_url: Type.Boolean({ default: false }),
parse_mult_msg: Type.Boolean({ default: true }),
quick_reply: Type.Boolean({ default: false }),
});
@@ -41,7 +44,7 @@ export default class GetFriendMsgHistory extends OneBotAction<Payload, Response>
}));
//烘焙消息
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat)))
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url)))
).filter(msg => msg !== undefined);
return { 'messages': ob11MsgList };
}
@@ -14,7 +14,10 @@ const SchemaData = Type.Object({
group_id: Type.String(),
message_seq: Type.Optional(Type.String()),
count: Type.Number({ default: 20 }),
reverseOrder: Type.Boolean({ default: false })
reverseOrder: Type.Boolean({ default: false }),
disable_get_url: Type.Boolean({ default: false }),
parse_mult_msg: Type.Boolean({ default: true }),
quick_reply: Type.Boolean({ default: false }),
});
@@ -39,7 +42,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction<Payload, Re
}));
//烘焙消息
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat)))
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url, payload.quick_reply)))
).filter(msg => msg !== undefined);
return { 'messages': ob11MsgList };
}
+8
View File
@@ -130,10 +130,18 @@ import { DoGroupAlbumComment } from './extends/DoGroupAlbumComment';
import { GetGroupAlbumMediaList } from './extends/GetGroupAlbumMediaList';
import { SetGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
import { DelGroupAlbumMedia } from './extends/DelGroupAlbumMedia';
import { CleanStreamTempFile } from './stream/CleanStreamTempFile';
import { DownloadFileStream } from './stream/DownloadFileStream';
import { TestStreamDownload } from './stream/TestStreamDownload';
import { UploadFileStream } from './stream/UploadFileStream';
export function createActionMap(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
const actionHandlers = [
new CleanStreamTempFile(obContext, core),
new DownloadFileStream(obContext, core),
new TestStreamDownload(obContext, core),
new UploadFileStream(obContext, core),
new DelGroupAlbumMedia(obContext, core),
new SetGroupAlbumMediaLike(obContext, core),
new DoGroupAlbumComment(obContext, core),
+4
View File
@@ -10,6 +10,10 @@ export interface InvalidCheckResult {
}
export const ActionName = {
CleanStreamTempFile: 'clean_stream_temp_file',
TestStreamDownload: 'test_stream_download',
UploadFileStream: 'upload_file_stream',
DownloadFileStream: 'download_file_stream',
DelGroupAlbumMedia: 'del_group_album_media',
SetGroupAlbumMediaLike: 'set_group_album_media_like',
DoGroupAlbumComment: 'do_group_album_comment',
@@ -0,0 +1,33 @@
import { ActionName } from '@/onebot/action/router';
import { OneBotAction } from '@/onebot/action/OneBotAction';
import { join } from 'node:path';
import { readdir, unlink } from 'node:fs/promises';
export class CleanStreamTempFile extends OneBotAction<void, void> {
override actionName = ActionName.CleanStreamTempFile;
async _handle(_payload: void): Promise<void> {
try {
// 获取临时文件夹路径
const tempPath = this.core.NapCatTempPath;
// 读取文件夹中的所有文件
const files = await readdir(tempPath);
// 删除每个文件
const deletePromises = files.map(async (file) => {
const filePath = join(tempPath, file);
try {
await unlink(filePath);
this.core.context.logger.log(`已删除文件: ${filePath}`);
} catch (err: unknown) {
this.core.context.logger.log(`删除文件 ${filePath} 失败: ${(err as Error).message}`);
}
});
await Promise.all(deletePromises);
} catch (err: unknown) {
this.core.context.logger.log(`清理流临时文件失败: ${(err as Error).message}`);
}
}
}
@@ -0,0 +1,101 @@
import { ActionName } from '@/onebot/action/router';
import { OneBotAction, OneBotRequestToolkit } from '@/onebot/action/OneBotAction';
import { Static, Type } from '@sinclair/typebox';
import { NetworkAdapterConfig } from '@/onebot/config/config';
import fs from 'fs';
import { FileNapCatOneBotUUID } from '@/common/file-uuid';
const SchemaData = Type.Object({
file: Type.Optional(Type.String()),
file_id: Type.Optional(Type.String()),
chunk_size: Type.Optional(Type.Number({ default: 64 * 1024 })) // 默认64KB分块
});
type Payload = Static<typeof SchemaData>;
export class DownloadFileStream extends OneBotAction<Payload, void> {
override actionName = ActionName.DownloadFileStream;
override payloadSchema = SchemaData;
async _handle(payload: Payload, _adaptername: string, _config: NetworkAdapterConfig, req: OneBotRequestToolkit) {
payload.file ||= payload.file_id || '';
const chunkSize = payload.chunk_size || 64 * 1024;
let downloadPath = '';
let fileName = '';
let fileSize = 0;
//接收消息标记模式
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file);
if (contextMsgFile && contextMsgFile.msgId && contextMsgFile.elementId) {
const { peer, msgId, elementId } = contextMsgFile;
downloadPath = await this.core.apis.FileApi.downloadMedia(msgId, peer.chatType, peer.peerUid, elementId, '', '');
const rawMessage = (await this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgId]))?.msgList
.find(msg => msg.msgId === msgId);
const mixElement = rawMessage?.elements.find(e => e.elementId === elementId);
const mixElementInner = mixElement?.videoElement ?? mixElement?.fileElement ?? mixElement?.pttElement ?? mixElement?.picElement;
if (!mixElementInner) throw new Error('element not found');
fileSize = parseInt(mixElementInner.fileSize?.toString() ?? '0');
fileName = mixElementInner.fileName ?? '';
}
//群文件模式
else if (FileNapCatOneBotUUID.decodeModelId(payload.file)) {
const contextModelIdFile = FileNapCatOneBotUUID.decodeModelId(payload.file);
if (contextModelIdFile && contextModelIdFile.modelId) {
const { peer, modelId } = contextModelIdFile;
downloadPath = await this.core.apis.FileApi.downloadFileForModelId(peer, modelId, '');
}
}
//搜索名字模式
else {
const searchResult = (await this.core.apis.FileApi.searchForFile([payload.file]));
if (searchResult) {
downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, parseInt(searchResult.fileSize));
fileSize = parseInt(searchResult.fileSize);
fileName = searchResult.fileName;
}
}
if (!downloadPath) {
throw new Error('file not found');
}
// 获取文件大小
const stats = await fs.promises.stat(downloadPath);
const totalSize = fileSize || stats.size;
// 发送文件信息
req.send({
type: 'file_info',
file_name: fileName,
file_size: totalSize,
chunk_size: chunkSize
});
// 创建读取流并分块发送
const readStream = fs.createReadStream(downloadPath, { highWaterMark: chunkSize });
let chunkIndex = 0;
let bytesRead = 0;
for await (const chunk of readStream) {
const base64Chunk = chunk.toString('base64');
bytesRead += chunk.length;
req.send({
type: 'chunk',
index: chunkIndex,
data: base64Chunk,
size: chunk.length,
progress: Math.round((bytesRead / totalSize) * 100),
base64_size: base64Chunk.length
});
chunkIndex++;
}
// 发送完成信号
req.send({
type: 'complete',
total_chunks: chunkIndex,
total_bytes: bytesRead
});
}
}
@@ -0,0 +1,23 @@
import { ActionName } from '@/onebot/action/router';
import { OneBotAction, OneBotRequestToolkit } from '@/onebot/action/OneBotAction';
import { Static, Type } from '@sinclair/typebox';
import { NetworkAdapterConfig } from '@/onebot/config/config';
const SchemaData = Type.Object({
});
type Payload = Static<typeof SchemaData>;
export class TestStreamDownload extends OneBotAction<Payload, string> {
override actionName = ActionName.TestStreamDownload;
override payloadSchema = SchemaData;
async _handle(_payload: Payload, _adaptername: string, _config: NetworkAdapterConfig, req: OneBotRequestToolkit) {
for (let i = 0; i < 10; i++) {
req.send({ index: i });
await new Promise(resolve => setTimeout(resolve, 100));
}
return 'done';
}
}
@@ -0,0 +1,368 @@
import asyncio
import websockets
import json
import base64
import hashlib
import os
from typing import Optional, Dict, Set
import time
from dataclasses import dataclass
@dataclass
class ChunkInfo:
index: int
data: bytes
size: int
retry_count: int = 0
uploaded: bool = False
class FileUploadTester:
def __init__(self, ws_uri: str, file_path: str, max_concurrent: int = 5):
self.ws_uri = ws_uri
self.file_path = file_path
self.chunk_size = 64 * 1024 # 64KB per chunk
self.max_concurrent = max_concurrent # 最大并发数
self.max_retries = 3 # 最大重试次数
self.stream_id = None
self.chunks: Dict[int, ChunkInfo] = {}
self.upload_semaphore = asyncio.Semaphore(max_concurrent)
self.failed_chunks: Set[int] = set()
# 消息路由机制
self.response_futures: Dict[str, asyncio.Future] = {}
self.message_receiver_task = None
async def connect_and_upload(self):
"""连接到WebSocket并上传文件"""
async with websockets.connect(self.ws_uri) as ws:
print(f"已连接到 {self.ws_uri}")
# 启动消息接收器
self.message_receiver_task = asyncio.create_task(self._message_receiver(ws))
try:
# 准备文件数据
file_info = self.prepare_file()
if not file_info:
return
print(f"文件信息: {file_info['filename']}, 大小: {file_info['file_size']} bytes, 块数: {file_info['total_chunks']}")
print(f"并发设置: 最大 {self.max_concurrent} 个并发上传")
# 生成stream_id
self.stream_id = f"upload_{hash(file_info['filename'] + str(file_info['file_size']))}"
print(f"Stream ID: {self.stream_id}")
# 重置流(如果存在)
await self.reset_stream(ws)
# 准备所有分片
self.prepare_chunks(file_info)
# 并行上传分片
await self.upload_chunks_parallel(ws, file_info)
# 重试失败的分片
if self.failed_chunks:
await self.retry_failed_chunks(ws, file_info)
# 完成上传
await self.complete_upload(ws)
# 等待一段时间确保所有响应都收到
await asyncio.sleep(2)
finally:
# 取消消息接收器
if self.message_receiver_task:
self.message_receiver_task.cancel()
try:
await self.message_receiver_task
except asyncio.CancelledError:
pass
# 清理未完成的Future
for future in self.response_futures.values():
if not future.done():
future.cancel()
async def _message_receiver(self, ws):
"""专门的消息接收协程,负责分发响应到对应的Future"""
try:
while True:
message = await ws.recv()
try:
data = json.loads(message)
echo = data.get('echo', 'unknown')
# 查找对应的Future
if echo in self.response_futures:
future = self.response_futures[echo]
if not future.done():
future.set_result(data)
else:
# 处理未预期的响应
print(f"📨 未预期响应 [{echo}]: {data}")
except json.JSONDecodeError as e:
print(f"⚠️ JSON解析错误: {e}")
except Exception as e:
print(f"⚠️ 消息处理错误: {e}")
except asyncio.CancelledError:
print("🔄 消息接收器已停止")
raise
except Exception as e:
print(f"💥 消息接收器异常: {e}")
async def _send_and_wait_response(self, ws, request: dict, timeout: float = 10.0) -> Optional[dict]:
"""发送请求并等待响应"""
echo = request.get('echo', 'unknown')
# 创建Future用于接收响应
future = asyncio.Future()
self.response_futures[echo] = future
try:
# 发送请求
await ws.send(json.dumps(request))
# 等待响应
response = await asyncio.wait_for(future, timeout=timeout)
return response
except asyncio.TimeoutError:
print(f"⏰ 请求超时: {echo}")
return None
except Exception as e:
print(f"💥 请求异常: {echo} - {e}")
return None
finally:
# 清理Future
if echo in self.response_futures:
del self.response_futures[echo]
def prepare_file(self):
"""准备文件信息"""
if not os.path.exists(self.file_path):
print(f"文件不存在: {self.file_path}")
return None
file_size = os.path.getsize(self.file_path)
filename = os.path.basename(self.file_path)
total_chunks = (file_size + self.chunk_size - 1) // self.chunk_size
# 计算SHA256
print("计算文件SHA256...")
sha256_hash = hashlib.sha256()
with open(self.file_path, 'rb') as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256_hash.update(chunk)
expected_sha256 = sha256_hash.hexdigest()
return {
'filename': filename,
'file_size': file_size,
'total_chunks': total_chunks,
'expected_sha256': expected_sha256
}
def prepare_chunks(self, file_info):
"""预读取所有分片数据"""
print("预读取分片数据...")
with open(self.file_path, 'rb') as f:
for chunk_index in range(file_info['total_chunks']):
chunk_data = f.read(self.chunk_size)
self.chunks[chunk_index] = ChunkInfo(
index=chunk_index,
data=chunk_data,
size=len(chunk_data)
)
print(f"已准备 {len(self.chunks)} 个分片")
async def reset_stream(self, ws):
"""重置流"""
req = {
"action": "upload_file_stream",
"params": {
"stream_id": self.stream_id,
"reset": True
},
"echo": "reset"
}
print("发送重置请求...")
response = await self._send_and_wait_response(ws, req, timeout=5.0)
if response and response.get('echo') == 'reset':
print("✅ 流重置完成")
else:
print(f"⚠️ 重置响应异常: {response}")
async def upload_chunks_parallel(self, ws, file_info):
"""并行上传所有分片"""
print(f"\n开始并行上传 {len(self.chunks)} 个分片...")
start_time = time.time()
# 创建上传任务
tasks = []
for chunk_index in range(file_info['total_chunks']):
task = asyncio.create_task(
self.upload_single_chunk(ws, chunk_index, file_info)
)
tasks.append(task)
# 等待所有任务完成
results = await asyncio.gather(*tasks, return_exceptions=True)
# 统计结果
successful = sum(1 for r in results if r is True)
failed = sum(1 for r in results if r is not True)
elapsed = time.time() - start_time
speed = file_info['file_size'] / elapsed / 1024 / 1024 # MB/s
print(f"\n📊 并行上传完成:")
print(f" 成功: {successful}/{len(self.chunks)}")
print(f" 失败: {failed}")
print(f" 耗时: {elapsed:.2f}秒")
print(f" 速度: {speed:.2f}MB/s")
if failed > 0:
print(f"⚠️ {failed} 个分片上传失败,将进行重试")
async def upload_single_chunk(self, ws, chunk_index: int, file_info) -> bool:
"""上传单个分片"""
async with self.upload_semaphore: # 限制并发数
chunk = self.chunks[chunk_index]
try:
chunk_base64 = base64.b64encode(chunk.data).decode('utf-8')
req = {
"action": "upload_file_stream",
"params": {
"stream_id": self.stream_id,
"chunk_data": chunk_base64,
"chunk_index": chunk_index,
"total_chunks": file_info['total_chunks'],
"file_size": file_info['file_size'],
"filename": file_info['filename'],
"expected_sha256": file_info['expected_sha256']
},
"echo": f"chunk_{chunk_index}"
}
# 使用统一的发送和接收方法
response = await self._send_and_wait_response(ws, req, timeout=10.0)
if response and response.get('echo') == f"chunk_{chunk_index}":
if response.get('status') == 'ok':
chunk.uploaded = True
data = response.get('data', {})
progress = data.get('received_chunks', 0)
total = data.get('total_chunks', file_info['total_chunks'])
print(f"✅ 块 {chunk_index + 1:3d}/{total} ({chunk.size:5d}B) - 进度: {progress}/{total}")
return True
else:
error_msg = response.get('message', 'Unknown error')
print(f"❌ 块 {chunk_index + 1} 失败: {error_msg}")
self.failed_chunks.add(chunk_index)
return False
else:
print(f"⚠️ 块 {chunk_index + 1} 响应异常或超时")
self.failed_chunks.add(chunk_index)
return False
except Exception as e:
print(f"💥 块 {chunk_index + 1} 异常: {e}")
self.failed_chunks.add(chunk_index)
return False
async def retry_failed_chunks(self, ws, file_info):
"""重试失败的分片"""
print(f"\n🔄 开始重试 {len(self.failed_chunks)} 个失败分片...")
for retry_round in range(self.max_retries):
if not self.failed_chunks:
break
print(f"第 {retry_round + 1} 轮重试,剩余 {len(self.failed_chunks)} 个分片")
current_failed = self.failed_chunks.copy()
self.failed_chunks.clear()
# 重试当前失败的分片
retry_tasks = []
for chunk_index in current_failed:
task = asyncio.create_task(
self.upload_single_chunk(ws, chunk_index, file_info)
)
retry_tasks.append(task)
retry_results = await asyncio.gather(*retry_tasks, return_exceptions=True)
successful_retries = sum(1 for r in retry_results if r is True)
print(f"重试结果: {successful_retries}/{len(current_failed)} 成功")
if not self.failed_chunks:
print("✅ 所有分片重试成功!")
break
else:
await asyncio.sleep(1) # 重试间隔
if self.failed_chunks:
print(f"❌ 仍有 {len(self.failed_chunks)} 个分片失败: {sorted(self.failed_chunks)}")
async def complete_upload(self, ws):
"""完成上传"""
req = {
"action": "upload_file_stream",
"params": {
"stream_id": self.stream_id,
"is_complete": True
},
"echo": "complete"
}
print("\n发送完成请求...")
response = await self._send_and_wait_response(ws, req, timeout=10.0)
if response:
if response.get('status') == 'ok':
data = response.get('data', {})
print(f"✅ 上传完成!")
print(f" 文件路径: {data.get('file_path')}")
print(f" 文件大小: {data.get('file_size')} bytes")
print(f" SHA256: {data.get('sha256')}")
print(f" 状态: {data.get('status')}")
else:
print(f"❌ 上传失败: {response.get('message')}")
else:
print("⚠️ 完成请求超时或失败")
async def main():
# 配置
WS_URI = "ws://localhost:3001" # 修改为你的WebSocket地址
FILE_PATH = r"C:\Users\nanaeo\Pictures\CatPicture.zip" #!!!!!!!!!!!
MAX_CONCURRENT = 8 # 最大并发上传数,可根据服务器性能调整
# 创建测试文件(如果不存在)
if not os.path.exists(FILE_PATH):
with open(FILE_PATH, 'w', encoding='utf-8') as f:
f.write("这是一个测试文件,用于演示并行文件分片上传功能。\n" * 100)
print(f"✅ 创建测试文件: {FILE_PATH}")
print("=== 并行文件流上传测试 ===")
print(f"WebSocket URI: {WS_URI}")
print(f"文件路径: {FILE_PATH}")
print(f"最大并发数: {MAX_CONCURRENT}")
try:
tester = FileUploadTester(WS_URI, FILE_PATH, MAX_CONCURRENT)
await tester.connect_and_upload()
print("🎉 测试完成!")
except Exception as e:
print(f"💥 测试出错: {e}")
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,384 @@
import { ActionName } from '@/onebot/action/router';
import { OneBotAction } from '@/onebot/action/OneBotAction';
import { Static, Type } from '@sinclair/typebox';
import fs from 'fs';
import { join as joinPath } from 'node:path';
import { randomUUID } from 'crypto';
import { createHash } from 'crypto';
// 简化配置
const CONFIG = {
TIMEOUT: 10 * 60 * 1000, // 10分钟超时
MEMORY_THRESHOLD: 10 * 1024 * 1024, // 10MB,超过使用磁盘
MEMORY_LIMIT: 100 * 1024 * 1024 // 100MB内存总限制
} as const;
const SchemaData = Type.Object({
stream_id: Type.String(),
chunk_data: Type.Optional(Type.String()),
chunk_index: Type.Optional(Type.Number()),
total_chunks: Type.Optional(Type.Number()),
file_size: Type.Optional(Type.Number()),
expected_sha256: Type.Optional(Type.String()),
is_complete: Type.Optional(Type.Boolean()),
filename: Type.Optional(Type.String()),
reset: Type.Optional(Type.Boolean()),
verify_only: Type.Optional(Type.Boolean())
});
type Payload = Static<typeof SchemaData>;
// 简化流状态接口
interface StreamState {
id: string;
filename: string;
totalChunks: number;
receivedChunks: number;
missingChunks: Set<number>;
// 可选属性
fileSize?: number;
expectedSha256?: string;
// 存储策略
useMemory: boolean;
memoryChunks?: Map<number, Buffer>;
tempDir?: string;
finalPath?: string;
// 管理
createdAt: number;
timeoutId: NodeJS.Timeout;
}
interface StreamResult {
stream_id: string;
status: 'receiving' | 'completed' | 'error' | 'ready';
received_chunks: number;
total_chunks?: number;
missing_chunks?: number[];
file_path?: string;
file_size?: number;
sha256?: string;
message?: string;
}
export class UploadFileStream extends OneBotAction<Payload, StreamResult> {
override actionName = ActionName.UploadFileStream;
override payloadSchema = SchemaData;
private static streams = new Map<string, StreamState>();
private static memoryUsage = 0;
async _handle(payload: Payload): Promise<StreamResult> {
const { stream_id, reset, verify_only } = payload;
try {
if (reset) return this.resetStream(stream_id);
if (verify_only) return this.verifyStream(stream_id);
const stream = this.getOrCreateStream(payload);
if (payload.chunk_data && payload.chunk_index !== undefined) {
const result = await this.processChunk(stream, payload.chunk_data, payload.chunk_index);
if (result.status === 'error') return result;
}
if (payload.is_complete || stream.receivedChunks === stream.totalChunks) {
return await this.completeStream(stream);
}
return this.getStreamStatus(stream);
} catch (error) {
// 确保在任何错误情况下都清理资源
this.cleanupStream(stream_id, true);
return this.errorResult(stream_id, error);
}
}
private resetStream(streamId: string): StreamResult {
this.cleanupStream(streamId);
return {
stream_id: streamId,
status: 'ready',
received_chunks: 0,
message: 'Stream reset'
};
}
private verifyStream(streamId: string): StreamResult {
const stream = UploadFileStream.streams.get(streamId);
if (!stream) {
return this.errorResult(streamId, new Error('Stream not found'));
}
return this.getStreamStatus(stream);
}
private getOrCreateStream(payload: Payload): StreamState {
let stream = UploadFileStream.streams.get(payload.stream_id);
if (!stream) {
if (!payload.total_chunks) {
throw new Error('total_chunks required for new stream');
}
stream = this.createStream(payload);
}
return stream;
}
private createStream(payload: Payload): StreamState {
const { stream_id, total_chunks, file_size, filename, expected_sha256 } = payload;
const useMemory = this.shouldUseMemory(file_size);
if (useMemory && file_size && (UploadFileStream.memoryUsage + file_size) > CONFIG.MEMORY_LIMIT) {
throw new Error('Memory limit exceeded');
}
const stream: StreamState = {
id: stream_id,
filename: filename || `upload_${randomUUID()}`,
totalChunks: total_chunks!,
receivedChunks: 0,
missingChunks: new Set(Array.from({ length: total_chunks! }, (_, i) => i)),
fileSize: file_size,
expectedSha256: expected_sha256,
useMemory,
createdAt: Date.now(),
timeoutId: this.setupTimeout(stream_id)
};
try {
if (useMemory) {
stream.memoryChunks = new Map();
if (file_size) UploadFileStream.memoryUsage += file_size;
} else {
this.setupDiskStorage(stream);
}
UploadFileStream.streams.set(stream_id, stream);
return stream;
} catch (error) {
// 如果设置存储失败,清理已创建的资源
clearTimeout(stream.timeoutId);
if (stream.tempDir && fs.existsSync(stream.tempDir)) {
try {
fs.rmSync(stream.tempDir, { recursive: true, force: true });
} catch (cleanupError) {
console.error(`Failed to cleanup temp dir during creation error:`, cleanupError);
}
}
throw error;
}
}
private shouldUseMemory(fileSize?: number): boolean {
return fileSize !== undefined && fileSize <= CONFIG.MEMORY_THRESHOLD;
}
private setupDiskStorage(stream: StreamState): void {
const tempDir = joinPath(this.core.NapCatTempPath, `upload_${stream.id}`);
const finalPath = joinPath(this.core.NapCatTempPath, stream.filename);
fs.mkdirSync(tempDir, { recursive: true });
stream.tempDir = tempDir;
stream.finalPath = finalPath;
}
private setupTimeout(streamId: string): NodeJS.Timeout {
return setTimeout(() => {
console.log(`Stream ${streamId} timeout`);
this.cleanupStream(streamId);
}, CONFIG.TIMEOUT);
}
private async processChunk(stream: StreamState, chunkData: string, chunkIndex: number): Promise<StreamResult> {
// 验证索引
if (chunkIndex < 0 || chunkIndex >= stream.totalChunks) {
throw new Error(`Invalid chunk index: ${chunkIndex}`);
}
// 检查重复
if (!stream.missingChunks.has(chunkIndex)) {
return this.getStreamStatus(stream, `Chunk ${chunkIndex} already received`);
}
try {
const buffer = Buffer.from(chunkData, 'base64');
// 存储分片
if (stream.useMemory) {
stream.memoryChunks!.set(chunkIndex, buffer);
} else {
const chunkPath = joinPath(stream.tempDir!, `${chunkIndex}.chunk`);
await fs.promises.writeFile(chunkPath, buffer);
}
// 更新状态
stream.missingChunks.delete(chunkIndex);
stream.receivedChunks++;
this.refreshTimeout(stream);
return this.getStreamStatus(stream);
} catch (error) {
throw new Error(`Chunk processing failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private refreshTimeout(stream: StreamState): void {
clearTimeout(stream.timeoutId);
stream.timeoutId = this.setupTimeout(stream.id);
}
private getStreamStatus(stream: StreamState, message?: string): StreamResult {
const missingChunks = Array.from(stream.missingChunks).sort();
return {
stream_id: stream.id,
status: 'receiving',
received_chunks: stream.receivedChunks,
total_chunks: stream.totalChunks,
missing_chunks: missingChunks.length > 0 ? missingChunks : undefined,
file_size: stream.fileSize,
message
};
}
private async completeStream(stream: StreamState): Promise<StreamResult> {
try {
// 合并分片
const finalBuffer = stream.useMemory ?
await this.mergeMemoryChunks(stream) :
await this.mergeDiskChunks(stream);
// 验证SHA256
const sha256 = this.validateSha256(stream, finalBuffer);
// 保存文件
const finalPath = stream.finalPath || joinPath(this.core.NapCatTempPath, stream.filename);
await fs.promises.writeFile(finalPath, finalBuffer);
// 清理资源但保留文件
this.cleanupStream(stream.id, false);
return {
stream_id: stream.id,
status: 'completed',
received_chunks: stream.receivedChunks,
total_chunks: stream.totalChunks,
file_path: finalPath,
file_size: finalBuffer.length,
sha256,
message: 'Upload completed'
};
} catch (error) {
throw new Error(`Stream completion failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async mergeMemoryChunks(stream: StreamState): Promise<Buffer> {
const chunks: Buffer[] = [];
for (let i = 0; i < stream.totalChunks; i++) {
const chunk = stream.memoryChunks!.get(i);
if (!chunk) throw new Error(`Missing memory chunk ${i}`);
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
private async mergeDiskChunks(stream: StreamState): Promise<Buffer> {
const chunks: Buffer[] = [];
for (let i = 0; i < stream.totalChunks; i++) {
const chunkPath = joinPath(stream.tempDir!, `${i}.chunk`);
if (!fs.existsSync(chunkPath)) throw new Error(`Missing chunk file ${i}`);
chunks.push(await fs.promises.readFile(chunkPath));
}
return Buffer.concat(chunks);
}
private validateSha256(stream: StreamState, buffer: Buffer): string | undefined {
if (!stream.expectedSha256) return undefined;
const actualSha256 = createHash('sha256').update(buffer).digest('hex');
if (actualSha256 !== stream.expectedSha256) {
throw new Error(`SHA256 mismatch. Expected: ${stream.expectedSha256}, Got: ${actualSha256}`);
}
return actualSha256;
}
private cleanupStream(streamId: string, deleteFinalFile = true): void {
const stream = UploadFileStream.streams.get(streamId);
if (!stream) return;
try {
// 清理超时
clearTimeout(stream.timeoutId);
// 清理内存
if (stream.useMemory) {
if (stream.fileSize) {
UploadFileStream.memoryUsage = Math.max(0, UploadFileStream.memoryUsage - stream.fileSize);
}
stream.memoryChunks?.clear();
}
// 清理临时文件夹及其所有内容
if (stream.tempDir) {
try {
if (fs.existsSync(stream.tempDir)) {
fs.rmSync(stream.tempDir, { recursive: true, force: true });
console.log(`Cleaned up temp directory: ${stream.tempDir}`);
}
} catch (error) {
console.error(`Failed to cleanup temp directory ${stream.tempDir}:`, error);
}
}
// 删除最终文件(如果需要)
if (deleteFinalFile && stream.finalPath) {
try {
if (fs.existsSync(stream.finalPath)) {
fs.unlinkSync(stream.finalPath);
console.log(`Deleted final file: ${stream.finalPath}`);
}
} catch (error) {
console.error(`Failed to delete final file ${stream.finalPath}:`, error);
}
}
} catch (error) {
console.error(`Cleanup error for stream ${streamId}:`, error);
} finally {
UploadFileStream.streams.delete(streamId);
console.log(`Stream ${streamId} cleaned up`);
}
}
private errorResult(streamId: string, error: any): StreamResult {
return {
stream_id: streamId,
status: 'error',
received_chunks: 0,
message: error instanceof Error ? error.message : 'Unknown error'
};
}
// 全局状态查询
static getGlobalStatus() {
return {
activeStreams: this.streams.size,
memoryUsageMB: Math.round(this.memoryUsage / 1024 / 1024 * 100) / 100,
streams: Array.from(this.streams.values()).map(stream => ({
streamId: stream.id,
filename: stream.filename,
progress: `${stream.receivedChunks}/${stream.totalChunks}`,
useMemory: stream.useMemory,
createdAt: new Date(stream.createdAt).toISOString()
}))
};
}
}
@@ -0,0 +1,201 @@
import asyncio
import websockets
import json
import base64
import hashlib
import os
from typing import Optional
class FileUploadTester:
def __init__(self, ws_uri: str, file_path: str):
self.ws_uri = ws_uri
self.file_path = file_path
self.chunk_size = 64 * 1024 # 64KB per chunk
self.stream_id = None
async def connect_and_upload(self):
"""连接到WebSocket并上传文件"""
async with websockets.connect(self.ws_uri) as ws:
print(f"已连接到 {self.ws_uri}")
# 准备文件数据
file_info = self.prepare_file()
if not file_info:
return
print(f"文件信息: {file_info['filename']}, 大小: {file_info['file_size']} bytes, 块数: {file_info['total_chunks']}")
# 生成stream_id
self.stream_id = f"upload_{hash(file_info['filename'] + str(file_info['file_size']))}"
print(f"Stream ID: {self.stream_id}")
# 重置流(如果存在)
await self.reset_stream(ws)
# 开始分块上传
await self.upload_chunks(ws, file_info)
# 完成上传
await self.complete_upload(ws)
# 等待一些响应
await self.listen_for_responses(ws)
def prepare_file(self):
"""准备文件信息"""
if not os.path.exists(self.file_path):
print(f"文件不存在: {self.file_path}")
return None
file_size = os.path.getsize(self.file_path)
filename = os.path.basename(self.file_path)
total_chunks = (file_size + self.chunk_size - 1) // self.chunk_size
# 计算SHA256
sha256_hash = hashlib.sha256()
with open(self.file_path, 'rb') as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256_hash.update(chunk)
expected_sha256 = sha256_hash.hexdigest()
return {
'filename': filename,
'file_size': file_size,
'total_chunks': total_chunks,
'expected_sha256': expected_sha256
}
async def reset_stream(self, ws):
"""重置流"""
req = {
"action": "upload_file_stream",
"params": {
"stream_id": self.stream_id,
"reset": True
},
"echo": "reset"
}
await ws.send(json.dumps(req))
print("发送重置请求...")
async def upload_chunks(self, ws, file_info):
"""上传文件块"""
with open(self.file_path, 'rb') as f:
for chunk_index in range(file_info['total_chunks']):
# 读取块数据
chunk_data = f.read(self.chunk_size)
chunk_base64 = base64.b64encode(chunk_data).decode('utf-8')
# 准备请求
req = {
"action": "upload_file_stream",
"params": {
"stream_id": self.stream_id,
"chunk_data": chunk_base64,
"chunk_index": chunk_index,
"total_chunks": file_info['total_chunks'],
"file_size": file_info['file_size'],
"filename": file_info['filename'],
#"expected_sha256": file_info['expected_sha256']
},
"echo": f"chunk_{chunk_index}"
}
await ws.send(json.dumps(req))
print(f"发送块 {chunk_index + 1}/{file_info['total_chunks']} ({len(chunk_data)} bytes)")
# 等待响应
try:
response = await asyncio.wait_for(ws.recv(), timeout=5.0)
resp_data = json.loads(response)
if resp_data.get('echo') == f"chunk_{chunk_index}":
if resp_data.get('status') == 'ok':
data = resp_data.get('data', {})
print(f" -> 状态: {data.get('status')}, 已接收: {data.get('received_chunks')}")
else:
print(f" -> 错误: {resp_data.get('message')}")
except asyncio.TimeoutError:
print(f" -> 块 {chunk_index} 响应超时")
# 小延迟避免过快发送
await asyncio.sleep(0.1)
async def complete_upload(self, ws):
"""完成上传"""
req = {
"action": "upload_file_stream",
"params": {
"stream_id": self.stream_id,
"is_complete": True
},
"echo": "complete"
}
await ws.send(json.dumps(req))
print("发送完成请求...")
async def verify_stream(self, ws):
"""验证流状态"""
req = {
"action": "upload_file_stream",
"params": {
"stream_id": self.stream_id,
"verify_only": True
},
"echo": "verify"
}
await ws.send(json.dumps(req))
print("发送验证请求...")
async def listen_for_responses(self, ws, duration=10):
"""监听响应"""
print(f"监听响应 {duration} 秒...")
try:
end_time = asyncio.get_event_loop().time() + duration
while asyncio.get_event_loop().time() < end_time:
try:
msg = await asyncio.wait_for(ws.recv(), timeout=1.0)
resp_data = json.loads(msg)
echo = resp_data.get('echo', 'unknown')
if echo == "complete":
if resp_data.get('status') == 'ok':
data = resp_data.get('data', {})
print(f"✅ 上传完成!")
print(f" 文件路径: {data.get('file_path')}")
print(f" 文件大小: {data.get('file_size')} bytes")
print(f" SHA256: {data.get('sha256')}")
print(f" 状态: {data.get('status')}")
else:
print(f"❌ 上传失败: {resp_data.get('message')}")
elif echo == "verify":
if resp_data.get('status') == 'ok':
data = resp_data.get('data', {})
print(f"🔍 验证结果: {data}")
elif echo == "reset":
print(f"🔄 重置完成: {resp_data}")
else:
print(f"📨 收到响应 [{echo}]: {resp_data}")
except asyncio.TimeoutError:
continue
except Exception as e:
print(f"监听出错: {e}")
async def main():
# 配置
WS_URI = "ws://localhost:3001" # 修改为你的WebSocket地址
FILE_PATH = "C:\\Users\\nanaeo\\Pictures\\CatPicture.zip"
print("=== 文件流上传测试 ===")
print(f"WebSocket URI: {WS_URI}")
print(f"文件路径: {FILE_PATH}")
try:
tester = FileUploadTester(WS_URI, FILE_PATH)
await tester.connect_and_upload()
except Exception as e:
print(f"测试出错: {e}")
if __name__ == "__main__":
asyncio.run(main())
+80 -25
View File
@@ -46,6 +46,7 @@ import { GroupChange, GroupChangeInfo, GroupInvite, PushMsgBody } from '@/core/p
import { OB11GroupRequestEvent } from '../event/request/OB11GroupRequest';
import { LRUCache } from '@/common/lru-cache';
import { cleanTaskQueue } from '@/common/clean-task';
import { registerResource } from '@/common/health';
type RawToOb11Converters = {
[Key in keyof MessageElement as Key extends `${string}Element` ? Key : never]: (
@@ -69,7 +70,9 @@ export type SendMessageContext = {
}
export type RecvMessageContext = {
parseMultMsg: boolean
parseMultMsg: boolean,
disableGetUrl: boolean,
quick_reply: boolean
}
function keyCanBeParsed(key: string, parser: RawToOb11Converters): key is keyof RawToOb11Converters {
@@ -109,7 +112,7 @@ export class OneBotMsgApi {
}
},
picElement: async (element, msg, elementWrapper) => {
picElement: async (element, msg, elementWrapper, { disableGetUrl }) => {
try {
const peer = {
chatType: msg.chatType,
@@ -129,7 +132,7 @@ export class OneBotMsgApi {
summary: element.summary,
file: element.fileName,
sub_type: element.picSubType,
url: await this.core.apis.FileApi.getImageUrl(element),
url: disableGetUrl ? (element.filePath ?? '') : await this.core.apis.FileApi.getImageUrl(element),
file_size: element.fileSize,
},
};
@@ -139,7 +142,7 @@ export class OneBotMsgApi {
}
},
fileElement: async (element, msg, elementWrapper) => {
fileElement: async (element, msg, elementWrapper, { disableGetUrl }) => {
const peer = {
chatType: msg.chatType,
peerUid: msg.peerUid,
@@ -147,10 +150,24 @@ export class OneBotMsgApi {
};
FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileUuid);
FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileName);
if (this.core.apis.PacketApi.packetStatus) {
if (this.core.apis.PacketApi.packetStatus && !disableGetUrl) {
let url;
try {
url = await this.core.apis.FileApi.getFileUrl(msg.chatType, msg.peerUid, element.fileUuid, element.file10MMd5)
//url = await this.core.apis.FileApi.getFileUrl(msg.chatType, msg.peerUid, element.fileUuid, element.file10MMd5, 1500)
url = await registerResource(
'file-url-get',
{
resourceFn: async () => {
return await this.core.apis.FileApi.getFileUrl(msg.chatType, msg.peerUid, element.fileUuid, element.file10MMd5, 1500);
},
healthCheckFn: async () => {
return await this.core.apis.PacketApi.pkt.operation.FetchRkey().then(() => true).catch(() => false);
},
testArgs: [],
healthCheckInterval: 30000,
maxHealthCheckFailures: 3
},
);
} catch (error) {
url = '';
}
@@ -240,7 +257,7 @@ export class OneBotMsgApi {
};
},
replyElement: async (element, msg) => {
replyElement: async (element, msg, _, quick_reply) => {
const peer = {
chatType: msg.chatType,
peerUid: msg.peerUid,
@@ -277,7 +294,10 @@ export class OneBotMsgApi {
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
if (replyMsg) return replyMsg;
if (quick_reply) {
this.core.context.logger.logWarn(`快速回复,跳过方法1查询,序号: ${msgSeq}, 消息数: ${replyMsgList.length}`);
return undefined;
}
this.core.context.logger.logWarn(`方法1查询失败,序号: ${msgSeq}, 消息数: ${replyMsgList.length}`);
}
@@ -345,7 +365,7 @@ export class OneBotMsgApi {
return null;
},
videoElement: async (element, msg, elementWrapper) => {
videoElement: async (element, msg, elementWrapper, { disableGetUrl }) => {
const peer = {
chatType: msg.chatType,
peerUid: msg.peerUid,
@@ -390,10 +410,24 @@ export class OneBotMsgApi {
}
//开始兜底
if (!videoDownUrl) {
if (!videoDownUrl && !disableGetUrl) {
if (this.core.apis.PacketApi.packetStatus) {
try {
videoDownUrl = await this.core.apis.FileApi.getVideoUrlPacket(msg.peerUid, element.fileUuid);
//videoDownUrl = await this.core.apis.FileApi.getVideoUrlPacket(msg.peerUid, element.fileUuid, 1500);
videoDownUrl = await registerResource(
'video-url-get',
{
resourceFn: async () => {
return await this.core.apis.FileApi.getVideoUrlPacket(msg.peerUid, element.fileUuid, 1500);
},
healthCheckFn: async () => {
return await this.core.apis.PacketApi.pkt.operation.FetchRkey().then(() => true).catch(() => false);
},
testArgs: [],
healthCheckInterval: 30000,
maxHealthCheckFailures: 3
},
);
} catch (e) {
this.core.context.logger.logError('获取视频url失败', (e as Error).stack);
videoDownUrl = element.filePath;
@@ -414,7 +448,7 @@ export class OneBotMsgApi {
};
},
pttElement: async (element, msg, elementWrapper) => {
pttElement: async (element, msg, elementWrapper, { disableGetUrl }) => {
const peer = {
chatType: msg.chatType,
peerUid: msg.peerUid,
@@ -422,9 +456,23 @@ export class OneBotMsgApi {
};
const fileCode = FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, '', element.fileName);
let pttUrl = '';
if (this.core.apis.PacketApi.packetStatus) {
if (this.core.apis.PacketApi.packetStatus && !disableGetUrl) {
try {
pttUrl = await this.core.apis.FileApi.getPttUrl(msg.peerUid, element.fileUuid);
pttUrl = await registerResource(
'ptt-url-get',
{
resourceFn: async () => {
return await this.core.apis.FileApi.getPttUrl(msg.peerUid, element.fileUuid, 1500);
},
healthCheckFn: async () => {
return await this.core.apis.PacketApi.pkt.operation.FetchRkey().then(() => true).catch(() => false);
},
testArgs: [],
healthCheckInterval: 30000,
maxHealthCheckFailures: 3
},
);
//pttUrl = await this.core.apis.FileApi.getPttUrl(msg.peerUid, element.fileUuid, 1500);
} catch (e) {
this.core.context.logger.logError('获取语音url失败', (e as Error).stack);
pttUrl = element.filePath;
@@ -908,17 +956,21 @@ export class OneBotMsgApi {
async parseMessage(
msg: RawMessage,
messagePostFormat: string,
parseMultMsg: boolean = true
parseMultMsg: boolean = true,
disableGetUrl: boolean = false,
quick_reply: boolean = false
) {
if (messagePostFormat === 'string') {
return (await this.parseMessageV2(msg, parseMultMsg))?.stringMsg;
return (await this.parseMessageV2(msg, parseMultMsg, disableGetUrl, quick_reply))?.stringMsg;
}
return (await this.parseMessageV2(msg, parseMultMsg))?.arrayMsg;
return (await this.parseMessageV2(msg, parseMultMsg, disableGetUrl, quick_reply))?.arrayMsg;
}
async parseMessageV2(
msg: RawMessage,
parseMultMsg: boolean = true
parseMultMsg: boolean = true,
disableGetUrl: boolean = false,
quick_reply: boolean = false
) {
if (msg.senderUin == '0' || msg.senderUin == '') return;
if (msg.peerUin == '0' || msg.peerUin == '') return;
@@ -939,7 +991,7 @@ export class OneBotMsgApi {
return undefined;
}
const validSegments = await this.parseMessageSegments(msg, parseMultMsg);
const validSegments = await this.parseMessageSegments(msg, parseMultMsg, disableGetUrl, quick_reply);
resMsg.message = validSegments;
resMsg.raw_message = validSegments.map(msg => encodeCQCode(msg)).join('').trim();
@@ -1010,7 +1062,7 @@ export class OneBotMsgApi {
}
}
private async parseMessageSegments(msg: RawMessage, parseMultMsg: boolean): Promise<OB11MessageData[]> {
private async parseMessageSegments(msg: RawMessage, parseMultMsg: boolean, disableGetUrl: boolean = false, quick_reply: boolean = false): Promise<OB11MessageData[]> {
const msgSegments = await Promise.allSettled(msg.elements.map(
async (element) => {
for (const key in element) {
@@ -1025,7 +1077,7 @@ export class OneBotMsgApi {
element[key],
msg,
element,
{ parseMultMsg }
{ parseMultMsg, disableGetUrl, quick_reply }
);
if (key === 'faceElement' && !parsedElement) {
return null;
@@ -1072,10 +1124,13 @@ export class OneBotMsgApi {
if (ignoreTypes.includes(sendMsg.type)) {
continue;
}
const converter = this.ob11ToRawConverters[sendMsg.type] as (
const converter = this.ob11ToRawConverters[sendMsg.type] as ((
sendMsg: Extract<OB11MessageData, { type: OB11MessageData['type'] }>,
context: SendMessageContext,
) => Promise<SendMessageElement | undefined>;
) => Promise<SendMessageElement | undefined>) | undefined;
if (converter == undefined) {
throw new Error('未知的消息类型:' + sendMsg.type);
}
const callResult = converter(
sendMsg,
{ peer, deleteAfterSentFiles },
@@ -1179,12 +1234,12 @@ export class OneBotMsgApi {
let url = '';
if (mixElement?.picElement && rawMessage) {
const tempData =
await this.obContext.apis.MsgApi.rawToOb11Converters.picElement?.(mixElement?.picElement, rawMessage, mixElement, { parseMultMsg: false }) as OB11MessageImage | undefined;
await this.obContext.apis.MsgApi.rawToOb11Converters.picElement?.(mixElement?.picElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: false }) as OB11MessageImage | undefined;
url = tempData?.data.url ?? '';
}
if (mixElement?.videoElement && rawMessage) {
const tempData =
await this.obContext.apis.MsgApi.rawToOb11Converters.videoElement?.(mixElement?.videoElement, rawMessage, mixElement, { parseMultMsg: false }) as OB11MessageVideo | undefined;
await this.obContext.apis.MsgApi.rawToOb11Converters.videoElement?.(mixElement?.videoElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: false }) as OB11MessageVideo | undefined;
url = tempData?.data.url ?? '';
}
return url !== '' ? url : await this.core.apis.FileApi.downloadMedia(msgId, peer.chatType, peer.peerUid, elementId, '', '');
+3 -4
View File
@@ -1,11 +1,10 @@
import { Type, Static } from '@sinclair/typebox';
import Ajv from 'ajv';
const HttpServerConfigSchema = Type.Object({
name: Type.String({ default: 'http-server' }),
enable: Type.Boolean({ default: false }),
port: Type.Number({ default: 3000 }),
host: Type.String({ default: '0.0.0.0' }),
host: Type.String({ default: '127.0.0.1' }),
enableCors: Type.Boolean({ default: true }),
enableWebsocket: Type.Boolean({ default: true }),
messagePostFormat: Type.String({ default: 'array' }),
@@ -17,7 +16,7 @@ const HttpSseServerConfigSchema = Type.Object({
name: Type.String({ default: 'http-sse-server' }),
enable: Type.Boolean({ default: false }),
port: Type.Number({ default: 3000 }),
host: Type.String({ default: '0.0.0.0' }),
host: Type.String({ default: '127.0.0.1' }),
enableCors: Type.Boolean({ default: true }),
enableWebsocket: Type.Boolean({ default: true }),
messagePostFormat: Type.String({ default: 'array' }),
@@ -39,7 +38,7 @@ const HttpClientConfigSchema = Type.Object({
const WebsocketServerConfigSchema = Type.Object({
name: Type.String({ default: 'websocket-server' }),
enable: Type.Boolean({ default: false }),
host: Type.String({ default: '0.0.0.0' }),
host: Type.String({ default: '127.0.0.1' }),
port: Type.Number({ default: 3001 }),
messagePostFormat: Type.String({ default: 'array' }),
reportSelfMessage: Type.Boolean({ default: false }),
+66 -27
View File
@@ -13,8 +13,11 @@ import {
SendStatusType,
NTMsgType,
MessageElement,
ElementType,
NTMsgAtType,
} from '@/core';
import { OB11ConfigLoader } from '@/onebot/config';
import { pendingTokenToSend } from '@/webui/index';
import {
OB11HttpClientAdapter,
OB11WebSocketClientAdapter,
@@ -49,7 +52,8 @@ import {
import { OB11Message } from './types';
import { IOB11NetworkAdapter } from '@/onebot/network/adapter';
import { OB11HttpSSEServerAdapter } from './network/http-server-sse';
import { OB11PluginAdapter } from './network/plugin';
import { OB11PluginMangerAdapter } from './network/plugin-manger';
import { existsSync } from 'node:fs';
//OneBot实现类
export class NapCatOneBot11Adapter {
@@ -61,9 +65,8 @@ export class NapCatOneBot11Adapter {
networkManager: OB11NetworkManager;
actions: ActionMap;
private readonly bootTime = Date.now() / 1000;
//recallMsgCache = new LRUCache<string, boolean>(100);
recallEventCache = new Map<string, any>();
constructor(core: NapCatCore, context: InstanceContext, pathWrapper: NapCatPathWrapper) {
recallEventCache = new Map<string, NodeJS.Timeout>();
constructor (core: NapCatCore, context: InstanceContext, pathWrapper: NapCatPathWrapper) {
this.core = core;
this.context = context;
this.configLoader = new OB11ConfigLoader(core, pathWrapper.configPath, OneBotConfigSchema);
@@ -77,7 +80,7 @@ export class NapCatOneBot11Adapter {
this.actions = createActionMap(this, core);
this.networkManager = new OB11NetworkManager();
}
async creatOneBotLog(ob11Config: OneBotConfig) {
async creatOneBotLog (ob11Config: OneBotConfig) {
let log = '[network] 配置加载\n';
for (const key of ob11Config.network.httpServers) {
log += `HTTP服务: ${key.host}:${key.port}, : ${key.enable ? '已启动' : '未启动'}\n`;
@@ -96,14 +99,44 @@ export class NapCatOneBot11Adapter {
}
return log;
}
async InitOneBot() {
async InitOneBot () {
const selfInfo = this.core.selfInfo;
const ob11Config = this.configLoader.configData;
this.core.apis.UserApi.getUserDetailInfo(selfInfo.uid, false)
.then((user) => {
.then(async (user) => {
selfInfo.nick = user.nick;
this.context.logger.setLogSelfInfo(selfInfo);
// 检查是否有待发送的token
if (pendingTokenToSend) {
this.context.logger.log('[NapCat] [OneBot] 🔐 检测到待发送的WebUI Token,开始发送');
try {
await this.core.apis.MsgApi.sendMsg(
{ chatType: ChatType.KCHATTYPEC2C, peerUid: selfInfo.uid, guildId: '' },
[{
elementType: ElementType.TEXT,
elementId: '',
textElement: {
content:
'[NapCat] 温馨提示:\n'+
'WebUI密码为默认密码,已进行强制修改\n'+
'新密码: ' +pendingTokenToSend,
atType: NTMsgAtType.ATTYPEUNKNOWN,
atUid: '',
atTinyId: '',
atNtUid: '',
}
}],
5000
);
this.context.logger.log('[NapCat] [OneBot] ✅ WebUI Token 消息发送成功');
} catch (error) {
this.context.logger.logError('[NapCat] [OneBot] ❌ WebUI Token 消息发送失败:', error);
}
}
WebUiDataRuntime.getQQLoginCallback()(true);
})
.catch(e => this.context.logger.logError(e));
@@ -116,6 +149,12 @@ export class NapCatOneBot11Adapter {
// this.networkManager.registerAdapter(
// new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
// );
if (existsSync(this.context.pathWrapper.pluginPath)) {
this.context.logger.log('[Plugins] 插件目录存在,开始加载插件');
this.networkManager.registerAdapter(
new OB11PluginMangerAdapter('plugin_manager', this.core, this, this.actions)
);
}
for (const key of ob11Config.network.httpServers) {
if (key.enable) {
this.networkManager.registerAdapter(
@@ -181,7 +220,7 @@ export class NapCatOneBot11Adapter {
}
private async reloadNetwork(prev: OneBotConfig, now: OneBotConfig): Promise<void> {
private async reloadNetwork (prev: OneBotConfig, now: OneBotConfig): Promise<void> {
const prevLog = await this.creatOneBotLog(prev);
const newLog = await this.creatOneBotLog(now);
this.context.logger.log(`[Notice] [OneBot11] 配置变更前:\n${prevLog}`);
@@ -194,7 +233,7 @@ export class NapCatOneBot11Adapter {
await this.handleConfigChange(prev.network.websocketClients, now.network.websocketClients, OB11WebSocketClientAdapter);
}
private async handleConfigChange<CT extends NetworkAdapterConfig>(
private async handleConfigChange<CT extends NetworkAdapterConfig> (
prevConfig: NetworkAdapterConfig[],
nowConfig: NetworkAdapterConfig[],
adapterClass: new (
@@ -226,7 +265,7 @@ export class NapCatOneBot11Adapter {
}
}
private initMsgListener() {
private initMsgListener () {
const msgListener = new NodeIKernelMsgListener();
msgListener.onRecvSysMsg = (msg) => {
this.apis.MsgApi.parseSysMessage(msg)
@@ -340,7 +379,7 @@ export class NapCatOneBot11Adapter {
this.context.session.getMsgService().addKernelMsgListener(proxiedListenerOf(msgListener, this.context.logger));
}
private initBuddyListener() {
private initBuddyListener () {
const buddyListener = new NodeIKernelBuddyListener();
buddyListener.onBuddyReqChange = async (reqs) => {
@@ -371,7 +410,7 @@ export class NapCatOneBot11Adapter {
.addKernelBuddyListener(proxiedListenerOf(buddyListener, this.context.logger));
}
private initGroupListener() {
private initGroupListener () {
const groupListener = new NodeIKernelGroupListener();
groupListener.onGroupNotifiesUpdated = async (_, notifies) => {
@@ -464,7 +503,7 @@ export class NapCatOneBot11Adapter {
.addKernelGroupListener(proxiedListenerOf(groupListener, this.context.logger));
}
private async emitMsg(message: RawMessage) {
private async emitMsg (message: RawMessage) {
const network = await this.networkManager.getAllConfig();
this.context.logger.logDebug('收到新消息 RawMessage', message);
await Promise.allSettled([
@@ -473,7 +512,7 @@ export class NapCatOneBot11Adapter {
]);
}
private async handleMsg(message: RawMessage, network: Array<NetworkAdapterConfig>) {
private async handleMsg (message: RawMessage, network: Array<NetworkAdapterConfig>) {
// 过滤无效消息
if (message.msgType === NTMsgType.KMSGTYPENULL) {
return;
@@ -494,17 +533,17 @@ export class NapCatOneBot11Adapter {
}
}
private isSelfMessage(ob11Msg: {
stringMsg: OB11Message;
arrayMsg: OB11Message;
private isSelfMessage (ob11Msg: {
stringMsg: OB11Message
arrayMsg: OB11Message
}): boolean {
return ob11Msg.stringMsg.user_id.toString() == this.core.selfInfo.uin ||
ob11Msg.arrayMsg.user_id.toString() == this.core.selfInfo.uin;
}
private createMsgMap(network: Array<NetworkAdapterConfig>, ob11Msg: {
stringMsg: OB11Message;
arrayMsg: OB11Message;
private createMsgMap (network: Array<NetworkAdapterConfig>, ob11Msg: {
stringMsg: OB11Message
arrayMsg: OB11Message
}, isSelfMsg: boolean, message: RawMessage): Map<string, OB11Message> {
const msgMap: Map<string, OB11Message> = new Map();
network.filter(e => e.enable).forEach(e => {
@@ -522,7 +561,7 @@ export class NapCatOneBot11Adapter {
return msgMap;
}
private handleDebugNetwork(network: Array<NetworkAdapterConfig>, msgMap: Map<string, OB11Message>, message: RawMessage) {
private handleDebugNetwork (network: Array<NetworkAdapterConfig>, msgMap: Map<string, OB11Message>, message: RawMessage) {
const debugNetwork = network.filter(e => e.enable && e.debug);
if (debugNetwork.length > 0) {
debugNetwork.forEach(adapter => {
@@ -536,7 +575,7 @@ export class NapCatOneBot11Adapter {
}
}
private handleNotReportSelfNetwork(network: Array<NetworkAdapterConfig>, msgMap: Map<string, OB11Message>, isSelfMsg: boolean) {
private handleNotReportSelfNetwork (network: Array<NetworkAdapterConfig>, msgMap: Map<string, OB11Message>, isSelfMsg: boolean) {
if (isSelfMsg) {
const notReportSelfNetwork = network.filter(e => e.enable && (('reportSelfMessage' in e && !e.reportSelfMessage) || !('reportSelfMessage' in e)));
notReportSelfNetwork.forEach(adapter => {
@@ -545,7 +584,7 @@ export class NapCatOneBot11Adapter {
}
}
private async handleGroupEvent(message: RawMessage) {
private async handleGroupEvent (message: RawMessage) {
try {
// 群名片修改事件解析 任何都该判断
if (message.senderUin && message.senderUin !== '0') {
@@ -578,7 +617,7 @@ export class NapCatOneBot11Adapter {
}
}
private async handlePrivateMsgEvent(message: RawMessage) {
private async handlePrivateMsgEvent (message: RawMessage) {
try {
if (message.msgType === NTMsgType.KMSGTYPEGRAYTIPS) {
// 灰条为单元素消息
@@ -596,7 +635,7 @@ export class NapCatOneBot11Adapter {
}
}
private async emitRecallMsg(message: RawMessage, element: MessageElement) {
private async emitRecallMsg (message: RawMessage, element: MessageElement) {
const peer: Peer = { chatType: message.chatType, peerUid: message.peerUid, guildId: '' };
const oriMessageId = MessageUnique.getShortIdByMsgId(message.msgId) ?? MessageUnique.createUniqueMsgId(peer, message.msgId);
if (message.chatType == ChatType.KCHATTYPEC2C) {
@@ -607,7 +646,7 @@ export class NapCatOneBot11Adapter {
return;
}
private async emitFriendRecallMsg(message: RawMessage, oriMessageId: number, element: MessageElement) {
private async emitFriendRecallMsg (message: RawMessage, oriMessageId: number, element: MessageElement) {
const operatorUid = element.grayTipElement?.revokeElement.operatorUid;
if (!operatorUid) return undefined;
return new OB11FriendRecallNoticeEvent(
@@ -617,7 +656,7 @@ export class NapCatOneBot11Adapter {
);
}
private async emitGroupRecallMsg(message: RawMessage, oriMessageId: number, element: MessageElement) {
private async emitGroupRecallMsg (message: RawMessage, oriMessageId: number, element: MessageElement) {
const operatorUid = element.grayTipElement?.revokeElement.operatorUid;
if (!operatorUid) return undefined;
const operatorId = await this.core.apis.UserApi.getUinByUidV2(operatorUid);
+1 -1
View File
@@ -9,7 +9,7 @@ export class OB11HttpSSEServerAdapter extends OB11HttpServerAdapter {
if (req.path === '/_events') {
this.createSseSupport(req, res);
} else {
super.httpApiRequest(req, res);
super.httpApiRequest(req, res, true);
}
}
+18 -4
View File
@@ -104,7 +104,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
}
}
async httpApiRequest(req: Request, res: Response) {
async httpApiRequest(req: Request, res: Response, request_sse: boolean = false) {
let payload = req.body;
if (req.method == 'get') {
payload = req.query;
@@ -117,17 +117,31 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
return res.json(hello);
}
const actionName = req.path.split('/')[1];
const payload_echo = payload['echo'];
const real_echo = payload_echo ?? Math.random().toString(36).substring(2, 15);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const action = this.actions.get(actionName as any);
if (action) {
try {
const result = await action.handle(payload, this.name, this.config);
let stream = false;
const result = await action.handle(payload, this.name, this.config, {
send: request_sse ? async (data: object) => {
this.onEvent({ ...OB11Response.ok(data, real_echo), type: 'sse-action' } as unknown as OB11EmitEventContent);
} : async (data: object) => {
stream = true;
res.write(JSON.stringify({ ...OB11Response.ok(data, real_echo), type: 'stream-action' }) + "\r\n\r\n");
}
}, real_echo);
if (stream) {
res.write(JSON.stringify({ ...result, type: 'stream-action' }) + "\r\n\r\n");
return res.end();
};
return res.json(result);
} catch (error: unknown) {
return res.json(OB11Response.error((error as Error)?.stack?.toString() || (error as Error)?.message || 'Error Handle', 200));
return res.json(OB11Response.error((error as Error)?.stack?.toString() || (error as Error)?.message || 'Error Handle', 200, real_echo));
}
} else {
return res.json(OB11Response.error('不支持的Api ' + actionName, 200));
return res.json(OB11Response.error('不支持的Api ' + actionName, 200, real_echo));
}
}
+373
View File
@@ -0,0 +1,373 @@
import { OB11EmitEventContent, OB11NetworkReloadType } from './index';
import { NapCatOneBot11Adapter, OB11Message } from '@/onebot';
import { NapCatCore } from '@/core';
import { PluginConfig } from '../config/config';
import { ActionMap } from '../action';
import { IOB11NetworkAdapter } from '@/onebot/network/adapter';
import fs from 'fs';
import path from 'path';
export interface PluginPackageJson {
name?: string;
version?: string;
main?: string;
}
export interface PluginModule<T extends OB11EmitEventContent = OB11EmitEventContent> {
plugin_init: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginMangerAdapter) => void | Promise<void>;
plugin_onmessage?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: OB11Message, actions: ActionMap, instance: OB11PluginMangerAdapter) => void | Promise<void>;
plugin_onevent?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: T, actions: ActionMap, instance: OB11PluginMangerAdapter) => void | Promise<void>;
plugin_cleanup?: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginMangerAdapter) => void | Promise<void>;
}
export interface LoadedPlugin {
name: string;
version?: string;
pluginPath: string;
entryPath: string;
packageJson?: PluginPackageJson;
module: PluginModule;
}
export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> {
private readonly pluginPath: string;
private loadedPlugins: Map<string, LoadedPlugin> = new Map();
declare config: PluginConfig;
constructor(
name: string, core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap
) {
const config = {
name: name,
messagePostFormat: 'array',
reportSelfMessage: true,
enable: true,
debug: true,
};
super(name, config, core, obContext, actions);
this.pluginPath = this.core.context.pathWrapper.pluginPath;
}
/**
* 扫描并加载插件
*/
private async loadPlugins(): Promise<void> {
try {
// 确保插件目录存在
if (!fs.existsSync(this.pluginPath)) {
this.logger.logWarn(`[Plugin Adapter] Plugin directory does not exist: ${this.pluginPath}`);
fs.mkdirSync(this.pluginPath, { recursive: true });
return;
}
const items = fs.readdirSync(this.pluginPath, { withFileTypes: true });
// 扫描文件和目录
for (const item of items) {
if (item.isFile()) {
// 处理单文件插件
await this.loadFilePlugin(item.name);
} else if (item.isDirectory()) {
// 处理目录插件
await this.loadDirectoryPlugin(item.name);
}
}
this.logger.log(`[Plugin Adapter] Loaded ${this.loadedPlugins.size} plugins`);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading plugins:`, error);
}
}
/**
* 加载单文件插件 (.mjs, .js)
*/
private async loadFilePlugin(filename: string): Promise<void> {
// 只处理支持的文件类型
if (!this.isSupportedFile(filename)) {
return;
}
const filePath = path.join(this.pluginPath, filename);
const pluginName = path.parse(filename).name;
try {
const module = await this.importModule(filePath);
if (!this.isValidPluginModule(module)) {
this.logger.logWarn(`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`);
return;
}
const plugin: LoadedPlugin = {
name: pluginName,
pluginPath: this.pluginPath,
entryPath: filePath,
module: module
};
await this.registerPlugin(plugin);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading file plugin ${filename}:`, error);
}
}
/**
* 加载目录插件
*/
private async loadDirectoryPlugin(dirname: string): Promise<void> {
const pluginDir = path.join(this.pluginPath, dirname);
try {
// 尝试读取 package.json
let packageJson: PluginPackageJson | undefined;
const packageJsonPath = path.join(pluginDir, 'package.json');
if (fs.existsSync(packageJsonPath)) {
try {
const packageContent = fs.readFileSync(packageJsonPath, 'utf-8');
packageJson = JSON.parse(packageContent);
} catch (error) {
this.logger.logWarn(`[Plugin Adapter] Invalid package.json in ${dirname}:`, error);
}
}
// 确定入口文件
const entryFile = this.findEntryFile(pluginDir, packageJson);
if (!entryFile) {
this.logger.logWarn(`[Plugin Adapter] No valid entry file found for plugin directory: ${dirname}`);
return;
}
const entryPath = path.join(pluginDir, entryFile);
const module = await this.importModule(entryPath);
if (!this.isValidPluginModule(module)) {
this.logger.logWarn(`[Plugin Adapter] Directory ${dirname} does not contain a valid plugin`);
return;
}
const plugin: LoadedPlugin = {
name: packageJson?.name || dirname,
version: packageJson?.version,
pluginPath: pluginDir,
entryPath: entryPath,
packageJson: packageJson,
module: module
};
await this.registerPlugin(plugin);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading directory plugin ${dirname}:`, error);
}
}
/**
* 查找插件目录的入口文件
*/
private findEntryFile(pluginDir: string, packageJson?: PluginPackageJson): string | null {
// 优先级:package.json main > 默认文件名
const possibleEntries = [
packageJson?.main,
'index.mjs',
'index.js',
'main.mjs',
'main.js'
].filter(Boolean) as string[];
for (const entry of possibleEntries) {
const entryPath = path.join(pluginDir, entry);
if (fs.existsSync(entryPath) && fs.statSync(entryPath).isFile()) {
return entry;
}
}
return null;
}
/**
* 检查是否为支持的文件类型
*/
private isSupportedFile(filename: string): boolean {
const ext = path.extname(filename).toLowerCase();
return ['.mjs', '.js'].includes(ext);
}
/**
* 动态导入模块
*/
private async importModule(filePath: string): Promise<any> {
const fileUrl = `file://${filePath.replace(/\\/g, '/')}`;
return await import(fileUrl);
}
/**
* 检查模块是否为有效的插件模块
*/
private isValidPluginModule(module: any): module is PluginModule {
return module && typeof module.plugin_init === 'function';
}
/**
* 注册插件
*/
private async registerPlugin(plugin: LoadedPlugin): Promise<void> {
// 检查名称冲突
if (this.loadedPlugins.has(plugin.name)) {
this.logger.logWarn(`[Plugin Adapter] Plugin name conflict: ${plugin.name}, skipping...`);
return;
}
this.loadedPlugins.set(plugin.name, plugin);
this.logger.log(`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ''}`);
// 调用插件初始化方法(必须存在)
try {
await plugin.module.plugin_init(this.core, this.obContext, this.actions, this);
this.logger.log(`[Plugin Adapter] Initialized plugin: ${plugin.name}`);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error initializing plugin ${plugin.name}:`, error);
}
}
/**
* 卸载插件
*/
private async unloadPlugin(pluginName: string): Promise<void> {
const plugin = this.loadedPlugins.get(pluginName);
if (!plugin) {
return;
}
// 调用插件清理方法
if (typeof plugin.module.plugin_cleanup === 'function') {
try {
await plugin.module.plugin_cleanup(this.core, this.obContext, this.actions, this);
this.logger.log(`[Plugin Adapter] Cleaned up plugin: ${pluginName}`);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error cleaning up plugin ${pluginName}:`, error);
}
}
this.loadedPlugins.delete(pluginName);
this.logger.log(`[Plugin Adapter] Unloaded plugin: ${pluginName}`);
}
onEvent<T extends OB11EmitEventContent>(event: T) {
if (!this.isEnable) {
return;
}
// 遍历所有已加载的插件,调用它们的事件处理方法
for (const [, plugin] of this.loadedPlugins) {
this.callPluginEventHandler(plugin, event);
}
}
/**
* 调用插件的事件处理方法
*/
private async callPluginEventHandler(plugin: LoadedPlugin, event: OB11EmitEventContent): Promise<void> {
try {
// 优先使用 plugin_onevent 方法
if (typeof plugin.module.plugin_onevent === 'function') {
await plugin.module.plugin_onevent(this.name, this.core, this.obContext, event, this.actions, this);
}
// 如果是消息事件并且插件有 plugin_onmessage 方法,也调用
if ((event as any).message_type && typeof plugin.module.plugin_onmessage === 'function') {
await plugin.module.plugin_onmessage(this.name, this.core, this.obContext, event as OB11Message, this.actions, this);
}
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error calling plugin ${plugin.name} event handler:`, error);
}
}
async open() {
if (this.isEnable) {
return;
}
this.logger.log('[Plugin Adapter] Opening plugin adapter...');
this.isEnable = true;
// 加载所有插件
await this.loadPlugins();
this.logger.log(`[Plugin Adapter] Plugin adapter opened with ${this.loadedPlugins.size} plugins loaded`);
}
async close() {
if (!this.isEnable) {
return;
}
this.logger.log('[Plugin Adapter] Closing plugin adapter...');
this.isEnable = false;
// 卸载所有插件
const pluginNames = Array.from(this.loadedPlugins.keys());
for (const pluginName of pluginNames) {
await this.unloadPlugin(pluginName);
}
this.logger.log('[Plugin Adapter] Plugin adapter closed');
}
async reload() {
this.logger.log('[Plugin Adapter] Reloading plugin adapter...');
// 先关闭然后重新打开
await this.close();
await this.open();
this.logger.log('[Plugin Adapter] Plugin adapter reloaded');
return OB11NetworkReloadType.Normal;
}
/**
* 获取已加载的插件列表
*/
public getLoadedPlugins(): LoadedPlugin[] {
return Array.from(this.loadedPlugins.values());
}
/**
* 获取插件信息
*/
public getPluginInfo(pluginName: string): LoadedPlugin | undefined {
return this.loadedPlugins.get(pluginName);
}
/**
* 重载指定插件
*/
public async reloadPlugin(pluginName: string): Promise<boolean> {
const plugin = this.loadedPlugins.get(pluginName);
if (!plugin) {
this.logger.logWarn(`[Plugin Adapter] Plugin ${pluginName} not found`);
return false;
}
try {
// 卸载插件
await this.unloadPlugin(pluginName);
// 重新加载插件
const isDirectory = fs.statSync(plugin.pluginPath).isDirectory() &&
plugin.pluginPath !== this.pluginPath;
if (isDirectory) {
const dirname = path.basename(plugin.pluginPath);
await this.loadDirectoryPlugin(dirname);
} else {
const filename = path.basename(plugin.entryPath);
await this.loadFilePlugin(filename);
}
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`);
return true;
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error reloading plugin ${pluginName}:`, error);
return false;
}
}
}
+341 -7
View File
@@ -2,38 +2,372 @@ import { OB11EmitEventContent, OB11NetworkReloadType } from './index';
import { NapCatOneBot11Adapter, OB11Message } from '@/onebot';
import { NapCatCore } from '@/core';
import { PluginConfig } from '../config/config';
import { plugin_onmessage } from '@/plugin';
import { ActionMap } from '../action';
import { IOB11NetworkAdapter } from '@/onebot/network/adapter';
import fs from 'fs';
import path from 'path';
export interface PluginPackageJson {
name?: string;
version?: string;
main?: string;
}
export interface PluginModule<T extends OB11EmitEventContent = OB11EmitEventContent> {
plugin_init: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
plugin_onmessage?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: OB11Message, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
plugin_onevent?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: T, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
plugin_cleanup?: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
}
export interface LoadedPlugin {
name: string;
version?: string;
pluginPath: string;
entryPath: string;
packageJson?: PluginPackageJson;
module: PluginModule;
}
export class OB11PluginAdapter extends IOB11NetworkAdapter<PluginConfig> {
private readonly pluginPath: string;
private loadedPlugins: Map<string, LoadedPlugin> = new Map();
constructor(
name: string, core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap
) {
const config = {
name: name,
messagePostFormat: 'array',
reportSelfMessage: false,
reportSelfMessage: true,
enable: true,
debug: false,
debug: true,
};
super(name, config, core, obContext, actions);
this.pluginPath = this.core.context.pathWrapper.pluginPath;
}
onEvent<T extends OB11EmitEventContent>(event: T) {
if (event.post_type === 'message') {
plugin_onmessage(this.config.name, this.core, this.obContext, event as OB11Message, this.actions, this).then().catch();
/**
* 扫描并加载插件
*/
private async loadPlugins(): Promise<void> {
try {
// 确保插件目录存在
if (!fs.existsSync(this.pluginPath)) {
this.logger.logWarn(`[Plugin Adapter] Plugin directory does not exist: ${this.pluginPath}`);
fs.mkdirSync(this.pluginPath, { recursive: true });
return;
}
const items = fs.readdirSync(this.pluginPath, { withFileTypes: true });
// 扫描文件和目录
for (const item of items) {
if (item.isFile()) {
// 处理单文件插件
await this.loadFilePlugin(item.name);
} else if (item.isDirectory()) {
// 处理目录插件
await this.loadDirectoryPlugin(item.name);
}
}
this.logger.log(`[Plugin Adapter] Loaded ${this.loadedPlugins.size} plugins`);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading plugins:`, error);
}
}
open() {
/**
* 加载单文件插件 (.mjs, .js)
*/
private async loadFilePlugin(filename: string): Promise<void> {
// 只处理支持的文件类型
if (!this.isSupportedFile(filename)) {
return;
}
const filePath = path.join(this.pluginPath, filename);
const pluginName = path.parse(filename).name;
try {
const module = await this.importModule(filePath);
if (!this.isValidPluginModule(module)) {
this.logger.logWarn(`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`);
return;
}
const plugin: LoadedPlugin = {
name: pluginName,
pluginPath: this.pluginPath,
entryPath: filePath,
module: module
};
await this.registerPlugin(plugin);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading file plugin ${filename}:`, error);
}
}
/**
* 加载目录插件
*/
private async loadDirectoryPlugin(dirname: string): Promise<void> {
const pluginDir = path.join(this.pluginPath, dirname);
try {
// 尝试读取 package.json
let packageJson: PluginPackageJson | undefined;
const packageJsonPath = path.join(pluginDir, 'package.json');
if (fs.existsSync(packageJsonPath)) {
try {
const packageContent = fs.readFileSync(packageJsonPath, 'utf-8');
packageJson = JSON.parse(packageContent);
} catch (error) {
this.logger.logWarn(`[Plugin Adapter] Invalid package.json in ${dirname}:`, error);
}
}
// 确定入口文件
const entryFile = this.findEntryFile(pluginDir, packageJson);
if (!entryFile) {
this.logger.logWarn(`[Plugin Adapter] No valid entry file found for plugin directory: ${dirname}`);
return;
}
const entryPath = path.join(pluginDir, entryFile);
const module = await this.importModule(entryPath);
if (!this.isValidPluginModule(module)) {
this.logger.logWarn(`[Plugin Adapter] Directory ${dirname} does not contain a valid plugin`);
return;
}
const plugin: LoadedPlugin = {
name: packageJson?.name || dirname,
version: packageJson?.version,
pluginPath: pluginDir,
entryPath: entryPath,
packageJson: packageJson,
module: module
};
await this.registerPlugin(plugin);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error loading directory plugin ${dirname}:`, error);
}
}
/**
* 查找插件目录的入口文件
*/
private findEntryFile(pluginDir: string, packageJson?: PluginPackageJson): string | null {
// 优先级:package.json main > 默认文件名
const possibleEntries = [
packageJson?.main,
'index.mjs',
'index.js',
'main.mjs',
'main.js'
].filter(Boolean) as string[];
for (const entry of possibleEntries) {
const entryPath = path.join(pluginDir, entry);
if (fs.existsSync(entryPath) && fs.statSync(entryPath).isFile()) {
return entry;
}
}
return null;
}
/**
* 检查是否为支持的文件类型
*/
private isSupportedFile(filename: string): boolean {
const ext = path.extname(filename).toLowerCase();
return ['.mjs', '.js'].includes(ext);
}
/**
* 动态导入模块
*/
private async importModule(filePath: string): Promise<any> {
const fileUrl = `file://${filePath.replace(/\\/g, '/')}`;
return await import(fileUrl);
}
/**
* 检查模块是否为有效的插件模块
*/
private isValidPluginModule(module: any): module is PluginModule {
return module && typeof module.plugin_init === 'function';
}
/**
* 注册插件
*/
private async registerPlugin(plugin: LoadedPlugin): Promise<void> {
// 检查名称冲突
if (this.loadedPlugins.has(plugin.name)) {
this.logger.logWarn(`[Plugin Adapter] Plugin name conflict: ${plugin.name}, skipping...`);
return;
}
this.loadedPlugins.set(plugin.name, plugin);
this.logger.log(`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ''}`);
// 调用插件初始化方法(必须存在)
try {
await plugin.module.plugin_init(this.core, this.obContext, this.actions, this);
this.logger.log(`[Plugin Adapter] Initialized plugin: ${plugin.name}`);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error initializing plugin ${plugin.name}:`, error);
}
}
/**
* 卸载插件
*/
private async unloadPlugin(pluginName: string): Promise<void> {
const plugin = this.loadedPlugins.get(pluginName);
if (!plugin) {
return;
}
// 调用插件清理方法
if (typeof plugin.module.plugin_cleanup === 'function') {
try {
await plugin.module.plugin_cleanup(this.core, this.obContext, this.actions, this);
this.logger.log(`[Plugin Adapter] Cleaned up plugin: ${pluginName}`);
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error cleaning up plugin ${pluginName}:`, error);
}
}
this.loadedPlugins.delete(pluginName);
this.logger.log(`[Plugin Adapter] Unloaded plugin: ${pluginName}`);
}
onEvent<T extends OB11EmitEventContent>(event: T) {
if (!this.isEnable) {
return;
}
// 遍历所有已加载的插件,调用它们的事件处理方法
for (const [, plugin] of this.loadedPlugins) {
this.callPluginEventHandler(plugin, event);
}
}
/**
* 调用插件的事件处理方法
*/
private async callPluginEventHandler(plugin: LoadedPlugin, event: OB11EmitEventContent): Promise<void> {
try {
// 优先使用 plugin_onevent 方法
if (typeof plugin.module.plugin_onevent === 'function') {
await plugin.module.plugin_onevent(this.name, this.core, this.obContext, event, this.actions, this);
}
// 如果是消息事件并且插件有 plugin_onmessage 方法,也调用
if ((event as any).message_type && typeof plugin.module.plugin_onmessage === 'function') {
await plugin.module.plugin_onmessage(this.name, this.core, this.obContext, event as OB11Message, this.actions, this);
}
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error calling plugin ${plugin.name} event handler:`, error);
}
}
async open() {
if (this.isEnable) {
return;
}
this.logger.log('[Plugin Adapter] Opening plugin adapter...');
this.isEnable = true;
// 加载所有插件
await this.loadPlugins();
this.logger.log(`[Plugin Adapter] Plugin adapter opened with ${this.loadedPlugins.size} plugins loaded`);
}
async close() {
if (!this.isEnable) {
return;
}
this.logger.log('[Plugin Adapter] Closing plugin adapter...');
this.isEnable = false;
// 卸载所有插件
const pluginNames = Array.from(this.loadedPlugins.keys());
for (const pluginName of pluginNames) {
await this.unloadPlugin(pluginName);
}
this.logger.log('[Plugin Adapter] Plugin adapter closed');
}
async reload() {
this.logger.log('[Plugin Adapter] Reloading plugin adapter...');
// 先关闭然后重新打开
await this.close();
await this.open();
this.logger.log('[Plugin Adapter] Plugin adapter reloaded');
return OB11NetworkReloadType.Normal;
}
/**
* 获取已加载的插件列表
*/
public getLoadedPlugins(): LoadedPlugin[] {
return Array.from(this.loadedPlugins.values());
}
/**
* 获取插件信息
*/
public getPluginInfo(pluginName: string): LoadedPlugin | undefined {
return this.loadedPlugins.get(pluginName);
}
/**
* 重载指定插件
*/
public async reloadPlugin(pluginName: string): Promise<boolean> {
const plugin = this.loadedPlugins.get(pluginName);
if (!plugin) {
this.logger.logWarn(`[Plugin Adapter] Plugin ${pluginName} not found`);
return false;
}
try {
// 卸载插件
await this.unloadPlugin(pluginName);
// 重新加载插件
const isDirectory = fs.statSync(plugin.pluginPath).isDirectory() &&
plugin.pluginPath !== this.pluginPath;
if (isDirectory) {
const dirname = path.basename(plugin.pluginPath);
await this.loadDirectoryPlugin(dirname);
} else {
const filename = path.basename(plugin.entryPath);
await this.loadFilePlugin(filename);
}
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`);
return true;
} catch (error) {
this.logger.logError(`[Plugin Adapter] Error reloading plugin ${pluginName}:`, error);
return false;
}
}
}
+5 -1
View File
@@ -151,7 +151,11 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
this.checkStateAndReply<unknown>(OB11Response.error('不支持的Api ' + receiveData.action, 1404, echo));
return;
}
const retdata = await action.websocketHandle(receiveData.params, echo ?? '', this.name, this.config);
const retdata = await action.websocketHandle(receiveData.params, echo ?? '', this.name, this.config, {
send: async (data: object) => {
this.checkStateAndReply<unknown>({ ...OB11Response.ok(data, echo ?? '') });
}
});
this.checkStateAndReply<unknown>({ ...retdata });
}
async reload(newConfig: WebsocketClientConfig) {
+5 -1
View File
@@ -186,7 +186,11 @@ export class OB11WebSocketServerAdapter extends IOB11NetworkAdapter<WebsocketSer
this.checkStateAndReply<unknown>(OB11Response.error('不支持的API ' + receiveData.action, 1404, echo), wsClient);
return;
}
const retdata = await action.websocketHandle(receiveData.params, echo ?? '', this.name, this.config);
const retdata = await action.websocketHandle(receiveData.params, echo ?? '', this.name, this.config, {
send: async (data: object) => {
this.checkStateAndReply<unknown>({ ...OB11Response.ok(data, echo ?? '') }, wsClient);
}
});
this.checkStateAndReply<unknown>({ ...retdata }, wsClient);
}
+2 -2
View File
@@ -1,9 +1,9 @@
import { NapCatOneBot11Adapter, OB11Message } from '@/onebot';
import { NapCatCore } from '@/core';
import { ActionMap } from '@/onebot/action';
import { OB11PluginAdapter } from '@/onebot/network/plugin';
import { OB11PluginMangerAdapter } from '@/onebot/network/plugin-manger';
export const plugin_onmessage = async (adapter: string, _core: NapCatCore, _obCtx: NapCatOneBot11Adapter, message: OB11Message, action: ActionMap, instance: OB11PluginAdapter) => {
export const plugin_onmessage = async (adapter: string, _core: NapCatCore, _obCtx: NapCatOneBot11Adapter, message: OB11Message, action: ActionMap, instance: OB11PluginMangerAdapter) => {
if (message.raw_message === 'ping') {
const ret = await action.get('send_group_msg')?.handle({ group_id: String(message.group_id), message: 'pong' }, adapter, instance.config);
console.log(ret);
+7 -1
View File
@@ -203,7 +203,13 @@ export class WindowsPtyAgent {
}
private _getWindowsBuildNumber(): number {
const osVersion = (/(\d+)\.(\d+)\.(\d+)/g).exec(os.release());
const release = os.release();
// Limit input length to prevent potential DoS attacks
if (release.length > 50) {
return 0;
}
// Use non-global regex with more specific pattern to prevent backtracking
const osVersion = /^(\d{1,5})\.(\d{1,5})\.(\d{1,10})/.exec(release);
let buildNumber: number = 0;
if (osVersion && osVersion.length === 4) {
buildNumber = parseInt(osVersion[3]!);
+64 -9
View File
@@ -4,13 +4,14 @@
import express from 'express';
import { createServer } from 'http';
import { randomUUID } from 'node:crypto'
import { createServer as createHttpsServer } from 'https';
import { LogWrapper } from '@/common/log';
import { NapCatPathWrapper } from '@/common/path';
import { WebUiConfigWrapper } from '@webapi/helper/config';
import { ALLRouter } from '@webapi/router';
import { cors } from '@webapi/middleware/cors';
import { createUrl } from '@webapi/utils/url';
import { createUrl, getRandomToken } from '@webapi/utils/url';
import { sendError } from '@webapi/utils/response';
import { join } from 'node:path';
import { terminalManager } from '@webapi/terminal/terminal_manager';
@@ -30,17 +31,42 @@ const MAX_PORT_TRY = 100;
import * as net from 'node:net';
import { WebUiDataRuntime } from './src/helper/Data';
import { existsSync, readFileSync } from 'node:fs';
export let webUiRuntimePort = 6099;
export async function InitPort(parsedConfig: WebUiConfigType): Promise<[string, number, string]> {
// 全局变量:存储需要在QQ登录成功后发送的新token
export let pendingTokenToSend: string | null = null;
/**
* 存储WebUI启动时的初始token,用于鉴权
* - 无论是否在运行时修改密码,都应该使用此token进行鉴权
* - 运行时手动修改的密码将会在下次napcat重启后生效
* - 如果需要在运行时修改密码并立即生效,则需要在前端调用路由进行修改
*/
let initialWebUiToken: string = '';
export function setInitialWebUiToken(token: string) {
initialWebUiToken = token;
}
export function getInitialWebUiToken(): string {
return initialWebUiToken;
}
export function setPendingTokenToSend(token: string | null) {
pendingTokenToSend = token;
}
export async function InitPort(parsedConfig: WebUiConfigType): Promise<[string, number,string]> {
try {
await tryUseHost(parsedConfig.host);
const port = await tryUsePort(parsedConfig.port, parsedConfig.host);
return [parsedConfig.host, port, parsedConfig.token];
} catch (error) {
console.log('host或port不可用', error);
return ['', 0, ''];
return ['', 0, randomUUID()];
}
}
async function checkCertificates(logger: LogWrapper): Promise<{ key: string, cert: string } | null> {
try {
const certPath = join(webUiPathWrapper.configPath, 'cert.pem');
@@ -61,7 +87,35 @@ async function checkCertificates(logger: LogWrapper): Promise<{ key: string, cer
export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapper) {
webUiPathWrapper = pathWrapper;
WebUiConfig = new WebUiConfigWrapper();
const [host, port, token] = await InitPort(await WebUiConfig.GetWebUIConfig());
let config = await WebUiConfig.GetWebUIConfig();
// 检查并更新默认密码 - 最高优先级
if (config.token === 'napcat' || !config.token) {
const randomToken = getRandomToken(8);
await WebUiConfig.UpdateWebUIConfig({ token: randomToken });
logger.log(`[NapCat] [WebUi] 🔐 检测到默认密码,已自动更新为安全密码`);
// 存储token到全局变量,等待QQ登录成功后发送
setPendingTokenToSend(randomToken);
logger.log(`[NapCat] [WebUi] 📤 新密码将在QQ登录成功后发送给用户`);
// 重新获取更新后的配置
config = await WebUiConfig.GetWebUIConfig();
} else {
logger.log(`[NapCat] [WebUi] ✅ 当前使用安全密码`);
}
// 存储启动时的初始token用于鉴权
setInitialWebUiToken(config.token);
logger.log(`[NapCat] [WebUi] 🔑 已缓存启动时的token用于鉴权,运行时手动修改配置文件密码将不会生效`);
// 检查是否禁用WebUI
if (config.disableWebUI) {
logger.log('[NapCat] [WebUi] WebUI is disabled by configuration.');
return;
}
const [host, port, token] = await InitPort(config);
webUiRuntimePort = port;
if (port == 0) {
logger.log('[NapCat] [WebUi] Current WebUi is not run.');
@@ -161,17 +215,18 @@ export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapp
// ------------启动服务------------
server.listen(port, host, async () => {
// 启动后打印出相关地址
let searchParams = { token: token };
if (host !== '' && host !== '0.0.0.0') {
logger.log(`[NapCat] [WebUi] 🔑 token=${token}`);
logger.log(
`[NapCat] [WebUi] WebUi User Panel Url: ${createUrl('127.0.0.1', port.toString(), '/webui', searchParams)}`
);
if (host !== '') {
logger.log(
`[NapCat] [WebUi] WebUi User Panel Url: ${createUrl(host, port.toString(), '/webui', searchParams)}`
);
}
logger.log(
`[NapCat] [WebUi] WebUi Local Panel Url: ${createUrl('127.0.0.1', port.toString(), '/webui', searchParams)}`
);
});
// ------------Over!------------
}
+54 -18
View File
@@ -1,21 +1,12 @@
import { RequestHandler } from 'express';
import { WebUiConfig } from '@/webui';
import { WebUiConfig, getInitialWebUiToken, setInitialWebUiToken } from '@/webui';
import { AuthHelper } from '@webapi/helper/SignToken';
import { WebUiDataRuntime } from '@webapi/helper/Data';
import { sendSuccess, sendError } from '@webapi/utils/response';
import { isEmpty } from '@webapi/utils/check';
// 检查是否使用默认Token
export const CheckDefaultTokenHandler: RequestHandler = async (_, res) => {
const webuiToken = await WebUiConfig.GetWebUIConfig();
if (webuiToken.token === 'napcat') {
return sendSuccess(res, true);
}
return sendSuccess(res, false);
};
// 登录
export const LoginHandler: RequestHandler = async (req, res) => {
// 获取WebUI配置
@@ -33,8 +24,13 @@ export const LoginHandler: RequestHandler = async (req, res) => {
if (!WebUiDataRuntime.checkLoginRate(clientIP, WebUiConfigData.loginRate)) {
return sendError(res, 'login rate limit');
}
//验证config.token hash是否等于token hash
if (!AuthHelper.comparePasswordHash(WebUiConfigData.token, hash)) {
// 使用启动时缓存的token进行验证,而不是动态读取配置文件
const initialToken = getInitialWebUiToken();
if (!initialToken) {
return sendError(res, 'Server token not initialized');
}
//验证初始token hash是否等于提交的token hash
if (!AuthHelper.comparePasswordHash(initialToken, hash)) {
return sendError(res, 'token is invalid');
}
@@ -63,8 +59,6 @@ export const LogoutHandler: RequestHandler = async (req, res) => {
// 检查登录状态
export const checkHandler: RequestHandler = async (req, res) => {
// 获取WebUI配置
const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
// 获取请求头中的Authorization
const authorization = req.headers.authorization;
// 检查凭证
@@ -79,8 +73,13 @@ export const checkHandler: RequestHandler = async (req, res) => {
return sendError(res, 'Token has been revoked');
}
// 使用启动时缓存的token进行验证
const initialToken = getInitialWebUiToken();
if (!initialToken) {
return sendError(res, 'Server token not initialized');
}
// 验证凭证是否在一小时内有效
const valid = AuthHelper.validateCredentialWithinOneHour(WebUiConfigData.token, Credential);
const valid = AuthHelper.validateCredentialWithinOneHour(initialToken, Credential);
// 返回成功信息
if (valid) return sendSuccess(res, null);
// 返回错误信息
@@ -96,8 +95,33 @@ export const UpdateTokenHandler: RequestHandler = async (req, res) => {
const { oldToken, newToken } = req.body;
const authorization = req.headers.authorization;
if (isEmpty(oldToken) || isEmpty(newToken)) {
return sendError(res, 'oldToken or newToken is empty');
if (isEmpty(newToken)) {
return sendError(res, 'newToken is empty');
}
// 强制要求旧密码
if (isEmpty(oldToken)) {
return sendError(res, 'oldToken is required');
}
// 检查新旧密码是否相同
if (oldToken === newToken) {
return sendError(res, '新密码不能与旧密码相同');
}
// 检查新密码强度
if (newToken.length < 6) {
return sendError(res, '新密码至少需要6个字符');
}
// 检查是否包含字母
if (!/[a-zA-Z]/.test(newToken)) {
return sendError(res, '新密码必须包含字母');
}
// 检查是否包含数字
if (!/[0-9]/.test(newToken)) {
return sendError(res, '新密码必须包含数字');
}
try {
@@ -108,7 +132,19 @@ export const UpdateTokenHandler: RequestHandler = async (req, res) => {
AuthHelper.revokeCredential(Credential);
}
await WebUiConfig.UpdateToken(oldToken, newToken);
// 使用启动时缓存的token进行验证
const initialToken = getInitialWebUiToken();
if (!initialToken) {
return sendError(res, 'Server token not initialized');
}
if (initialToken !== oldToken) {
return sendError(res, '旧 token 不匹配');
}
// 直接更新配置文件中的token,不需要通过WebUiConfig.UpdateToken方法
await WebUiConfig.UpdateWebUIConfig({ token: newToken });
// 更新内存中的缓存token,使新密码立即生效
setInitialWebUiToken(newToken);
return sendSuccess(res, 'Token updated successfully');
} catch (e: any) {
return sendError(res, `Failed to update token: ${e.message}`);
+280 -26
View File
@@ -9,10 +9,18 @@ import { PassThrough } from 'stream';
import multer from 'multer';
import webUIFontUploader from '../uploader/webui_font';
import diskUploader from '../uploader/disk';
import { WebUiConfig } from '@/webui';
import { WebUiConfig, getInitialWebUiToken, webUiPathWrapper } from '@/webui';
const isWindows = os.platform() === 'win32';
// 安全地从查询参数中提取字符串值,防止类型混淆
const getQueryStringParam = (param: any): string => {
if (Array.isArray(param)) {
return String(param[0] || '');
}
return String(param || '');
};
// 获取系统根目录列表(Windows返回盘符列表,其他系统返回['/'])
const getRootDirs = async (): Promise<string[]> => {
if (!isWindows) return ['/'];
@@ -32,14 +40,68 @@ const getRootDirs = async (): Promise<string[]> => {
return drives.length > 0 ? drives : ['C:'];
};
// 规范化路径
// 规范化路径并进行安全验证
const normalizePath = (inputPath: string): string => {
if (!inputPath) return isWindows ? 'C:\\' : '/';
// 如果是Windows且输入为纯盘符(可能带或不带斜杠),统一返回 "X:\"
if (isWindows && /^[A-Z]:[\\/]*$/i.test(inputPath)) {
return inputPath.slice(0, 2) + '\\';
if (!inputPath) {
// 对于空路径,Windows返回用户主目录,其他系统返回根目录
return isWindows ? process.env['USERPROFILE'] || 'C:\\' : '/';
}
return path.normalize(inputPath);
// 对输入路径进行清理,移除潜在的危险字符
const cleanedPath = inputPath.replace(/[\x00-\x1f\x7f]/g, ''); // 移除控制字符
// 如果是Windows且输入为纯盘符(可能带或不带斜杠),统一返回 "X:\"
if (isWindows && /^[A-Z]:[\\/]*$/i.test(cleanedPath)) {
return cleanedPath.slice(0, 2) + '\\';
}
// 安全验证:检查是否包含危险的路径遍历模式(在规范化之前)
if (containsPathTraversal(cleanedPath)) {
throw new Error('Invalid path: path traversal detected');
}
// 进行路径规范化
const normalized = path.resolve(cleanedPath);
// 再次检查规范化后的路径,确保没有绕过安全检查
if (containsPathTraversal(normalized)) {
throw new Error('Invalid path: path traversal detected after normalization');
}
// 额外安全检查:确保规范化后的路径不包含连续的路径分隔符
const finalPath = normalized.replace(/[\\\/]+/g, path.sep);
return finalPath;
};
// 检查路径是否包含路径遍历攻击模式
const containsPathTraversal = (inputPath: string): boolean => {
// 对输入进行URL解码,防止编码绕过
let decodedPath = inputPath;
try {
decodedPath = decodeURIComponent(inputPath);
} catch {
// 如果解码失败,使用原始路径
}
// 将路径统一为正斜杠格式进行检查
const normalizedForCheck = decodedPath.replace(/\\/g, '/');
// 检查危险模式 - 更全面的路径遍历检测
const dangerousPatterns = [
/\.\.\//, // ../ 模式
/\/\.\./, // /.. 模式
/^\.\./, // 以.. 开头
/\.\.$/, // 以.. 结尾
/\.\.\\/, // ..\ 模式(Windows)
/\\\.\./, // \.. 模式(Windows)
/%2e%2e/i, // URL编码的..
/%252e%252e/i, // 双重URL编码的..
/\.\.\x00/, // null字节攻击
/\0/, // null字节
];
return dangerousPatterns.some(pattern => pattern.test(normalizedForCheck));
};
interface FileInfo {
@@ -52,6 +114,35 @@ interface FileInfo {
// 添加系统文件黑名单
const SYSTEM_FILES = new Set(['pagefile.sys', 'swapfile.sys', 'hiberfil.sys', 'System Volume Information']);
// 检查是否为WebUI配置文件
const isWebUIConfigFile = (filePath: string): boolean => {
// 先用字符串快速筛选
if (!filePath.includes('webui.json')) {
return false;
}
// 进入更严格的路径判断 - 统一路径分隔符为 /
const webUIConfigPath = path.resolve(webUiPathWrapper.configPath, 'webui.json').replace(/\\/g, '/');
const targetPath = path.resolve(filePath).replace(/\\/g, '/');
// 统一分隔符后进行路径比较
return targetPath === webUIConfigPath;
};
// WebUI配置文件脱敏处理
const sanitizeWebUIConfig = (content: string): string => {
try {
const config = JSON.parse(content);
if (config.token) {
config.token = '******';
}
return JSON.stringify(config, null, 4);
} catch {
// 如果解析失败,返回原内容
return content;
}
};
// 检查同类型的文件或目录是否存在
const checkSameTypeExists = async (pathToCheck: string, isDirectory: boolean): Promise<boolean> => {
try {
@@ -66,8 +157,15 @@ const checkSameTypeExists = async (pathToCheck: string, isDirectory: boolean): P
// 获取目录内容
export const ListFilesHandler: RequestHandler = async (req, res) => {
try {
const requestPath = (req.query['path'] as string) || (isWindows ? 'C:\\' : '/');
const normalizedPath = normalizePath(requestPath);
const requestPath = getQueryStringParam(req.query['path']) || (isWindows ? process.env['USERPROFILE'] || 'C:\\' : '/');
let normalizedPath: string;
try {
normalizedPath = normalizePath(requestPath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
const onlyDirectory = req.query['onlyDirectory'] === 'true';
// 如果是根路径且在Windows系统上,返回盘符列表
@@ -135,7 +233,18 @@ export const ListFilesHandler: RequestHandler = async (req, res) => {
export const CreateDirHandler: RequestHandler = async (req, res) => {
try {
const { path: dirPath } = req.body;
const normalizedPath = normalizePath(dirPath);
let normalizedPath: string;
try {
normalizedPath = normalizePath(dirPath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(normalizedPath)) {
return sendError(res, '路径必须是绝对路径');
}
// 检查是否已存在同类型(目录)
if (await checkSameTypeExists(normalizedPath, true)) {
@@ -153,7 +262,19 @@ export const CreateDirHandler: RequestHandler = async (req, res) => {
export const DeleteHandler: RequestHandler = async (req, res) => {
try {
const { path: targetPath } = req.body;
const normalizedPath = normalizePath(targetPath);
let normalizedPath: string;
try {
normalizedPath = normalizePath(targetPath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(normalizedPath)) {
return sendError(res, '路径必须是绝对路径');
}
const stat = await fsProm.stat(normalizedPath);
if (stat.isDirectory()) {
await fsProm.rm(normalizedPath, { recursive: true });
@@ -171,7 +292,18 @@ export const BatchDeleteHandler: RequestHandler = async (req, res) => {
try {
const { paths } = req.body;
for (const targetPath of paths) {
const normalizedPath = normalizePath(targetPath);
let normalizedPath: string;
try {
normalizedPath = normalizePath(targetPath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(normalizedPath)) {
return sendError(res, '路径必须是绝对路径');
}
const stat = await fsProm.stat(normalizedPath);
if (stat.isDirectory()) {
await fsProm.rm(normalizedPath, { recursive: true });
@@ -188,8 +320,25 @@ export const BatchDeleteHandler: RequestHandler = async (req, res) => {
// 读取文件内容
export const ReadFileHandler: RequestHandler = async (req, res) => {
try {
const filePath = normalizePath(req.query['path'] as string);
const content = await fsProm.readFile(filePath, 'utf-8');
let filePath: string;
try {
filePath = normalizePath(getQueryStringParam(req.query['path']));
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(filePath)) {
return sendError(res, '路径必须是绝对路径');
}
let content = await fsProm.readFile(filePath, 'utf-8');
// 如果是WebUI配置文件,对token进行脱敏处理
if (isWebUIConfigFile(filePath)) {
content = sanitizeWebUIConfig(content);
}
return sendSuccess(res, content);
} catch (error) {
return sendError(res, '读取文件失败');
@@ -200,8 +349,40 @@ export const ReadFileHandler: RequestHandler = async (req, res) => {
export const WriteFileHandler: RequestHandler = async (req, res) => {
try {
const { path: filePath, content } = req.body;
const normalizedPath = normalizePath(filePath);
await fsProm.writeFile(normalizedPath, content, 'utf-8');
// 安全的路径规范化,如果检测到路径遍历攻击会抛出异常
let normalizedPath: string;
try {
normalizedPath = normalizePath(filePath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(normalizedPath)) {
return sendError(res, '路径必须是绝对路径');
}
let finalContent = content;
// 检查是否为WebUI配置文件
if (isWebUIConfigFile(normalizedPath)) {
try {
// 解析要写入的配置
const configToWrite = JSON.parse(content);
// 获取内存中的token,覆盖前端传来的token
const memoryToken = getInitialWebUiToken();
if (memoryToken) {
configToWrite.token = memoryToken;
finalContent = JSON.stringify(configToWrite, null, 4);
}
} catch (e) {
// 如果解析失败 说明不符合json格式 不允许写入
return sendError(res, '写入的WebUI配置文件内容格式错误,必须是合法的JSON');
}
}
await fsProm.writeFile(normalizedPath, finalContent, 'utf-8');
return sendSuccess(res, true);
} catch (error) {
return sendError(res, '写入文件失败');
@@ -212,7 +393,18 @@ export const WriteFileHandler: RequestHandler = async (req, res) => {
export const CreateFileHandler: RequestHandler = async (req, res) => {
try {
const { path: filePath } = req.body;
const normalizedPath = normalizePath(filePath);
let normalizedPath: string;
try {
normalizedPath = normalizePath(filePath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(normalizedPath)) {
return sendError(res, '路径必须是绝对路径');
}
// 检查是否已存在同类型(文件)
if (await checkSameTypeExists(normalizedPath, false)) {
@@ -230,8 +422,21 @@ export const CreateFileHandler: RequestHandler = async (req, res) => {
export const RenameHandler: RequestHandler = async (req, res) => {
try {
const { oldPath, newPath } = req.body;
const normalizedOldPath = normalizePath(oldPath);
const normalizedNewPath = normalizePath(newPath);
let normalizedOldPath: string;
let normalizedNewPath: string;
try {
normalizedOldPath = normalizePath(oldPath);
normalizedNewPath = normalizePath(newPath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(normalizedOldPath) || !path.isAbsolute(normalizedNewPath)) {
return sendError(res, '路径必须是绝对路径');
}
await fsProm.rename(normalizedOldPath, normalizedNewPath);
return sendSuccess(res, true);
} catch (error) {
@@ -243,8 +448,21 @@ export const RenameHandler: RequestHandler = async (req, res) => {
export const MoveHandler: RequestHandler = async (req, res) => {
try {
const { sourcePath, targetPath } = req.body;
const normalizedSourcePath = normalizePath(sourcePath);
const normalizedTargetPath = normalizePath(targetPath);
let normalizedSourcePath: string;
let normalizedTargetPath: string;
try {
normalizedSourcePath = normalizePath(sourcePath);
normalizedTargetPath = normalizePath(targetPath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(normalizedSourcePath) || !path.isAbsolute(normalizedTargetPath)) {
return sendError(res, '路径必须是绝对路径');
}
await fsProm.rename(normalizedSourcePath, normalizedTargetPath);
return sendSuccess(res, true);
} catch (error) {
@@ -257,8 +475,20 @@ export const BatchMoveHandler: RequestHandler = async (req, res) => {
try {
const { items } = req.body;
for (const { sourcePath, targetPath } of items) {
const normalizedSourcePath = normalizePath(sourcePath);
const normalizedTargetPath = normalizePath(targetPath);
let normalizedSourcePath: string;
let normalizedTargetPath: string;
try {
normalizedSourcePath = normalizePath(sourcePath);
normalizedTargetPath = normalizePath(targetPath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(normalizedSourcePath) || !path.isAbsolute(normalizedTargetPath)) {
return sendError(res, '路径必须是绝对路径');
}
await fsProm.rename(normalizedSourcePath, normalizedTargetPath);
}
return sendSuccess(res, true);
@@ -270,10 +500,21 @@ export const BatchMoveHandler: RequestHandler = async (req, res) => {
// 新增:文件下载处理方法(注意流式传输,不将整个文件读入内存)
export const DownloadHandler: RequestHandler = async (req, res) => {
try {
const filePath = normalizePath(req.query['path'] as string);
let filePath: string;
try {
filePath = normalizePath(getQueryStringParam(req.query['path']));
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
if (!filePath) {
return sendError(res, '参数错误');
}
// 额外安全检查:确保路径是绝对路径
if (!path.isAbsolute(filePath)) {
return sendError(res, '路径必须是绝对路径');
}
const stat = await fsProm.stat(filePath);
@@ -312,12 +553,25 @@ export const BatchDownloadHandler: RequestHandler = async (req, res) => {
const zipStream = new compressing.zip.Stream();
// 修改:根据文件类型设置 relativePath
for (const filePath of paths) {
const normalizedPath = normalizePath(filePath);
let normalizedPath: string;
try {
normalizedPath = normalizePath(filePath);
} catch (pathError) {
return sendError(res, '无效的文件路径');
}
// 额外安全检查:确保规范化后的路径是绝对路径
if (!path.isAbsolute(normalizedPath)) {
return sendError(res, '路径必须是绝对路径');
}
const stat = await fsProm.stat(normalizedPath);
if (stat.isDirectory()) {
zipStream.addEntry(normalizedPath, { relativePath: '' });
} else {
zipStream.addEntry(normalizedPath, { relativePath: path.basename(normalizedPath) });
// 确保相对路径只使用文件名,防止路径遍历
const safeName = path.basename(normalizedPath);
zipStream.addEntry(normalizedPath, { relativePath: safeName });
}
}
zipStream.pipe(res);
+10 -5
View File
@@ -5,6 +5,12 @@ import { terminalManager } from '../terminal/terminal_manager';
import { WebUiConfig } from '@/webui';
// 判断是否是 macos
const isMacOS = process.platform === 'darwin';
// 日志脱敏函数
const sanitizeLog = (log: string): string => {
// 脱敏 token 参数,将 token=xxx 替换为 token=***
return log.replace(/token=[\w\d]+/gi, 'token=***');
};
// 日志记录
export const LogHandler: RequestHandler = async (req, res) => {
const filename = req.query['id'];
@@ -16,7 +22,8 @@ export const LogHandler: RequestHandler = async (req, res) => {
return sendError(res, 'ID不合法');
}
const logContent = await WebUiConfig.GetLogContent(filename);
return sendSuccess(res, logContent);
const sanitizedLogContent = sanitizeLog(logContent);
return sendSuccess(res, sanitizedLogContent);
};
// 日志列表
@@ -31,7 +38,8 @@ export const LogRealTimeHandler: RequestHandler = async (req, res) => {
res.setHeader('Connection', 'keep-alive');
const listener = (log: string) => {
try {
res.write(`data: ${log}\n\n`);
const sanitizedLog = sanitizeLog(log);
res.write(`data: ${sanitizedLog}\n\n`);
} catch (error) {
console.error('向客户端写入日志数据时出错:', error);
}
@@ -47,9 +55,6 @@ export const CreateTerminalHandler: RequestHandler = async (req, res) => {
if (isMacOS) {
return sendError(res, 'MacOS不支持终端');
}
if ((await WebUiConfig.GetWebUIConfig()).token === 'napcat') {
return sendError(res, '默认密码禁止创建终端');
}
try {
const { cols, rows } = req.body;
const { id } = terminalManager.createTerminal(cols, rows);
+1 -1
View File
@@ -57,4 +57,4 @@ export const OB11SetConfigHandler: RequestHandler = async (req, res) => {
} catch (e) {
return sendError(res, 'Error: ' + e);
}
};
};
+127
View File
@@ -0,0 +1,127 @@
import { RequestHandler } from 'express';
import { WebUiConfig } from '@/webui';
import { sendError, sendSuccess } from '@webapi/utils/response';
import { isEmpty } from '@webapi/utils/check';
// 获取WebUI基础配置
export const GetWebUIConfigHandler: RequestHandler = async (_, res) => {
try {
const config = await WebUiConfig.GetWebUIConfig();
return sendSuccess(res, {
host: config.host,
port: config.port,
loginRate: config.loginRate,
disableWebUI: config.disableWebUI,
disableNonLANAccess: config.disableNonLANAccess
});
} catch (error) {
const msg = (error as Error).message;
return sendError(res, `获取WebUI配置失败: ${msg}`);
}
};
// 获取是否禁用WebUI
export const GetDisableWebUIHandler: RequestHandler = async (_, res) => {
try {
const disable = await WebUiConfig.GetDisableWebUI();
return sendSuccess(res, disable);
} catch (error) {
const msg = (error as Error).message;
return sendError(res, `获取WebUI禁用状态失败: ${msg}`);
}
};
// 更新是否禁用WebUI
export const UpdateDisableWebUIHandler: RequestHandler = async (req, res) => {
try {
const { disable } = req.body;
if (typeof disable !== 'boolean') {
return sendError(res, 'disable参数必须是布尔值');
}
await WebUiConfig.UpdateDisableWebUI(disable);
return sendSuccess(res, null);
} catch (error) {
const msg = (error as Error).message;
return sendError(res, `更新WebUI禁用状态失败: ${msg}`);
}
};
// 获取是否禁用非局域网访问
export const GetDisableNonLANAccessHandler: RequestHandler = async (_, res) => {
try {
const disable = await WebUiConfig.GetDisableNonLANAccess();
return sendSuccess(res, disable);
} catch (error) {
const msg = (error as Error).message;
return sendError(res, `获取非局域网访问禁用状态失败: ${msg}`);
}
};
// 更新是否禁用非局域网访问
export const UpdateDisableNonLANAccessHandler: RequestHandler = async (req, res) => {
try {
const { disable } = req.body;
if (typeof disable !== 'boolean') {
return sendError(res, 'disable参数必须是布尔值');
}
await WebUiConfig.UpdateDisableNonLANAccess(disable);
return sendSuccess(res, null);
} catch (error) {
const msg = (error as Error).message;
return sendError(res, `更新非局域网访问禁用状态失败: ${msg}`);
}
};
// 更新WebUI基础配置
export const UpdateWebUIConfigHandler: RequestHandler = async (req, res) => {
try {
const { host, port, loginRate, disableWebUI, disableNonLANAccess } = req.body;
const updateConfig: any = {};
if (host !== undefined) {
if (isEmpty(host)) {
return sendError(res, 'host不能为空');
}
updateConfig.host = host;
}
if (port !== undefined) {
if (!Number.isInteger(port) || port < 1 || port > 65535) {
return sendError(res, 'port必须是1-65535之间的整数');
}
updateConfig.port = port;
}
if (loginRate !== undefined) {
if (!Number.isInteger(loginRate) || loginRate < 1) {
return sendError(res, 'loginRate必须是大于0的整数');
}
updateConfig.loginRate = loginRate;
}
if (disableWebUI !== undefined) {
if (typeof disableWebUI !== 'boolean') {
return sendError(res, 'disableWebUI必须是布尔值');
}
updateConfig.disableWebUI = disableWebUI;
}
if (disableNonLANAccess !== undefined) {
if (typeof disableNonLANAccess !== 'boolean') {
return sendError(res, 'disableNonLANAccess必须是布尔值');
}
updateConfig.disableNonLANAccess = disableNonLANAccess;
}
await WebUiConfig.UpdateWebUIConfig(updateConfig);
return sendSuccess(res, null);
} catch (error) {
const msg = (error as Error).message;
return sendError(res, `更新WebUI配置失败: ${msg}`);
}
};
+20
View File
@@ -14,6 +14,12 @@ const LoginRuntime: LoginRuntimeType = {
nick: '',
},
QQVersion: 'unknown',
onQQLoginStatusChange: async (status: boolean) => {
LoginRuntime.QQLoginStatus = status;
},
onWebUiTokenChange: async (_token: string) => {
return;
},
NapCatHelper: {
onOB11ConfigChanged: async () => {
return;
@@ -31,6 +37,12 @@ const LoginRuntime: LoginRuntimeType = {
};
export const WebUiDataRuntime = {
setWebUiTokenChangeCallback(func: (token: string) => Promise<void>): void {
LoginRuntime.onWebUiTokenChange = func;
},
getWebUiTokenChangeCallback(): (token: string) => Promise<void> {
return LoginRuntime.onWebUiTokenChange;
},
checkLoginRate(ip: string, RateLimit: number): boolean {
const key = `login_rate:${ip}`;
const count = store.get<number>(key) || 0;
@@ -53,6 +65,14 @@ export const WebUiDataRuntime = {
return LoginRuntime.QQLoginStatus;
},
setQQLoginCallback(func: (status: boolean) => Promise<void>): void {
LoginRuntime.onQQLoginStatusChange = func;
},
getQQLoginCallback(): (status: boolean) => Promise<void> {
return LoginRuntime.onQQLoginStatusChange;
},
setQQLoginStatus(status: LoginRuntimeType['QQLoginStatus']): void {
LoginRuntime.QQLoginStatus = status;
},
+75 -14
View File
@@ -1,4 +1,4 @@
import { webUiPathWrapper } from '@/webui';
import { webUiPathWrapper, getInitialWebUiToken } from '@/webui';
import { Type, Static } from '@sinclair/typebox';
import Ajv from 'ajv';
import fs, { constants } from 'node:fs/promises';
@@ -7,17 +7,21 @@ import { resolve } from 'node:path';
import { deepMerge } from '../utils/object';
import { themeType } from '../types/theme';
import { getRandomToken } from '../utils/url'
// 限制尝试端口的次数,避免死循环
// 定义配置的类型
const WebUiConfigSchema = Type.Object({
host: Type.String({ default: '0.0.0.0' }),
port: Type.Number({ default: 6099 }),
token: Type.String({ default: 'napcat' }),
token: Type.String({ default: getRandomToken(12) }),
loginRate: Type.Number({ default: 10 }),
autoLoginAccount: Type.String({ default: '' }),
theme: themeType,
// 是否关闭WebUI
disableWebUI: Type.Boolean({ default: false }),
// 是否关闭非局域网访问
disableNonLANAccess: Type.Boolean({ default: false }),
});
export type WebUiConfigType = Static<typeof WebUiConfigSchema>;
@@ -59,6 +63,47 @@ export class WebUiConfigWrapper {
}
async GetWebUIConfig(): Promise<WebUiConfigType> {
if (this.WebUiConfigData) {
return this.WebUiConfigData
}
try {
const configPath = resolve(webUiPathWrapper.configPath, './webui.json');
await this.ensureConfigFileExists(configPath);
const parsedConfig = await this.readAndValidateConfig(configPath);
// 使用内存中缓存的token进行覆盖,确保强兼容性
this.WebUiConfigData = {
...parsedConfig,
// 首次读取内存中是没有token的,需要进行一层兜底
token: getInitialWebUiToken() || parsedConfig.token,
};
return this.WebUiConfigData;
} catch (e) {
console.log('读取配置文件失败', e);
const defaultConfig = this.validateAndApplyDefaults({});
this.WebUiConfigData = {
...defaultConfig,
token: getInitialWebUiToken() || defaultConfig.token,
}
return this.WebUiConfigData;
}
}
async UpdateWebUIConfig(newConfig: Partial<WebUiConfigType>): Promise<void> {
const configPath = resolve(webUiPathWrapper.configPath, './webui.json');
// 使用原始配置进行合并,避免内存token覆盖影响配置更新
const currentConfig = await this.GetRawWebUIConfig();
const mergedConfig = deepMerge({ ...currentConfig }, newConfig);
const updatedConfig = this.validateAndApplyDefaults(mergedConfig);
await this.writeConfig(configPath, updatedConfig);
this.WebUiConfigData = updatedConfig;
}
/**
* 获取配置文件中实际存储的配置(不被内存token覆盖)
* 主要用于配置更新和特殊场景
*/
async GetRawWebUIConfig(): Promise<WebUiConfigType> {
if (this.WebUiConfigData) {
return this.WebUiConfigData;
}
@@ -74,18 +119,12 @@ export class WebUiConfigWrapper {
}
}
async UpdateWebUIConfig(newConfig: Partial<WebUiConfigType>): Promise<void> {
const configPath = resolve(webUiPathWrapper.configPath, './webui.json');
const currentConfig = await this.GetWebUIConfig();
const mergedConfig = deepMerge({ ...currentConfig }, newConfig);
const updatedConfig = this.validateAndApplyDefaults(mergedConfig);
await this.writeConfig(configPath, updatedConfig);
this.WebUiConfigData = updatedConfig;
}
async UpdateToken(oldToken: string, newToken: string): Promise<void> {
const currentConfig = await this.GetWebUIConfig();
if (currentConfig.token !== oldToken) {
// 使用内存中缓存的token进行验证,确保强兼容性
const cachedToken = getInitialWebUiToken();
const tokenToCheck = cachedToken || (await this.GetWebUIConfig()).token;
if (tokenToCheck !== oldToken) {
throw new Error('旧 token 不匹配');
}
await this.UpdateWebUIConfig({ token: newToken });
@@ -176,4 +215,26 @@ export class WebUiConfigWrapper {
async UpdateTheme(theme: WebUiConfigType['theme']): Promise<void> {
await this.UpdateWebUIConfig({ theme: theme });
}
// 获取是否禁用WebUI
async GetDisableWebUI(): Promise<boolean> {
const config = await this.GetWebUIConfig();
return config.disableWebUI;
}
// 更新是否禁用WebUI
async UpdateDisableWebUI(disable: boolean): Promise<void> {
await this.UpdateWebUIConfig({ disableWebUI: disable });
}
// 获取是否禁用非局域网访问
async GetDisableNonLANAccess(): Promise<boolean> {
const config = await this.GetWebUIConfig();
return config.disableNonLANAccess;
}
// 更新是否禁用非局域网访问
async UpdateDisableNonLANAccess(disable: boolean): Promise<void> {
await this.UpdateWebUIConfig({ disableNonLANAccess: disable });
}
}
+7 -4
View File
@@ -1,6 +1,6 @@
import { NextFunction, Request, Response } from 'express';
import { WebUiConfig } from '@/webui';
import { getInitialWebUiToken } from '@/webui';
import { AuthHelper } from '@webapi/helper/SignToken';
import { sendError } from '@webapi/utils/response';
@@ -30,10 +30,13 @@ export async function auth(req: Request, res: Response, next: NextFunction) {
} catch (e) {
return sendError(res, 'Unauthorized');
}
// 获取配置
const config = await WebUiConfig.GetWebUIConfig();
// 使用启动时缓存的token进行验证,而不是动态读取配置文件 因为有可能运行时手动修改了密码
const initialToken = getInitialWebUiToken();
if (!initialToken) {
return sendError(res, 'Server token not initialized');
}
// 验证凭证在1小时内有效
const credentialJson = AuthHelper.validateCredentialWithinOneHour(config.token, Credential);
const credentialJson = AuthHelper.validateCredentialWithinOneHour(initialToken, Credential);
if (credentialJson) {
// 通过验证
return next();
+47 -1
View File
@@ -1,7 +1,53 @@
import type { RequestHandler } from 'express';
import { WebUiConfig } from '@/webui';
// 检查是否为局域网IP地址
function isLANIP(ip: string): boolean {
if (!ip) return false;
// 移除IPv6的前缀,如果存在
const cleanIP = ip.replace(/^::ffff:/, '');
// 本地回环地址
if (cleanIP === '127.0.0.1' || cleanIP === 'localhost' || cleanIP === '::1') {
return true;
}
// 检查IPv4私有网络地址
const ipv4Regex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
const match = cleanIP.match(ipv4Regex);
if (match) {
const [, a, b] = match.map(Number);
// 10.0.0.0/8
if (a === 10) return true;
// 172.16.0.0/12
if (a === 172 && b !== undefined && b >= 16 && b <= 31) return true;
// 192.168.0.0/16
if (a === 192 && b === 168) return true;
// 169.254.0.0/16 (链路本地地址)
if (a === 169 && b === 254) return true;
}
return false;
}
// CORS 中间件,跨域用
export const cors: RequestHandler = (req, res, next) => {
export const cors: RequestHandler = async (req, res, next) => {
// 检查是否禁用非局域网访问
const config = await WebUiConfig.GetWebUIConfig();
if (config.disableNonLANAccess) {
const clientIP = req.ip || req.socket.remoteAddress || '';
if (!isLANIP(clientIP)) {
res.status(403).json({ error: '非局域网访问被禁止' });
return;
}
}
const origin = req.headers.origin || '*';
res.header('Access-Control-Allow-Origin', origin);
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
+31
View File
@@ -0,0 +1,31 @@
import { Router } from 'express';
import {
GetWebUIConfigHandler,
GetDisableWebUIHandler,
UpdateDisableWebUIHandler,
GetDisableNonLANAccessHandler,
UpdateDisableNonLANAccessHandler,
UpdateWebUIConfigHandler
} from '@webapi/api/WebUIConfig';
const router = Router();
// 获取WebUI基础配置
router.get('/GetConfig', GetWebUIConfigHandler);
// 更新WebUI基础配置
router.post('/UpdateConfig', UpdateWebUIConfigHandler);
// 获取是否禁用WebUI
router.get('/GetDisableWebUI', GetDisableWebUIHandler);
// 更新是否禁用WebUI
router.post('/UpdateDisableWebUI', UpdateDisableWebUIHandler);
// 获取是否禁用非局域网访问
router.get('/GetDisableNonLANAccess', GetDisableNonLANAccessHandler);
// 更新是否禁用非局域网访问
router.post('/UpdateDisableNonLANAccess', UpdateDisableNonLANAccessHandler);
export { router as WebUIConfigRouter };
-3
View File
@@ -1,7 +1,6 @@
import { Router } from 'express';
import {
CheckDefaultTokenHandler,
checkHandler,
LoginHandler,
LogoutHandler,
@@ -17,7 +16,5 @@ router.post('/check', checkHandler);
router.post('/logout', LogoutHandler);
// router:更新token
router.post('/update_token', UpdateTokenHandler);
// router:检查默认token
router.get('/check_using_default_token', CheckDefaultTokenHandler);
export { router as AuthRouter };
+3
View File
@@ -13,6 +13,7 @@ import { AuthRouter } from '@webapi/router/auth';
import { LogRouter } from '@webapi/router/Log';
import { BaseRouter } from '@webapi/router/Base';
import { FileRouter } from './File';
import { WebUIConfigRouter } from './WebUIConfig';
const router = Router();
@@ -35,5 +36,7 @@ router.use('/OB11Config', OB11ConfigRouter);
router.use('/Log', LogRouter);
// file:文件相关路由
router.use('/File', FileRouter);
// router:WebUI配置相关路由
router.use('/WebUIConfig', WebUIConfigRouter);
export { router as ALLRouter };
+26 -17
View File
@@ -1,21 +1,30 @@
import path from 'path';
import path from 'path'
import { fileURLToPath } from 'url'
export function callsites () {
const _prepareStackTrace = Error.prepareStackTrace
try {
let result: NodeJS.CallSite[] = []
Error.prepareStackTrace = (_, callSites) => {
const callSitesWithoutCurrent = callSites.slice(1)
result = callSitesWithoutCurrent
return callSitesWithoutCurrent
}
new Error().stack
return result
} finally {
Error.prepareStackTrace = _prepareStackTrace
}
}
Object.defineProperty(global, '__dirname', {
get() {
const err = new Error();
const stack = err.stack?.split('\n') || [];
let callerFile = '';
// 遍历错误堆栈,跳过当前文件所在行
// 注意:堆栈格式可能不同,请根据实际环境调整索引及正则表达式
for (const line of stack) {
const match = line.match(/\((.*):\d+:\d+\)/);
if (match?.[1]) {
callerFile = match[1];
if (!callerFile.includes('init-dynamic-dirname.ts')) {
break;
}
}
get () {
const sites = callsites()
const file = sites?.[1]?.getFileName()
if (file) {
return path.dirname(fileURLToPath(file))
}
return callerFile ? path.dirname(callerFile) : '';
return ''
},
});
})
+1 -1
View File
@@ -1,4 +1,4 @@
import './init-dynamic-dirname';
// import './init-dynamic-dirname';
import { WebUiConfig } from '@/webui';
import { AuthHelper } from '../helper/SignToken';
import { LogWrapper } from '@/common/log';
+2
View File
@@ -9,6 +9,8 @@ interface LoginRuntimeType {
QQLoginUin: string;
QQLoginInfo: SelfInfo;
QQVersion: string;
onQQLoginStatusChange: (status: boolean) => Promise<void>;
onWebUiTokenChange: (token: string) => Promise<void>;
WebUiConfigQuickFunction: () => Promise<void>;
NapCatHelper: {
onQuickLoginRequested: (uin: string) => Promise<{ result: boolean; message: string }>;
+21 -1
View File
@@ -66,7 +66,15 @@ export const createDiskStorage = (uploadPath: string) => {
};
export const createDiskUpload = (uploadPath: string) => {
const upload = multer({ storage: createDiskStorage(uploadPath) }).array('files');
const upload = multer({
storage: createDiskStorage(uploadPath),
limits: {
fileSize: 100 * 1024 * 1024, // 100MB 文件大小限制
files: 20, // 最多同时上传20个文件
fieldSize: 1024 * 1024, // 1MB 字段大小限制
fields: 10 // 最多10个字段
}
}).array('files');
return upload;
};
@@ -76,6 +84,18 @@ const diskUploader = (req: Request, res: Response) => {
createDiskUpload(uploadPath)(req, res, (error) => {
if (error) {
// 错误处理
if (error.code === 'LIMIT_FILE_SIZE') {
return reject(new Error('文件大小超过限制(最大100MB)'));
}
if (error.code === 'LIMIT_FILE_COUNT') {
return reject(new Error('文件数量超过限制(最多20个文件)'));
}
if (error.code === 'LIMIT_FIELD_VALUE') {
return reject(new Error('字段值大小超过限制'));
}
if (error.code === 'LIMIT_FIELD_COUNT') {
return reject(new Error('字段数量超过限制'));
}
return reject(error);
}
return resolve(true);
+69 -11
View File
@@ -1,8 +1,57 @@
/**
* @file URL工具
*/
import fs from 'node:fs'
import { isIP } from 'node:net'
import { randomBytes } from 'node:crypto'
import { isIP } from 'node:net';
type Protocol = 'http' | 'https'
let isDockerCached: boolean
function hasDockerEnv () {
try {
fs.statSync('/.dockerenv')
return true
} catch {
return false
}
}
function hasDockerCGroup () {
try {
return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker')
} catch {
return false
}
}
const hasContainerEnv = () => {
try {
fs.statSync('/run/.containerenv')
return true
} catch {
return false
}
}
const isDocker = () => {
if (isDockerCached === undefined) {
isDockerCached = hasContainerEnv() || hasDockerEnv() || hasDockerCGroup()
}
return isDockerCached
}
/**
* 获取默认host地址
* @returns 根据环境返回合适的host地址
* @example getDefaultHost() => '127.0.0.1' // 非Docker环境
* @example getDefaultHost() => '0.0.0.0' // Docker环境
*/
export const getDefaultHost = (): string => {
return isDocker() ? '0.0.0.0' : '127.0.0.1'
}
/**
* 将 host(主机地址) 转换为标准格式
@@ -13,10 +62,9 @@ import { isIP } from 'node:net';
* @example normalizeHost('2001:4860:4801:51::27') => '[2001:4860:4801:51::27]'
*/
export const normalizeHost = (host: string) => {
if (host === '0.0.0.0') return '127.0.0.1';
if (isIP(host) === 6) return `[${host}]`;
return host;
};
if (isIP(host) === 6) return `[${host}]`
return host
}
/**
* 创建URL
@@ -35,13 +83,23 @@ export const createUrl = (
search?: Record<string, any>,
protocol: Protocol = 'http'
) => {
const url = new URL(`${protocol}://${normalizeHost(host)}`);
url.port = port;
url.pathname = path;
const url = new URL(`${protocol}://${normalizeHost(host)}`)
url.port = port
url.pathname = path
if (search) {
for (const key in search) {
url.searchParams.set(key, search[key]);
url.searchParams.set(key, search[key])
}
}
return url.toString();
};
return url.toString()
}
/**
* 生成随机Token
* @param length Token长度 默认8
* @returns 随机Token字符串
* @example getRandomToken
*/
export const getRandomToken = (length = 8) => {
return randomBytes(36).toString('hex').slice(0, length)
}