mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2025-07-19 12:03:37 +00:00
Compare commits
12 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
5c932e5a27 | ||
![]() |
4bd63c6267 | ||
![]() |
aabe24f903 | ||
![]() |
69cebd7fbc | ||
![]() |
8da371176a | ||
![]() |
dd08adf1d1 | ||
![]() |
2f67bef139 | ||
![]() |
8968c51cdc | ||
![]() |
f2fdcc9289 | ||
![]() |
aa3a575cbe | ||
![]() |
11816d038d | ||
![]() |
6a990edb38 |
@@ -4,7 +4,7 @@
|
||||
"name": "NapCatQQ",
|
||||
"slug": "NapCat.Framework",
|
||||
"description": "高性能的 OneBot 11 协议实现",
|
||||
"version": "4.5.12",
|
||||
"version": "4.5.16",
|
||||
"icon": "./logo.png",
|
||||
"authors": [
|
||||
{
|
||||
|
@@ -9,14 +9,6 @@ export interface Log {
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface TerminalSession {
|
||||
id: string
|
||||
}
|
||||
|
||||
export interface TerminalInfo {
|
||||
id: string
|
||||
}
|
||||
|
||||
export default class WebUIManager {
|
||||
public static async checkWebUiLogined() {
|
||||
const { data } =
|
||||
@@ -40,6 +32,13 @@ 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)
|
||||
|
@@ -1,6 +1,7 @@
|
||||
import { Card, CardBody } from '@heroui/card'
|
||||
import { Tab, Tabs } from '@heroui/tabs'
|
||||
import { useMediaQuery } from 'react-responsive'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
|
||||
import ChangePasswordCard from './change_password'
|
||||
import OneBotConfigCard from './onebot'
|
||||
@@ -22,6 +23,11 @@ const ConfingPageItem: React.FC<ConfigPageProps> = ({ children }) => {
|
||||
|
||||
export default function ConfigPage() {
|
||||
const isMediumUp = useMediaQuery({ minWidth: 768 })
|
||||
const navigate = useNavigate()
|
||||
const search = useSearchParams({
|
||||
tab: 'onebot'
|
||||
})[0]
|
||||
const tab = search.get('tab') ?? 'onebot'
|
||||
|
||||
return (
|
||||
<section className="w-[1000px] max-w-full md:mx-auto gap-4 py-8 px-2 md:py-10">
|
||||
@@ -30,6 +36,10 @@ export default function ConfigPage() {
|
||||
fullWidth
|
||||
className="w-full"
|
||||
isVertical={isMediumUp}
|
||||
selectedKey={tab}
|
||||
onSelectionChange={(key) => {
|
||||
navigate(`/config?tab=${key}`)
|
||||
}}
|
||||
classNames={{
|
||||
tabList: 'sticky flex top-14 bg-opacity-50 backdrop-blur-sm',
|
||||
panel: 'w-full relative',
|
||||
|
@@ -81,6 +81,10 @@ const WebUIConfigCard = () => {
|
||||
onDelete={async () => {
|
||||
try {
|
||||
await FileManager.deleteWebUIFont()
|
||||
toast.success('删除成功')
|
||||
setTimeout(() => {
|
||||
window.location.reload()
|
||||
}, 1000)
|
||||
} catch (error) {
|
||||
toast.error('删除失败: ' + (error as Error).message)
|
||||
}
|
||||
|
@@ -1,14 +1,46 @@
|
||||
import { Spinner } from '@heroui/spinner'
|
||||
import { AnimatePresence, motion } from 'motion/react'
|
||||
import { Suspense } from 'react'
|
||||
import { Outlet, useLocation } from 'react-router-dom'
|
||||
import { Suspense, useEffect } from 'react'
|
||||
import { Outlet, useLocation, useNavigate } 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">
|
||||
|
@@ -2,7 +2,7 @@
|
||||
"name": "napcat",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "4.5.12",
|
||||
"version": "4.5.16",
|
||||
"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",
|
||||
|
@@ -1 +1 @@
|
||||
export const napCatVersion = '4.5.12';
|
||||
export const napCatVersion = '4.5.16';
|
||||
|
@@ -434,9 +434,9 @@ export class NTQQFileApi {
|
||||
};
|
||||
|
||||
try {
|
||||
if (this.core.apis.PacketApi.available && this.packetRkey?.[0] && this.packetRkey?.[1]) {
|
||||
const rkey_expired_private = !this.packetRkey || this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1000;
|
||||
const rkey_expired_group = !this.packetRkey || this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1000;
|
||||
if (this.core.apis.PacketApi.available) {
|
||||
const rkey_expired_private = !this.packetRkey || (this.packetRkey[0] && this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1000);
|
||||
const rkey_expired_group = !this.packetRkey || (this.packetRkey[0] && this.packetRkey[0].time + Number(this.packetRkey[0].ttl) < Date.now() / 1000);
|
||||
if (rkey_expired_private || rkey_expired_group) {
|
||||
this.packetRkey = await this.fetchRkeyWithRetry();
|
||||
}
|
||||
|
@@ -11,7 +11,7 @@ export class NodeIKernelSessionListener {
|
||||
|
||||
}
|
||||
|
||||
onOpentelemetryInit(args: unknown): any {
|
||||
onOpentelemetryInit(info: { is_init: boolean, is_report: boolean }): any {
|
||||
|
||||
}
|
||||
|
||||
|
@@ -1,5 +1,9 @@
|
||||
import { GeneralCallResult } from './common';
|
||||
|
||||
enum ProxyType {
|
||||
CLOSE = 0,
|
||||
HTTP = 1,
|
||||
SOCKET = 2
|
||||
}
|
||||
export interface NodeIKernelMSFService {
|
||||
getServerTime(): string;
|
||||
setNetworkProxy(param: {
|
||||
@@ -7,10 +11,19 @@ export interface NodeIKernelMSFService {
|
||||
userPwd: string,
|
||||
address: string,
|
||||
port: number,
|
||||
proxyType: number,
|
||||
proxyType: ProxyType,
|
||||
domain: string,
|
||||
isSocket: boolean
|
||||
}): Promise<GeneralCallResult>;
|
||||
getNetworkProxy(): Promise<{
|
||||
userName: string,
|
||||
userPwd: string,
|
||||
address: string,
|
||||
port: number,
|
||||
proxyType: ProxyType,
|
||||
domain: string,
|
||||
isSocket: boolean
|
||||
}>;
|
||||
//http
|
||||
// userName: '',
|
||||
// userPwd: '',
|
||||
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -236,11 +236,11 @@ async function initializeSession(
|
||||
) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const sessionListener = new NodeIKernelSessionListener();
|
||||
sessionListener.onSessionInitComplete = (r: unknown) => {
|
||||
if (r === 0) {
|
||||
sessionListener.onOpentelemetryInit = (info) => {
|
||||
if (info.is_init) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error('登录异常' + r?.toString()));
|
||||
reject(new Error('opentelemetry init failed'));
|
||||
}
|
||||
};
|
||||
session.init(
|
||||
@@ -260,7 +260,30 @@ async function initializeSession(
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function handleProxy(session: NodeIQQNTWrapperSession, logger: LogWrapper) {
|
||||
if (process.env['NAPCAT_PROXY_PORT']) {
|
||||
session.getMSFService().setNetworkProxy({
|
||||
userName: '',
|
||||
userPwd: '',
|
||||
address: process.env['NAPCAT_PROXY_ADDRESS'] || '127.0.0.1',
|
||||
port: +process.env['NAPCAT_PROXY_PORT'],
|
||||
proxyType: 2,
|
||||
domain: '',
|
||||
isSocket: true
|
||||
});
|
||||
logger.logWarn('已设置代理', process.env['NAPCAT_PROXY_ADDRESS'], process.env['NAPCAT_PROXY_PORT']);
|
||||
} else if (process.env['NAPCAT_PROXY_CLOSE']) {
|
||||
session.getMSFService().setNetworkProxy({
|
||||
userName: '',
|
||||
userPwd: '',
|
||||
address: '',
|
||||
port: 0,
|
||||
proxyType: 0,
|
||||
domain: '',
|
||||
isSocket: false
|
||||
});
|
||||
}
|
||||
}
|
||||
export async function NCoreInitShell() {
|
||||
console.log('NapCat Shell App Loading...');
|
||||
const pathWrapper = new NapCatPathWrapper();
|
||||
@@ -286,7 +309,7 @@ export async function NCoreInitShell() {
|
||||
|
||||
await initializeEngine(engine, basicInfoWrapper, dataPathGlobal, systemPlatform, systemVersion);
|
||||
await initializeLoginService(loginService, basicInfoWrapper, dataPathGlobal, systemVersion, hostname);
|
||||
|
||||
handleProxy(session, logger);
|
||||
program.option('-q, --qq [number]', 'QQ号').parse(process.argv);
|
||||
const cmdOptions = program.opts();
|
||||
const quickLoginUin = cmdOptions['qq'];
|
||||
@@ -294,6 +317,7 @@ export async function NCoreInitShell() {
|
||||
|
||||
const dataTimestape = new Date().getTime().toString();
|
||||
o3Service.reportAmgomWeather('login', 'a1', [dataTimestape, '0', '0']);
|
||||
|
||||
const selfInfo = await handleLogin(loginService, logger, pathWrapper, quickLoginUin, historyLoginList);
|
||||
const amgomDataPiece = 'eb1fd6ac257461580dc7438eb099f23aae04ca679f4d88f53072dc56e3bb1129';
|
||||
o3Service.setAmgomDataPiece(basicInfoWrapper.QQVersionAppid, new Uint8Array(Buffer.from(amgomDataPiece, 'hex')));
|
||||
|
@@ -10,7 +10,7 @@ import { WebUiConfigWrapper } from '@webapi/helper/config';
|
||||
import { ALLRouter } from '@webapi/router';
|
||||
import { cors } from '@webapi/middleware/cors';
|
||||
import { createUrl } from '@webapi/utils/url';
|
||||
import { sendError, sendSuccess } from '@webapi/utils/response';
|
||||
import { sendError } from '@webapi/utils/response';
|
||||
import { join } from 'node:path';
|
||||
import { terminalManager } from '@webapi/terminal/terminal_manager';
|
||||
import multer from 'multer'; // 新增:引入multer用于错误捕获
|
||||
@@ -26,12 +26,25 @@ const server = createServer(app);
|
||||
*/
|
||||
export let WebUiConfig: WebUiConfigWrapper;
|
||||
export let webUiPathWrapper: NapCatPathWrapper;
|
||||
const MAX_PORT_TRY = 100;
|
||||
import * as net from 'node:net';
|
||||
|
||||
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, ''];
|
||||
}
|
||||
}
|
||||
|
||||
export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapper) {
|
||||
webUiPathWrapper = pathWrapper;
|
||||
WebUiConfig = new WebUiConfigWrapper();
|
||||
const config = await WebUiConfig.GetWebUIConfig();
|
||||
if (config.port == 0) {
|
||||
const [host, port, token] = await InitPort(await WebUiConfig.GetWebUIConfig());
|
||||
if (port == 0) {
|
||||
logger.log('[NapCat] [WebUi] Current WebUi is not run.');
|
||||
return;
|
||||
}
|
||||
@@ -47,7 +60,6 @@ export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapp
|
||||
// 如果是webui字体文件,挂载字体文件
|
||||
app.use('/webui/fonts/AaCute.woff', async (_req, res, next) => {
|
||||
const isFontExist = await WebUiConfigWrapper.CheckWebUIFontExist();
|
||||
console.log(isFontExist, 'isFontExist');
|
||||
if (isFontExist) {
|
||||
res.sendFile(WebUiConfigWrapper.GetWebUIFontPath());
|
||||
} else {
|
||||
@@ -75,7 +87,7 @@ export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapp
|
||||
|
||||
// 初始服务(先放个首页)
|
||||
app.all('/', (_req, res) => {
|
||||
sendSuccess(res, null, 'NapCat WebAPI is now running!');
|
||||
res.status(301).header('Location', '/webui').send();
|
||||
});
|
||||
|
||||
// 错误处理中间件,捕获multer的错误
|
||||
@@ -92,16 +104,74 @@ export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapp
|
||||
});
|
||||
|
||||
// ------------启动服务------------
|
||||
server.listen(config.port, config.host, async () => {
|
||||
server.listen(port, host, async () => {
|
||||
// 启动后打印出相关地址
|
||||
const port = config.port.toString(),
|
||||
searchParams = { token: config.token };
|
||||
if (config.host !== '' && config.host !== '0.0.0.0') {
|
||||
let searchParams = { token: token };
|
||||
if (host !== '' && host !== '0.0.0.0') {
|
||||
logger.log(
|
||||
`[NapCat] [WebUi] WebUi User Panel Url: ${createUrl(config.host, port, '/webui', searchParams)}`
|
||||
`[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, '/webui', searchParams)}`);
|
||||
logger.log(
|
||||
`[NapCat] [WebUi] WebUi Local Panel Url: ${createUrl('127.0.0.1', port.toString(), '/webui', searchParams)}`
|
||||
);
|
||||
});
|
||||
// ------------Over!------------
|
||||
}
|
||||
|
||||
async function tryUseHost(host: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const server = net.createServer();
|
||||
server.on('listening', () => {
|
||||
server.close();
|
||||
resolve(host);
|
||||
});
|
||||
|
||||
server.on('error', (err: any) => {
|
||||
if (err.code === 'EADDRNOTAVAIL') {
|
||||
reject(new Error('主机地址验证失败,可能为非本机地址'));
|
||||
} else {
|
||||
reject(new Error(`遇到错误: ${err.code}`));
|
||||
}
|
||||
});
|
||||
|
||||
// 尝试监听 让系统随机分配一个端口
|
||||
server.listen(0, host);
|
||||
} catch (error) {
|
||||
// 这里捕获到的错误应该是启动服务器时的同步错误
|
||||
reject(new Error(`服务器启动时发生错误: ${error}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function tryUsePort(port: number, host: string, tryCount: number = 0): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const server = net.createServer();
|
||||
server.on('listening', () => {
|
||||
server.close();
|
||||
resolve(port);
|
||||
});
|
||||
|
||||
server.on('error', (err: any) => {
|
||||
if (err.code === 'EADDRINUSE') {
|
||||
if (tryCount < MAX_PORT_TRY) {
|
||||
// 使用循环代替递归
|
||||
resolve(tryUsePort(port + 1, host, tryCount + 1));
|
||||
} else {
|
||||
reject(new Error(`端口尝试失败,达到最大尝试次数: ${MAX_PORT_TRY}`));
|
||||
}
|
||||
} else {
|
||||
reject(new Error(`遇到错误: ${err.code}`));
|
||||
}
|
||||
});
|
||||
|
||||
// 尝试监听端口
|
||||
server.listen(port, host);
|
||||
} catch (error) {
|
||||
// 这里捕获到的错误应该是启动服务器时的同步错误
|
||||
reject(new Error(`服务器启动时发生错误: ${error}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@@ -7,6 +7,15 @@ 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配置
|
||||
@@ -93,7 +102,7 @@ export const UpdateTokenHandler: RequestHandler = async (req, res) => {
|
||||
try {
|
||||
// 注销当前的Token
|
||||
if (authorization) {
|
||||
const CredentialBase64: string = authorization.split(' ')[1];
|
||||
const CredentialBase64: string = authorization.split(' ')[1] as string;
|
||||
const Credential = JSON.parse(Buffer.from(CredentialBase64, 'base64').toString());
|
||||
AuthHelper.revokeCredential(Credential);
|
||||
}
|
||||
|
@@ -3,7 +3,8 @@ import { sendError, sendSuccess } from '../utils/response';
|
||||
import { WebUiConfigWrapper } from '../helper/config';
|
||||
import { logSubscription } from '@/common/log';
|
||||
import { terminalManager } from '../terminal/terminal_manager';
|
||||
|
||||
// 判断是否是 macos
|
||||
const isMacOS = process.platform === 'darwin';
|
||||
// 日志记录
|
||||
export const LogHandler: RequestHandler = async (req, res) => {
|
||||
const filename = req.query['id'];
|
||||
@@ -43,6 +44,9 @@ export const LogRealTimeHandler: RequestHandler = async (req, res) => {
|
||||
|
||||
// 终端相关处理器
|
||||
export const CreateTerminalHandler: RequestHandler = async (req, res) => {
|
||||
if (isMacOS) {
|
||||
return sendError(res, 'MacOS不支持终端');
|
||||
}
|
||||
try {
|
||||
const { cols, rows } = req.body;
|
||||
const { id } = terminalManager.createTerminal(cols, rows);
|
||||
|
@@ -1,167 +1,75 @@
|
||||
import { webUiPathWrapper } from '@/webui';
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
import Ajv from 'ajv';
|
||||
import fs, { constants } from 'node:fs/promises';
|
||||
import * as net from 'node:net';
|
||||
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
// 限制尝试端口的次数,避免死循环
|
||||
const MAX_PORT_TRY = 100;
|
||||
|
||||
async function tryUseHost(host: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const server = net.createServer();
|
||||
server.on('listening', () => {
|
||||
server.close();
|
||||
resolve(host);
|
||||
});
|
||||
// 定义配置的类型
|
||||
const WebUiConfigSchema = Type.Object({
|
||||
host: Type.String({ default: '0.0.0.0' }),
|
||||
port: Type.Number({ default: 6099 }),
|
||||
token: Type.String({ default: 'napcat' }),
|
||||
loginRate: Type.Number({ default: 10 }),
|
||||
});
|
||||
|
||||
server.on('error', (err: any) => {
|
||||
if (err.code === 'EADDRNOTAVAIL') {
|
||||
reject(new Error('主机地址验证失败,可能为非本机地址'));
|
||||
} else {
|
||||
reject(new Error(`遇到错误: ${err.code}`));
|
||||
}
|
||||
});
|
||||
export type WebUiConfigType = Static<typeof WebUiConfigSchema>;
|
||||
|
||||
// 尝试监听 让系统随机分配一个端口
|
||||
server.listen(0, host);
|
||||
} catch (error) {
|
||||
// 这里捕获到的错误应该是启动服务器时的同步错误
|
||||
reject(new Error(`服务器启动时发生错误: ${error}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function tryUsePort(port: number, host: string, tryCount: number = 0): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const server = net.createServer();
|
||||
server.on('listening', () => {
|
||||
server.close();
|
||||
resolve(port);
|
||||
});
|
||||
|
||||
server.on('error', (err: any) => {
|
||||
if (err.code === 'EADDRINUSE') {
|
||||
if (tryCount < MAX_PORT_TRY) {
|
||||
// 使用循环代替递归
|
||||
resolve(tryUsePort(port + 1, host, tryCount + 1));
|
||||
} else {
|
||||
reject(new Error(`端口尝试失败,达到最大尝试次数: ${MAX_PORT_TRY}`));
|
||||
}
|
||||
} else {
|
||||
reject(new Error(`遇到错误: ${err.code}`));
|
||||
}
|
||||
});
|
||||
|
||||
// 尝试监听端口
|
||||
server.listen(port, host);
|
||||
} catch (error) {
|
||||
// 这里捕获到的错误应该是启动服务器时的同步错误
|
||||
reject(new Error(`服务器启动时发生错误: ${error}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 读取当前目录下名为 webui.json 的配置文件,如果不存在则创建初始化配置文件
|
||||
export class WebUiConfigWrapper {
|
||||
WebUiConfigData: WebUiConfigType | undefined = undefined;
|
||||
|
||||
private applyDefaults<T>(obj: Partial<T>, defaults: T): T {
|
||||
const result = { ...defaults } as T;
|
||||
for (const key in obj) {
|
||||
if (obj[key] && typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
|
||||
result[key] = this.applyDefaults(obj[key], defaults[key]);
|
||||
} else if (obj[key] !== undefined) {
|
||||
result[key] = obj[key] as T[Extract<keyof T, string>];
|
||||
}
|
||||
private validateAndApplyDefaults(config: Partial<WebUiConfigType>): WebUiConfigType {
|
||||
new Ajv({ coerceTypes: true, useDefaults: true }).compile(WebUiConfigSchema)(config);
|
||||
return config as WebUiConfigType;
|
||||
}
|
||||
|
||||
private async ensureConfigFileExists(configPath: string): Promise<void> {
|
||||
const configExists = await fs.access(configPath, constants.F_OK).then(() => true).catch(() => false);
|
||||
if (!configExists) {
|
||||
await fs.writeFile(configPath, JSON.stringify(this.validateAndApplyDefaults({}), null, 4));
|
||||
}
|
||||
}
|
||||
|
||||
private async readAndValidateConfig(configPath: string): Promise<WebUiConfigType> {
|
||||
const fileContent = await fs.readFile(configPath, 'utf-8');
|
||||
return this.validateAndApplyDefaults(JSON.parse(fileContent));
|
||||
}
|
||||
|
||||
private async writeConfig(configPath: string, config: WebUiConfigType): Promise<void> {
|
||||
const hasWritePermission = await fs.access(configPath, constants.W_OK).then(() => true).catch(() => false);
|
||||
if (hasWritePermission) {
|
||||
await fs.writeFile(configPath, JSON.stringify(config, null, 4));
|
||||
} else {
|
||||
console.warn(`文件: ${configPath} 没有写入权限, 配置的更改部分可能会在重启后还原.`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async GetWebUIConfig(): Promise<WebUiConfigType> {
|
||||
if (this.WebUiConfigData) {
|
||||
return this.WebUiConfigData;
|
||||
}
|
||||
const defaultconfig: WebUiConfigType = {
|
||||
host: '0.0.0.0',
|
||||
port: 6099,
|
||||
token: '', // 默认先填空,空密码无法登录
|
||||
loginRate: 3,
|
||||
};
|
||||
try {
|
||||
defaultconfig.token = Math.random().toString(36).slice(2); //生成随机密码
|
||||
} catch (e) {
|
||||
console.log('随机密码生成失败', e);
|
||||
}
|
||||
try {
|
||||
const configPath = resolve(webUiPathWrapper.configPath, './webui.json');
|
||||
|
||||
if (
|
||||
!(await fs
|
||||
.access(configPath, constants.F_OK)
|
||||
.then(() => true)
|
||||
.catch(() => false))
|
||||
) {
|
||||
await fs.writeFile(configPath, JSON.stringify(defaultconfig, null, 4));
|
||||
}
|
||||
|
||||
const fileContent = await fs.readFile(configPath, 'utf-8');
|
||||
const parsedConfig = this.applyDefaults(JSON.parse(fileContent) as Partial<WebUiConfigType>, defaultconfig);
|
||||
|
||||
if (
|
||||
await fs
|
||||
.access(configPath, constants.W_OK)
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
) {
|
||||
await fs.writeFile(configPath, JSON.stringify(parsedConfig, null, 4));
|
||||
} else {
|
||||
console.warn(`文件: ${configPath} 没有写入权限, 配置的更改部分可能会在重启后还原.`);
|
||||
}
|
||||
|
||||
const [host_err, host] = await tryUseHost(parsedConfig.host)
|
||||
.then((data) => [null, data])
|
||||
.catch((err) => [err, null]);
|
||||
if (host_err) {
|
||||
console.log('host不可用', host_err);
|
||||
parsedConfig.port = 0; // 设置为0,禁用WebUI
|
||||
} else {
|
||||
parsedConfig.host = host;
|
||||
const [port_err, port] = await tryUsePort(parsedConfig.port, parsedConfig.host)
|
||||
.then((data) => [null, data])
|
||||
.catch((err) => [err, null]);
|
||||
if (port_err) {
|
||||
console.log('port不可用', port_err);
|
||||
parsedConfig.port = 0; // 设置为0,禁用WebUI
|
||||
} else {
|
||||
parsedConfig.port = port;
|
||||
}
|
||||
}
|
||||
await this.ensureConfigFileExists(configPath);
|
||||
const parsedConfig = await this.readAndValidateConfig(configPath);
|
||||
this.WebUiConfigData = parsedConfig;
|
||||
return this.WebUiConfigData;
|
||||
} catch (e) {
|
||||
console.log('读取配置文件失败', e);
|
||||
return this.validateAndApplyDefaults({});
|
||||
}
|
||||
return defaultconfig; // 理论上这行代码到不了,到了只能返回默认配置了
|
||||
}
|
||||
|
||||
async UpdateWebUIConfig(newConfig: Partial<WebUiConfigType>): Promise<void> {
|
||||
const configPath = resolve(webUiPathWrapper.configPath, './webui.json');
|
||||
const currentConfig = await this.GetWebUIConfig();
|
||||
const updatedConfig = this.applyDefaults(newConfig, currentConfig);
|
||||
|
||||
if (
|
||||
await fs
|
||||
.access(configPath, constants.W_OK)
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
) {
|
||||
await fs.writeFile(configPath, JSON.stringify(updatedConfig, null, 4));
|
||||
this.WebUiConfigData = updatedConfig;
|
||||
} else {
|
||||
console.warn(`文件: ${configPath} 没有写入权限, 配置的更改部分可能会在重启后还原.`);
|
||||
}
|
||||
const updatedConfig = this.validateAndApplyDefaults({ ...currentConfig, ...newConfig });
|
||||
await this.writeConfig(configPath, updatedConfig);
|
||||
this.WebUiConfigData = updatedConfig;
|
||||
}
|
||||
|
||||
async UpdateToken(oldToken: string, newToken: string): Promise<void> {
|
||||
@@ -176,29 +84,22 @@ export class WebUiConfigWrapper {
|
||||
public static async GetLogsPath(): Promise<string> {
|
||||
return resolve(webUiPathWrapper.logsPath);
|
||||
}
|
||||
|
||||
// 获取日志列表
|
||||
public static async GetLogsList(): Promise<string[]> {
|
||||
if (
|
||||
await fs
|
||||
.access(webUiPathWrapper.logsPath, constants.F_OK)
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
) {
|
||||
return (await fs.readdir(webUiPathWrapper.logsPath))
|
||||
.filter((file) => file.endsWith('.log'))
|
||||
.map((file) => file.replace('.log', ''));
|
||||
const logsPath = resolve(webUiPathWrapper.logsPath);
|
||||
const logsExist = await fs.access(logsPath, constants.F_OK).then(() => true).catch(() => false);
|
||||
if (logsExist) {
|
||||
return (await fs.readdir(logsPath)).filter(file => file.endsWith('.log')).map(file => file.replace('.log', ''));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// 获取指定日志文件内容
|
||||
public static async GetLogContent(filename: string): Promise<string> {
|
||||
const logPath = resolve(webUiPathWrapper.logsPath, `${filename}.log`);
|
||||
if (
|
||||
await fs
|
||||
.access(logPath, constants.R_OK)
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
) {
|
||||
const logExists = await fs.access(logPath, constants.R_OK).then(() => true).catch(() => false);
|
||||
if (logExists) {
|
||||
return await fs.readFile(logPath, 'utf-8');
|
||||
}
|
||||
return '';
|
||||
@@ -207,13 +108,9 @@ export class WebUiConfigWrapper {
|
||||
// 获取字体文件夹内的字体列表
|
||||
public static async GetFontList(): Promise<string[]> {
|
||||
const fontsPath = resolve(webUiPathWrapper.configPath, './fonts');
|
||||
if (
|
||||
await fs
|
||||
.access(fontsPath, constants.F_OK)
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
) {
|
||||
return (await fs.readdir(fontsPath)).filter((file) => file.endsWith('.ttf'));
|
||||
const fontsExist = await fs.access(fontsPath, constants.F_OK).then(() => true).catch(() => false);
|
||||
if (fontsExist) {
|
||||
return (await fs.readdir(fontsPath)).filter(file => file.endsWith('.ttf'));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
@@ -221,14 +118,11 @@ export class WebUiConfigWrapper {
|
||||
// 判断字体是否存在(webui.woff)
|
||||
public static async CheckWebUIFontExist(): Promise<boolean> {
|
||||
const fontsPath = resolve(webUiPathWrapper.configPath, './fonts');
|
||||
return await fs
|
||||
.access(resolve(fontsPath, './webui.woff'), constants.F_OK)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
return await fs.access(resolve(fontsPath, './webui.woff'), constants.F_OK).then(() => true).catch(() => false);
|
||||
}
|
||||
|
||||
// 获取webui字体文件路径
|
||||
public static GetWebUIFontPath(): string {
|
||||
return resolve(webUiPathWrapper.configPath, './fonts/webui.woff');
|
||||
}
|
||||
}
|
||||
}
|
@@ -23,6 +23,9 @@ const router = Router();
|
||||
const apiLimiter = rateLimit({
|
||||
windowMs: 1 * 60 * 1000, // 1分钟内
|
||||
max: 60, // 最大60个请求
|
||||
validate: {
|
||||
xForwardedForHeader: false,
|
||||
},
|
||||
});
|
||||
|
||||
router.use(apiLimiter);
|
||||
|
@@ -1,6 +1,12 @@
|
||||
import { Router } from 'express';
|
||||
|
||||
import { checkHandler, LoginHandler, LogoutHandler, UpdateTokenHandler } from '@webapi/api/Auth';
|
||||
import {
|
||||
CheckDefaultTokenHandler,
|
||||
checkHandler,
|
||||
LoginHandler,
|
||||
LogoutHandler,
|
||||
UpdateTokenHandler,
|
||||
} from '@webapi/api/Auth';
|
||||
|
||||
const router = Router();
|
||||
// router:登录
|
||||
@@ -11,5 +17,7 @@ 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 };
|
||||
|
Reference in New Issue
Block a user