Compare commits

..
13 Commits
Author SHA1 Message Date
手瓜一十雪 17322bb5a4 Add mappings for 9.9.26-45627 and 6.9.88-44725
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Add support for new client builds by updating external mappings. appid.json: add 9.9.26-45627 (appid 537340060) and 6.9.88-44725 (appid 537337594) with QUA strings. napi2native.json: add send/recv entries for 9.9.26-45627-x64, 6.9.88-44725-x64 and 6.9.88-44725-arm64. packet.json: add corresponding send/recv offsets for the same builds/architectures. These additions enable handling of the new versions in napcat-core.
2026-01-31 15:55:36 +08:00
冷曦 c0bcced5fb 增加个网络配置导出导入 (#1567)
* 增加个网络配置导出导入

重装容器时可以直接导出导入

* Remove unused import for useRef in network.tsx
2026-01-31 15:28:18 +08:00
手瓜一十雪 805c1d5ea2 Default plugins disabled; skip loading disabled
Change plugin loader to treat plugins as disabled by default (unless the id/dir is 'napcat-plugin-builtin') by using nullish coalescing when reading statusConfig. Add an early-return guard in the plugin manager/adapter that logs and skips loading when entry.enable is false. This prevents disabled plugins from being loaded automatically and provides a clear log message when skipped.
2026-01-31 15:26:56 +08:00
手瓜一十雪 b3399b07ad Silence update log; change update UI colors
Comment out the noisy '[NapCat Update] No pending updates found' log in UpdateNapCat.ts. Update frontend color choices: switch the plugin store action color from 'success' to 'default', and change the NewVersion chip and spinner from 'danger' to 'primary' in system_info.tsx. These tweaks reduce alarming red styling and quiet an unnecessary backend log.
2026-01-31 15:15:01 +08:00
手瓜一十雪 71f8504849 Refactor extension page layout and tab handling
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Improves the layout of the extension page by adjusting container heights and restructuring the header to better support responsive design. Moves the tab navigation to the header and displays only the selected extension page in the main content area, simplifying the rendering logic and improving user experience.
2026-01-30 19:41:27 +08:00
手瓜一十雪 3b7ca1a08f Remove flex-wrap from tabList class in ExtensionPage
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
The 'flex-wrap' class was removed from the tabList classNames in the ExtensionPage component, likely to prevent tab items from wrapping onto multiple lines and to maintain a single-line tab layout.
2026-01-30 19:35:46 +08:00
手瓜一十雪 57f3c4dd31 Support nested innerPacketMsg in SendMsgBase
Adds handling for innerPacketMsg arrays within uploadReturnData, allowing nested packet messages to be included in the result. This change ensures that all relevant inner messages are processed and returned.
2026-01-30 19:25:01 +08:00
时瑾 5b20ebb7b0 fix: webui 随机token仅生成不会被url编码的随机字符 (#1565)
* fix: webui 随机token仅生成不会被url编码的随机字符

* fix: 移除调试模块中的encodeURIComponent
2026-01-30 18:51:13 +08:00
手瓜一十雪 3a3eaeec7c Add UploadForwardMsgV2 support for multi-message forwarding
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Introduces UploadForwardMsgV2 transformer and integrates it into the message sending flow to support forwarding multiple messages with custom action commands. Updates related interfaces and logic to handle UUIDs and nested forwarded messages, improving flexibility and extensibility for message forwarding operations.
2026-01-30 18:47:45 +08:00
手瓜一十雪 b0cc7b6ee5 Update Vite aliases in napcat-schema config
Expanded the alias configuration in vite.config.ts to include specific paths for napcat-onebot, napcat-common, napcat-schema, and napcat-core. This improves module resolution and import clarity within the project.
2026-01-30 14:41:46 +08:00
冷曦 e5108c0427 增加判断插件启用状态显示配置提示 (#1562)
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-01-30 14:31:56 +08:00
手瓜一十雪 927797f3d5 Add SSL certificate management to WebUI config
Introduces backend API endpoints and frontend UI for managing SSL certificates, including viewing status, uploading, and deleting cert/key files. Adds a new SSL configuration tab in the dashboard, allowing users to enable HTTPS by providing PEM-formatted certificate and key, with changes taking effect after restart.
2026-01-30 14:28:47 +08:00
手瓜一十雪 72e01f8c84 Change default host to IPv6 (::) in config schema
Updated the default value of the 'host' field in WebUiConfigSchema from '0.0.0.0' (IPv4) to '::' (IPv6) to support IPv6 by default.
2026-01-30 14:11:53 +08:00
25 changed files with 566 additions and 74 deletions

No files matched your search

+8
View File
@@ -518,5 +518,13 @@
"9.9.26-44725": {
"appid": 537337569,
"qua": "V1_WIN_NQ_9.9.26_44725_GW_B"
},
"9.9.26-45627": {
"appid": 537340060,
"qua": "V1_WIN_NQ_9.9.26_45627_GW_B"
},
"6.9.88-44725": {
"appid": 537337594,
"qua": "V1_MAC_NQ_6.9.88_44725_GW_B"
}
}
+12
View File
@@ -154,5 +154,17 @@
"9.9.26-44725-x64": {
"send": "0A18D0C",
"recv": "1D4BF0D"
},
"9.9.26-45627-x64": {
"send": "0A697CC",
"recv": "1E86AC1"
},
"6.9.88-44725-x64": {
"send": "2756EF6",
"recv": "0A36152"
},
"6.9.88-44725-arm64": {
"send": "2313C68",
"recv": "09693E4"
}
}
+12
View File
@@ -662,5 +662,17 @@
"9.9.26-44725-x64": {
"send": "2CEBB20",
"recv": "2CEF0A0"
},
"9.9.26-45627-x64": {
"send": "2E59CC0",
"recv": "2E5D240"
},
"6.9.88-44725-x64": {
"send": "451FE90",
"recv": "4522A40"
},
"6.9.88-44725-arm64": {
"send": "3D79168",
"recv": "3D7BA78"
}
}
@@ -2,14 +2,14 @@ import * as crypto from 'node:crypto';
import { PacketMsg } from '@/napcat-core/packet/message/message';
interface ForwardMsgJson {
app: string
app: string;
config: ForwardMsgJsonConfig,
desc: string,
extra: ForwardMsgJsonExtra,
meta: ForwardMsgJsonMeta,
prompt: string,
ver: string,
view: string
view: string;
}
interface ForwardMsgJsonConfig {
@@ -17,7 +17,7 @@ interface ForwardMsgJsonConfig {
forward: number,
round: number,
type: string,
width: number
width: number;
}
interface ForwardMsgJsonExtra {
@@ -26,17 +26,17 @@ interface ForwardMsgJsonExtra {
}
interface ForwardMsgJsonMeta {
detail: ForwardMsgJsonMetaDetail
detail: ForwardMsgJsonMetaDetail;
}
interface ForwardMsgJsonMetaDetail {
news: {
text: string
text: string;
}[],
resid: string,
source: string,
summary: string,
uniseq: string
uniseq: string;
}
interface ForwardAdaptMsg {
@@ -50,8 +50,8 @@ interface ForwardAdaptMsgElement {
}
export class ForwardMsgBuilder {
private static build (resId: string, msg: ForwardAdaptMsg[], source?: string, news?: ForwardMsgJsonMetaDetail['news'], summary?: string, prompt?: string): ForwardMsgJson {
const id = crypto.randomUUID();
private static build (resId: string, msg: ForwardAdaptMsg[], source?: string, news?: ForwardMsgJsonMetaDetail['news'], summary?: string, prompt?: string, uuid?: string): ForwardMsgJson {
const id = uuid ?? crypto.randomUUID();
const isGroupMsg = msg.some(m => m.isGroupMsg);
if (!source) {
source = msg.length === 0 ? '聊天记录' : (isGroupMsg ? '群聊的聊天记录' : msg.map(m => m.senderName).filter((v, i, a) => a.indexOf(v) === i).slice(0, 4).join('和') + '的聊天记录');
@@ -104,13 +104,19 @@ export class ForwardMsgBuilder {
return this.build(resId, []);
}
static fromPacketMsg (resId: string, packetMsg: PacketMsg[], source?: string, news?: ForwardMsgJsonMetaDetail['news'], summary?: string, prompt?: string): ForwardMsgJson {
static fromPacketMsg (resId: string, packetMsg: PacketMsg[], source?: string, news?: ForwardMsgJsonMetaDetail['news'], summary?: string, prompt?: string, uuid?: string): ForwardMsgJson {
return this.build(resId, packetMsg.map(msg => ({
senderName: msg.senderName,
isGroupMsg: msg.groupId !== undefined,
msg: msg.msg.map(m => ({
preview: m.valid ? m.toPreview() : '[该消息类型暂不支持查看]',
})),
})), source, news, summary, prompt);
})),
source,
news,
summary,
prompt,
uuid,
);
}
}
@@ -18,6 +18,7 @@ import { OidbPacket } from '@/napcat-core/packet/transformer/base';
import { ImageOcrResult } from '@/napcat-core/packet/entities/ocrResult';
import { gunzipSync } from 'zlib';
import { PacketMsgConverter } from '@/napcat-core/packet/message/converter';
import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
export class PacketOperationContext {
private readonly context: PacketContext;
@@ -26,7 +27,7 @@ export class PacketOperationContext {
this.context = context;
}
async sendPacket<T extends boolean = false>(pkt: OidbPacket, rsp?: T): Promise<T extends true ? Buffer : void> {
async sendPacket<T extends boolean = false> (pkt: OidbPacket, rsp?: T): Promise<T extends true ? Buffer : void> {
return await this.context.client.sendOidbPacket(pkt, rsp);
}
@@ -224,7 +225,15 @@ export class PacketOperationContext {
const res = trans.UploadForwardMsg.parse(resp);
return res.result.resId;
}
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
//await this.SendPreprocess(msg, groupUin);
// 遍历上传资源
await Promise.allSettled(msg.map(async (item) => { return await this.SendPreprocess(item.actionMsg, groupUin); }));
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
const resp = await this.context.client.sendOidbPacket(req, true);
const res = trans.UploadForwardMsg.parse(resp);
return res.result.resId;
}
async MoveGroupFile (
groupUin: number,
fileUUID: string,
@@ -0,0 +1,51 @@
import zlib from 'node:zlib';
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from 'napcat-protobuf';
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import { PacketMsg } from '@/napcat-core/packet/message/message';
export interface UploadForwardMsgParams {
actionCommand: string;
actionMsg: PacketMsg[];
}
class UploadForwardMsgV2 extends PacketTransformer<typeof proto.SendLongMsgResp> {
build (selfUid: string, msg: UploadForwardMsgParams[], groupUin: number = 0): OidbPacket {
const reqdata = msg.map((item) => ({
actionCommand: item.actionCommand,
actionData: {
msgBody: this.msgBuilder.buildFakeMsg(selfUid, item.actionMsg),
}
}));
const longMsgResultData = new NapProtoMsg(proto.LongMsgResult).encode(
{
action: reqdata,
}
);
const payload = zlib.gzipSync(Buffer.from(longMsgResultData));
const req = new NapProtoMsg(proto.SendLongMsgReq).encode(
{
info: {
type: groupUin === 0 ? 1 : 3,
uid: {
uid: groupUin === 0 ? selfUid : groupUin.toString(),
},
groupUin,
payload,
},
settings: {
field1: 4, field2: 1, field3: 7, field4: 0,
},
}
);
return {
cmd: 'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg',
data: PacketBufBuilder(req),
};
}
parse (data: Buffer) {
return new NapProtoMsg(proto.SendLongMsgResp).decode(data);
}
}
export default new UploadForwardMsgV2();
@@ -2,3 +2,4 @@ export { default as UploadForwardMsg } from './UploadForwardMsg';
export { default as FetchGroupMessage } from './FetchGroupMessage';
export { default as FetchC2CMessage } from './FetchC2CMessage';
export { default as DownloadForwardMsg } from './DownloadForwardMsg';
export { default as UploadForwardMsgV2 } from './UploadForwardMsgV2';
+28 -2
View File
@@ -17,6 +17,7 @@ import { rawMsgWithSendMsg } from 'napcat-core/packet/message/converter';
import { Static, Type } from '@sinclair/typebox';
import { MsgActionsExamples } from '@/napcat-onebot/action/msg/examples';
import { OB11MessageMixTypeSchema } from '@/napcat-onebot/types/message';
import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
export const SendMsgPayloadSchema = Type.Object({
message_type: Type.Optional(Type.Union([Type.Literal('private'), Type.Literal('group')], { description: '消息类型 (private/group)' })),
@@ -211,10 +212,14 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
}, dp: number = 0): Promise<{
finallySendElements: SendArkElement,
res_id?: string,
uuid?: string,
packetMsg: PacketMsg[],
deleteAfterSentFiles: string[],
innerPacketMsg?: Array<{ uuid: string, packetMsg: PacketMsg[]; }>;
} | null> {
const packetMsg: PacketMsg[] = [];
const delFiles: string[] = [];
const innerMsg: Array<{ uuid: string, packetMsg: PacketMsg[]; }> = new Array();
for (const node of messageNodes) {
if (dp >= 3) {
this.core.context.logger.logWarn('转发消息深度超过3层,将停止解析!');
@@ -232,6 +237,13 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
}, dp + 1);
sendElements = uploadReturnData?.finallySendElements ? [uploadReturnData.finallySendElements] : [];
delFiles.push(...(uploadReturnData?.deleteAfterSentFiles || []));
if (uploadReturnData?.uuid) {
innerMsg.push({ uuid: uploadReturnData.uuid, packetMsg: uploadReturnData.packetMsg });
uploadReturnData.innerPacketMsg?.forEach(m => {
innerMsg.push({ uuid: m.uuid, packetMsg: m.packetMsg });
});
}
} else {
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
sendElements = sendElementsCreateReturn.sendElements;
@@ -273,8 +285,19 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
this.core.context.logger.logWarn('handleForwardedNodesPacket 元素为空!');
return null;
}
const resid = await this.core.apis.PacketApi.pkt.operation.UploadForwardMsg(packetMsg, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
const forwardJson = ForwardMsgBuilder.fromPacketMsg(resid, packetMsg, source, news, summary, prompt);
const uploadMsgData: UploadForwardMsgParams[] = [{
actionCommand: 'MultiMsg',
actionMsg: packetMsg,
}];
innerMsg.forEach(({ uuid, packetMsg: msg }) => {
uploadMsgData.push({
actionCommand: uuid,
actionMsg: msg,
});
});
const resid = await this.core.apis.PacketApi.pkt.operation.UploadForwardMsgV2(uploadMsgData, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
const uuid = crypto.randomUUID();
const forwardJson = ForwardMsgBuilder.fromPacketMsg(resid, packetMsg, source, news, summary, prompt, uuid);
return {
deleteAfterSentFiles: delFiles,
finallySendElements: {
@@ -285,6 +308,9 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
},
} as SendArkElement,
res_id: resid,
uuid: uuid,
packetMsg: packetMsg,
innerPacketMsg: innerMsg,
};
}
@@ -316,6 +316,11 @@ export class OB11PluginMangerAdapter extends IOB11NetworkAdapter<PluginConfig> i
entry = newEntry;
}
if (!entry.enable) {
this.logger.log(`[PluginManager] Skipping loading disabled plugin: ${pluginId}`);
return false;
}
return await this.loadPlugin(entry);
}
@@ -123,8 +123,8 @@ export class PluginLoader {
const entryFile = this.findEntryFile(pluginDir, packageJson);
const entryPath = entryFile ? path.join(pluginDir, entryFile) : undefined;
// 获取启用状态(默认启用)
const enable = statusConfig[pluginId] !== false;
// 获取启用状态(默认禁用,内置插件除外)
const enable = statusConfig[pluginId] ?? (pluginId === 'napcat-plugin-builtin');
// 创建插件条目
const entry: PluginEntry = {
@@ -159,7 +159,7 @@ export class PluginLoader {
id: dirname, // 使用目录名作为 ID
fileId: dirname,
pluginPath: path.join(this.pluginPath, dirname),
enable: statusConfig[dirname] !== false,
enable: statusConfig[dirname] ?? (dirname === 'napcat-plugin-builtin'),
loaded: false,
runtime: {
status: 'error',
@@ -285,6 +285,11 @@ export class OB11PluginManager extends IOB11NetworkAdapter<PluginConfig> impleme
entry = newEntry;
}
if (!entry.enable) {
this.logger.log(`[PluginManager] Skipping loading disabled plugin: ${pluginId}`);
return false;
}
return await this.loadPlugin(entry);
}
+5 -1
View File
@@ -15,7 +15,11 @@ export default defineConfig({
resolve: {
conditions: ['node', 'default'],
alias: {
'@/': resolve(__dirname, '../'),
'@/napcat-onebot': resolve(__dirname, '../napcat-onebot'),
'@/napcat-common': resolve(__dirname, '../napcat-common'),
'@/napcat-schema': resolve(__dirname, './src'),
'@/napcat-core': resolve(__dirname, '../napcat-core'),
'@/napcat-webui-backend': resolve(__dirname, '../napcat-webui-backend'),
},
},
plugins: [
@@ -340,7 +340,7 @@ export async function applyPendingUpdates (webUiPathWrapper: NapCatPathWrapper,
const configPath = path.join(webUiPathWrapper.configPath, 'napcat-update.json');
if (!fs.existsSync(configPath)) {
logger.log('[NapCat Update] No pending updates found');
//logger.log('[NapCat Update] No pending updates found');
return;
}
@@ -1,7 +1,9 @@
import { RequestHandler } from 'express';
import { WebUiConfig } from '@/napcat-webui-backend/index';
import { WebUiConfig, webUiPathWrapper } from '@/napcat-webui-backend/index';
import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response';
import { isEmpty } from '@/napcat-webui-backend/src/utils/check';
import { existsSync, promises as fsProm } from 'node:fs';
import { join } from 'node:path';
// 获取WebUI基础配置
export const GetWebUIConfigHandler: RequestHandler = async (_, res) => {
@@ -158,3 +160,86 @@ export const UpdateWebUIConfigHandler: RequestHandler = async (req, res) => {
return sendError(res, `更新WebUI配置失败: ${msg}`);
}
};
// 获取SSL证书状态
export const GetSSLStatusHandler: RequestHandler = async (_, res) => {
try {
const certPath = join(webUiPathWrapper.configPath, 'cert.pem');
const keyPath = join(webUiPathWrapper.configPath, 'key.pem');
const certExists = existsSync(certPath);
const keyExists = existsSync(keyPath);
let certContent = '';
let keyContent = '';
if (certExists) {
certContent = await fsProm.readFile(certPath, 'utf-8');
}
if (keyExists) {
keyContent = await fsProm.readFile(keyPath, 'utf-8');
}
return sendSuccess(res, {
enabled: certExists && keyExists,
certExists,
keyExists,
certContent,
keyContent,
});
} catch (error) {
const msg = (error as Error).message;
return sendError(res, `获取SSL状态失败: ${msg}`);
}
};
// 保存SSL证书(通过文本内容)
export const UploadSSLCertHandler: RequestHandler = async (req, res) => {
try {
const { cert, key } = req.body;
if (isEmpty(cert) || isEmpty(key)) {
return sendError(res, 'cert和key内容不能为空');
}
// 简单验证证书格式
if (!cert.includes('-----BEGIN CERTIFICATE-----') || !cert.includes('-----END CERTIFICATE-----')) {
return sendError(res, 'cert格式不正确,应为PEM格式的证书');
}
if (!key.includes('-----BEGIN') || !key.includes('KEY-----')) {
return sendError(res, 'key格式不正确,应为PEM格式的私钥');
}
const certPath = join(webUiPathWrapper.configPath, 'cert.pem');
const keyPath = join(webUiPathWrapper.configPath, 'key.pem');
await fsProm.writeFile(certPath, cert, 'utf-8');
await fsProm.writeFile(keyPath, key, 'utf-8');
return sendSuccess(res, { message: 'SSL证书保存成功,重启后生效' });
} catch (error) {
const msg = (error as Error).message;
return sendError(res, `保存SSL证书失败: ${msg}`);
}
};
// 删除SSL证书
export const DeleteSSLCertHandler: RequestHandler = async (_, res) => {
try {
const certPath = join(webUiPathWrapper.configPath, 'cert.pem');
const keyPath = join(webUiPathWrapper.configPath, 'key.pem');
if (existsSync(certPath)) {
await fsProm.unlink(certPath);
}
if (existsSync(keyPath)) {
await fsProm.unlink(keyPath);
}
return sendSuccess(res, { message: 'SSL证书已删除,重启后生效' });
} catch (error) {
const msg = (error as Error).message;
return sendError(res, `删除SSL证书失败: ${msg}`);
}
};
@@ -12,7 +12,7 @@ import { getRandomToken } from '../utils/url';
// 限制尝试端口的次数,避免死循环
// 定义配置的类型
const WebUiConfigSchema = Type.Object({
host: Type.String({ default: '0.0.0.0' }),
host: Type.String({ default: '::' }),
port: Type.Number({ default: 6099 }),
token: Type.String({ default: getRandomToken(12) }),
loginRate: Type.Number({ default: 10 }),
@@ -5,6 +5,9 @@ import {
UpdateDisableWebUIHandler,
UpdateWebUIConfigHandler,
GetClientIPHandler,
GetSSLStatusHandler,
UploadSSLCertHandler,
DeleteSSLCertHandler,
} from '@/napcat-webui-backend/src/api/WebUIConfig';
const router: Router = Router();
@@ -24,4 +27,13 @@ router.post('/UpdateDisableWebUI', UpdateDisableWebUIHandler);
// 获取当前客户端IP
router.get('/GetClientIP', GetClientIPHandler);
// 获取SSL证书状态
router.get('/GetSSLStatus', GetSSLStatusHandler);
// 上传SSL证书
router.post('/UploadSSLCert', UploadSSLCertHandler);
// 删除SSL证书
router.post('/DeleteSSLCert', DeleteSSLCertHandler);
export { router as WebUIConfigRouter };
@@ -41,7 +41,7 @@ const PluginStoreCard: React.FC<PluginStoreCardProps> = ({
return {
text: '更新',
icon: <IoMdDownload size={16} />,
color: 'success' as const,
color: 'default' as const,
};
default:
return {
@@ -180,7 +180,7 @@ const GenericForm = <T extends keyof NetworkConfigType> ({
export default GenericForm;
export function random_token (length: number) {
const chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%^&*()-_=+[]{}|;:,.<>?';
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
@@ -260,14 +260,14 @@ const NewVersionTip = (props: NewVersionTipProps) => {
<div className="cursor-pointer flex items-center justify-center" onClick={updateStatus === 'updating' ? undefined : showUpdateDialog}>
<Chip
size="sm"
color="danger"
color="primary"
variant="flat"
classNames={{
content: "font-bold text-[10px] px-1 flex items-center justify-center",
base: "h-5 min-h-5 min-w-[42px]"
}}
>
{updateStatus === 'updating' ? <Spinner size="sm" color="danger" classNames={{ wrapper: "w-3 h-3" }} /> : 'New'}
{updateStatus === 'updating' ? <Spinner size="sm" color="primary" classNames={{ wrapper: "w-3 h-3" }} /> : 'New'}
</Chip>
</div>
</Tooltip>
@@ -281,6 +281,35 @@ export default class WebUIManager {
return data.data;
}
// 获取SSL证书状态
public static async getSSLStatus () {
const { data } = await serverRequest.get<ServerResponse<{
enabled: boolean;
certExists: boolean;
keyExists: boolean;
certContent: string;
keyContent: string;
}>>('/WebUIConfig/GetSSLStatus');
return data.data;
}
// 保存SSL证书
public static async saveSSLCert (cert: string, key: string) {
const { data } = await serverRequest.post<ServerResponse<{ message: string; }>>(
'/WebUIConfig/UploadSSLCert',
{ cert, key }
);
return data.data;
}
// 删除SSL证书
public static async deleteSSLCert () {
const { data } = await serverRequest.post<ServerResponse<{ message: string; }>>(
'/WebUIConfig/DeleteSSLCert'
);
return data.data;
}
// Passkey相关方法
public static async generatePasskeyRegistrationOptions () {
const { data } = await serverRequest.post<ServerResponse<any>>(
@@ -10,6 +10,7 @@ import ChangePasswordCard from './change_password';
import LoginConfigCard from './login';
import OneBotConfigCard from './onebot';
import ServerConfigCard from './server';
import SSLConfigCard from './ssl';
import ThemeConfigCard from './theme';
import WebUIConfigCard from './webui';
@@ -81,6 +82,11 @@ export default function ConfigPage () {
<ServerConfigCard />
</ConfigPageItem>
</Tab>
<Tab title='SSL配置' key='ssl'>
<ConfigPageItem size='sm'>
<SSLConfigCard />
</ConfigPageItem>
</Tab>
<Tab title='WebUI配置' key='webui'>
<ConfigPageItem>
<WebUIConfigCard />
@@ -0,0 +1,161 @@
import { useRequest } from 'ahooks';
import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { Button } from '@heroui/button';
import { Textarea } from '@heroui/input';
import PageLoading from '@/components/page_loading';
import WebUIManager from '@/controllers/webui_manager';
const SSLConfigCard = () => {
const {
data: sslData,
loading: sslLoading,
refreshAsync: refreshSSL,
} = useRequest(WebUIManager.getSSLStatus);
const [sslCert, setSslCert] = useState('');
const [sslKey, setSslKey] = useState('');
const [sslSaving, setSslSaving] = useState(false);
useEffect(() => {
if (sslData) {
setSslCert(sslData.certContent || '');
setSslKey(sslData.keyContent || '');
}
}, [sslData]);
const handleSaveSSL = async () => {
if (!sslCert.trim() || !sslKey.trim()) {
toast.error('证书和私钥内容不能为空');
return;
}
setSslSaving(true);
try {
const result = await WebUIManager.saveSSLCert(sslCert, sslKey);
toast.success(result.message || 'SSL证书保存成功');
await refreshSSL();
} catch (error) {
const msg = (error as Error).message;
toast.error(`保存SSL证书失败: ${msg}`);
} finally {
setSslSaving(false);
}
};
const handleDeleteSSL = async () => {
setSslSaving(true);
try {
const result = await WebUIManager.deleteSSLCert();
toast.success(result.message || 'SSL证书已删除');
setSslCert('');
setSslKey('');
await refreshSSL();
} catch (error) {
const msg = (error as Error).message;
toast.error(`删除SSL证书失败: ${msg}`);
} finally {
setSslSaving(false);
}
};
const handleRefresh = async () => {
try {
await refreshSSL();
toast.success('刷新成功');
} catch (error) {
const msg = (error as Error).message;
toast.error(`刷新失败: ${msg}`);
}
};
if (sslLoading) return <PageLoading loading />;
return (
<>
<title>SSL配置 - NapCat WebUI</title>
<div className='flex flex-col gap-4'>
<div className='flex flex-col gap-3'>
<div className='flex items-center gap-2'>
<div className='flex-shrink-0 w-full font-bold text-default-600 dark:text-default-400 px-1'>SSL/HTTPS 配置</div>
{sslData?.enabled && (
<span className='px-2 py-0.5 text-xs bg-success-100 text-success-700 dark:bg-success-900/30 dark:text-success-400 rounded-full whitespace-nowrap'>
已启用
</span>
)}
</div>
<p className='text-sm text-default-500 px-1'>
配置SSL证书后重启即可启用HTTPS。将证书(cert.pem)和私钥(key.pem)的内容粘贴到下方文本框中。
</p>
<div className='p-3 bg-warning-50 dark:bg-warning-900/20 rounded-lg border border-warning-200 dark:border-warning-800'>
<p className='text-sm text-warning-700 dark:text-warning-400'>
<strong>注意:</strong>保存证书后需要重启服务才能生效。删除证书后同样需要重启才能切换回HTTP模式。
</p>
</div>
</div>
<div className='flex flex-col gap-4'>
<Textarea
label='证书内容 (cert.pem)'
placeholder={'-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----'}
value={sslCert}
onValueChange={setSslCert}
minRows={6}
maxRows={12}
classNames={{
inputWrapper:
'bg-default-100/50 dark:bg-white/5 backdrop-blur-md border border-transparent hover:bg-default-200/50 dark:hover:bg-white/10 transition-all shadow-sm data-[hover=true]:border-default-300',
input: 'bg-transparent text-default-700 placeholder:text-default-400 font-mono text-sm',
}}
/>
<Textarea
label='私钥内容 (key.pem)'
placeholder={'-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----'}
value={sslKey}
onValueChange={setSslKey}
minRows={6}
maxRows={12}
classNames={{
inputWrapper:
'bg-default-100/50 dark:bg-white/5 backdrop-blur-md border border-transparent hover:bg-default-200/50 dark:hover:bg-white/10 transition-all shadow-sm data-[hover=true]:border-default-300',
input: 'bg-transparent text-default-700 placeholder:text-default-400 font-mono text-sm',
}}
/>
</div>
<div className='flex gap-2 justify-end'>
<Button
variant='flat'
isLoading={sslSaving || sslLoading}
onPress={handleRefresh}
size='sm'
>
刷新
</Button>
{sslData?.enabled && (
<Button
color='danger'
variant='flat'
isLoading={sslSaving || sslLoading}
onPress={handleDeleteSSL}
size='sm'
>
删除SSL证书
</Button>
)}
<Button
color='primary'
isLoading={sslSaving || sslLoading}
onPress={handleSaveSSL}
size='sm'
>
保存SSL证书
</Button>
</div>
</div>
</>
);
};
export default SSLConfigCard;
@@ -58,7 +58,7 @@ export default function ExtensionPage () {
pluginName: page.pluginName,
path: page.path,
icon: page.icon,
description: page.description
description: page.description,
}));
}, [extensionPages]);
@@ -69,7 +69,7 @@ export default function ExtensionPage () {
const path = pathParts.join(':').replace(/^\//, '');
// 获取认证 token
const token = localStorage.getItem('token') || '';
return `/api/Plugin/page/${pluginId}/${path}?webui_token=${encodeURIComponent(token)}`;
return `/api/Plugin/page/${pluginId}/${path}?webui_token=${token}`;
}, [selectedTab]);
useEffect(() => {
@@ -89,71 +89,72 @@ export default function ExtensionPage () {
return (
<>
<title>扩展页面 - NapCat WebUI</title>
<div className="p-2 md:p-4 relative h-full flex flex-col">
<div className='p-2 md:p-4 relative h-[calc(100vh-6rem)] md:h-[calc(100vh-4rem)] flex flex-col'>
<PageLoading loading={loading} />
<div className="flex mb-4 items-center gap-4">
<div className="flex items-center gap-2 text-default-600">
<MdExtension size={24} />
<span className="text-lg font-medium">插件扩展页面</span>
<div className='flex mb-4 items-center justify-between gap-4 flex-wrap'>
<div className='flex items-center gap-4'>
<div className='flex items-center gap-2 text-default-600'>
<MdExtension size={24} />
<span className='text-lg font-medium'>插件扩展页面</span>
</div>
<Button
isIconOnly
className='bg-default-100/50 hover:bg-default-200/50 text-default-700 backdrop-blur-md'
radius='full'
onPress={refresh}
>
<IoMdRefresh size={24} />
</Button>
</div>
<Button
isIconOnly
className="bg-default-100/50 hover:bg-default-200/50 text-default-700 backdrop-blur-md"
radius="full"
onPress={refresh}
>
<IoMdRefresh size={24} />
</Button>
</div>
{extensionPages.length === 0 && !loading ? (
<div className="flex-1 flex flex-col items-center justify-center text-default-400">
<MdExtension size={64} className="mb-4 opacity-50" />
<p className="text-lg">暂无插件扩展页面</p>
<p className="text-sm mt-2">插件可以通过注册页面来扩展 WebUI 功能</p>
</div>
) : (
<div className="flex-1 flex flex-col min-h-0">
{extensionPages.length > 0 && (
<Tabs
aria-label="Extension Pages"
className="max-w-full"
aria-label='Extension Pages'
className='max-w-full'
selectedKey={selectedTab}
onSelectionChange={(key) => setSelectedTab(key as string)}
classNames={{
tabList: 'bg-white/40 dark:bg-black/20 backdrop-blur-md flex-wrap',
tabList: 'bg-white/40 dark:bg-black/20 backdrop-blur-md',
cursor: 'bg-white/80 dark:bg-white/10 backdrop-blur-md shadow-sm',
panel: 'flex-1 min-h-0 p-0'
panel: 'hidden',
}}
>
{tabs.map((tab) => (
<Tab
key={tab.key}
title={
<div className="flex items-center gap-2">
<div className='flex items-center gap-2'>
{tab.icon && <span>{tab.icon}</span>}
<span>{tab.title}</span>
<span className="text-xs text-default-400">({tab.pluginName})</span>
<span className='text-xs text-default-400'>({tab.pluginName})</span>
</div>
}
>
<div className="relative w-full h-[calc(100vh-220px)] bg-white/40 dark:bg-black/20 backdrop-blur-md rounded-lg overflow-hidden">
{iframeLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-default-100/50 z-10">
<Spinner size="lg" />
</div>
)}
<iframe
src={currentPageUrl}
className="w-full h-full border-0"
onLoad={handleIframeLoad}
title={tab.title}
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
/>
</div>
</Tab>
/>
))}
</Tabs>
)}
</div>
{extensionPages.length === 0 && !loading ? (
<div className='flex-1 flex flex-col items-center justify-center text-default-400'>
<MdExtension size={64} className='mb-4 opacity-50' />
<p className='text-lg'>暂无插件扩展页面</p>
<p className='text-sm mt-2'>插件可以通过注册页面来扩展 WebUI 功能</p>
</div>
) : (
<div className='flex-1 min-h-0 bg-white/40 dark:bg-black/20 backdrop-blur-md rounded-lg overflow-hidden relative'>
{iframeLoading && (
<div className='absolute inset-0 flex items-center justify-center bg-default-100/50 z-10'>
<Spinner size='lg' />
</div>
)}
<iframe
src={currentPageUrl}
className='w-full h-full border-0'
onLoad={handleIframeLoad}
title='extension-page'
sandbox='allow-scripts allow-same-origin allow-forms allow-popups'
/>
</div>
)}
</div>
@@ -2,9 +2,10 @@ import { Button } from '@heroui/button';
import { useDisclosure } from '@heroui/modal';
import { Tab, Tabs } from '@heroui/tabs';
import clsx from 'clsx';
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import toast from 'react-hot-toast';
import { IoMdRefresh } from 'react-icons/io';
import { FiDownload, FiUpload } from 'react-icons/fi';
import AddButton from '@/components/button/add_button';
import HTTPClientDisplayCard from '@/components/display_card/http_client';
@@ -55,7 +56,9 @@ export default function NetworkPage () {
deleteNetworkConfig,
enableNetworkConfig,
enableDebugNetworkConfig,
updateSingleConfig,
} = useConfig();
const fileInputRef = useRef<HTMLInputElement>(null);
const [activeField, setActiveField] =
useState<keyof OneBotConfig['network']>('httpServers');
const [activeName, setActiveName] = useState<string>('');
@@ -99,6 +102,45 @@ export default function NetworkPage () {
onOpen();
};
// 导出网络配置
const handleExport = () => {
const blob = new Blob([JSON.stringify(config.network, null, 2)], { type: 'application/json' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `network-config-${Date.now()}.json`;
link.click();
URL.revokeObjectURL(link.href);
toast.success('导出成功');
};
// 导入网络配置
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
try {
const data = JSON.parse(await file.text()) as OneBotConfig['network'];
const keys: (keyof OneBotConfig['network'])[] = ['httpServers', 'httpClients', 'httpSseServers', 'websocketServers', 'websocketClients'];
if (keys.some(k => !Array.isArray(data[k]))) throw new Error('配置格式错误');
dialog.confirm({
title: '导入配置',
content: '确定导入?这将覆盖现有网络配置。',
onConfirm: async () => {
try {
await updateSingleConfig('network', data);
toast.success('导入成功');
} catch (err) {
toast.error(`导入失败: ${(err as Error).message}`);
}
},
});
} catch (err) {
toast.error(`解析失败: ${(err as Error).message}`);
}
};
const onDelete = async (
field: keyof OneBotConfig['network'],
name: string
@@ -373,6 +415,21 @@ export default function NetworkPage () {
<PageLoading loading={loading} />
<div className='flex mb-6 items-center gap-4'>
<AddButton onOpen={handleClickCreate} />
<Button
className="bg-default-100/50 hover:bg-default-200/50 text-default-700 backdrop-blur-md"
startContent={<FiUpload size={18} />}
onPress={handleExport}
>
导出
</Button>
<Button
className="bg-default-100/50 hover:bg-default-200/50 text-default-700 backdrop-blur-md"
startContent={<FiDownload size={18} />}
onPress={() => fileInputRef.current?.click()}
>
导入
</Button>
<input ref={fileInputRef} type="file" accept=".json" className="hidden" onChange={handleFileChange} />
<Button
isIconOnly
className="bg-default-100/50 hover:bg-default-200/50 text-default-700 backdrop-blur-md"
@@ -222,7 +222,9 @@ export default function PluginPage () {
onToggleStatus={() => handleToggle(plugin)}
onUninstall={() => handleUninstall(plugin)}
onConfig={() => {
if (plugin.hasConfig) {
if (plugin.status !== 'active') {
toast.error('未启用插件,无法配置插件');
} else if (plugin.hasConfig) {
handleConfig(plugin);
} else {
toast.error('此插件没有配置哦');