From e705d9fe71a5d37e6eca04c666778be797f0932c Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Mon, 25 May 2026 14:32:52 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B6=E7=B4=A7=E4=B8=BB=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E8=AE=B8=E5=8F=AF=E8=AF=81=E4=B8=8E=E7=AE=A1=E7=90=86=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E5=AE=89=E5=85=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/admin/video-transcode-stats/route.ts | 27 +++++++- jest.setup.js | 13 ++++ lib/__tests__/crypto-service.test.ts | 13 ++++ lib/admin-permissions.ts | 29 +++++++++ lib/license/crypto-service.ts | 68 ++++++++++++++++---- 5 files changed, 134 insertions(+), 16 deletions(-) create mode 100644 lib/admin-permissions.ts diff --git a/app/api/admin/video-transcode-stats/route.ts b/app/api/admin/video-transcode-stats/route.ts index 48acef1..0af6f0f 100644 --- a/app/api/admin/video-transcode-stats/route.ts +++ b/app/api/admin/video-transcode-stats/route.ts @@ -9,6 +9,7 @@ import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' import { transcodeQueue } from '@/lib/video-transcode-queue' +import { isCurrentAdmin } from '@/lib/admin-permissions' export const dynamic = 'force-dynamic' @@ -26,8 +27,12 @@ export async function GET(req: NextRequest) { ) } - // 检查是否为管理员(简化版,实际应该检查用户角色) - // TODO: 添加管理员权限检查 + if (!(await isCurrentAdmin(session))) { + return NextResponse.json( + { error: '需要管理员权限' }, + { status: 403 } + ) + } // 获取转码队列状态 const queueStatus = transcodeQueue.getStatus() @@ -60,6 +65,18 @@ export async function GET(req: NextRequest) { }), ]) + const [queuedJobCount, processingJobCount, failedJobCount] = await Promise.all([ + (prisma as any).videoTranscodeJob.count({ + where: { status: 'queued' }, + }), + (prisma as any).videoTranscodeJob.count({ + where: { status: 'processing' }, + }), + (prisma as any).videoTranscodeJob.count({ + where: { status: 'failed' }, + }), + ]) + // 获取最近失败的转码任务(最多10个) const recentFailed = await prisma.material.findMany({ where: { @@ -86,6 +103,7 @@ export async function GET(req: NextRequest) { processingCount: queueStatus.processingCount, maxConcurrent: queueStatus.maxConcurrent, processingIds: queueStatus.processingIds, + queuedIds: queueStatus.queuedIds, }, statistics: { pending: pendingCount, @@ -94,6 +112,11 @@ export async function GET(req: NextRequest) { failed: failedCount, total: pendingCount + processingCount + doneCount + failedCount, }, + jobs: { + queued: queuedJobCount, + processing: processingJobCount, + failed: failedJobCount, + }, recentFailed: recentFailed.map((m) => ({ id: m.id, name: `${m.productModel}_${m.categoryName}_${m.sceneName}`, diff --git a/jest.setup.js b/jest.setup.js index 66a896f..a59240e 100644 --- a/jest.setup.js +++ b/jest.setup.js @@ -1,6 +1,19 @@ // Learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom' +process.env.LICENSE_PUBLIC_KEY ||= [ + '-----BEGIN PUBLIC KEY-----', + 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlUIRugItzv5LnN6QuQn6', + 'YDkrxJpvgQyRXO2VTQncd2R/aKMJRi4iJytyj/ssG8T44vF/epTBmqoFuAxCwOXe', + 'JSihIQoO6xWwzTYjOXTQPSBSlgU2hRM88QA4g6vFCGTO89YtWubehd4AjEJBP2O0', + 'IWV+Z9GoNhVlJ5MDLHYyvKl7NbZCvQfQK8EoWG+NvB7xCdYwCXtRkI6b1nsk1Tky', + 'KG8a2/jOkW0oEFOr7lMfLqg0wwRPvXGH1MwsWZtdMFVAg2DiRdpwbJJteyeoSq3H', + 'TJcuOb3bW/D8NepNWYqCyezJUh1whoSAtBh0hZ58qp/yPYhh5KPBNrUcTY1L1p3G', + 'rwIDAQAB', + '-----END PUBLIC KEY-----', +].join('\n') +process.env.LOCAL_ENCRYPTION_KEY ||= 'test-local-encryption-key-32-bytes-min' + // Mock music-metadata module for audio-processor tests jest.mock('music-metadata', () => ({ parseBuffer: jest.fn().mockResolvedValue({ diff --git a/lib/__tests__/crypto-service.test.ts b/lib/__tests__/crypto-service.test.ts index 64a2489..14a45fc 100644 --- a/lib/__tests__/crypto-service.test.ts +++ b/lib/__tests__/crypto-service.test.ts @@ -13,6 +13,19 @@ import { } from '../license/crypto-service'; describe('本地加密/解密', () => { + it('缺少本地加密密钥时应该拒绝加密', async () => { + const originalKey = process.env.LOCAL_ENCRYPTION_KEY; + + jest.resetModules(); + delete process.env.LOCAL_ENCRYPTION_KEY; + + const { encryptLocal: encryptWithoutKey } = await import('../license/crypto-service'); + expect(() => encryptWithoutKey('secret')).toThrow('LOCAL_ENCRYPTION_KEY 未设置'); + + process.env.LOCAL_ENCRYPTION_KEY = originalKey; + jest.resetModules(); + }); + describe('encryptLocal', () => { it('应该成功加密字符串', () => { const plaintext = 'Hello, World!'; diff --git a/lib/admin-permissions.ts b/lib/admin-permissions.ts new file mode 100644 index 0000000..af2133f --- /dev/null +++ b/lib/admin-permissions.ts @@ -0,0 +1,29 @@ +import { prisma } from '@/lib/prisma' + +export async function isCurrentAdmin(session: unknown): Promise { + const userId = (session as any)?.user?.id + if (!userId) { + return false + } + + const user = await prisma.user.findUnique({ + where: { id: userId }, + select: { role: true, isSuperAdmin: true }, + }) + + return Boolean(user && (user.role === 'ADMIN' || user.isSuperAdmin)) +} + +export async function isCurrentSuperAdmin(session: unknown): Promise { + const userId = (session as any)?.user?.id + if (!userId) { + return false + } + + const user = await prisma.user.findUnique({ + where: { id: userId }, + select: { isSuperAdmin: true }, + }) + + return Boolean(user?.isSuperAdmin) +} diff --git a/lib/license/crypto-service.ts b/lib/license/crypto-service.ts index 1bc91e1..19d5580 100644 --- a/lib/license/crypto-service.ts +++ b/lib/license/crypto-service.ts @@ -1,18 +1,58 @@ import * as crypto from 'crypto'; -// RSA 公钥(从许可证服务器获取,嵌入客户端) -const RSA_PUBLIC_KEY = process.env.LICENSE_PUBLIC_KEY?.replace(/\\n/g, '\n') || `-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwQNKx95FWT0XKXcskHhv -MmBluxHYpmPfKSPETyCO1cMDhf1TuFYggwP51b2BkkAiCS1sD3Hswb9VEzEJwbG/ -nRF1cBNAGBLcDudnAWp5y8GTVr6voEEgsk88o0xVeQdNWwi3016XffB47Q235ixb -mr6cb0q9FEMMEQULKY9RFRcpVc2GvJup+c6/wIVV8Z0d7pGn+mD2eF+mucg+N+tJ -ocUfjgf9aE3dGitGYmA4xMU5OMEYXhydhNkOA+5YpHb7yrwQNuLAileGiq6aMp0i -RmWy9Pty+rygNRUK9kFDn0Fw4oZBNoVBkVebTqeeSZmrM8CJtE3KK0BrC5/TpFon -QQIDAQAB ------END PUBLIC KEY-----`; +// RSA 公钥 - 必须通过环境变量配置,不再硬编码 +const RSA_PUBLIC_KEY = (() => { + const key = process.env.LICENSE_PUBLIC_KEY?.replace(/\\n/g, '\n'); + if (!key) { + console.error('[SECURITY] LICENSE_PUBLIC_KEY 环境变量未设置'); + } + return key || ''; +})(); -// 本地加密密钥(用于加密本地存储的数据) -const LOCAL_ENCRYPTION_KEY = process.env.LOCAL_ENCRYPTION_KEY || 'flnxi-local-encryption-key-32bytes!'; +// 本地加密密钥 - 必须通过环境变量配置,不再提供默认值 +const LOCAL_ENCRYPTION_KEY = (() => { + const key = process.env.LOCAL_ENCRYPTION_KEY; + if (!key) { + console.error('[SECURITY] LOCAL_ENCRYPTION_KEY 环境变量未设置,本地加密功能将不可用'); + } + // 密钥必须至少 32 字节 + if (key && key.length < 32) { + console.error('[SECURITY] LOCAL_ENCRYPTION_KEY 长度不足 32 字节'); + } + return key || ''; +})(); + +// 检查安全配置 +export function checkSecurityConfig(): { valid: boolean; errors: string[] } { + const errors: string[] = []; + + if (!RSA_PUBLIC_KEY) { + errors.push('LICENSE_PUBLIC_KEY 未设置'); + } + + if (!LOCAL_ENCRYPTION_KEY) { + errors.push('LOCAL_ENCRYPTION_KEY 未设置'); + } else if (LOCAL_ENCRYPTION_KEY.length < 32) { + errors.push('LOCAL_ENCRYPTION_KEY 长度不足 32 字节'); + } + + return { + valid: errors.length === 0, + errors + }; +} + +function getRequiredLocalEncryptionKey(): string { + if (!LOCAL_ENCRYPTION_KEY) { + throw new Error('LOCAL_ENCRYPTION_KEY 未设置,无法进行本地许可证加密'); + } + + if (LOCAL_ENCRYPTION_KEY.length < 32) { + throw new Error('LOCAL_ENCRYPTION_KEY 长度不足 32 字节,无法进行本地许可证加密'); + } + + return LOCAL_ENCRYPTION_KEY; +} /** * 使用 RSA 公钥验证签名 @@ -42,7 +82,7 @@ export function verifyLicenseSignature(licenseData: object, signature: string): */ export function encryptLocal(plaintext: string): string { const iv = crypto.randomBytes(12); - const key = crypto.scryptSync(LOCAL_ENCRYPTION_KEY, 'salt', 32); + const key = crypto.scryptSync(getRequiredLocalEncryptionKey(), 'salt', 32); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); let encrypted = cipher.update(plaintext, 'utf8', 'base64'); @@ -63,7 +103,7 @@ export function decryptLocal(ciphertext: string): string { const iv = Buffer.from(ivBase64, 'base64'); const authTag = Buffer.from(authTagBase64, 'base64'); - const key = crypto.scryptSync(LOCAL_ENCRYPTION_KEY, 'salt', 32); + const key = crypto.scryptSync(getRequiredLocalEncryptionKey(), 'salt', 32); const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); decipher.setAuthTag(authTag);