fix: security audit - prisma singleton, rate limits, encryption key validation, syntax fixes

This commit is contained in:
2026-05-11 23:40:44 +08:00
parent 3044b3d921
commit 9b924d5e5d
11 changed files with 49 additions and 62 deletions

View File

@@ -1,7 +1,15 @@
import crypto from 'crypto';
const ALGORITHM = 'aes-256-cbc';
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || '0123456789abcdef0123456789abcdef';
const KEY = (() => {
const raw = process.env.ENCRYPTION_KEY || '0123456789abcdef0123456789abcdef';
const buf = Buffer.from(raw, 'utf-8');
if (buf.length !== 32) {
console.error(`ENCRYPTION_KEY must be exactly 32 bytes, got ${buf.length}`);
process.exit(1);
}
return buf;
})();
export interface EncryptedData {
encrypted: boolean;
@@ -14,9 +22,7 @@ export interface EncryptedData {
*/
export function encrypt(text: string): EncryptedData {
const iv = crypto.randomBytes(16);
const key = Buffer.from(ENCRYPTION_KEY, 'utf-8');
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv);
let encrypted = cipher.update(text, 'utf-8', 'hex');
encrypted += cipher.final('hex');
@@ -33,9 +39,7 @@ export function encrypt(text: string): EncryptedData {
export function decrypt(ivHex: string, dataHex: string): string {
const iv = Buffer.from(ivHex, 'hex');
const encryptedData = Buffer.from(dataHex, 'hex');
const key = Buffer.from(ENCRYPTION_KEY, 'utf-8');
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
const decipher = crypto.createDecipheriv(ALGORITHM, KEY, iv);
let decrypted = decipher.update(encryptedData, undefined, 'utf-8');
decrypted += decipher.final('utf-8');

7
src/utils/prisma.ts Normal file
View File

@@ -0,0 +1,7 @@
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
export const prisma = globalForPrisma.prisma || new PrismaClient();
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;