收紧主应用许可证与管理接口安全

This commit is contained in:
WuYongJie 2026-05-25 14:32:52 +08:00
parent d9955b6835
commit e705d9fe71
5 changed files with 134 additions and 16 deletions

View File

@ -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}`,

View File

@ -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({

View File

@ -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!';

29
lib/admin-permissions.ts Normal file
View File

@ -0,0 +1,29 @@
import { prisma } from '@/lib/prisma'
export async function isCurrentAdmin(session: unknown): Promise<boolean> {
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<boolean> {
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)
}

View File

@ -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);