Compare commits

...
15 Commits
Author SHA1 Message Date
手瓜一十雪 3a4b335062 feat
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
2026-06-08 20:01:03 +08:00
Qiao 9aa11fd7c4 fix: 校验群名片设置结果 (#1880) 2026-06-04 23:56:45 +08:00
手瓜一十雪 8ae11bfdca Add 49738 build metadata to external JSONs
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Register new builds and architecture-specific offsets/IDs for 9.9.31-49738 and 3.2.29-49738. Updated packages/napcat-core/external/appid.json to add appid/qua entries, and napi2native.json and packet.json to add send/recv offsets for x64 (and arm64 where applicable). These additions track the new builds and their native mappings.
2026-06-03 12:13:20 +08:00
Qiao 6acf350613 feat(onebot): add custom face management actions (#1879) 2026-06-02 22:51:27 +08:00
liuwanwan 0af6445d5a fix: 修复 lint 校验失败 (#1867) 2026-05-28 14:14:50 +08:00
liuwanwan a716a1a185 fix: correct HTTP method case comparison in httpApiRequest (#1865)
Express req.method returns uppercase strings ('GET', 'POST', etc.),
so `req.method === 'get'` never matches. This caused GET requests
to fall through to the else-if branch instead of directly using
req.query as the payload.

Closes NapNeko/NapCatQQ#1864
2026-05-26 22:41:33 +08:00
手瓜一十雪 8c9fc7edf4 README: suggest SnowLuma as GUI replacement
Replace the previous "New Feature" section with a short suggestion to try SnowLuma as a NapCat GUI alternative. Removes the v4.8.115+ notes about Stream API and recommending string IDs, simplifying the README and pointing users to the SnowLuma GitHub repository.
2026-05-26 18:23:23 +08:00
idranme 1abad76ac9 feat: 新增获取群组今日打卡列表功能 (#1855)
* feat: add group signed list API and OneBot action

* feat: register GetGroupSignedList action handler
2026-05-24 20:16:14 +08:00
手瓜一十雪 484c181050 Set rootDir in package tsconfigs
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add compilerOptions.rootDir = ".." to tsconfig.json for napcat-onebot, napcat-shell, and napcat-webui-backend to ensure the TypeScript compiler uses the monorepo package root for source resolution. Also remove an extraneous blank line in theme.tsx near FileManager.uploadWebUIFont (minor formatting cleanup).
2026-05-22 22:31:11 +08:00
手瓜一十雪 9d652be35d fix: #1774 2026-05-22 22:27:19 +08:00
手瓜一十雪 f226c83595 Skip pnpm install scripts; defer QR code fetch & fix #1804
CI: use `pnpm i --ignore-scripts` in release-publish workflow to avoid running package install scripts during CI.

Shell: defer showing the QR code until after attempting WebUi quick-login/password fallback. Adds checks for NAPCAT_QUICK_ACCOUNT and quick-password env vars (and WebUi quick-login list), runs WebUi quick config, and only calls getQRCodePicture() if no fallback was attempted and the user is not logged in. Includes error handling for the quick-login attempt.
2026-05-22 22:23:45 +08:00
手瓜一十雪 b565f876c5 Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2026-05-22 22:12:05 +08:00
手瓜一十雪 19a5febb1a fix: #1827 2026-05-22 22:06:00 +08:00
Copilotandsj817 bbf822035f fix: restart HTTP server when host changes (#1836)
* Initial plan

* fix: restart HTTP server when host changes

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/0ead0c47-df0d-4666-8877-775c9c641ed8

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-05-22 22:05:23 +08:00
手瓜一十雪 a2b0ac10a0 fix: #1843 2026-05-22 22:02:38 +08:00
36 changed files with 686 additions and 1158 deletions

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
{
"permissions": {
"allow": [
"Bash(tasklist)",
"Bash(sort -rk5)",
"Bash(powershell \"Get-Process | Sort-Object CPU -Descending | Select-Object -First 15 Name,CPU,Id,WorkingSet | Format-Table -AutoSize\")",
"Bash(powershell *)",
"Bash(where ssh *)",
"Bash(where plink *)",
"Bash(where sshpass *)",
"Bash(echo \"exit=$?\")",
"Bash(python -c \"import paramiko; print\\('paramiko OK'\\)\")",
"Bash(pnpm --filter napcat-common run typecheck)",
"Bash(pnpm --filter napcat-core run typecheck)",
"Bash(pnpm --filter napcat-onebot run typecheck)",
"Bash(git *)"
]
}
}
+1 -1
View File
@@ -19,7 +19,7 @@
import { execSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
import { join, basename, resolve } from 'node:path';
import { join, resolve } from 'node:path';
import { GitHubAPI, getEnv, setOutput } from './lib/github.ts';
import { toProxyUrl } from './lib/comment.ts';
+1 -1
View File
@@ -419,7 +419,7 @@ jobs:
APIFOX_TOKEN: ${{ secrets.APIFOX_TOKEN }}
run: |
npm i -g pnpm
pnpm i
pnpm i --ignore-scripts
pnpm run build:openapi
jq -n --rawfile input packages/napcat-schema/dist/openapi.json \
+2 -8
View File
@@ -11,15 +11,9 @@ _Modern protocol-side framework implemented based on NTQQ._
---
## New Feature
## New Framework ?
在 v4.8.115+ 版本开始
1. NapCatQQ 支持 [Stream Api](https://napneko.github.io/develop/file)
2. NapCatQQ 推荐 message_id/user_id/group_id 均使用字符串类型
- [1] 解决 Docker/跨设备/大文件 的多媒体上下传问题
- [2] 采用字符串可以解决扩展到int64的问题,同时也可以解决部分语言(如JavaScript)对大整数支持不佳的问题,增加极少成本。
可以试试更新更好用的 [SnowLuma](https://github.com/SnowLuma/SnowLuma) 作为NapCat Gui替代品。
## Welcome
+12
View File
@@ -67,6 +67,18 @@ export class NTQQMsgApi {
return this.context.session.getMsgService().fetchFavEmojiList('', num, true, true);
}
async addFavEmoji (req: Parameters<NodeIKernelMsgService['addFavEmoji']>[0]) {
return this.context.session.getMsgService().addFavEmoji(req);
}
async deleteFavEmoji (ids: string[]) {
return this.context.session.getMsgService().deleteFavEmoji(ids);
}
async modifyFavEmojiDesc (items: Parameters<NodeIKernelMsgService['modifyFavEmojiDesc']>[0]) {
return this.context.session.getMsgService().modifyFavEmojiDesc(items);
}
async queryMsgsWithFilterExWithSeq (peer: Peer, msgSeq: string) {
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
chatInfo: peer,
+37
View File
@@ -539,4 +539,41 @@ export class NTQQWebApi {
createAlbumFeedPublish(qunId, uin, albumId, batchId)
);
}
async getDaySignedList (groupCode: string) {
const pSkey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const selfUin = this.core.selfInfo.uin;
const cookie = `p_uin=o${selfUin}; p_skey=${pSkey}; uin=o${selfUin}`;
const post = await RequestUtil.HttpGetJson<{
retCode: number,
costTime: number,
response: {
ret?: {
code: string,
msg: string,
},
page?: {
infos?: {
uid: string,
uidGroupNick: string,
signedTimeStamp: string,
signInRank: number,
}[],
offset: number,
total: number,
}[],
},
funcCode: number,
}>(`https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${this.getBknFromPSKey(pSkey)}`, 'POST', {
dayYmd: new Date().toISOString().slice(0, 10).replace(/-/g, ''),
offset: 0,
limit: 100,
uid: selfUin,
groupId: groupCode,
}, {
Cookie: cookie,
'Content-Type': 'application/json',
});
return post;
}
}
+8
View File
@@ -582,5 +582,13 @@
"9.9.31-49599": {
"appid": 537355779,
"qua": "V1_WIN_NQ_9.9.31_49599_GW_B"
},
"9.9.31-49738": {
"appid": 537355830,
"qua": "V1_WIN_NQ_9.9.31_49738_GW_B"
},
"3.2.29-49738": {
"appid": 537355867,
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
}
}
+12
View File
@@ -242,5 +242,17 @@
"9.9.31-49599-x64": {
"send": "0AF885C",
"recv": "20058E1"
},
"9.9.31-49738-x64": {
"send": "0AF9FCC",
"recv": "2007901"
},
"3.2.29-49738-x64": {
"send": "6234600",
"recv": "33D89D0"
},
"3.2.29-49738-arm64": {
"send": "426AA04",
"recv": "1596254"
}
}
+12
View File
@@ -750,5 +750,17 @@
"9.9.31-49599-x64": {
"send": "3082C40",
"recv": "30861C8"
},
"9.9.31-49738-x64": {
"send": "3086C80",
"recv": "308A208"
},
"3.2.29-49738-x64": {
"send": "B3B20A0",
"recv": "B3B5B40"
},
"3.2.29-49738-arm64": {
"send": "7342800",
"recv": "73461B0"
}
}
@@ -138,14 +138,14 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
/**
* 获取时长
*/
async getDuration(filePath: string): Promise<number> {
async getDuration (filePath: string): Promise<number> {
const { stdout } = await execFileAsync(this.ffprobePath, [
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
'-v',
'error',
'-show_entries',
'format=duration',
'-of',
'default=noprint_wrappers=1:nokey=1',
filePath,
]);
@@ -373,8 +373,19 @@ export class PacketOperationContext {
return element;
})
);
const isGroup = msg?.responseHead.grp !== undefined;
const peerUin = isGroup
? String(msg?.responseHead.grp?.groupUin ?? 0)
: String(msg?.responseHead.fromUin ?? 0);
const peerUid = isGroup
? String(msg?.responseHead.grp?.groupUin ?? 0)
: String(msg?.responseHead.fromUid ?? '');
const sendNickName = isGroup
? (msg?.responseHead.grp?.memberName ?? '')
: (msg?.responseHead.forward?.friendName ?? '');
return {
chatType: ChatType.KCHATTYPEGROUP,
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
elements,
guildId: '',
isOnlineMsg: false,
@@ -385,18 +396,18 @@ export class PacketOperationContext {
msgType: NTMsgType.KMSGTYPEMIX,
parentMsgIdList: [],
parentMsgPeer: {
chatType: ChatType.KCHATTYPEGROUP,
peerUid: String(msg?.responseHead.grp?.groupUin ?? 0),
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
peerUid,
},
peerName: '',
peerUid: '1094950020',
peerUin: '1094950020',
peerUid,
peerUin,
recallTime: '0',
records: [],
sendNickName: msg?.responseHead.grp?.memberName ?? '',
sendRemarkName: msg?.responseHead.grp?.memberName ?? '',
senderUid: '',
senderUin: '1094950020',
sendNickName,
sendRemarkName: sendNickName,
senderUid: msg?.responseHead.fromUid ?? '',
senderUin: String(msg?.responseHead.fromUin ?? 0),
sourceType: MsgSourceType.K_DOWN_SOURCETYPE_UNKNOWN,
subMsgType: 1,
};
@@ -369,7 +369,16 @@ export interface NodeIKernelMsgService {
}>;
}>;
addFavEmoji (arg: unknown): unknown;
addFavEmoji (arg: {
emojiId?: string,
packageId?: number,
emojiPath: string,
fileSize: string,
fileName: string,
md5: string,
isMarkFace?: boolean,
isOrigin?: boolean,
}): unknown;
fetchMarketEmoticonList (arg1: number, arg2: number): unknown;
@@ -397,9 +406,14 @@ export interface NodeIKernelMsgService {
downloadEmojiPic (arg1: number, arg2: Array<unknown>[], arg3: number, arg4: Map<unknown, unknown>): unknown;
deleteFavEmoji (arg: unknown): unknown;
deleteFavEmoji (arg: string[]): unknown;
modifyFavEmojiDesc (arg: unknown): unknown;
modifyFavEmojiDesc (arg: Array<{
emojiId: number,
resId: string,
md5: string,
desc: string,
}>): unknown;
queryFavEmojiByDesc (arg: unknown): unknown;
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"**/*.ts"
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"**/*.ts"
@@ -0,0 +1,162 @@
import { createHash } from 'node:crypto';
import { stat, readFile } from 'node:fs/promises';
import { basename } from 'node:path';
import { Type, Static } from '@sinclair/typebox';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
const FetchCustomFaceDetailPayloadSchema = Type.Object({
count: Type.Union([Type.Number(), Type.String()], { default: 48, description: '获取数量' }),
});
type FetchCustomFaceDetailPayloadType = Static<typeof FetchCustomFaceDetailPayloadSchema>;
const FetchCustomFaceDetailReturnSchema = Type.Any({ description: '自定义表情详情列表' });
type FetchCustomFaceDetailReturnType = Static<typeof FetchCustomFaceDetailReturnSchema>;
export class FetchCustomFaceDetail extends OneBotAction<FetchCustomFaceDetailPayloadType, FetchCustomFaceDetailReturnType> {
override actionName = ActionName.FetchCustomFaceDetail;
override payloadSchema = FetchCustomFaceDetailPayloadSchema;
override returnSchema = FetchCustomFaceDetailReturnSchema;
override actionSummary = '获取自定义表情详情';
override actionTags = ['系统扩展'];
override payloadExample = {
count: 10,
};
override returnExample = null;
async _handle (payload: FetchCustomFaceDetailPayloadType) {
const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count);
return ret.emojiInfoList;
}
}
const AddCustomFacePayloadSchema = Type.Object({
file: Type.String({ description: '本地表情文件路径' }),
emoji_id: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '表情ID,未提供时传空字符串' })),
package_id: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '表情包ID,未提供时传0' })),
file_name: Type.Optional(Type.String({ description: '文件名,未提供时从file路径取basename' })),
file_size: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '文件大小,未提供时读取本地文件' })),
md5: Type.Optional(Type.String({ description: '文件MD5,未提供时读取本地文件计算' })),
is_mark_face: Type.Optional(Type.Boolean({ description: '是否商城表情' })),
is_origin: Type.Optional(Type.Boolean({ description: '是否原图' })),
});
type AddCustomFacePayloadType = Static<typeof AddCustomFacePayloadSchema>;
const AddCustomFaceReturnSchema = Type.Any({ description: '添加结果' });
type AddCustomFaceReturnType = Static<typeof AddCustomFaceReturnSchema>;
export class AddCustomFace extends OneBotAction<AddCustomFacePayloadType, AddCustomFaceReturnType> {
override actionName = ActionName.AddCustomFace;
override payloadSchema = AddCustomFacePayloadSchema;
override returnSchema = AddCustomFaceReturnSchema;
override actionSummary = '添加自定义表情';
override actionTags = ['系统扩展'];
override payloadExample = {
file: 'C:\\Users\\Public\\face.png',
is_origin: true,
};
override returnExample = null;
async _handle (payload: AddCustomFacePayloadType) {
const fileStat = await stat(payload.file);
const md5 = payload.md5 ?? createHash('md5').update(await readFile(payload.file)).digest('hex');
return await this.core.apis.MsgApi.addFavEmoji({
emojiId: payload.emoji_id?.toString() ?? '',
packageId: payload.package_id === undefined ? 0 : Number(payload.package_id),
emojiPath: payload.file,
fileSize: payload.file_size?.toString() ?? fileStat.size.toString(),
fileName: payload.file_name ?? basename(payload.file),
md5,
isMarkFace: payload.is_mark_face ?? false,
isOrigin: payload.is_origin ?? true,
});
}
}
const DeleteCustomFacePayloadSchema = Type.Object({
res_id: Type.Optional(Type.Union([
Type.String({ description: 'fetch_custom_face_detail返回的resId' }),
Type.Array(Type.String({ description: 'fetch_custom_face_detail返回的resId' })),
])),
id: Type.Optional(Type.Union([
Type.String({ description: 'native deleteFavEmoji字符串ID,通常为resId' }),
Type.Array(Type.String({ description: 'native deleteFavEmoji字符串ID,通常为resId' })),
])),
ids: Type.Optional(Type.Array(Type.String({ description: 'native deleteFavEmoji字符串ID列表,通常为resId列表' }))),
md5: Type.Optional(Type.Union([
Type.String({ description: '表情MD5,不能直接删除,请先通过fetch_custom_face_detail获取resId' }),
Type.Array(Type.String({ description: '表情MD5,不能直接删除,请先通过fetch_custom_face_detail获取resId' })),
])),
});
type DeleteCustomFacePayloadType = Static<typeof DeleteCustomFacePayloadSchema>;
const DeleteCustomFaceReturnSchema = Type.Any({ description: '删除结果' });
type DeleteCustomFaceReturnType = Static<typeof DeleteCustomFaceReturnSchema>;
export class DeleteCustomFace extends OneBotAction<DeleteCustomFacePayloadType, DeleteCustomFaceReturnType> {
override actionName = ActionName.DeleteCustomFace;
override payloadSchema = DeleteCustomFacePayloadSchema;
override returnSchema = DeleteCustomFaceReturnSchema;
override actionSummary = '删除自定义表情';
override actionTags = ['系统扩展'];
override payloadExample = {
res_id: '2707600964_0_0_0_D8EAA70984B402EE10B0F33DB88F4173_0_0',
};
override returnExample = null;
async _handle (payload: DeleteCustomFacePayloadType) {
const ids = payload.ids ??
(Array.isArray(payload.res_id) ? payload.res_id : payload.res_id ? [payload.res_id] : undefined) ??
(Array.isArray(payload.id) ? payload.id : payload.id ? [payload.id] : undefined) ??
[];
if (ids.length === 0) throw new Error('res_id or ids is required');
return await this.core.apis.MsgApi.deleteFavEmoji(ids);
}
}
const SetCustomFaceDescPayloadSchema = Type.Object({
emoji_id: Type.Union([Type.Number(), Type.String()], { description: '表情ID' }),
res_id: Type.String({ description: '资源ID' }),
md5: Type.String({ description: '表情MD5' }),
desc: Type.String({ description: '新的表情描述' }),
});
type SetCustomFaceDescPayloadType = Static<typeof SetCustomFaceDescPayloadSchema>;
const SetCustomFaceDescReturnSchema = Type.Any({ description: '修改结果' });
type SetCustomFaceDescReturnType = Static<typeof SetCustomFaceDescReturnSchema>;
export class SetCustomFaceDesc extends OneBotAction<SetCustomFaceDescPayloadType, SetCustomFaceDescReturnType> {
override actionName = ActionName.SetCustomFaceDesc;
override payloadSchema = SetCustomFaceDescPayloadSchema;
override returnSchema = SetCustomFaceDescReturnSchema;
override actionSummary = '修改自定义表情描述';
override actionTags = ['系统扩展'];
override payloadExample = {
emoji_id: 1,
res_id: 'resource-id',
md5: 'd41d8cd98f00b204e9800998ecf8427e',
desc: '新的描述',
};
override returnExample = null;
async _handle (payload: SetCustomFaceDescPayloadType) {
return await this.core.apis.MsgApi.modifyFavEmojiDesc([{
emojiId: Number(payload.emoji_id),
resId: payload.res_id,
md5: payload.md5,
desc: payload.desc,
}]);
}
}
@@ -0,0 +1,48 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
const PayloadSchema = Type.Object({
group_id: Type.Union([Type.String(), Type.Number()], { description: '群号' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Array(
Type.Object({
user_id: Type.Number({ description: '打卡者QQ' }),
nick: Type.String({ description: '打卡者昵称' }),
time: Type.Number({ description: '打卡时间' }),
rank: Type.Number({ description: '打卡排名' }),
}),
{ description: '群组今日打卡列表' }
);
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupSignedList extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetGroupSignedList;
override actionSummary = '获取群组今日打卡列表';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
};
override returnExample = {
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
const data = await this.core.apis.WebApi.getDaySignedList(payload.group_id.toString());
if (!data.response.page) throw new Error('无法获取该群组打卡列表');
return data.response.page[0]?.infos?.map(info => ({
user_id: +info.uid,
nick: info.uidGroupNick,
time: +info.signedTimeStamp,
rank: (info.signInRank - 1) / 2 + 1,
})) ?? [];
}
}
@@ -1,6 +1,7 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { sleep } from '@/napcat-common/src/helper';
import { GroupActionsExamples } from '../example/GroupActionsExamples';
@@ -27,8 +28,24 @@ export default class SetGroupCard extends OneBotAction<PayloadType, ReturnType>
override returnExample = GroupActionsExamples.SetGroupCard.response;
async _handle (payload: PayloadType): Promise<null> {
const member = await this.core.apis.GroupApi.getGroupMember(payload.group_id.toString(), payload.user_id.toString());
if (member) await this.core.apis.GroupApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || '');
return null;
const groupId = payload.group_id.toString();
const userId = payload.user_id.toString();
const card = payload.card || '';
const member = await this.core.apis.GroupApi.getGroupMember(groupId, userId);
if (!member) {
throw new Error(`群(${groupId})成员${userId}不存在`);
}
await this.core.apis.GroupApi.setMemberCard(groupId, member.uid, card);
for (let i = 0; i < 3; i++) {
await sleep(1000);
const updatedMember = await this.core.apis.GroupApi.refreshGroupMemberCachePartial(groupId, member.uid);
if (updatedMember?.cardName === card) {
return null;
}
}
throw new Error('设置群名片未生效');
}
}
+7
View File
@@ -63,6 +63,7 @@ import GetRecentContact from './user/GetRecentContact';
import { GetProfileLike } from './extends/GetProfileLike';
import SetGroupPortrait from './go-cqhttp/SetGroupPortrait';
import { FetchCustomFace } from './extends/FetchCustomFace';
import { AddCustomFace, DeleteCustomFace, FetchCustomFaceDetail, SetCustomFaceDesc } from './extends/CustomFace';
import GoCQHTTPUploadPrivateFile from './go-cqhttp/UploadPrivateFile';
import { FetchEmojiLike } from './extends/FetchEmojiLike';
import { GetEmojiLikes } from './extends/GetEmojiLikes';
@@ -158,6 +159,7 @@ import { ReceiveOnlineFile } from './file/online/ReceiveOnlineFile';
import { RefuseOnlineFile } from './file/online/RefuseOnlineFile';
import { GetFilesetId } from './file/flash/GetFilesetIdByCode';
import { FetchPttText } from '@/napcat-onebot/action/msg/FetchPttText';
import { GetGroupSignedList } from './extends/GetGroupSignedList';
export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCore) {
const actionHandlers = [
@@ -213,6 +215,7 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new MoveGroupFile(obContext, core),
new RenameGroupFile(obContext, core),
new TransGroupFile(obContext, core),
new GetGroupSignedList(obContext, core),
// onebot11
new SendLike(obContext, core),
new GetMsg(obContext, core),
@@ -277,6 +280,10 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
new GetProfileLike(obContext, core),
new SetGroupPortrait(obContext, core),
new FetchCustomFace(obContext, core),
new FetchCustomFaceDetail(obContext, core),
new AddCustomFace(obContext, core),
new DeleteCustomFace(obContext, core),
new SetCustomFaceDesc(obContext, core),
new GoCQHTTPUploadPrivateFile(obContext, core),
new GetGuildProfile(obContext, core),
new GoCQHTTPGetModelShow(obContext, core),
@@ -16,7 +16,7 @@ export abstract class BaseGroupTodoAction extends GetPacketStatusDepends<GroupTo
override returnSchema = Type.Null();
override actionTags = ['核心接口'];
protected abstract handleGroupTodo(groupId: number, msgSeq: string): Promise<void>;
protected abstract handleGroupTodo (groupId: number, msgSeq: string): Promise<void>;
async _handle (payload: GroupTodoPayload) {
const groupId = +payload.group_id;
+6
View File
@@ -155,6 +155,10 @@ export const ActionName = {
_MarkAllMsgAsRead: '_mark_all_as_read',
GetProfileLike: 'get_profile_like',
FetchCustomFace: 'fetch_custom_face',
FetchCustomFaceDetail: 'fetch_custom_face_detail',
AddCustomFace: 'add_custom_face',
DeleteCustomFace: 'delete_custom_face',
SetCustomFaceDesc: 'set_custom_face_desc',
FetchEmojiLike: 'fetch_emoji_like',
GetEmojiLikes: 'get_emoji_likes',
SetInputStatus: 'set_input_status',
@@ -208,4 +212,6 @@ export const ActionName = {
ReceiveOnlineFile: 'receive_online_file',
RefuseOnlineFile: 'refuse_online_file',
CancelOnlineFile: 'cancel_online_file',
GetGroupSignedList: 'get_group_signed_list',
} as const;
-4
View File
@@ -157,10 +157,6 @@ export class NapCatOneBot11Adapter {
// 创建NetWork服务
// 注册Plugin 如果需要基于NapCat进行快速开发
// this.networkManager.registerAdapter(
// new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
// );
// 检查插件目录是否存在,不存在则不加载插件管理器
if (existsSync(this.context.pathWrapper.pluginPath)) {
this.context.logger.log('[Plugins] 插件目录存在,开始加载插件');
@@ -250,7 +250,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
async httpApiRequest (req: Request, res: Response, request_sse: boolean = false) {
let payload = req.body;
if (req.method === 'get') {
if (req.method === 'GET') {
payload = req.query;
} else if (req.query) {
payload = { ...req.body, ...req.query };
@@ -307,6 +307,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
async reload (newConfig: HttpServerConfig) {
const wasEnabled = this.isEnable;
const oldPort = this.config.port;
const oldHost = this.config.host;
const oldEnableWebsocket = this.config.enableWebsocket;
this.config = newConfig;
@@ -318,7 +319,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
return OB11NetworkReloadType.NetWorkClose;
}
if (oldPort !== newConfig.port || oldEnableWebsocket !== newConfig.enableWebsocket) {
if (oldPort !== newConfig.port || oldHost !== newConfig.host || oldEnableWebsocket !== newConfig.enableWebsocket) {
this.close();
if (newConfig.enable) {
this.open();
@@ -1,378 +0,0 @@
import { OB11EmitEventContent, OB11NetworkReloadType } from './index';
import { NapCatOneBot11Adapter, OB11Message } from '@/napcat-onebot/index';
import { NapCatCore } from 'napcat-core';
import { PluginConfig } from '../config/config';
import { ActionMap } from '../action';
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
import fs from 'fs';
import path from 'path';
export interface PluginPackageJson {
name?: string;
plugin?: 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();
declare config: PluginConfig;
override get isActive (): boolean {
return this.isEnable && this.loadedPlugins.size > 0;
}
constructor (
name: string, core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap
) {
const config = {
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,
};
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,
packageJson,
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}`);
}
async 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;
}
}
}
+109 -1
View File
@@ -10,6 +10,31 @@ import {
} from './types';
const require = createRequire(import.meta.url);
/** 允许加载的官方插件 ID 白名单。不在表内的插件一律拒绝加载。 */
const OFFICIAL_PLUGIN_IDS = new Set<string>([
'napcat-plugin-builtin',
'napcat-plugin-cleaner',
'napcat-plugin-ssqq',
'napcat-plugin-qce',
]);
/**
* 敏感词表:插件源码命中(黑灰产 / 支付发卡相关)即拒绝加载。
* 仅作启发式威慑,混淆/编码可绕过,并非唯一防线。
*/
const SENSITIVE_KEYWORDS: string[] = [
'发卡', '卡密', '卡网', '自动发卡', '寄售', '代刷', '刷单', '跑分',
'四件套', '洗钱', '黑产', '灰产', '博彩', '赌博', '菠菜', '涉黄',
'色情', '收款码', '代付', '担保交易', '第三方支付', 'USDT',
];
/** 纳入敏感词检测的源码扩展名 */
const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts']);
/** 跳过敏感词扫描的目录名 */
const SCAN_SKIP_DIRS = new Set(['data', 'node_modules', '.git']);
/** 单文件扫描大小上限,避免超大文件拖慢启动 */
const SCAN_MAX_FILE_BYTES = 5 * 1024 * 1024;
/**
* 插件加载器
* 负责扫描、加载和导入插件模块
@@ -121,6 +146,15 @@ export class PluginLoader {
// 获取插件 ID(包名或目录名)
const pluginId = packageJson?.name || dirname;
// 官方白名单 + 敏感词校验:被拒绝的插件视为不可见,
// 不入列表、不加载、更不会被动态导入执行。
// 该检查置于此处统一拦截 scanPlugins 与 rescanPlugin(安装/重载)两条路径。
const rejectReason = this.getRejectReason(pluginId, pluginDir);
if (rejectReason) {
this.logger.logWarn(`[PluginLoader] Rejected ${pluginId} (${dirname}): ${rejectReason}`);
return null;
}
// 确定入口文件
const entryFile = this.findEntryFile(pluginDir, packageJson);
const entryPath = entryFile ? path.join(pluginDir, entryFile) : undefined;
@@ -184,7 +218,12 @@ export class PluginLoader {
].filter(Boolean) as string[];
for (const entry of possibleEntries) {
const entryPath = path.join(pluginDir, entry);
const root = path.resolve(pluginDir);
const entryPath = path.resolve(pluginDir, entry);
// 拒绝 package.json main 指向插件目录之外(防路径穿越)
if (entryPath !== root && !entryPath.startsWith(root + path.sep)) {
continue;
}
if (fs.existsSync(entryPath) && fs.statSync(entryPath).isFile()) {
return entry;
}
@@ -193,6 +232,75 @@ export class PluginLoader {
return null;
}
/** 是否为白名单内的官方插件 */
isOfficialPlugin (pluginId: string): boolean {
return OFFICIAL_PLUGIN_IDS.has(pluginId);
}
/**
* 判断插件是否应被拒绝(非官方 / 命中敏感词)。
* @returns 拒绝原因;通过校验返回 null
*/
private getRejectReason (pluginId: string, pluginDir: string): string | null {
if (!this.isOfficialPlugin(pluginId)) {
return 'non-official plugin (not in whitelist)';
}
const hit = this.scanSensitiveWords(pluginDir);
if (hit) {
return `sensitive keyword "${hit}"`;
}
return null;
}
/**
* 递归扫描插件目录内源码是否命中敏感词(黑灰产 / 支付发卡)。
* @returns 命中的敏感词;未命中返回 null
*/
scanSensitiveWords (pluginDir: string): string | null {
const visit = (dir: string): string | null => {
let items: fs.Dirent[];
try {
items = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return null;
}
for (const item of items) {
if (item.isDirectory()) {
if (SCAN_SKIP_DIRS.has(item.name)) {
continue;
}
const hit = visit(path.join(dir, item.name));
if (hit) {
return hit;
}
continue;
}
if (!item.isFile()) {
continue;
}
if (!SCAN_EXTS.has(path.extname(item.name).toLowerCase())) {
continue;
}
const filePath = path.join(dir, item.name);
try {
if (fs.statSync(filePath).size > SCAN_MAX_FILE_BYTES) {
continue;
}
const content = fs.readFileSync(filePath, 'utf-8');
for (const word of SENSITIVE_KEYWORDS) {
if (content.includes(word)) {
return word;
}
}
} catch {
// 读取失败忽略该文件
}
}
return null;
};
return visit(pluginDir);
}
/**
* 动态导入模块
*/
@@ -1,529 +0,0 @@
import fs from 'fs';
import path from 'path';
import { ActionMap } from '@/napcat-onebot/action';
import { NapCatCore } from 'napcat-core';
import { NapCatOneBot11Adapter, OB11Message } from '@/napcat-onebot/index';
import { OB11EmitEventContent, OB11NetworkReloadType } from '@/napcat-onebot/network/index';
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
import { PluginConfig } from '@/napcat-onebot/config/config';
import { NapCatConfig } from './config';
import { PluginLoader } from './loader';
import { PluginRouterRegistryImpl } from './router-registry';
import {
PluginEntry,
PluginLogger,
PluginStatusConfig,
NapCatPluginContext,
IPluginManager,
} from './types';
export class OB11PluginManager extends IOB11NetworkAdapter<PluginConfig> implements IPluginManager {
private readonly pluginPath: string;
private readonly configPath: string;
private readonly loader: PluginLoader;
/** 插件注册表: ID -> 插件条目 */
private plugins: Map<string, PluginEntry> = new Map();
/** 插件路由注册表: pluginId -> PluginRouterRegistry */
private pluginRouters: Map<string, PluginRouterRegistryImpl> = new Map();
declare config: PluginConfig;
public NapCatConfig = NapCatConfig;
override get isActive (): boolean {
return this.isEnable && this.getLoadedPlugins().length > 0;
}
constructor (
name: string,
core: NapCatCore,
obContext: NapCatOneBot11Adapter,
actions: ActionMap
) {
const config = {
name,
messagePostFormat: 'array',
reportSelfMessage: true,
enable: true,
debug: true,
};
super(name, config, core, obContext, actions);
this.pluginPath = this.core.context.pathWrapper.pluginPath;
this.configPath = path.join(this.core.context.pathWrapper.configPath, 'plugins.json');
this.loader = new PluginLoader(this.pluginPath, this.configPath, this.logger);
}
// ==================== 插件状态配置 ====================
public getPluginConfig (): PluginStatusConfig {
return this.loader.loadPluginStatusConfig();
}
private savePluginConfig (config: PluginStatusConfig): void {
this.loader.savePluginStatusConfig(config);
}
// ==================== 插件扫描与加载 ====================
/**
* 扫描并加载所有插件
*/
private async scanAndLoadPlugins (): Promise<void> {
// 扫描所有插件目录
const entries = await this.loader.scanPlugins();
// 清空现有注册表
this.plugins.clear();
// 注册所有插件条目
for (const entry of entries) {
this.plugins.set(entry.id, entry);
}
this.logger.log(`[PluginManager] Scanned ${this.plugins.size} plugins`);
// 加载启用的插件
for (const entry of this.plugins.values()) {
if (entry.enable && entry.runtime.status !== 'error') {
await this.loadPlugin(entry);
}
}
const loadedCount = this.getLoadedPlugins().length;
this.logger.log(`[PluginManager] Loaded ${loadedCount} plugins`);
}
/**
* 加载单个插件
*/
private async loadPlugin (entry: PluginEntry): Promise<boolean> {
if (entry.loaded) {
return true;
}
if (entry.runtime.status === 'error') {
return false;
}
// 加载模块
const module = await this.loader.loadPluginModule(entry);
if (!module) {
return false;
}
// 创建上下文
const context = this.createPluginContext(entry);
// 初始化插件
try {
await module.plugin_init(context);
entry.loaded = true;
entry.runtime = {
status: 'loaded',
module,
context,
};
this.logger.log(`[PluginManager] Initialized plugin: ${entry.id}${entry.version ? ` v${entry.version}` : ''}`);
return true;
} catch (error: any) {
entry.loaded = false;
entry.runtime = {
status: 'error',
error: error.message || 'Initialization failed',
};
this.logger.logError(`[PluginManager] Error initializing plugin ${entry.id}:`, error);
return false;
}
}
/**
* 卸载单个插件
*/
private async unloadPlugin (entry: PluginEntry): Promise<void> {
if (!entry.loaded || entry.runtime.status !== 'loaded') {
return;
}
const { module, context } = entry.runtime;
// 调用清理方法
if (module && context && typeof module.plugin_cleanup === 'function') {
try {
await module.plugin_cleanup(context);
this.logger.log(`[PluginManager] Cleaned up plugin: ${entry.id}`);
} catch (error) {
this.logger.logError(`[PluginManager] Error cleaning up plugin ${entry.id}:`, error);
}
}
// 重置状态
entry.loaded = false;
entry.runtime = {
status: 'unloaded',
};
this.logger.log(`[PluginManager] Unloaded plugin: ${entry.id}`);
}
/**
* 创建插件上下文
*/
private createPluginContext (entry: PluginEntry): NapCatPluginContext {
const dataPath = path.join(this.core.context.pathWrapper.configPath, 'plugins', entry.id);
const configPath = path.join(dataPath, 'config.json');
// 确保插件配置目录存在
if (!fs.existsSync(dataPath)) {
fs.mkdirSync(dataPath, { recursive: true });
}
// 创建插件专用日志器
const pluginPrefix = `[Plugin: ${entry.id}]`;
const coreLogger = this.logger;
const pluginLogger: PluginLogger = {
log: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
debug: (...args: any[]) => coreLogger.logDebug(pluginPrefix, ...args),
info: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
warn: (...args: any[]) => coreLogger.logWarn(pluginPrefix, ...args),
error: (...args: any[]) => coreLogger.logError(pluginPrefix, ...args),
};
// 创建或获取插件路由注册器
let router = this.pluginRouters.get(entry.id);
if (!router) {
router = new PluginRouterRegistryImpl(entry.id, entry.pluginPath);
this.pluginRouters.set(entry.id, router);
}
// 创建获取其他插件导出的方法
const getPluginExports = <T = any> (pluginId: string): T | undefined => {
const targetEntry = this.plugins.get(pluginId);
if (!targetEntry || !targetEntry.loaded || targetEntry.runtime.status !== 'loaded') {
return undefined;
}
return targetEntry.runtime.module as T;
};
return {
core: this.core,
oneBot: this.obContext,
actions: this.actions,
pluginName: entry.id,
pluginPath: entry.pluginPath,
dataPath,
configPath,
NapCatConfig,
adapterName: this.name,
pluginManager: this,
logger: pluginLogger,
router,
getPluginExports,
};
}
// ==================== 公共 API ====================
/**
* 获取插件目录路径
*/
public getPluginPath (): string {
return this.pluginPath;
}
/**
* 获取所有插件条目
*/
public getAllPlugins (): PluginEntry[] {
return Array.from(this.plugins.values());
}
/**
* 获取已加载的插件列表
*/
public getLoadedPlugins (): PluginEntry[] {
return Array.from(this.plugins.values()).filter(p => p.loaded);
}
/**
* 通过 ID 获取插件信息
*/
public getPluginInfo (pluginId: string): PluginEntry | undefined {
return this.plugins.get(pluginId);
}
/**
* 设置插件状态(启用/禁用)
*/
public async setPluginStatus (pluginId: string, enable: boolean): Promise<void> {
const config = this.getPluginConfig();
config[pluginId] = enable;
this.savePluginConfig(config);
const entry = this.plugins.get(pluginId);
if (entry) {
entry.enable = enable;
if (enable && !entry.loaded) {
// 启用插件
await this.loadPlugin(entry);
} else if (!enable && entry.loaded) {
// 禁用插件
await this.unloadPlugin(entry);
}
}
}
/**
* 通过 ID 加载插件
*/
public async loadPluginById (pluginId: string): Promise<boolean> {
let entry = this.plugins.get(pluginId);
if (!entry) {
// 尝试查找并扫描
const dirname = this.loader.findPluginDirById(pluginId);
if (!dirname) {
this.logger.logWarn(`[PluginManager] Plugin ${pluginId} not found in filesystem`);
return false;
}
const newEntry = this.loader.rescanPlugin(dirname);
if (!newEntry) {
return false;
}
this.plugins.set(newEntry.id, newEntry);
entry = newEntry;
}
if (!entry.enable) {
this.logger.log(`[PluginManager] Skipping loading disabled plugin: ${pluginId}`);
return false;
}
return await this.loadPlugin(entry);
}
/**
* 卸载插件(仅从内存卸载)
*/
public async unregisterPlugin (pluginId: string): Promise<void> {
const entry = this.plugins.get(pluginId);
if (entry) {
await this.unloadPlugin(entry);
}
}
/**
* 卸载并删除插件
*/
public async uninstallPlugin (pluginId: string, cleanData: boolean = false): Promise<void> {
const entry = this.plugins.get(pluginId);
if (!entry) {
throw new Error(`Plugin ${pluginId} not found`);
}
const pluginPath = entry.pluginPath;
const dataPath = path.join(this.core.context.pathWrapper.configPath, 'plugins', pluginId);
// 先卸载插件
await this.unloadPlugin(entry);
// 从注册表移除
this.plugins.delete(pluginId);
// 删除插件目录
if (fs.existsSync(pluginPath)) {
fs.rmSync(pluginPath, { recursive: true, force: true });
}
// 清理插件配置数据
if (cleanData && fs.existsSync(dataPath)) {
fs.rmSync(dataPath, { recursive: true, force: true });
}
}
/**
* 重载指定插件
*/
public async reloadPlugin (pluginId: string): Promise<boolean> {
const entry = this.plugins.get(pluginId);
if (!entry) {
this.logger.logWarn(`[PluginManager] Plugin ${pluginId} not found`);
return false;
}
try {
// 卸载插件
await this.unloadPlugin(entry);
// 重新扫描
const newEntry = this.loader.rescanPlugin(entry.fileId);
if (!newEntry) {
return false;
}
// 更新注册表
this.plugins.set(newEntry.id, newEntry);
// 重新加载
if (newEntry.enable) {
await this.loadPlugin(newEntry);
}
this.logger.log(`[PluginManager] Plugin ${pluginId} reloaded successfully`);
return true;
} catch (error) {
this.logger.logError(`[PluginManager] Error reloading plugin ${pluginId}:`, error);
return false;
}
}
/**
* 加载目录插件(用于新安装的插件)
*/
public async loadDirectoryPlugin (dirname: string): Promise<void> {
const entry = this.loader.rescanPlugin(dirname);
if (!entry) {
return;
}
// 检查是否已存在
if (this.plugins.has(entry.id)) {
this.logger.logWarn(`[PluginManager] Plugin ${entry.id} already exists`);
return;
}
this.plugins.set(entry.id, entry);
if (entry.enable && entry.runtime.status !== 'error') {
await this.loadPlugin(entry);
}
}
/**
* 获取插件数据目录路径
*/
public getPluginDataPath (pluginId: string): string {
return path.join(this.core.context.pathWrapper.configPath, 'plugins', pluginId);
}
/**
* 获取插件配置文件路径
*/
public getPluginConfigPath (pluginId: string): string {
return path.join(this.getPluginDataPath(pluginId), 'config.json');
}
/**
* 获取插件路由注册器
*/
public getPluginRouter (pluginId: string): PluginRouterRegistryImpl | undefined {
return this.pluginRouters.get(pluginId);
}
/**
* 获取所有插件路由注册器
*/
public getAllPluginRouters (): Map<string, PluginRouterRegistryImpl> {
return this.pluginRouters;
}
// ==================== 事件处理 ====================
async onEvent<T extends OB11EmitEventContent> (event: T): Promise<void> {
if (!this.isEnable) {
return;
}
try {
await Promise.allSettled(
this.getLoadedPlugins().map((entry) =>
this.callPluginEventHandler(entry, event)
)
);
} catch (error) {
this.logger.logError('[PluginManager] Error handling event:', error);
}
}
/**
* 调用插件的事件处理方法
*/
private async callPluginEventHandler (
entry: PluginEntry,
event: OB11EmitEventContent
): Promise<void> {
if (entry.runtime.status !== 'loaded' || !entry.runtime.module || !entry.runtime.context) {
return;
}
const { module, context } = entry.runtime;
try {
// 优先使用 plugin_onevent 方法
if (typeof module.plugin_onevent === 'function') {
await module.plugin_onevent(context, event);
}
// 如果是消息事件并且插件有 plugin_onmessage 方法,也调用
if (
(event as any).message_type &&
typeof module.plugin_onmessage === 'function'
) {
await module.plugin_onmessage(context, event as OB11Message);
}
} catch (error) {
this.logger.logError(`[PluginManager] Error calling plugin ${entry.id} event handler:`, error);
}
}
// ==================== 生命周期 ====================
async open (): Promise<void> {
if (this.isEnable) {
return;
}
this.logger.log('[PluginManager] Opening plugin manager...');
this.isEnable = true;
// 扫描并加载所有插件
await this.scanAndLoadPlugins();
this.logger.log(`[PluginManager] Plugin manager opened with ${this.getLoadedPlugins().length} plugins loaded`);
}
async close (): Promise<void> {
if (!this.isEnable) {
return;
}
this.logger.log('[PluginManager] Closing plugin manager...');
this.isEnable = false;
// 卸载所有已加载的插件
for (const entry of this.plugins.values()) {
if (entry.loaded) {
await this.unloadPlugin(entry);
}
}
this.logger.log('[PluginManager] Plugin manager closed');
}
async reload (): Promise<OB11NetworkReloadType> {
this.logger.log('[PluginManager] Reloading plugin manager...');
// 先关闭然后重新打开
await this.close();
await this.open();
this.logger.log('[PluginManager] Plugin manager reloaded');
return OB11NetworkReloadType.Normal;
}
}
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "../../packages"
},
"include": [
"*.ts",
"**/*.ts"
+1 -75
View File
@@ -2,84 +2,10 @@ import { defineConfig } from 'vite';
import { resolve } from 'path';
import nodeResolve from '@rollup/plugin-node-resolve';
import { builtinModules } from 'module';
import fs from 'fs';
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
// 依赖排除
const external = [];
// 构建后拷贝插件
function copyToShellPlugin () {
return {
name: 'copy-to-shell',
writeBundle () {
try {
const sourceDir = resolve(__dirname, 'dist');
const targetDir = resolve(__dirname, '../napcat-shell/dist/plugins/napcat-plugin-builtin');
const packageJsonSource = resolve(__dirname, 'package.json');
const webuiSourceDir = resolve(__dirname, 'webui');
const webuiTargetDir = resolve(targetDir, 'webui');
// 确保目标目录存在
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true });
console.log(`[copy-to-shell] Created directory: ${targetDir}`);
}
// 拷贝 dist 目录下的所有文件
const files = fs.readdirSync(sourceDir);
let copiedCount = 0;
files.forEach(file => {
const sourcePath = resolve(sourceDir, file);
const targetPath = resolve(targetDir, file);
if (fs.statSync(sourcePath).isFile()) {
fs.copyFileSync(sourcePath, targetPath);
copiedCount++;
}
});
// 拷贝 package.json
if (fs.existsSync(packageJsonSource)) {
const packageJsonTarget = resolve(targetDir, 'package.json');
fs.copyFileSync(packageJsonSource, packageJsonTarget);
copiedCount++;
}
// 拷贝 webui 目录
if (fs.existsSync(webuiSourceDir)) {
copyDirRecursive(webuiSourceDir, webuiTargetDir);
console.log(`[copy-to-shell] Copied webui directory to ${webuiTargetDir}`);
}
console.log(`[copy-to-shell] Successfully copied ${copiedCount} file(s) to ${targetDir}`);
} catch (error) {
console.error('[copy-to-shell] Failed to copy files:', error);
throw error;
}
},
};
}
// 递归复制目录
function copyDirRecursive (src: string, dest: string) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest, { recursive: true });
}
const entries = fs.readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = resolve(src, entry.name);
const destPath = resolve(dest, entry.name);
if (entry.isDirectory()) {
copyDirRecursive(srcPath, destPath);
} else {
fs.copyFileSync(srcPath, destPath);
}
}
}
export default defineConfig({
resolve: {
@@ -102,5 +28,5 @@ export default defineConfig({
external: [...nodeModules, ...external],
},
},
plugins: [nodeResolve(), copyToShellPlugin()],
plugins: [nodeResolve()],
});
+12 -2
View File
@@ -483,17 +483,27 @@ async function handleLoginInner (context: { isLogined: boolean; }, logger: LogWr
} else {
logger.log('没有 -q 指令指定快速登录,将使用二维码登录方式');
if (historyLoginList.length > 0) {
logger.log(`可用于快速登录的 QQ:\n${historyLoginList
logger.log(`可用于快速登录 of QQ:\n${historyLoginList
.map((u, index) => `${index + 1}. ${u.uin} ${u.nickName}`)
.join('\n')
}`);
}
loginService.getQRCodePicture();
let hasAttemptedFallback = false;
try {
// 检查是否配置了自动登录账号,并尝试 WebUi 快速/密码回退登录。
// 这可以避免在已经有自动登录配置的情况下过早输出二维码。
const quickLoginList = WebUiDataRuntime.getQQQuickLoginList() || [];
const hasAutoLogin = process.env['NAPCAT_QUICK_ACCOUNT'] || (quickLoginList.length > 0); // 假如有历史登录列表
if (hasAutoLogin || process.env['NAPCAT_QUICK_PASSWORD'] || process.env['NAPCAT_QUICK_PASSWORD_MD5']) {
hasAttemptedFallback = true;
}
await WebUiDataRuntime.runWebUiConfigQuickFunction();
} catch (error) {
logger.logError('WebUi 快速登录失败 执行失败', error);
}
if (!hasAttemptedFallback && !context.isLogined) {
loginService.getQRCodePicture();
}
}
loginService.getLoginList().then((res) => {
+3
View File
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"**/*.ts"
+1 -1
View File
@@ -54,7 +54,7 @@ const ShellBaseConfig = (source_map: boolean = false) =>
build: {
sourcemap: source_map,
target: 'esnext',
minify: false,
minify: source_map ? false : 'esbuild',
lib: {
entry: {
napcat: path.resolve(__dirname, 'napcat.ts'),
@@ -2,6 +2,9 @@ import { describe, expect, test, vi } from 'vitest';
import { NapProtoMsg } from 'napcat-protobuf';
import { OidbSvcTrpcTcpBase } from '@/napcat-core/packet/transformer/proto/oidb/OidbBase';
import { OidbSvcTrpcTcp0XF90 } from '@/napcat-core/packet/transformer/proto/oidb/Oidb.0xf90';
import SetGroupTodo from '@/napcat-core/packet/transformer/action/SetGroupTodo';
import CompleteGroupTodo from '@/napcat-core/packet/transformer/action/CompleteGroupTodo';
import CancelGroupTodo from '@/napcat-core/packet/transformer/action/CancelGroupTodo';
vi.mock('@/napcat-core/packet/transformer/base', () => ({
PacketTransformer: class PacketTransformer {
@@ -14,10 +17,6 @@ vi.mock('@/napcat-core/packet/transformer/base', () => ({
PacketBufBuilder: (str: Uint8Array) => Buffer.from(str),
}));
import SetGroupTodo from '@/napcat-core/packet/transformer/action/SetGroupTodo';
import CompleteGroupTodo from '@/napcat-core/packet/transformer/action/CompleteGroupTodo';
import CancelGroupTodo from '@/napcat-core/packet/transformer/action/CancelGroupTodo';
const decodePacket = (data: Buffer) => {
const base = new NapProtoMsg(OidbSvcTrpcTcpBase).decode(data);
const body = new NapProtoMsg(OidbSvcTrpcTcp0XF90).decode(base.body);
@@ -40,6 +40,7 @@ interface UpdateConfig {
const SKIP_UPDATE_FILES = [
'NapCatWinBootMain.exe',
'NapCatWinBootHook.dll',
'quickLoginExample.bat',
];
// 更新时若文件已存在则保留(不覆盖)的用户配置文件(使用相对路径精确匹配)
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".."
},
"include": [
"*.ts",
"src/**/*.ts",
@@ -92,7 +92,7 @@ const BackupConfigCard: React.FC = () => {
onPress={handleExportConfig}
title='导出配置'
>
<LuDownload size={20} />
<LuUpload size={20} />
</Button>
<label className='cursor-pointer'>
<input
@@ -108,7 +108,7 @@ const BackupConfigCard: React.FC = () => {
as='span'
title='导入配置'
>
<LuUpload size={20} />
<LuDownload size={20} />
</Button>
</label>
</div>
@@ -436,15 +436,33 @@ const ThemeConfigCard = () => {
}
}
await FileManager.uploadWebUIFont(file);
toast.success('上传成功,即将刷新页面');
// 先自动把选择的字体模式设置为 custom,并保存配置,避免刷新后又变成了旧的/没保存的模式
const updatedTheme = { ...theme, fontMode: 'custom' };
await WebUIManager.setThemeConfig(updatedTheme);
originalDataRef.current = updatedTheme;
updateFontCache('custom');
setHasUnsavedChanges(false);
loadTheme();
toast.success('上传并保存成功,即将刷新页面');
setTimeout(() => window.location.reload(), 1000);
} catch (error) {
toast.error('上传失败: ' + (error as Error).message);
toast.error('上传或保存失败: ' + (error as Error).message);
}
}}
onDelete={async () => {
try {
await FileManager.deleteWebUIFont();
// 删除字体后,若当前选中的是自定义字体,则将其重置为系统默认(或其它)并保存,以防页面报错
if (theme.fontMode === 'custom') {
const updatedTheme = { ...theme, fontMode: 'system' };
await WebUIManager.setThemeConfig(updatedTheme);
originalDataRef.current = updatedTheme;
updateFontCache('system');
setHasUnsavedChanges(false);
loadTheme();
}
toast.success('删除成功,即将刷新页面');
setTimeout(() => window.location.reload(), 1000);
} catch (error) {
@@ -121,133 +121,135 @@ const WebUIConfigCard = () => {
<div className='flex flex-col gap-2'>
<div className='flex-shrink-0 w-full font-bold text-default-600 dark:text-default-400 px-1'>Passkey认证</div>
{!window.isSecureContext ? (
<div className='text-sm text-warning-500 bg-warning-50 p-2 rounded-md border border-warning-200'>
⚠️ 当前处于非安全环境(即既非 HTTPS 也非 localhost),浏览器已禁用 WebAuthn 功能。<br />
如果您是通过局域网 IP 访问 WebUI,将无法注册和使用 Passkey。
</div>
) : (
<>
<div className='text-sm text-default-400 mb-2'>
注册Passkey后,您可以更便捷地登录WebUI,无需每次输入token
{!window.isSecureContext
? (
<div className='text-sm text-warning-500 bg-warning-50 p-2 rounded-md border border-warning-200'>
⚠️ 当前处于非安全环境(即既非 HTTPS 也非 localhost),浏览器已禁用 WebAuthn 功能。<br />
如果您是通过局域网 IP 访问 WebUI,将无法注册和使用 Passkey。
</div>
<div className='flex gap-2'>
<Button
color='secondary'
variant='flat'
onPress={preloadRegistrationOptions}
isLoading={isLoadingOptions}
className='w-fit'
>
{!isLoadingOptions}
准备选项
</Button>
<Button
color='primary'
variant='flat'
onPress={() => {
// 必须在用户手势的同步上下文中立即调用WebAuthn API
if (!registrationOptions) {
toast.error('请先点击"准备选项"按钮获取注册选项');
return;
}
console.log('开始Passkey注册...');
console.log('使用预先获取的选项:', registrationOptions);
if (!navigator.credentials || !navigator.credentials.create) {
toast.error('当前浏览器环境不支持 Passkey 注册。');
return;
}
// 立即调用WebAuthn API,不要用async/await
navigator.credentials.create({
publicKey: {
challenge: base64UrlToUint8Array(registrationOptions.challenge) as BufferSource,
rp: {
name: registrationOptions.rp.name,
id: registrationOptions.rp.id,
},
user: {
id: base64UrlToUint8Array(registrationOptions.user.id) as BufferSource,
name: registrationOptions.user.name,
displayName: registrationOptions.user.displayName,
},
pubKeyCredParams: registrationOptions.pubKeyCredParams,
timeout: 30000,
excludeCredentials: registrationOptions.excludeCredentials?.map((cred: any) => ({
id: base64UrlToUint8Array(cred.id) as BufferSource,
type: cred.type,
transports: cred.transports,
})) || [],
attestation: registrationOptions.attestation,
},
}).then(async (credential) => {
console.log('✅ 注册成功!凭据已创建');
console.log('凭据ID:', (credential as PublicKeyCredential).id);
console.log('凭据类型:', (credential as PublicKeyCredential).type);
// Prepare response for verification - convert to expected format
const cred = credential as PublicKeyCredential;
const response = {
id: cred.id, // 保持为base64url字符串
rawId: uint8ArrayToBase64Url(new Uint8Array(cred.rawId)), // 转换为base64url字符串
response: {
attestationObject: uint8ArrayToBase64Url(new Uint8Array((cred.response as AuthenticatorAttestationResponse).attestationObject)), // 转换为base64url字符串
clientDataJSON: uint8ArrayToBase64Url(new Uint8Array(cred.response.clientDataJSON)), // 转换为base64url字符串
transports: (cred.response as AuthenticatorAttestationResponse).getTransports?.() || [],
},
type: cred.type,
};
console.log('准备验证响应:', response);
try {
// Verify registration
const result = await WebUIManager.verifyPasskeyRegistration(response);
if (result.verified) {
toast.success('Passkey注册成功!现在您可以使用Passkey自动登录');
setRegistrationOptions(null); // 清除已使用的选项
} else {
throw new Error('Passkey registration failed');
}
} catch (verifyError) {
console.error('❌ 验证失败:', verifyError);
const err = verifyError as Error;
toast.error(`Passkey验证失败: ${err.message}`);
}
}).catch((error) => {
console.error('❌ 注册失败:', error);
const err = error as Error;
console.error('错误名称:', err.name);
console.error('错误信息:', err.message);
// Provide more specific error messages
if (err.name === 'NotAllowedError') {
toast.error('Passkey注册被拒绝。请确保您允许了生物识别认证权限。');
} else if (err.name === 'NotSupportedError') {
toast.error('您的浏览器不支持Passkey功能。');
} else if (err.name === 'SecurityError') {
toast.error('安全错误:请确保使用HTTPS或localhost环境。');
} else {
toast.error(`Passkey注册失败: ${err.message}`);
}
});
}}
disabled={!registrationOptions}
className='w-fit'
>
注册Passkey
</Button>
</div>
{registrationOptions && (
<div className='text-xs text-green-600'>
注册选项已准备就绪,可以开始注册
)
: (
<>
<div className='text-sm text-default-400 mb-2'>
注册Passkey后,您可以更便捷地登录WebUI,无需每次输入token
</div>
)}
</>
)}
<div className='flex gap-2'>
<Button
color='secondary'
variant='flat'
onPress={preloadRegistrationOptions}
isLoading={isLoadingOptions}
className='w-fit'
>
{!isLoadingOptions}
准备选项
</Button>
<Button
color='primary'
variant='flat'
onPress={() => {
// 必须在用户手势的同步上下文中立即调用WebAuthn API
if (!registrationOptions) {
toast.error('请先点击"准备选项"按钮获取注册选项');
return;
}
console.log('开始Passkey注册...');
console.log('使用预先获取的选项:', registrationOptions);
if (!navigator.credentials || !navigator.credentials.create) {
toast.error('当前浏览器环境不支持 Passkey 注册。');
return;
}
// 立即调用WebAuthn API,不要用async/await
navigator.credentials.create({
publicKey: {
challenge: base64UrlToUint8Array(registrationOptions.challenge) as BufferSource,
rp: {
name: registrationOptions.rp.name,
id: registrationOptions.rp.id,
},
user: {
id: base64UrlToUint8Array(registrationOptions.user.id) as BufferSource,
name: registrationOptions.user.name,
displayName: registrationOptions.user.displayName,
},
pubKeyCredParams: registrationOptions.pubKeyCredParams,
timeout: 30000,
excludeCredentials: registrationOptions.excludeCredentials?.map((cred: any) => ({
id: base64UrlToUint8Array(cred.id) as BufferSource,
type: cred.type,
transports: cred.transports,
})) || [],
attestation: registrationOptions.attestation,
},
}).then(async (credential) => {
console.log('✅ 注册成功!凭据已创建');
console.log('凭据ID:', (credential as PublicKeyCredential).id);
console.log('凭据类型:', (credential as PublicKeyCredential).type);
// Prepare response for verification - convert to expected format
const cred = credential as PublicKeyCredential;
const response = {
id: cred.id, // 保持为base64url字符串
rawId: uint8ArrayToBase64Url(new Uint8Array(cred.rawId)), // 转换为base64url字符串
response: {
attestationObject: uint8ArrayToBase64Url(new Uint8Array((cred.response as AuthenticatorAttestationResponse).attestationObject)), // 转换为base64url字符串
clientDataJSON: uint8ArrayToBase64Url(new Uint8Array(cred.response.clientDataJSON)), // 转换为base64url字符串
transports: (cred.response as AuthenticatorAttestationResponse).getTransports?.() || [],
},
type: cred.type,
};
console.log('准备验证响应:', response);
try {
// Verify registration
const result = await WebUIManager.verifyPasskeyRegistration(response);
if (result.verified) {
toast.success('Passkey注册成功!现在您可以使用Passkey自动登录');
setRegistrationOptions(null); // 清除已使用的选项
} else {
throw new Error('Passkey registration failed');
}
} catch (verifyError) {
console.error('❌ 验证失败:', verifyError);
const err = verifyError as Error;
toast.error(`Passkey验证失败: ${err.message}`);
}
}).catch((error) => {
console.error('❌ 注册失败:', error);
const err = error as Error;
console.error('错误名称:', err.name);
console.error('错误信息:', err.message);
// Provide more specific error messages
if (err.name === 'NotAllowedError') {
toast.error('Passkey注册被拒绝。请确保您允许了生物识别认证权限。');
} else if (err.name === 'NotSupportedError') {
toast.error('您的浏览器不支持Passkey功能。');
} else if (err.name === 'SecurityError') {
toast.error('安全错误:请确保使用HTTPS或localhost环境。');
} else {
toast.error(`Passkey注册失败: ${err.message}`);
}
});
}}
disabled={!registrationOptions}
className='w-fit'
>
注册Passkey
</Button>
</div>
{registrationOptions && (
<div className='text-xs text-green-600'>
注册选项已准备就绪,可以开始注册
</div>
)}
</>
)}
</div>
<SaveButtons
onSubmit={onSubmit}