Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8447a46f8b | ||
|
|
7c2514be6c | ||
|
|
738e272d2c | ||
|
|
f7edbfd8d9 | ||
|
|
74dc33fee6 | ||
|
|
c95dd3d030 | ||
|
|
68e6a9bff9 | ||
|
|
5c18a62530 | ||
|
|
a82a5d5203 | ||
|
|
93efce86ca | ||
|
|
091c012427 | ||
|
|
8a3faf64f9 | ||
|
|
fbd70bbb04 | ||
|
|
c405b6d0a4 | ||
|
|
3a4b335062 | ||
|
|
9aa11fd7c4 | ||
|
|
8ae11bfdca | ||
|
|
6acf350613 | ||
|
|
0af6445d5a | ||
|
|
a716a1a185 | ||
|
|
8c9fc7edf4 | ||
|
|
1abad76ac9 | ||
|
|
484c181050 | ||
|
|
9d652be35d | ||
|
|
f226c83595 | ||
|
|
b565f876c5 | ||
|
|
19a5febb1a | ||
|
|
bbf822035f | ||
|
|
a2b0ac10a0 | ||
|
|
279b3ea4eb | ||
|
|
33cc11ba84 | ||
|
|
b058604077 | ||
|
|
1c703a60ed | ||
|
|
285ba9cf2d |
No files matched your search
@@ -254,6 +254,28 @@ export class GitHubAPI {
|
||||
}
|
||||
}
|
||||
|
||||
async createWorkflowDispatch (
|
||||
owner: string,
|
||||
repo: string,
|
||||
workflowFile: string,
|
||||
ref: string,
|
||||
inputs: Record<string, string>
|
||||
): Promise<void> {
|
||||
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/actions/workflows/${workflowFile}/dispatches`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
Accept: 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ ref, inputs }),
|
||||
});
|
||||
if (!response.ok && response.status !== 204) {
|
||||
throw new Error(`Workflow dispatch failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ============== Release Cleanup API ==============
|
||||
|
||||
async listReleases (owner: string, repo: string, perPage = 100, page = 1): Promise<Release[]> {
|
||||
@@ -293,7 +315,7 @@ export function getEnv (name: string, required = false): string | undefined {
|
||||
}
|
||||
|
||||
export function getRepository (): { owner: string, repo: string; } {
|
||||
const repository = getEnv('GITHUB_REPOSITORY', true);
|
||||
const repository = getEnv('GITHUB_REPOSITORY', true)!;
|
||||
const [owner, repo] = repository.split('/');
|
||||
return { owner, repo };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* PR Build - Dispatch untrusted build workflow
|
||||
*
|
||||
* 环境变量:
|
||||
* - GITHUB_TOKEN: GitHub API Token
|
||||
* - PR_NUMBER: PR 编号
|
||||
* - PR_SHA: PR HEAD SHA
|
||||
* - PR_HEAD_REPO: PR 源仓库
|
||||
* - PR_HEAD_REF: PR 源分支
|
||||
* - WORKFLOW_FILE: 工作流文件名,默认 build-pr.yml
|
||||
* - DISPATCH_REF: 触发分支,默认当前分支
|
||||
*/
|
||||
|
||||
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
|
||||
|
||||
declare const process: { exit(code?: number): never; };
|
||||
|
||||
async function main (): Promise<void> {
|
||||
console.log('🚀 Dispatching PR build workflow\n');
|
||||
|
||||
const token = getEnv('GITHUB_TOKEN', true)!;
|
||||
const prNumber = getEnv('PR_NUMBER', true)!;
|
||||
const prSha = getEnv('PR_SHA', true)!;
|
||||
const prHeadRepo = getEnv('PR_HEAD_REPO', true)!;
|
||||
const prHeadRef = getEnv('PR_HEAD_REF') || '';
|
||||
const workflowFile = getEnv('WORKFLOW_FILE') || 'build-pr.yml';
|
||||
const dispatchRef = getEnv('DISPATCH_REF') || getEnv('GITHUB_REF_NAME') || 'main';
|
||||
const { owner, repo } = getRepository();
|
||||
|
||||
console.log(`PR: #${prNumber}`);
|
||||
console.log(`SHA: ${prSha}`);
|
||||
console.log(`Head repo: ${prHeadRepo}`);
|
||||
console.log(`Workflow: ${workflowFile}`);
|
||||
console.log(`Ref: ${dispatchRef}\n`);
|
||||
|
||||
const github = new GitHubAPI(token);
|
||||
await github.createWorkflowDispatch(owner, repo, workflowFile, dispatchRef, {
|
||||
pr_number: prNumber,
|
||||
pr_sha: prSha,
|
||||
pr_head_repo: prHeadRepo,
|
||||
pr_head_ref: prHeadRef,
|
||||
});
|
||||
|
||||
console.log('✅ Dispatch created');
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('❌ Error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -22,11 +22,7 @@ interface BuildStep {
|
||||
|
||||
function getCommonSteps (): BuildStep[] {
|
||||
return [
|
||||
{
|
||||
name: 'Install pnpm',
|
||||
command: 'npm i -g pnpm',
|
||||
errorMessage: 'Failed to install pnpm',
|
||||
},
|
||||
// pnpm 已通过 GitHub Action (pnpm/action-setup) 预安装并固定 v9, 此处无需再次安装
|
||||
{
|
||||
name: 'Install dependencies',
|
||||
command: 'pnpm i',
|
||||
|
||||
@@ -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';
|
||||
|
||||
|
||||
@@ -17,14 +17,17 @@ jobs:
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
run: pnpm i
|
||||
- name: Type Check
|
||||
run: pnpm run typecheck
|
||||
- name: Run Tests
|
||||
@@ -50,6 +53,11 @@ jobs:
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
@@ -68,7 +76,6 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run ${{ matrix.target.build_cmd }}
|
||||
|
||||
+187
-178
@@ -1,118 +1,106 @@
|
||||
# =============================================================================
|
||||
# PR 构建工作流
|
||||
# =============================================================================
|
||||
# 功能:
|
||||
# 1. 在 PR 提交时自动构建 Framework 和 Shell 包
|
||||
# 2. 支持通过 /build 命令手动触发构建(仅协作者/组织成员)
|
||||
# 3. 在 PR 中发布构建状态评论,并持续更新(不会重复创建)
|
||||
# 4. 支持 Fork PR 的构建(使用 pull_request_target 获取写权限)
|
||||
#
|
||||
# 安全说明:
|
||||
# - 使用 pull_request_target 事件,在 base 分支上下文运行
|
||||
# - 构建脚本始终从 base 分支 checkout,避免恶意 PR 篡改脚本
|
||||
# - PR 代码单独 checkout 到 workspace 目录
|
||||
# 安全模型:
|
||||
# 1. pull_request_target / issue_comment 入口只读取元数据、检查权限、更新评论并触发构建。
|
||||
# 2. 真正执行 PR 代码的构建流程只在 workflow_dispatch 中运行。
|
||||
# 3. 构建流程不具备写仓库/写评论/读 secrets 权限,显式清空 GITHUB_TOKEN,不持久化 checkout 凭据。
|
||||
# 4. 版本号在 Action 中提前生成,通过 NAPCAT_VERSION 传给 Vite 插件,插件无需 GitHub token。
|
||||
# 5. 发布 Release、触发 Docker 等可信操作只消费构建 artifact,不执行 PR artifact 中的代码。
|
||||
# =============================================================================
|
||||
|
||||
name: Build PR
|
||||
|
||||
# =============================================================================
|
||||
# 触发条件
|
||||
# =============================================================================
|
||||
on:
|
||||
# PR 事件:打开、同步(新推送)、重新打开时触发
|
||||
# 注意:使用 pull_request_target 而非 pull_request,以便对 Fork PR 有写权限
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
# Issue 评论事件:用于响应 /build 命令
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
# =============================================================================
|
||||
# 权限配置
|
||||
# =============================================================================
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr_number:
|
||||
description: PR 编号
|
||||
required: true
|
||||
type: string
|
||||
pr_sha:
|
||||
description: PR HEAD SHA
|
||||
required: true
|
||||
type: string
|
||||
pr_head_repo:
|
||||
description: PR 源仓库
|
||||
required: true
|
||||
type: string
|
||||
pr_head_ref:
|
||||
description: PR 源分支
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read # 读取仓库内容
|
||||
pull-requests: write # 写入 PR 评论
|
||||
issues: write # 写入 Issue 评论(/build 命令响应)
|
||||
actions: read # 读取 Actions 信息(获取构建日志链接)
|
||||
contents: read
|
||||
|
||||
# =============================================================================
|
||||
# 并发控制
|
||||
# =============================================================================
|
||||
# 同一 PR 的多次构建会取消之前未完成的构建,避免资源浪费
|
||||
# 注意:只有在 should_build=true 时才会进入实际构建流程,
|
||||
# issue_comment 事件如果不是 /build 命令,会在 check-build 阶段快速退出,
|
||||
# 不会取消正在进行的构建(因为 cancel-in-progress 只影响同 group 的后续任务)
|
||||
concurrency:
|
||||
# 使用不同的 group 策略:
|
||||
# - pull_request_target: 使用 PR 号
|
||||
# - issue_comment: 只有确认是 /build 命令时才使用 PR 号,否则使用 run_id(不冲突)
|
||||
group: pr-build-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
|
||||
group: pr-build-${{ github.event_name == 'workflow_dispatch' && inputs.pr_number || github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# =============================================================================
|
||||
# 任务定义
|
||||
# =============================================================================
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 1: 检查构建条件
|
||||
# ---------------------------------------------------------------------------
|
||||
# 判断是否应该触发构建:
|
||||
# - pull_request_target 事件:总是触发
|
||||
# - issue_comment 事件:检查是否为 /build 命令,且用户有权限
|
||||
# 特权入口:只检查条件、写入“构建中”评论、触发无权限构建
|
||||
# ---------------------------------------------------------------------------
|
||||
check-build:
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: write
|
||||
outputs:
|
||||
should_build: ${{ steps.check.outputs.should_build }} # 是否应该构建
|
||||
pr_number: ${{ steps.check.outputs.pr_number }} # PR 编号
|
||||
pr_sha: ${{ steps.check.outputs.pr_sha }} # PR 最新提交 SHA
|
||||
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }} # PR 源仓库(用于 Fork)
|
||||
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }} # PR 源分支
|
||||
should_build: ${{ steps.check.outputs.should_build }}
|
||||
pr_number: ${{ steps.check.outputs.pr_number }}
|
||||
pr_sha: ${{ steps.check.outputs.pr_sha }}
|
||||
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }}
|
||||
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }}
|
||||
steps:
|
||||
# 仅 checkout 脚本目录,加快速度
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
# 使用 Node.js 24 以支持原生 TypeScript 执行
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 执行检查脚本,判断是否触发构建
|
||||
- name: Check trigger condition
|
||||
id: check
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-check.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 2: 更新评论为"构建中"状态
|
||||
# ---------------------------------------------------------------------------
|
||||
# 在 PR 中创建或更新评论,显示构建正在进行中
|
||||
# ---------------------------------------------------------------------------
|
||||
update-comment-building:
|
||||
needs: check-build
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 更新 PR 评论,显示构建中状态
|
||||
- name: Update building comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -120,215 +108,200 @@ jobs:
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-building.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 3: 构建 Framework 包
|
||||
# ---------------------------------------------------------------------------
|
||||
# 执行 napcat-framework 的构建流程
|
||||
# ---------------------------------------------------------------------------
|
||||
build-framework:
|
||||
dispatch-build:
|
||||
needs: [check-build, update-comment-building]
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }} # 构建结果:success/failure
|
||||
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
|
||||
version: ${{ steps.version.outputs.version }} # 构建版本号
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
steps:
|
||||
# 【安全】先从 base 分支 checkout 构建脚本
|
||||
# 这样即使 PR 中修改了脚本,也不会被执行
|
||||
- name: Checkout scripts from base
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
|
||||
# 将 PR 代码 checkout 到单独的 workspace 目录
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
repository: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
ref: ${{ needs.check-build.outputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 获取最新 release tag 并生成版本号
|
||||
- name: Dispatch untrusted build
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
PR_HEAD_REPO: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
PR_HEAD_REF: ${{ needs.check-build.outputs.pr_head_ref }}
|
||||
WORKFLOW_FILE: build-pr.yml
|
||||
DISPATCH_REF: ${{ github.event.repository.default_branch }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-dispatch.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 无权限构建:只由 workflow_dispatch 执行 PR 代码
|
||||
# ---------------------------------------------------------------------------
|
||||
build-framework:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }}
|
||||
error: ${{ steps.build.outputs.error }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
persist-credentials: false
|
||||
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
repository: ${{ inputs.pr_head_repo }}
|
||||
ref: ${{ inputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
|
||||
SHORT_SHA="${{ inputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
# 执行构建,使用 base 分支的脚本处理 workspace 中的代码
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITHUB_TOKEN: ''
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
|
||||
continue-on-error: true # 允许失败,后续更新评论时处理
|
||||
continue-on-error: true
|
||||
|
||||
# 构建成功时上传产物
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: workspace/framework-dist
|
||||
retention-days: 5 # 保留 5 天(仓库上限)
|
||||
retention-days: 5
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 4: 构建 Shell 包
|
||||
# ---------------------------------------------------------------------------
|
||||
# 执行 napcat-shell 的构建流程(与 Framework 并行执行)
|
||||
# ---------------------------------------------------------------------------
|
||||
build-shell:
|
||||
needs: [check-build, update-comment-building]
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }} # 构建结果:success/failure
|
||||
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
|
||||
version: ${{ steps.version.outputs.version }} # 构建版本号
|
||||
status: ${{ steps.build.outcome }}
|
||||
error: ${{ steps.build.outputs.error }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
# 【安全】先从 base 分支 checkout 构建脚本
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
persist-credentials: false
|
||||
|
||||
# 将 PR 代码 checkout 到单独的 workspace 目录
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
repository: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
ref: ${{ needs.check-build.outputs.pr_sha }}
|
||||
repository: ${{ inputs.pr_head_repo }}
|
||||
ref: ${{ inputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 获取最新 release tag 并生成版本号
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
|
||||
SHORT_SHA="${{ inputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
# 执行构建
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITHUB_TOKEN: ''
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts shell
|
||||
continue-on-error: true
|
||||
|
||||
# 构建成功时上传产物
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: workspace/shell-dist
|
||||
retention-days: 5 # 保留 5 天(仓库上限)
|
||||
retention-days: 5
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 5: 更新评论为构建结果
|
||||
# ---------------------------------------------------------------------------
|
||||
# 汇总所有构建结果,更新 PR 评论显示最终状态
|
||||
# 使用 always() 确保即使构建失败/取消也会执行
|
||||
# ---------------------------------------------------------------------------
|
||||
update-comment-result:
|
||||
needs: [check-build, update-comment-building, build-framework, build-shell, publish-pr-release]
|
||||
if: always() && needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 更新评论,显示构建结果和下载链接
|
||||
- name: Update result comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
# 构建版本号
|
||||
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
|
||||
# 获取构建状态,如果 job 被跳过则标记为 cancelled
|
||||
FRAMEWORK_STATUS: ${{ needs.build-framework.outputs.status || 'cancelled' }}
|
||||
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
|
||||
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
|
||||
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
|
||||
# PR Release 信息(用于在评论中显示安装命令)
|
||||
INSTALL_URL: ${{ needs.publish-pr-release.outputs.install_url || '' }}
|
||||
RELEASE_URL: ${{ needs.publish-pr-release.outputs.release_url || '' }}
|
||||
PUBLISH_STATUS: ${{ needs.publish-pr-release.outputs.publish_status || '' }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 6: 发布 PR 构建产物到 napcat-pr-release 仓库
|
||||
# ---------------------------------------------------------------------------
|
||||
# 将所有构建产物打包 + 从 NapCat-Installer 拉取并修改安装脚本,
|
||||
# 一起发布为 GitHub Release(公开可下载,无需登录)。
|
||||
# Release 会由 napcat-pr-release 仓库的定时任务在 24h 后自动清理。
|
||||
# 可信后处理:只下载/打包/发布 artifact,不执行 artifact 中的代码
|
||||
# ---------------------------------------------------------------------------
|
||||
publish-pr-release:
|
||||
needs: [check-build, build-framework, build-shell]
|
||||
if: always() && needs.check-build.outputs.should_build == 'true' && (needs.build-framework.outputs.status == 'success' || needs.build-shell.outputs.status == 'success')
|
||||
needs: [build-framework, build-shell]
|
||||
if: always() && github.event_name == 'workflow_dispatch' && (needs.build-framework.outputs.status == 'success' || needs.build-shell.outputs.status == 'success')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
outputs:
|
||||
release_url: ${{ steps.publish.outputs.release_url }}
|
||||
release_tag: ${{ steps.publish.outputs.release_tag }}
|
||||
install_url: ${{ steps.publish.outputs.install_url }}
|
||||
publish_status: ${{ steps.publish.outcome }} # 'success' | 'failure' | 'skipped'
|
||||
publish_status: ${{ steps.publish.outcome }}
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
@@ -354,8 +327,8 @@ jobs:
|
||||
continue-on-error: true
|
||||
env:
|
||||
RELEASE_PAT: ${{ secrets.PR_RELEASE_PAT }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
PR_SHA: ${{ inputs.pr_sha }}
|
||||
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
|
||||
ARTIFACTS_DIR: ./artifacts
|
||||
run: |
|
||||
@@ -365,7 +338,6 @@ jobs:
|
||||
fi
|
||||
node --experimental-strip-types .github/scripts/pr-publish-release.ts
|
||||
|
||||
# 将修改后的安装脚本也上传为 CI artifact(自动过期)
|
||||
- name: Upload install script as artifact
|
||||
if: steps.publish.outcome == 'success'
|
||||
uses: actions/upload-artifact@v6
|
||||
@@ -375,22 +347,59 @@ jobs:
|
||||
retention-days: 5
|
||||
if-no-files-found: ignore
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 7: 触发 NapCat-Docker 仓库的 PR 测试镜像构建
|
||||
# ---------------------------------------------------------------------------
|
||||
# 仅当 Shell 构建成功、且 Release 已发布时触发。
|
||||
# Docker 构建从公开 Release 下载产物,无需跨仓 artifact PAT。
|
||||
# ---------------------------------------------------------------------------
|
||||
trigger-docker:
|
||||
needs: [check-build, build-shell, publish-pr-release]
|
||||
if: needs.check-build.outputs.should_build == 'true' && needs.build-shell.outputs.status == 'success' && needs.publish-pr-release.outputs.release_tag != ''
|
||||
update-comment-result:
|
||||
needs: [build-framework, build-shell, publish-pr-release]
|
||||
if: always() && github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Update result comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
PR_SHA: ${{ inputs.pr_sha }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
|
||||
FRAMEWORK_STATUS: ${{ needs.build-framework.outputs.status || 'cancelled' }}
|
||||
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
|
||||
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
|
||||
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
|
||||
INSTALL_URL: ${{ needs.publish-pr-release.outputs.install_url || '' }}
|
||||
RELEASE_URL: ${{ needs.publish-pr-release.outputs.release_url || '' }}
|
||||
PUBLISH_STATUS: ${{ needs.publish-pr-release.outputs.publish_status || '' }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
|
||||
|
||||
trigger-docker:
|
||||
needs: [build-shell, publish-pr-release]
|
||||
if: github.event_name == 'workflow_dispatch' && needs.build-shell.outputs.status == 'success' && needs.publish-pr-release.outputs.release_tag != ''
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
@@ -402,9 +411,9 @@ jobs:
|
||||
env:
|
||||
DISPATCH_PAT: ${{ secrets.PR_RELEASE_PAT }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
PR_HEAD_REPO: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
PR_SHA: ${{ inputs.pr_sha }}
|
||||
PR_HEAD_REPO: ${{ inputs.pr_head_repo }}
|
||||
SOURCE_REPO: ${{ github.repository }}
|
||||
RELEASE_REPO: NapNeko/napcat-pr-release
|
||||
run: |
|
||||
|
||||
@@ -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 \
|
||||
|
||||
@@ -21,3 +21,4 @@ tests/run/
|
||||
guild1.db-wal
|
||||
guild1.db-shm
|
||||
packages/napcat-develop/config/.env
|
||||
.claude
|
||||
@@ -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
|
||||
|
||||
@@ -64,7 +58,7 @@ _Modern protocol-side framework implemented based on NTQQ._
|
||||
|
||||
> QQ群因为特殊原因需要入群密钥,请在webui关于页面获取,仅最新的100个版本以内有效。
|
||||
|
||||
下面的QQ Group 无需密钥,随时清理不活跃人员和Bot,仅500人容量。
|
||||
社区相关日后会进一步加强审核,并严格限制一定时间的入群人数,请具备一定编程基础和问题解决能力再申请入群。
|
||||
|
||||
[困困猫猫的高中](https://qm.qq.com/q/14aUVclRUA)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": [
|
||||
"ES2021"
|
||||
],
|
||||
@@ -34,10 +34,15 @@
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"resolveJsonModule": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"napcat-common/src/*": [
|
||||
"../../packages/napcat-common/src/*"
|
||||
],
|
||||
"napcat-image-size/src/*": [
|
||||
"../../packages/napcat-image-size/src/*"
|
||||
],
|
||||
"@/*": [
|
||||
"../*"
|
||||
"../../packages/*"
|
||||
]
|
||||
},
|
||||
"skipLibCheck": true,
|
||||
|
||||
@@ -430,6 +430,24 @@ export class NTQQGroupApi {
|
||||
return this.context.session.getRichMediaService().batchGetGroupFileCount(groupCodes);
|
||||
}
|
||||
|
||||
// getGroupFileList also carries the group's used/total space in its call
|
||||
// result's `groupSpaceResult`; a single-item fetch is enough to read it.
|
||||
async getGroupFileSpace (groupCode: string) {
|
||||
const [result] = await this.core.eventWrapper.callNormalEventV2(
|
||||
'NodeIKernelRichMediaService/getGroupFileList',
|
||||
'NodeIKernelMsgListener/onGroupFileInfoUpdate',
|
||||
[
|
||||
groupCode,
|
||||
{ sortType: 1, fileCount: 1, startIndex: 0, sortOrder: 1, showOnlinedocFolder: 0 },
|
||||
],
|
||||
() => true,
|
||||
() => true,
|
||||
1,
|
||||
5000
|
||||
);
|
||||
return result?.groupSpaceResult;
|
||||
}
|
||||
|
||||
async getArkJsonGroupShare (groupCode: string) {
|
||||
const ret = await this.core.eventWrapper.callNoListenerEvent(
|
||||
'NodeIKernelGroupService/getGroupRecommendContactArkJson',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -36,7 +36,7 @@ export class NTQQPacketApi {
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.logError(err);
|
||||
this.errStack.push(err);
|
||||
this.pushError(err);
|
||||
return false;
|
||||
})) && this.pkt?.available;
|
||||
}
|
||||
@@ -46,7 +46,15 @@ export class NTQQPacketApi {
|
||||
}
|
||||
|
||||
get clientLogStack () {
|
||||
return this.pkt?.clientLogStack + '\n' + this.errStack.join('\n');
|
||||
return [this.pkt?.clientLogStack, ...this.errStack].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
private pushError (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
this.errStack.push(error.stack || error.message);
|
||||
return;
|
||||
}
|
||||
this.errStack.push(String(error));
|
||||
}
|
||||
|
||||
async InitSendPacket (qqVer: string) {
|
||||
@@ -67,10 +75,17 @@ export class NTQQPacketApi {
|
||||
}
|
||||
this.pkt = new PacketClientSession(this.core);
|
||||
await this.pkt.init(process.pid, table.recv, table.send);
|
||||
if (!this.pkt.available) {
|
||||
const err = '[Core] [Packet] NativePacketClient 初始化失败,PacketBackend 发包能力不可用!';
|
||||
this.logger.logError(err);
|
||||
this.errStack.push(err);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await this.pkt.operation.FetchRkey(3000);
|
||||
} catch (error) {
|
||||
this.logger.logError('测试Packet状态异常', error);
|
||||
this.pushError(error);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -507,20 +507,73 @@ export class NTQQWebApi {
|
||||
async doAlbumMediaLikeByNTQQ (
|
||||
qunId: string,
|
||||
albumId: string,
|
||||
lloc: string,
|
||||
id: string) {
|
||||
batchId: string,
|
||||
lloc: string | undefined,
|
||||
isLike: boolean
|
||||
) {
|
||||
const random_seq = Math.floor(Math.random() * 9000) + 1000;
|
||||
const uin = this.core.selfInfo.uin || '10001';
|
||||
|
||||
const type = isLike ? 2 : 1;
|
||||
const status = isLike ? 0 : 1;
|
||||
|
||||
let id = '';
|
||||
if (lloc) {
|
||||
id = `421_1_0_${qunId}|${albumId}|${batchId}^||^421_1_0_${qunId}|${albumId}|${lloc}^||^0`;
|
||||
} else {
|
||||
id = `421_1_0_${qunId}|${albumId}|${batchId}`;
|
||||
}
|
||||
|
||||
return await this.context.session.getAlbumService().doQunLike(
|
||||
random_seq, {
|
||||
random_seq,
|
||||
{
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
}, {
|
||||
id,
|
||||
status: 1,
|
||||
},
|
||||
createAlbumFeedPublish(qunId, uin, albumId, lloc)
|
||||
type,
|
||||
{
|
||||
id,
|
||||
status,
|
||||
},
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -163,14 +163,14 @@ export interface AlbumFeedLikePublish {
|
||||
};
|
||||
cell_media: {
|
||||
album_id: string;
|
||||
batch_id: number;
|
||||
media_items: Array<{
|
||||
batch_id: string | number;
|
||||
media_items?: {
|
||||
type: number;
|
||||
image: {
|
||||
lloc: string;
|
||||
sloc: string;
|
||||
};
|
||||
}>;
|
||||
}[];
|
||||
};
|
||||
cell_qun_info: {
|
||||
qun_id: string;
|
||||
@@ -182,21 +182,19 @@ export interface AlbumFeedLikePublish {
|
||||
* @param qunId 群号
|
||||
* @param uin 用户QQ号
|
||||
* @param albumId 相册ID
|
||||
* @param lloc 信息
|
||||
* @param sloc 信息(可选,默认与lloc相同)
|
||||
* @param batchId 批次ID
|
||||
* @returns 动态发布请求参数对象
|
||||
*/
|
||||
export function createAlbumFeedPublish (
|
||||
qunId: string,
|
||||
uin: string,
|
||||
albumId: string,
|
||||
lloc: string,
|
||||
sloc?: string
|
||||
): AlbumFeedLikePublish {
|
||||
batchId: string
|
||||
) {
|
||||
return {
|
||||
cell_common: {
|
||||
time: Date.now(),
|
||||
feed_id: '',
|
||||
feed_id: `422_0_${batchId}`, // 需要补全feed_id
|
||||
},
|
||||
cell_user_info: {
|
||||
user: {
|
||||
@@ -205,14 +203,7 @@ export function createAlbumFeedPublish (
|
||||
},
|
||||
cell_media: {
|
||||
album_id: albumId,
|
||||
batch_id: 0,
|
||||
media_items: [{
|
||||
type: 0,
|
||||
image: {
|
||||
lloc,
|
||||
sloc: sloc || lloc,
|
||||
},
|
||||
}],
|
||||
batch_id: batchId,
|
||||
},
|
||||
cell_qun_info: {
|
||||
qun_id: qunId,
|
||||
|
||||
+32
@@ -574,5 +574,37 @@
|
||||
"3.2.28-48517": {
|
||||
"appid": 537352510,
|
||||
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
|
||||
},
|
||||
"9.9.30-48762": {
|
||||
"appid": 537352525,
|
||||
"qua": "V1_WIN_NQ_9.9.30_48762_GW_B"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"9.9.32-50828": {
|
||||
"appid": 537358739,
|
||||
"qua": "V1_WIN_NQ_9.9.32_50828_GW_B"
|
||||
},
|
||||
"3.2.30-50828": {
|
||||
"appid": 537358775,
|
||||
"qua": "V1_LNX_NQ_3.2.30_50828_GW_B"
|
||||
},
|
||||
"9.9.32-50969": {
|
||||
"appid": 537376308,
|
||||
"qua": "V1_WIN_NQ_9.9.32_50969_GW_B"
|
||||
},
|
||||
"3.2.30-50969": {
|
||||
"appid": 537376344,
|
||||
"qua": "V1_LNX_NQ_3.2.30_50969_GW_B"
|
||||
}
|
||||
}
|
||||
+44
@@ -234,5 +234,49 @@
|
||||
"3.2.28-48517-arm64": {
|
||||
"send": "3F9C7E4",
|
||||
"recv": "14E1AA8"
|
||||
},
|
||||
"9.9.30-48762-x64": {
|
||||
"send": "0A9B1BC",
|
||||
"recv": "1F0324D"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"9.9.32-50828-x64": {
|
||||
"send": "0B245CC",
|
||||
"recv": "2073D65"
|
||||
},
|
||||
"3.2.30-50828-x64": {
|
||||
"send": "6340530",
|
||||
"recv": "346DA50"
|
||||
},
|
||||
"3.2.30-50828-arm64": {
|
||||
"send": "4327764",
|
||||
"recv": "15e3184"
|
||||
},
|
||||
"9.9.32-50969-x64": {
|
||||
"send": "0B2E2AC",
|
||||
"recv": "209C709"
|
||||
},
|
||||
"3.2.30-50969-x64": {
|
||||
"send": "63F47B0",
|
||||
"recv": "34B9E30"
|
||||
},
|
||||
"3.2.30-50969-arm64": {
|
||||
"send": "43A4804",
|
||||
"recv": "1608CC8"
|
||||
}
|
||||
}
|
||||
+44
@@ -742,5 +742,49 @@
|
||||
"3.2.28-48517-arm64": {
|
||||
"send": "6F48B70",
|
||||
"recv": "6F4C520"
|
||||
},
|
||||
"9.9.30-48762-x64": {
|
||||
"send": "2F3B960",
|
||||
"recv": "2F3EEE0"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"9.9.32-50828-x64": {
|
||||
"send": "3155200",
|
||||
"recv": "3158788"
|
||||
},
|
||||
"9.9.32-50828-arm64": {
|
||||
"send": "4327764",
|
||||
"recv": "15E3184"
|
||||
},
|
||||
"3.2.30-50828-x64": {
|
||||
"send": "B5D0FC0",
|
||||
"recv": "B5D4A60"
|
||||
},
|
||||
"9.9.32-50969-x64": {
|
||||
"send": "31994E0",
|
||||
"recv": "319CA68"
|
||||
},
|
||||
"3.2.30-50969-x64": {
|
||||
"send": "B7394C0",
|
||||
"recv": "B73CF60"
|
||||
},
|
||||
"3.2.30-50969-arm64": {
|
||||
"send": "75BD1D0",
|
||||
"recv": "75C0B80"
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
]);
|
||||
|
||||
|
||||
@@ -39,12 +39,17 @@ export class NativePacketClient {
|
||||
|
||||
async init (_pid: number, recv: string, send: string): Promise<void> {
|
||||
const isNewQQ = this.napcore.basicInfo.requireMinNTQQBuild('40824');
|
||||
if (isNewQQ) {
|
||||
const success = this.napi2nativeLoader.initHook(send, recv);
|
||||
if (success) {
|
||||
this.available = true;
|
||||
}
|
||||
if (!isNewQQ) {
|
||||
this.logStack.pushLogWarn('[PacketClient] 当前 QQ 版本低于 NativePacketClient 要求,跳过 Hook 初始化');
|
||||
return;
|
||||
}
|
||||
const success = this.napi2nativeLoader.initHook(send, recv);
|
||||
if (success) {
|
||||
this.available = true;
|
||||
this.logStack.pushLogInfo(`[PacketClient] NativePacketClient Hook 初始化成功 platform=${process.platform}.${process.arch}`);
|
||||
return;
|
||||
}
|
||||
this.logStack.pushLogError(`[PacketClient] NativePacketClient Hook 初始化失败 platform=${process.platform}.${process.arch} send=${send} recv=${recv}`);
|
||||
}
|
||||
|
||||
async sendPacket (
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -88,6 +88,7 @@ export interface NodeIKernelAlbumService {
|
||||
map_bytes_info: unknown[],
|
||||
map_user_account: unknown[];
|
||||
},
|
||||
type: number, // type : number 1 取消 2 点赞
|
||||
param: {
|
||||
// {"id":"421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3e*KqaLVYdic!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560336594^||^1","status":1}
|
||||
id: string,
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".."
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
|
||||
@@ -195,6 +195,11 @@ export async function NCoreInitFramework (
|
||||
if (oneBotAdapter) {
|
||||
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
|
||||
}
|
||||
|
||||
// 监听下线通知并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
|
||||
loaderObject.core.event.on('KickedOffLine', () => {
|
||||
WebUiDataRuntime.setQQLoginStatus(false);
|
||||
});
|
||||
}
|
||||
|
||||
function registerWebUiLoginCallbacks (
|
||||
|
||||
@@ -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,
|
||||
})) ?? [];
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,8 @@ import { Static, Type } from '@sinclair/typebox';
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
album_id: Type.String({ description: '相册ID' }),
|
||||
lloc: Type.String({ description: '媒体ID (lloc)' }),
|
||||
id: Type.String({ description: '点赞ID' }), // 421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3.PyqaPndPxg!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560363448^||^1
|
||||
set: Type.Boolean({ default: true, description: '是否点赞' }), // true=点赞 false=取消点赞 未实现
|
||||
batch_id: Type.String({ description: 'batch_id' }),
|
||||
lloc: Type.Optional(Type.String({ description: 'lloc,若对整个上传操作则不填' })),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
@@ -22,9 +21,9 @@ export class SetGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
album_id: 'album_id_1',
|
||||
lloc: 'media_id_1',
|
||||
id: '123456',
|
||||
album_id: 'album_id_123',
|
||||
batch_id: '112233',
|
||||
lloc: 'aabbcc12213123',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
@@ -38,8 +37,38 @@ export class SetGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType
|
||||
return await this.core.apis.WebApi.doAlbumMediaLikeByNTQQ(
|
||||
payload.group_id,
|
||||
payload.album_id,
|
||||
payload.batch_id,
|
||||
payload.lloc,
|
||||
payload.id
|
||||
true // isLike = true
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class CancelGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.CancelGroupAlbumMediaLike; // 注意:需要在 router/index.ts 的 ActionName 枚举中补充该定义
|
||||
override actionSummary = '取消点赞群相册媒体';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
album_id: 'album_id',
|
||||
batch_id: '112233',
|
||||
lloc: 'aabbcc',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: {},
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
return await this.core.apis.WebApi.doAlbumMediaLikeByNTQQ(
|
||||
payload.group_id,
|
||||
payload.album_id,
|
||||
payload.batch_id,
|
||||
payload.lloc,
|
||||
false
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -29,15 +29,22 @@ export class GetGroupFileSystemInfo extends OneBotAction<PayloadType, ReturnType
|
||||
override returnExample = GoCQHTTPActionsExamples.GetGroupFileSystemInfo.response;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
const groupFileCount = (await this.core.apis.GroupApi.getGroupFileCount([payload.group_id.toString()])).groupFileCounts[0];
|
||||
if (!groupFileCount) {
|
||||
const groupCode = payload.group_id.toString();
|
||||
const [countResult, space] = await Promise.all([
|
||||
this.core.apis.GroupApi.getGroupFileCount([groupCode]),
|
||||
this.core.apis.GroupApi.getGroupFileSpace(groupCode),
|
||||
]);
|
||||
const groupFileCount = countResult.groupFileCounts[0];
|
||||
if (groupFileCount === undefined) {
|
||||
throw new Error('Group not found');
|
||||
}
|
||||
return {
|
||||
file_count: groupFileCount,
|
||||
limit_count: 10000,
|
||||
used_space: 0,
|
||||
total_space: 10 * 1024 * 1024 * 1024,
|
||||
// Real values from the kernel's groupSpaceResult; fall back to the old
|
||||
// placeholders if the field is unexpectedly absent.
|
||||
used_space: space?.usedSpace ?? 0,
|
||||
total_space: space?.totalSpace ?? 10 * 1024 * 1024 * 1024,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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('设置群名片未生效');
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
@@ -134,7 +135,7 @@ import { GetQunAlbumList } from './extends/GetQunAlbumList';
|
||||
import { UploadImageToQunAlbum } from './extends/UploadImageToQunAlbum';
|
||||
import { DoGroupAlbumComment } from './extends/DoGroupAlbumComment';
|
||||
import { GetGroupAlbumMediaList } from './extends/GetGroupAlbumMediaList';
|
||||
import { SetGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
|
||||
import { SetGroupAlbumMediaLike, CancelGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
|
||||
import { DelGroupAlbumMedia } from './extends/DelGroupAlbumMedia';
|
||||
import { CleanStreamTempFile } from './stream/CleanStreamTempFile';
|
||||
import { DownloadFileStream } from './stream/DownloadFileStream';
|
||||
@@ -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 = [
|
||||
@@ -169,6 +171,7 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new UploadFileStream(obContext, core),
|
||||
new DelGroupAlbumMedia(obContext, core),
|
||||
new SetGroupAlbumMediaLike(obContext, core),
|
||||
new CancelGroupAlbumMediaLike(obContext, core),
|
||||
new DoGroupAlbumComment(obContext, core),
|
||||
new GetGroupAlbumMediaList(obContext, core),
|
||||
new GetQunAlbumList(obContext, core),
|
||||
@@ -212,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),
|
||||
@@ -276,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),
|
||||
|
||||
@@ -84,6 +84,13 @@ export async function createContext (core: NapCatCore, payload: OB11PostContext
|
||||
}
|
||||
const isBuddy = await core.apis.FriendApi.isBuddy(Uid);
|
||||
if (!isBuddy) {
|
||||
if (payload.group_id) {
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
|
||||
peerUid: Uid,
|
||||
guildId: payload.group_id.toString(),
|
||||
};
|
||||
}
|
||||
const ret = await core.apis.MsgApi.getTempChatInfo(ChatType.KCHATTYPETEMPC2CFROMGROUP, Uid);
|
||||
if (ret.tmpChatInfo?.groupCode) {
|
||||
return {
|
||||
@@ -92,13 +99,6 @@ export async function createContext (core: NapCatCore, payload: OB11PostContext
|
||||
guildId: '',
|
||||
};
|
||||
}
|
||||
if (payload.group_id) {
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPETEMPC2CFROMGROUP,
|
||||
peerUid: Uid,
|
||||
guildId: payload.group_id.toString(),
|
||||
};
|
||||
}
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPEC2C,
|
||||
peerUid: Uid,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -4,6 +4,8 @@ import { Type } from '@sinclair/typebox';
|
||||
|
||||
export abstract class GetPacketStatusDepends<PT, RT> extends OneBotAction<PT, RT> {
|
||||
protected override async check (payload: PT): Promise<BaseCheckResult> {
|
||||
const schemaResult = await super.check(payload);
|
||||
if (!schemaResult.valid) return schemaResult;
|
||||
if (!this.core.apis.PacketApi.packetStatus) {
|
||||
return {
|
||||
valid: false,
|
||||
@@ -11,7 +13,22 @@ export abstract class GetPacketStatusDepends<PT, RT> extends OneBotAction<PT, RT
|
||||
'错误堆栈信息:' + this.core.apis.PacketApi.clientLogStack,
|
||||
};
|
||||
}
|
||||
return await super.check(payload);
|
||||
return { valid: true };
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class PacketSendAvailableDepends<PT, RT> extends OneBotAction<PT, RT> {
|
||||
protected override async check (payload: PT): Promise<BaseCheckResult> {
|
||||
const schemaResult = await super.check(payload);
|
||||
if (!schemaResult.valid) return schemaResult;
|
||||
if (!this.core.apis.PacketApi.available) {
|
||||
return {
|
||||
valid: false,
|
||||
message: 'packetBackend发包能力不可用,请参照文档 https://napneko.github.io/config/advanced 和启动日志检查packetBackend状态或进行配置!' +
|
||||
'错误堆栈信息:' + this.core.apis.PacketApi.clientLogStack,
|
||||
};
|
||||
}
|
||||
return { valid: true };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
|
||||
import { PacketSendAvailableDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { PacketActionsExamples } from '../example/PacketActionsExamples';
|
||||
@@ -11,7 +11,7 @@ export const SendPokePayloadSchema = Type.Object({
|
||||
});
|
||||
|
||||
export type SendPokePayload = Static<typeof SendPokePayloadSchema>;
|
||||
export class SendPokeBase extends GetPacketStatusDepends<SendPokePayload, void> {
|
||||
export class SendPokeBase extends PacketSendAvailableDepends<SendPokePayload, void> {
|
||||
override payloadSchema = SendPokePayloadSchema;
|
||||
override returnSchema = Type.Null();
|
||||
override actionSummary = '发送戳一戳';
|
||||
|
||||
@@ -24,6 +24,7 @@ export const ActionName = {
|
||||
|
||||
DelGroupAlbumMedia: 'del_group_album_media',
|
||||
SetGroupAlbumMediaLike: 'set_group_album_media_like',
|
||||
CancelGroupAlbumMediaLike: 'cancel_group_album_media_like',
|
||||
DoGroupAlbumComment: 'do_group_album_comment',
|
||||
GetGroupAlbumMediaList: 'get_group_album_media_list',
|
||||
UploadImageToQunAlbum: 'upload_image_to_qun_album',
|
||||
@@ -154,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',
|
||||
@@ -207,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;
|
||||
@@ -278,7 +278,7 @@ export class OneBotMsgApi {
|
||||
};
|
||||
},
|
||||
|
||||
replyElement: async (element, msg, _, quick_reply) => {
|
||||
replyElement: async (element, msg, _, { quick_reply }) => {
|
||||
const peer = {
|
||||
chatType: msg.chatType,
|
||||
peerUid: msg.peerUid,
|
||||
@@ -310,9 +310,9 @@ export class OneBotMsgApi {
|
||||
peer, msgSeq, msgTime, [senderUid]
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
const replyMsg = replyMsgList.find(msg =>
|
||||
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
|
||||
);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
if (quick_reply) {
|
||||
@@ -327,9 +327,9 @@ export class OneBotMsgApi {
|
||||
peer, msgSeq, 1, true, true
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
const replyMsg = replyMsgList.find(msg =>
|
||||
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
|
||||
);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
|
||||
@@ -341,9 +341,9 @@ export class OneBotMsgApi {
|
||||
peer, msgSeq, [senderUid]
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
const replyMsg = replyMsgList.find(msg =>
|
||||
(msgRandom && msg.msgRandom === msgRandom) || msg.msgSeq === msgSeq
|
||||
);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
|
||||
|
||||
@@ -73,7 +73,12 @@ export function encodeCQCode (data: OB11MessageData) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const text = value?.toString();
|
||||
let text: string | undefined;
|
||||
if (typeof value === 'object' && value?.toString === Object.prototype.toString) {
|
||||
text = JSON.stringify(value);
|
||||
} else {
|
||||
text = value?.toString();
|
||||
}
|
||||
if (text) {
|
||||
result += `,${name}=${CQCodeEscape(text)}`;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
const hit = this.scanSensitiveWords(pluginDir);
|
||||
if (this.isOfficialPlugin(pluginId)) {
|
||||
return null;
|
||||
}
|
||||
if (hit) {
|
||||
return `sensitive keyword "${hit}"`;
|
||||
}
|
||||
return "not in official plugin whitelist";
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归扫描插件目录内源码是否命中敏感词(黑灰产 / 支付发卡)。
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "../../packages"
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
|
||||
@@ -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()],
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"moduleResolution": "bundler",
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": [
|
||||
"ES2021"
|
||||
],
|
||||
@@ -34,7 +34,6 @@
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"resolveJsonModule": true,
|
||||
"baseUrl": ".",
|
||||
"skipLibCheck": true,
|
||||
"skipDefaultLibCheck": true
|
||||
},
|
||||
|
||||
@@ -4,10 +4,9 @@
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"noEmit": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"../*/"
|
||||
"../../packages/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -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) => {
|
||||
@@ -784,6 +794,7 @@ export class NapCatShell {
|
||||
|
||||
// 监听下线通知并同步到 WebUI
|
||||
this.core.event.on('KickedOffLine', (tips: string) => {
|
||||
WebUiDataRuntime.setQQLoginStatus(false);
|
||||
WebUiDataRuntime.setQQLoginError(tips);
|
||||
});
|
||||
// 使用 NapCatAdapterManager 统一管理协议适配器
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".."
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"rootDir": "..",
|
||||
"baseUrl": ".",
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"skipLibCheck": true,
|
||||
@@ -11,25 +10,31 @@
|
||||
"noEmitOnError": false,
|
||||
"paths": {
|
||||
"napcat-core": [
|
||||
"../napcat-core/index.ts"
|
||||
"../../packages/napcat-core/index.ts"
|
||||
],
|
||||
"napcat-onebot": [
|
||||
"../napcat-onebot/index.ts"
|
||||
"../../packages/napcat-onebot/index.ts"
|
||||
],
|
||||
"napcat-common/src/*": [
|
||||
"../../packages/napcat-common/src/*"
|
||||
],
|
||||
"napcat-image-size/src/*": [
|
||||
"../../packages/napcat-image-size/src/*"
|
||||
],
|
||||
"@/napcat-core/*": [
|
||||
"../napcat-core/*"
|
||||
"../../packages/napcat-core/*"
|
||||
],
|
||||
"@/napcat-onebot/*": [
|
||||
"../napcat-onebot/*"
|
||||
"../../packages/napcat-onebot/*"
|
||||
],
|
||||
"@/napcat-common/*": [
|
||||
"../napcat-common/*"
|
||||
"../../packages/napcat-common/*"
|
||||
],
|
||||
"@/napcat-webui-backend/*": [
|
||||
"../napcat-webui-backend/*"
|
||||
"../../packages/napcat-webui-backend/*"
|
||||
],
|
||||
"@/*": [
|
||||
"../*"
|
||||
"../../packages/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -47,8 +47,8 @@ function validateVersion (version) {
|
||||
* 版本号来源优先级:
|
||||
* 1. 环境变量 NAPCAT_VERSION (用于 CI 构建)
|
||||
* 2. 缓存的 GitHub tag
|
||||
* 3. 从 GitHub API 获取最新 tag
|
||||
* 4. 兆底版本号: 1.0.0-dev
|
||||
* 3. 从 GitHub API 获取最新公开 tag(不携带 token)
|
||||
* 4. 兜底版本号: 1.0.0-dev
|
||||
*/
|
||||
export default function vitePluginNapcatVersion () {
|
||||
const pluginDir = path.resolve(__dirname, 'dist');
|
||||
@@ -56,7 +56,6 @@ export default function vitePluginNapcatVersion () {
|
||||
const owner = 'NapNeko';
|
||||
const repo = 'NapCatQQ';
|
||||
const maxAgeMs = 24 * 60 * 60 * 1000; // cache 1 day
|
||||
const githubToken = process.env.GITHUB_TOKEN;
|
||||
// CI 构建时可通过环境变量直接指定版本号
|
||||
const envVersion = process.env.NAPCAT_VERSION;
|
||||
const fallbackVersion = '1.0.0-dev';
|
||||
@@ -92,7 +91,6 @@ export default function vitePluginNapcatVersion () {
|
||||
headers: {
|
||||
'User-Agent': 'vite-plugin-napcat-version',
|
||||
Accept: 'application/vnd.github.v3+json',
|
||||
...(githubToken ? { Authorization: `token ${githubToken}` } : {}),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { RequestHandler } from 'express';
|
||||
import { AuthHelper } from '@/napcat-webui-backend/src/helper/SignToken';
|
||||
import { PasskeyHelper } from '@/napcat-webui-backend/src/helper/PasskeyHelper';
|
||||
import { TotpHelper } from '@/napcat-webui-backend/src/helper/TotpHelper';
|
||||
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
|
||||
import { sendSuccess, sendError } from '@/napcat-webui-backend/src/utils/response';
|
||||
import { isEmpty } from '@/napcat-webui-backend/src/utils/check';
|
||||
import { WebUiConfig, getInitialWebUiToken, setInitialWebUiToken } from '@/napcat-webui-backend/index';
|
||||
|
||||
// 登录
|
||||
// 登录 - 支持2FA验证
|
||||
export const LoginHandler: RequestHandler = async (req, res) => {
|
||||
// 获取WebUI配置
|
||||
const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
|
||||
// 获取请求体中的hash
|
||||
const { hash } = req.body;
|
||||
// 获取请求体中的hash和totpCode
|
||||
const { hash, totpCode } = req.body;
|
||||
// 获取客户端IP
|
||||
const clientIP = req.ip || req.socket.remoteAddress || '';
|
||||
|
||||
@@ -33,11 +34,31 @@ export const LoginHandler: RequestHandler = async (req, res) => {
|
||||
return sendError(res, 'token is invalid');
|
||||
}
|
||||
|
||||
// 签发凭证
|
||||
const signCredential = Buffer.from(JSON.stringify(AuthHelper.signCredential(hash))).toString(
|
||||
'base64'
|
||||
);
|
||||
// 返回成功信息
|
||||
// 检查是否启用了2FA
|
||||
if (WebUiConfigData.enable2FA && WebUiConfigData.totpSecret) {
|
||||
// 如果没有提供验证码,返回要求验证码
|
||||
if (!totpCode) {
|
||||
return sendSuccess(res, {
|
||||
require2FA: true,
|
||||
message: 'Please enter your authenticator code',
|
||||
});
|
||||
}
|
||||
|
||||
// 验证TOTP验证码
|
||||
if (!TotpHelper.verifyTotp(WebUiConfigData.totpSecret, totpCode)) {
|
||||
return sendError(res, 'Invalid or expired code');
|
||||
}
|
||||
|
||||
// 2FA验证成功,签发凭证
|
||||
const signCredential = Buffer.from(JSON.stringify(AuthHelper.signCredential(hash))).toString('base64');
|
||||
return sendSuccess(res, {
|
||||
Credential: signCredential,
|
||||
require2FA: false,
|
||||
});
|
||||
}
|
||||
|
||||
// 未启用2FA,直接签发凭证
|
||||
const signCredential = Buffer.from(JSON.stringify(AuthHelper.signCredential(hash))).toString('base64');
|
||||
return sendSuccess(res, {
|
||||
Credential: signCredential,
|
||||
});
|
||||
@@ -261,3 +282,85 @@ export const VerifyPasskeyAuthenticationHandler: RequestHandler = async (req, re
|
||||
return sendError(res, `Authentication verification failed: ${(error as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 获取2FA状态
|
||||
export const Get2FAStatusHandler: RequestHandler = async (_req, res) => {
|
||||
try {
|
||||
const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
|
||||
return sendSuccess(res, {
|
||||
enable2FA: WebUiConfigData.enable2FA || false,
|
||||
hasSecret: !!WebUiConfigData.totpSecret,
|
||||
});
|
||||
} catch (error) {
|
||||
return sendError(res, `获取2FA状态失败: ${(error as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 生成2FA密钥
|
||||
export const Generate2FASecretHandler: RequestHandler = async (_req, res) => {
|
||||
try {
|
||||
const secret = TotpHelper.generateSecret();
|
||||
const qrCodeUrl = TotpHelper.generateQrCodeUrl(secret, 'NapCat WebUI', 'NapCat');
|
||||
|
||||
return sendSuccess(res, {
|
||||
secret,
|
||||
qrCodeUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
return sendError(res, `Failed to generate 2FA secret: ${(error as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 启用2FA
|
||||
export const Enable2FAHandler: RequestHandler = async (req, res) => {
|
||||
try {
|
||||
const { secret, totpCode } = req.body;
|
||||
|
||||
if (!secret || !totpCode) {
|
||||
return sendError(res, 'secret and totpCode are required');
|
||||
}
|
||||
|
||||
if (!TotpHelper.verifyTotp(secret, totpCode)) {
|
||||
return sendError(res, 'Invalid code');
|
||||
}
|
||||
|
||||
await WebUiConfig.UpdateWebUIConfig({
|
||||
enable2FA: true,
|
||||
totpSecret: secret,
|
||||
});
|
||||
|
||||
return sendSuccess(res, { message: '2FA enabled' });
|
||||
} catch (error) {
|
||||
return sendError(res, `Failed to enable 2FA: ${(error as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 禁用2FA - 需要验证当前TOTP代码
|
||||
export const Disable2FAHandler: RequestHandler = async (req, res) => {
|
||||
try {
|
||||
const { totpCode } = req.body;
|
||||
|
||||
if (!totpCode) {
|
||||
return sendError(res, 'totpCode is required to disable 2FA');
|
||||
}
|
||||
|
||||
const WebUiConfigData = await WebUiConfig.GetWebUIConfig();
|
||||
if (!WebUiConfigData.totpSecret) {
|
||||
return sendError(res, '2FA is not enabled');
|
||||
}
|
||||
|
||||
// 验证当前TOTP代码
|
||||
if (!TotpHelper.verifyTotp(WebUiConfigData.totpSecret, totpCode)) {
|
||||
return sendError(res, 'Invalid code');
|
||||
}
|
||||
|
||||
await WebUiConfig.UpdateWebUIConfig({
|
||||
enable2FA: false,
|
||||
totpSecret: '',
|
||||
});
|
||||
|
||||
return sendSuccess(res, { message: '2FA disabled' });
|
||||
} catch (error) {
|
||||
return sendError(res, `Failed to disable 2FA: ${(error as Error).message}`);
|
||||
}
|
||||
};
|
||||
@@ -40,6 +40,7 @@ interface UpdateConfig {
|
||||
const SKIP_UPDATE_FILES = [
|
||||
'NapCatWinBootMain.exe',
|
||||
'NapCatWinBootHook.dll',
|
||||
'quickLoginExample.bat',
|
||||
];
|
||||
|
||||
// 更新时若文件已存在则保留(不覆盖)的用户配置文件(使用相对路径精确匹配)
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
/**
|
||||
* TOTP (Time-based One-Time Password) Helper
|
||||
* 用于生成和验证基于时间的一次性密码
|
||||
*/
|
||||
export class TotpHelper {
|
||||
/**
|
||||
* 生成随机密钥(Base32格式)
|
||||
* @param length 密钥长度(字节),默认16字节
|
||||
* @returns Base32编码的密钥
|
||||
*/
|
||||
static generateSecret(length: number = 16): string {
|
||||
const buffer = crypto.randomBytes(length);
|
||||
return this.toBase32(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证一次性密码
|
||||
* @param secret Base32编码的密钥
|
||||
* @param code 用户输入的验证码
|
||||
* @param timeStep 时间步长(秒),默认30秒
|
||||
* @param window 允许的时间窗口(前后各多少个时间步长),默认1
|
||||
* @returns 是否验证通过
|
||||
*/
|
||||
static verifyTotp(
|
||||
secret: string,
|
||||
code: string,
|
||||
timeStep: number = 30,
|
||||
window: number = 1
|
||||
): boolean {
|
||||
const time = Math.floor(Date.now() / 1000 / timeStep);
|
||||
|
||||
// 检查前后 window 个时间步长
|
||||
for (let i = -window; i <= window; i++) {
|
||||
const candidateCode = this.generateHotp(secret, time + i);
|
||||
if (candidateCode === code) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 HOTP (HMAC-based One-Time Password)
|
||||
* @param secret Base32编码的密钥
|
||||
* @param counter 计数器
|
||||
* @returns 6位数字验证码
|
||||
*/
|
||||
private static generateHotp(secret: string, counter: number): string {
|
||||
// 将 Base32 密钥转换为字节
|
||||
const key = this.base32ToBytes(secret);
|
||||
|
||||
// 将计数器转换为 8 字节大端序
|
||||
const counterBytes = Buffer.alloc(8);
|
||||
let tempCounter = counter;
|
||||
for (let i = 7; i >= 0; i--) {
|
||||
counterBytes[i] = tempCounter & 0xff;
|
||||
tempCounter = Math.floor(tempCounter / 256);
|
||||
}
|
||||
|
||||
// 计算 HMAC-SHA1
|
||||
const hmac = crypto.createHmac('sha1', key);
|
||||
hmac.update(counterBytes);
|
||||
const hash = hmac.digest();
|
||||
|
||||
// 动态截断
|
||||
const hashLength = hash.length;
|
||||
const lastByte = hash[hashLength - 1];
|
||||
if (lastByte === undefined) {
|
||||
return '000000';
|
||||
}
|
||||
const offset = lastByte & 0x0f;
|
||||
const byte0 = hash[offset] ?? 0;
|
||||
const byte1 = hash[offset + 1] ?? 0;
|
||||
const byte2 = hash[offset + 2] ?? 0;
|
||||
const byte3 = hash[offset + 3] ?? 0;
|
||||
const binary =
|
||||
((byte0 & 0x7f) << 24) |
|
||||
((byte1 & 0xff) << 16) |
|
||||
((byte2 & 0xff) << 8) |
|
||||
(byte3 & 0xff);
|
||||
|
||||
// 生成 6 位数字
|
||||
const otp = binary % 1000000;
|
||||
return otp.toString().padStart(6, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 QR Code URL
|
||||
* @param secret Base32编码的密钥
|
||||
* @param account 账户名称
|
||||
* @param issuer 发行方名称
|
||||
* @returns otpauth:// URL
|
||||
*/
|
||||
static generateQrCodeUrl(
|
||||
secret: string,
|
||||
account: string,
|
||||
issuer: string
|
||||
): string {
|
||||
const encodedIssuer = encodeURIComponent(issuer);
|
||||
const encodedAccount = encodeURIComponent(`${issuer}:${account}`);
|
||||
return `otpauth://totp/${encodedAccount}?secret=${secret}&issuer=${encodedIssuer}&algorithm=SHA1&digits=6&period=30`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组转换为 Base32 编码
|
||||
* @param buffer 字节数组
|
||||
* @returns Base32编码字符串
|
||||
*/
|
||||
private static toBase32(buffer: Buffer): string {
|
||||
const base32Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
let output = '';
|
||||
|
||||
for (let i = 0; i < buffer.length; i += 5) {
|
||||
const b0 = buffer[i] ?? 0;
|
||||
const b1 = buffer[i + 1] ?? 0;
|
||||
const b2 = buffer[i + 2] ?? 0;
|
||||
const b3 = buffer[i + 3] ?? 0;
|
||||
const b4 = buffer[i + 4] ?? 0;
|
||||
|
||||
output += base32Alphabet[(b0 >> 3) & 0x1f];
|
||||
output += base32Alphabet[((b0 << 2) | (b1 >> 6)) & 0x1f];
|
||||
output += base32Alphabet[(b1 >> 1) & 0x1f];
|
||||
output += base32Alphabet[((b1 << 4) | (b2 >> 4)) & 0x1f];
|
||||
output += base32Alphabet[((b2 << 1) | (b3 >> 7)) & 0x1f];
|
||||
output += base32Alphabet[(b3 >> 2) & 0x1f];
|
||||
output += base32Alphabet[((b3 << 3) | (b4 >> 5)) & 0x1f];
|
||||
output += base32Alphabet[b4 & 0x1f];
|
||||
}
|
||||
|
||||
// 移除填充的等号
|
||||
return output.replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Base32 字符串转换为字节数组
|
||||
* @param base32 Base32编码字符串
|
||||
* @returns 字节数组
|
||||
*/
|
||||
private static base32ToBytes(base32: string): Buffer {
|
||||
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
const base32Clean = base32.toUpperCase().replace(/=+$/, '');
|
||||
|
||||
const bytes: number[] = [];
|
||||
let buffer = 0;
|
||||
let bitsLeft = 0;
|
||||
|
||||
for (const char of base32Clean) {
|
||||
const value = alphabet.indexOf(char);
|
||||
if (value === -1) continue;
|
||||
|
||||
buffer = (buffer << 5) | value;
|
||||
bitsLeft += 5;
|
||||
|
||||
if (bitsLeft >= 8) {
|
||||
bytes.push((buffer >> (bitsLeft - 8)) & 0xff);
|
||||
bitsLeft -= 8;
|
||||
}
|
||||
}
|
||||
|
||||
return Buffer.from(bytes);
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,10 @@ const WebUiConfigSchema = Type.Object({
|
||||
ipBlacklist: Type.Array(Type.String(), { default: [] }),
|
||||
// 是否启用 X-Forwarded-For 获取真实IP
|
||||
enableXForwardedFor: Type.Boolean({ default: false }),
|
||||
// 是否启用双因素认证(2FA)
|
||||
enable2FA: Type.Boolean({ default: false }),
|
||||
// TOTP 密钥
|
||||
totpSecret: Type.String({ default: '' }),
|
||||
});
|
||||
|
||||
export type WebUiConfigType = Static<typeof WebUiConfigSchema>;
|
||||
|
||||
@@ -9,6 +9,10 @@ import {
|
||||
VerifyPasskeyRegistrationHandler,
|
||||
GeneratePasskeyAuthenticationOptionsHandler,
|
||||
VerifyPasskeyAuthenticationHandler,
|
||||
Get2FAStatusHandler,
|
||||
Generate2FASecretHandler,
|
||||
Enable2FAHandler,
|
||||
Disable2FAHandler,
|
||||
} from '@/napcat-webui-backend/src/api/Auth';
|
||||
|
||||
const router: Router = Router();
|
||||
@@ -28,5 +32,13 @@ router.post('/passkey/verify-registration', VerifyPasskeyRegistrationHandler);
|
||||
router.post('/passkey/generate-authentication-options', GeneratePasskeyAuthenticationOptionsHandler);
|
||||
// router:验证Passkey认证
|
||||
router.post('/passkey/verify-authentication', VerifyPasskeyAuthenticationHandler);
|
||||
// router:获取2FA状态
|
||||
router.get('/2fa/status', Get2FAStatusHandler);
|
||||
// router:生成2FA密钥
|
||||
router.post('/2fa/generate-secret', Generate2FASecretHandler);
|
||||
// router:启用2FA
|
||||
router.post('/2fa/enable', Enable2FAHandler);
|
||||
// router:禁用2FA
|
||||
router.post('/2fa/disable', Disable2FAHandler);
|
||||
|
||||
export { router as AuthRouter };
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".."
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"src/**/*.ts",
|
||||
|
||||
@@ -17,13 +17,43 @@ export default class WebUIManager {
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async loginWithToken (token: string) {
|
||||
public static async loginWithToken (token: string, totpCode?: string) {
|
||||
const sha256 = CryptoJS.SHA256(token + '.napcat').toString();
|
||||
const { data } = await serverRequest.post<ServerResponse<AuthResponse>>(
|
||||
'/auth/login',
|
||||
{ hash: sha256 }
|
||||
{ hash: sha256, totpCode }
|
||||
);
|
||||
return data.data.Credential;
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async get2FAStatus () {
|
||||
const { data } = await serverRequest.get<ServerResponse<{ enable2FA: boolean; hasSecret: boolean; }>>(
|
||||
'/auth/2fa/status'
|
||||
);
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async generate2FASecret () {
|
||||
const { data } = await serverRequest.post<ServerResponse<{ secret: string; qrCodeUrl: string; }>>(
|
||||
'/auth/2fa/generate-secret'
|
||||
);
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async enable2FA (secret: string, totpCode: string) {
|
||||
const { data } = await serverRequest.post<ServerResponse<{ message: string; }>>(
|
||||
'/auth/2fa/enable',
|
||||
{ secret, totpCode }
|
||||
);
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async disable2FA (totpCode: string) {
|
||||
const { data } = await serverRequest.post<ServerResponse<{ message: string; }>>(
|
||||
'/auth/2fa/disable',
|
||||
{ totpCode }
|
||||
);
|
||||
return data.data;
|
||||
}
|
||||
|
||||
public static async changePassword (oldToken: string, newToken: string) {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -6,7 +6,8 @@ import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
|
||||
import key from '@/const/key';
|
||||
|
||||
import ChangePasswordCard from './change_password';
|
||||
//把修改密码移动到WebUI栏目中
|
||||
//import ChangePasswordCard from './change_password';
|
||||
import LoginConfigCard from './login';
|
||||
import OneBotConfigCard from './onebot';
|
||||
import ServerConfigCard from './server';
|
||||
@@ -101,11 +102,16 @@ export default function ConfigPage () {
|
||||
<LoginConfigCard />
|
||||
</ConfigPageItem>
|
||||
</Tab>
|
||||
//把修改密码移动到WebUI栏目中
|
||||
{
|
||||
/*
|
||||
<Tab title='修改密码' key='token'>
|
||||
<ConfigPageItem size='sm'>
|
||||
<ChangePasswordCard />
|
||||
</ConfigPageItem>
|
||||
</Tab>
|
||||
*/
|
||||
}
|
||||
|
||||
<Tab title='主题配置' key='theme'>
|
||||
<ConfigPageItem size='lg'>
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Button } from '@heroui/button';
|
||||
import { Input } from '@heroui/input';
|
||||
import { useLocalStorage } from '@uidotdev/usehooks';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { IoQrCode } from 'react-icons/io5';
|
||||
import { QRCodeSVG } from 'qrcode.react';
|
||||
|
||||
import key from '@/const/key';
|
||||
|
||||
@@ -50,6 +54,118 @@ const WebUIConfigCard = () => {
|
||||
const [registrationOptions, setRegistrationOptions] = useState<any>(null);
|
||||
const [isLoadingOptions, setIsLoadingOptions] = useState(false);
|
||||
|
||||
// 2FA 相关状态
|
||||
const [twoFAStatus, setTwoFAStatus] = useState<{ enable2FA: boolean; hasSecret: boolean }>({ enable2FA: false, hasSecret: false });
|
||||
const [twoFASecret, setTwoFASecret] = useState<string>('');
|
||||
const [twoFAQrCodeUrl, setTwoFAQrCodeUrl] = useState<string>('');
|
||||
const [twoFATotpCode, setTwoFATotpCode] = useState<string>('');
|
||||
const [disableTotpCode, setDisableTotpCode] = useState<string>('');
|
||||
const [isGeneratingSecret, setIsGeneratingSecret] = useState(false);
|
||||
const [isEnabling2FA, setIsEnabling2FA] = useState(false);
|
||||
const [isDisabling2FA, setIsDisabling2FA] = useState(false);
|
||||
|
||||
const loadTwoFAStatus = async () => {
|
||||
try {
|
||||
const status = await WebUIManager.get2FAStatus();
|
||||
setTwoFAStatus(status);
|
||||
} catch (error) {
|
||||
console.error('获取2FA状态失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const generateTwoFASecret = async () => {
|
||||
setIsGeneratingSecret(true);
|
||||
try {
|
||||
const data = await WebUIManager.generate2FASecret();
|
||||
setTwoFASecret(data.secret);
|
||||
setTwoFAQrCodeUrl(data.qrCodeUrl);
|
||||
toast.success('密钥已生成,请使用Authenticator应用扫码');
|
||||
} catch (error) {
|
||||
toast.error(`生成密钥失败: ${(error as Error).message}`);
|
||||
} finally {
|
||||
setIsGeneratingSecret(false);
|
||||
}
|
||||
};
|
||||
|
||||
const enableTwoFA = async () => {
|
||||
if (!twoFASecret || !twoFATotpCode) {
|
||||
toast.error('请先生成密钥并输入验证码');
|
||||
return;
|
||||
}
|
||||
if (twoFATotpCode.length !== 6) {
|
||||
toast.error('验证码必须是6位数字');
|
||||
return;
|
||||
}
|
||||
setIsEnabling2FA(true);
|
||||
try {
|
||||
await WebUIManager.enable2FA(twoFASecret, twoFATotpCode);
|
||||
await loadTwoFAStatus();
|
||||
setTwoFASecret('');
|
||||
setTwoFAQrCodeUrl('');
|
||||
setTwoFATotpCode('');
|
||||
toast.success('双因素认证已启用');
|
||||
} catch (error) {
|
||||
toast.error(`启用失败: ${(error as Error).message}`);
|
||||
} finally {
|
||||
setIsEnabling2FA(false);
|
||||
}
|
||||
};
|
||||
|
||||
const disableTwoFA = async () => {
|
||||
if (!disableTotpCode || disableTotpCode.length !== 6) {
|
||||
toast.error('请输入6位验证码');
|
||||
return;
|
||||
}
|
||||
setIsDisabling2FA(true);
|
||||
try {
|
||||
await WebUIManager.disable2FA(disableTotpCode);
|
||||
await loadTwoFAStatus();
|
||||
setDisableTotpCode('');
|
||||
toast.success('双因素认证已禁用');
|
||||
} catch (error) {
|
||||
toast.error(`禁用失败: ${(error as Error).message}`);
|
||||
} finally {
|
||||
setIsDisabling2FA(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadTwoFAStatus();
|
||||
}, []);
|
||||
|
||||
// 修改密码独立表单
|
||||
const navigate = useNavigate();
|
||||
const [, setToken] = useLocalStorage(key.token, '');
|
||||
const {
|
||||
control: pwdControl,
|
||||
handleSubmit: handlePwdSubmit,
|
||||
formState: { isSubmitting: isPwdSubmitting, errors: pwdErrors },
|
||||
watch,
|
||||
} = useForm<{
|
||||
oldToken: string;
|
||||
newToken: string;
|
||||
}>({
|
||||
defaultValues: {
|
||||
oldToken: '',
|
||||
newToken: '',
|
||||
},
|
||||
});
|
||||
const oldTokenValue = watch('oldToken');
|
||||
|
||||
// 修复类型错误:显式包装为无参函数,满足 onPress 的类型要求
|
||||
const onPasswordSubmit = handlePwdSubmit(async (data) => {
|
||||
try {
|
||||
await WebUIManager.changePassword(data.oldToken, data.newToken);
|
||||
toast.success('修改成功');
|
||||
setToken('');
|
||||
localStorage.removeItem(key.token);
|
||||
navigate('/web_login');
|
||||
} catch (error) {
|
||||
const msg = (error as Error).message;
|
||||
toast.error(`修改失败: ${msg}`);
|
||||
}
|
||||
});
|
||||
|
||||
// 预先获取注册选项(可以在任何时候调用)
|
||||
const preloadRegistrationOptions = async () => {
|
||||
setIsLoadingOptions(true);
|
||||
@@ -90,6 +206,86 @@ const WebUIConfigCard = () => {
|
||||
return (
|
||||
<>
|
||||
<title>WebUI配置 - NapCat WebUI</title>
|
||||
|
||||
{/* 修改密码区块 - 移到顶部 */}
|
||||
<div className='flex flex-col gap-4'>
|
||||
<div className='flex-shrink-0 w-full font-bold text-default-600 dark:text-default-400 px-1'>修改密码</div>
|
||||
<Controller
|
||||
control={pwdControl}
|
||||
name='oldToken'
|
||||
rules={{
|
||||
required: '旧密码不能为空',
|
||||
validate: (value) => {
|
||||
if (!value || value.trim().length === 0) {
|
||||
return '旧密码不能为空';
|
||||
}
|
||||
return true;
|
||||
},
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<Input
|
||||
{...field}
|
||||
label='旧密码'
|
||||
placeholder='请输入旧密码'
|
||||
type='password'
|
||||
isRequired
|
||||
isInvalid={!!pwdErrors.oldToken}
|
||||
errorMessage={pwdErrors.oldToken?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
control={pwdControl}
|
||||
name='newToken'
|
||||
rules={{
|
||||
required: '新密码不能为空',
|
||||
minLength: {
|
||||
value: 6,
|
||||
message: '新密码至少需要6个字符',
|
||||
},
|
||||
validate: (value) => {
|
||||
if (!value || value.trim().length === 0) {
|
||||
return '新密码不能为空';
|
||||
}
|
||||
if (value.trim().length !== value.length) {
|
||||
return '新密码不能包含前后空格';
|
||||
}
|
||||
if (value === oldTokenValue) {
|
||||
return '新密码不能与旧密码相同';
|
||||
}
|
||||
if (!/[a-zA-Z]/.test(value)) {
|
||||
return '新密码必须包含字母';
|
||||
}
|
||||
if (!/[0-9]/.test(value)) {
|
||||
return '新密码必须包含数字';
|
||||
}
|
||||
return true;
|
||||
},
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<Input
|
||||
{...field}
|
||||
label='新密码'
|
||||
placeholder='至少6位,包含字母和数字'
|
||||
type='password'
|
||||
isRequired
|
||||
isInvalid={!!pwdErrors.newToken}
|
||||
errorMessage={pwdErrors.newToken?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{/* 自定义确认按钮,无取消按钮;onPress 调用 onPasswordSubmit(已通过 handlePwdSubmit 包装,类型兼容) */}
|
||||
<div className='flex justify-end'>
|
||||
<Button
|
||||
color='primary'
|
||||
onPress={() => { onPasswordSubmit(); }}
|
||||
isLoading={isPwdSubmitting}
|
||||
>
|
||||
确认修改密码
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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'>背景图</div>
|
||||
<Controller
|
||||
@@ -121,134 +317,241 @@ 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。
|
||||
{!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
|
||||
</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>
|
||||
|
||||
{/* 双因素认证 (2FA) */}
|
||||
<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 flex items-center gap-2'>
|
||||
<span>双因素认证 (2FA)</span>
|
||||
<span className={`text-sm px-2 py-0.5 rounded-full ${twoFAStatus.enable2FA ? 'bg-green-100 text-green-700' : 'bg-default-200 text-default-600'}`}>
|
||||
{twoFAStatus.enable2FA ? '已启用' : '已禁用'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{twoFAStatus.enable2FA ? (
|
||||
<div className='bg-green-50 border border-green-200 rounded-lg p-4'>
|
||||
<div className='text-sm text-green-700 mb-3'>✅ 双因素认证已启用</div>
|
||||
<div className='mb-3'>
|
||||
<div className='text-sm text-default-600 mb-2'>输入验证码以禁用</div>
|
||||
<input
|
||||
type='text'
|
||||
inputMode='numeric'
|
||||
pattern='[0-9]*'
|
||||
maxLength={6}
|
||||
value={disableTotpCode}
|
||||
onChange={(e) => setDisableTotpCode(e.target.value.replace(/\D/g, ''))}
|
||||
placeholder='000000'
|
||||
className='w-32 px-3 py-2 border border-default-300 rounded-lg text-center text-lg tracking-widest'
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
color='danger'
|
||||
variant='flat'
|
||||
onPress={disableTwoFA}
|
||||
isLoading={isDisabling2FA}
|
||||
disabled={!disableTotpCode || disableTotpCode.length !== 6}
|
||||
className='w-fit'
|
||||
>
|
||||
禁用双因素认证
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className='text-sm text-default-400 mb-2'>
|
||||
注册Passkey后,您可以更便捷地登录WebUI,无需每次输入token
|
||||
启用双因素认证后,登录时需要额外输入Authenticator应用生成的验证码
|
||||
</div>
|
||||
<div className='flex gap-2'>
|
||||
<div className='bg-default-50 border border-default-200 rounded-lg p-4'>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='flat'
|
||||
onPress={preloadRegistrationOptions}
|
||||
isLoading={isLoadingOptions}
|
||||
className='w-fit'
|
||||
onPress={generateTwoFASecret}
|
||||
isLoading={isGeneratingSecret}
|
||||
className='w-fit mb-4'
|
||||
>
|
||||
{!isLoadingOptions}
|
||||
准备选项
|
||||
<IoQrCode className='mr-2' />
|
||||
生成密钥
|
||||
</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>
|
||||
{twoFASecret && (
|
||||
<>
|
||||
<div className='mb-4'>
|
||||
<div className='text-sm text-default-600 mb-2'>请使用 Authenticator 应用扫描下方二维码</div>
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='bg-white border border-default-300 rounded-lg p-3'>
|
||||
<QRCodeSVG
|
||||
value={twoFAQrCodeUrl}
|
||||
size={128}
|
||||
level='M'
|
||||
includeMargin={false}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className='text-xs text-default-500 mb-1'>密钥(手动输入用)</div>
|
||||
<div className='font-mono text-sm bg-default-100 px-3 py-2 rounded break-all max-w-[200px]'>
|
||||
{twoFASecret}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='mb-4'>
|
||||
<div className='text-sm text-default-600 mb-2'>输入Authenticator验证码</div>
|
||||
<input
|
||||
type='text'
|
||||
inputMode='numeric'
|
||||
pattern='[0-9]*'
|
||||
maxLength={6}
|
||||
value={twoFATotpCode}
|
||||
onChange={(e) => setTwoFATotpCode(e.target.value.replace(/\D/g, ''))}
|
||||
placeholder='000000'
|
||||
className='w-32 px-3 py-2 border border-default-300 rounded-lg text-center text-lg tracking-widest'
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
color='primary'
|
||||
variant='flat'
|
||||
onPress={enableTwoFA}
|
||||
isLoading={isEnabling2FA}
|
||||
disabled={!twoFATotpCode || twoFATotpCode.length !== 6}
|
||||
className='w-fit'
|
||||
>
|
||||
启用双因素认证
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{registrationOptions && (
|
||||
<div className='text-xs text-green-600'>
|
||||
注册选项已准备就绪,可以开始注册
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SaveButtons
|
||||
onSubmit={onSubmit}
|
||||
reset={reset}
|
||||
@@ -258,4 +561,4 @@ const WebUIConfigCard = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default WebUIConfigCard;
|
||||
export default WebUIConfigCard;
|
||||
@@ -5,7 +5,7 @@ import { Input } from '@heroui/input';
|
||||
import { useLocalStorage } from '@uidotdev/usehooks';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { IoKeyOutline } from 'react-icons/io5';
|
||||
import { IoKeyOutline, IoArrowBack } from 'react-icons/io5';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
import logo from '@/assets/images/logo.png';
|
||||
@@ -29,6 +29,11 @@ export default function WebLoginPage () {
|
||||
const [isPasskeyLoading, setIsPasskeyLoading] = useState<boolean>(true); // 初始为true,表示正在检查passkey
|
||||
const [, setLocalToken] = useLocalStorage<string>(key.token, '');
|
||||
|
||||
// 2FA相关状态
|
||||
const [require2FA, setRequire2FA] = useState<boolean>(false);
|
||||
const [totpCode, setTotpCode] = useState<string>('');
|
||||
const [pendingToken, setPendingToken] = useState<string>('');
|
||||
|
||||
// Helper function to decode base64url
|
||||
function base64UrlToUint8Array (base64Url: string): Uint8Array {
|
||||
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
|
||||
@@ -102,10 +107,10 @@ export default function WebLoginPage () {
|
||||
return false; // 登录失败
|
||||
};
|
||||
|
||||
const onSubmit = async () => {
|
||||
// 第一次登录(输入token)
|
||||
const onSubmitToken = async () => {
|
||||
if (!tokenValue) {
|
||||
toast.error('请输入token');
|
||||
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
@@ -113,7 +118,18 @@ export default function WebLoginPage () {
|
||||
const data = await WebUIManager.loginWithToken(tokenValue);
|
||||
|
||||
if (data) {
|
||||
setLocalToken(data);
|
||||
if (data.require2FA) {
|
||||
// 需要2FA验证
|
||||
setRequire2FA(true);
|
||||
setPendingToken(tokenValue);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 不需要2FA,直接登录
|
||||
if (data.Credential) {
|
||||
setLocalToken(data.Credential);
|
||||
}
|
||||
navigate('/qq_login', { replace: true });
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -123,10 +139,42 @@ export default function WebLoginPage () {
|
||||
}
|
||||
};
|
||||
|
||||
// 2FA验证提交
|
||||
const onSubmit2FA = async () => {
|
||||
if (!totpCode || totpCode.length !== 6) {
|
||||
toast.error('Please enter 6-digit code');
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await WebUIManager.loginWithToken(pendingToken, totpCode);
|
||||
|
||||
if (data && data.Credential) {
|
||||
setLocalToken(data.Credential);
|
||||
navigate('/qq_login', { replace: true });
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error((error as Error).message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 返回token输入步骤
|
||||
const goBackToToken = () => {
|
||||
setRequire2FA(false);
|
||||
setTotpCode('');
|
||||
setPendingToken('');
|
||||
};
|
||||
|
||||
// 处理全局键盘事件
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !isLoading && !isPasskeyLoading) {
|
||||
onSubmit();
|
||||
if (require2FA) {
|
||||
onSubmit2FA();
|
||||
} else {
|
||||
onSubmitToken();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -137,14 +185,14 @@ export default function WebLoginPage () {
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [tokenValue, isLoading, isPasskeyLoading]); // 依赖项包含用于登录的状态
|
||||
}, [tokenValue, totpCode, isLoading, isPasskeyLoading, require2FA]); // 依赖项包含用于登录的状态
|
||||
|
||||
useEffect(() => {
|
||||
// 如果URL中有token,直接登录
|
||||
if (token) {
|
||||
// 不需要检查passkey,立即清除loading状态,避免登录失败后输入框被永久禁用
|
||||
setIsPasskeyLoading(false);
|
||||
onSubmit();
|
||||
onSubmitToken();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -188,86 +236,161 @@ export default function WebLoginPage () {
|
||||
🔐 正在检查Passkey...
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmit();
|
||||
}}
|
||||
>
|
||||
{/* 隐藏的用户名字段,帮助浏览器识别登录表单 */}
|
||||
<input
|
||||
type='text'
|
||||
name='username'
|
||||
value='napcat-webui'
|
||||
autoComplete='username'
|
||||
className='absolute -left-[9999px] opacity-0 pointer-events-none'
|
||||
readOnly
|
||||
tabIndex={-1}
|
||||
aria-label='Username'
|
||||
/>
|
||||
<Input
|
||||
isClearable
|
||||
type='password'
|
||||
name='password'
|
||||
autoComplete='current-password'
|
||||
classNames={{
|
||||
label: 'text-black/50 dark:text-white/90',
|
||||
input: [
|
||||
'bg-transparent',
|
||||
'text-black/90 dark:text-white/90',
|
||||
'placeholder:text-default-700/50 dark:placeholder:text-white/60',
|
||||
],
|
||||
innerWrapper: 'bg-transparent',
|
||||
inputWrapper: [
|
||||
'shadow-xl',
|
||||
'bg-default-100/70',
|
||||
'dark:bg-default/60',
|
||||
'backdrop-blur-xl',
|
||||
'backdrop-saturate-200',
|
||||
'hover:bg-default-0/70',
|
||||
'dark:hover:bg-default/70',
|
||||
'group-data-[focus=true]:bg-default-100/50',
|
||||
'dark:group-data-[focus=true]:bg-default/60',
|
||||
'!cursor-text',
|
||||
],
|
||||
}}
|
||||
isDisabled={isLoading || isPasskeyLoading}
|
||||
label='Token'
|
||||
placeholder='请输入token'
|
||||
radius='lg'
|
||||
size='lg'
|
||||
startContent={
|
||||
<IoKeyOutline className='text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0' />
|
||||
}
|
||||
value={tokenValue}
|
||||
onChange={(e) => setTokenValue(e.target.value)}
|
||||
onClear={() => setTokenValue('')}
|
||||
/>
|
||||
</form>
|
||||
<div className='text-center text-small text-default-600 dark:text-default-400 px-2'>
|
||||
💡 提示:请从 NapCat 启动日志中查看登录密钥
|
||||
</div>
|
||||
<Button
|
||||
className='mx-10 mt-10 text-lg py-7'
|
||||
color='primary'
|
||||
isLoading={isLoading}
|
||||
radius='full'
|
||||
size='lg'
|
||||
variant='shadow'
|
||||
onPress={onSubmit}
|
||||
>
|
||||
{!isLoading && (
|
||||
<Image
|
||||
alt='logo'
|
||||
classNames={{
|
||||
wrapper: '-ml-8',
|
||||
|
||||
{/* 2FA验证步骤 */}
|
||||
{require2FA ? (
|
||||
<>
|
||||
<Button
|
||||
isIconOnly
|
||||
variant='light'
|
||||
className='self-start -ml-2'
|
||||
onPress={goBackToToken}
|
||||
>
|
||||
<IoArrowBack size={20} />
|
||||
</Button>
|
||||
<div className='text-center text-default-600 dark:text-default-400'>
|
||||
请输入Authenticator中的验证码
|
||||
</div>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmit2FA();
|
||||
}}
|
||||
height='2em'
|
||||
src={logo}
|
||||
/>
|
||||
)}
|
||||
登录
|
||||
</Button>
|
||||
>
|
||||
<Input
|
||||
type='text'
|
||||
inputMode='numeric'
|
||||
pattern='[0-9]*'
|
||||
maxLength={6}
|
||||
classNames={{
|
||||
label: 'text-black/50 dark:text-white/90',
|
||||
input: [
|
||||
'bg-transparent',
|
||||
'text-black/90 dark:text-white/90',
|
||||
'placeholder:text-default-700/50 dark:placeholder:text-white/60',
|
||||
],
|
||||
innerWrapper: 'bg-transparent',
|
||||
inputWrapper: [
|
||||
'shadow-xl',
|
||||
'bg-default-100/70',
|
||||
'dark:bg-default/60',
|
||||
'backdrop-blur-xl',
|
||||
'backdrop-saturate-200',
|
||||
'hover:bg-default-0/70',
|
||||
'dark:hover:bg-default/70',
|
||||
'group-data-[focus=true]:bg-default-100/50',
|
||||
'dark:group-data-[focus=true]:bg-default/60',
|
||||
'!cursor-text',
|
||||
],
|
||||
}}
|
||||
isDisabled={isLoading}
|
||||
label='验证码'
|
||||
placeholder='请输入6位验证码'
|
||||
radius='lg'
|
||||
size='lg'
|
||||
startContent={
|
||||
<IoKeyOutline className='text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0' />
|
||||
}
|
||||
value={totpCode}
|
||||
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, ''))}
|
||||
/>
|
||||
</form>
|
||||
<Button
|
||||
className='mx-10 mt-10 text-lg py-7'
|
||||
color='primary'
|
||||
isLoading={isLoading}
|
||||
radius='full'
|
||||
size='lg'
|
||||
variant='shadow'
|
||||
onPress={onSubmit2FA}
|
||||
>
|
||||
验证
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmitToken();
|
||||
}}
|
||||
>
|
||||
{/* 隐藏的用户名字段,帮助浏览器识别登录表单 */}
|
||||
<input
|
||||
type='text'
|
||||
name='username'
|
||||
value='napcat-webui'
|
||||
autoComplete='username'
|
||||
className='absolute -left-[9999px] opacity-0 pointer-events-none'
|
||||
readOnly
|
||||
tabIndex={-1}
|
||||
aria-label='Username'
|
||||
/>
|
||||
<Input
|
||||
isClearable
|
||||
type='password'
|
||||
name='password'
|
||||
autoComplete='current-password'
|
||||
classNames={{
|
||||
label: 'text-black/50 dark:text-white/90',
|
||||
input: [
|
||||
'bg-transparent',
|
||||
'text-black/90 dark:text-white/90',
|
||||
'placeholder:text-default-700/50 dark:placeholder:text-white/60',
|
||||
],
|
||||
innerWrapper: 'bg-transparent',
|
||||
inputWrapper: [
|
||||
'shadow-xl',
|
||||
'bg-default-100/70',
|
||||
'dark:bg-default/60',
|
||||
'backdrop-blur-xl',
|
||||
'backdrop-saturate-200',
|
||||
'hover:bg-default-0/70',
|
||||
'dark:hover:bg-default/70',
|
||||
'group-data-[focus=true]:bg-default-100/50',
|
||||
'dark:group-data-[focus=true]:bg-default/60',
|
||||
'!cursor-text',
|
||||
],
|
||||
}}
|
||||
isDisabled={isLoading || isPasskeyLoading}
|
||||
label='Token'
|
||||
placeholder='请输入token'
|
||||
radius='lg'
|
||||
size='lg'
|
||||
startContent={
|
||||
<IoKeyOutline className='text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0' />
|
||||
}
|
||||
value={tokenValue}
|
||||
onChange={(e) => setTokenValue(e.target.value)}
|
||||
onClear={() => setTokenValue('')}
|
||||
/>
|
||||
</form>
|
||||
<div className='text-center text-small text-default-600 dark:text-default-400 px-2'>
|
||||
💡 提示:请从 NapCat 启动日志中查看登录密钥
|
||||
</div>
|
||||
<Button
|
||||
className='mx-10 mt-10 text-lg py-7'
|
||||
color='primary'
|
||||
isLoading={isLoading}
|
||||
radius='full'
|
||||
size='lg'
|
||||
variant='shadow'
|
||||
onPress={onSubmitToken}
|
||||
>
|
||||
{!isLoading && (
|
||||
<Image
|
||||
alt='logo'
|
||||
classNames={{
|
||||
wrapper: '-ml-8',
|
||||
}}
|
||||
height='2em'
|
||||
src={logo}
|
||||
/>
|
||||
)}
|
||||
登录
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</CardBody>
|
||||
</HoverEffectCard>
|
||||
</motion.div>
|
||||
|
||||
+3
-1
@@ -5,7 +5,9 @@ interface ServerResponse<T> {
|
||||
}
|
||||
|
||||
interface AuthResponse {
|
||||
Credential: string;
|
||||
Credential?: string;
|
||||
require2FA?: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
interface LoginListItem {
|
||||
|
||||
+53
-3
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": [
|
||||
"ES2021"
|
||||
],
|
||||
@@ -30,10 +30,60 @@
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"resolveJsonModule": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"napcat-core": [
|
||||
"./packages/napcat-core/index.ts"
|
||||
],
|
||||
"napcat-core/*": [
|
||||
"./packages/napcat-core/*"
|
||||
],
|
||||
"napcat-onebot": [
|
||||
"./packages/napcat-onebot/index.ts"
|
||||
],
|
||||
"napcat-onebot/*": [
|
||||
"./packages/napcat-onebot/*"
|
||||
],
|
||||
"napcat-common": [
|
||||
"./packages/napcat-common/src/index.ts"
|
||||
],
|
||||
"napcat-common/src/*": [
|
||||
"./packages/napcat-common/src/*"
|
||||
],
|
||||
"napcat-image-size": [
|
||||
"./packages/napcat-image-size/src/index.ts"
|
||||
],
|
||||
"napcat-image-size/src/*": [
|
||||
"./packages/napcat-image-size/src/*"
|
||||
],
|
||||
"napcat-database": [
|
||||
"./packages/napcat-database/src/index.ts"
|
||||
],
|
||||
"napcat-database/src/*": [
|
||||
"./packages/napcat-database/src/*"
|
||||
],
|
||||
"napcat-protocol": [
|
||||
"./packages/napcat-protocol/index.ts"
|
||||
],
|
||||
"napcat-protocol/*": [
|
||||
"./packages/napcat-protocol/*"
|
||||
],
|
||||
"napcat-qrcode": [
|
||||
"./packages/napcat-qrcode/index.ts"
|
||||
],
|
||||
"napcat-qrcode/*": [
|
||||
"./packages/napcat-qrcode/*"
|
||||
],
|
||||
"napcat-webui-backend": [
|
||||
"./packages/napcat-webui-backend/index.ts"
|
||||
],
|
||||
"napcat-webui-backend/*": [
|
||||
"./packages/napcat-webui-backend/*"
|
||||
],
|
||||
"napcat-pty": [
|
||||
"./packages/napcat-pty/node-pty.d.ts"
|
||||
],
|
||||
"@/*": [
|
||||
"packages/*"
|
||||
"./packages/*"
|
||||
]
|
||||
},
|
||||
"skipLibCheck": true,
|
||||
|
||||
Reference in new issue
Block a user