chore(安全): 强制环境变量配置并扩展路由保护

- auth.ts: JWT_SECRET必须通过环境变量配置
- crypto.ts: ENCRYPTION_KEY必须通过环境变量配置
- middleware.ts: 添加/assistants和/notes到受保护路由
- db.ts: 更新默认数据库名称
This commit is contained in:
gaoziman 2025-12-23 14:33:37 +08:00
parent a7972f8768
commit b3d151c9f9
4 changed files with 14 additions and 10 deletions

View File

@ -8,7 +8,7 @@ const pool = new Pool({
port: parseInt(process.env.DB_PORT || '35433'), port: parseInt(process.env.DB_PORT || '35433'),
user: process.env.DB_USER || 'postgres', user: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD || 'postgres', password: process.env.DB_PASSWORD || 'postgres',
database: process.env.DB_NAME || 'lioncode_ui', database: process.env.DB_NAME || 'cchcode_ui',
max: 10, // 最大连接数 max: 10, // 最大连接数
idleTimeoutMillis: 30000, // 空闲超时 idleTimeoutMillis: 30000, // 空闲超时
connectionTimeoutMillis: 5000, // 连接超时 connectionTimeoutMillis: 5000, // 连接超时

View File

@ -1,10 +1,11 @@
import { SignJWT, jwtVerify } from 'jose'; import { SignJWT, jwtVerify } from 'jose';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
// JWT 密钥(生产环境应使用环境变量) // JWT 密钥(必须通过环境变量配置)
const JWT_SECRET = new TextEncoder().encode( if (!process.env.JWT_SECRET) {
process.env.JWT_SECRET || 'lioncode-jwt-secret-key-2024' throw new Error('环境变量 JWT_SECRET 未配置,请在 .env.local 中设置');
); }
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET);
// Token 有效期7 天 // Token 有效期7 天
const TOKEN_EXPIRY = '7d'; const TOKEN_EXPIRY = '7d';

View File

@ -1,8 +1,11 @@
import crypto from 'crypto'; import crypto from 'crypto';
// 加密密钥32字节 = 256位用于 AES-256 // 加密密钥32字节 = 256位用于 AES-256
// 生产环境应使用环境变量 // 必须通过环境变量配置
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || 'lioncode-encryption-key-2024-sec'; if (!process.env.ENCRYPTION_KEY) {
throw new Error('环境变量 ENCRYPTION_KEY 未配置,请在 .env.local 中设置');
}
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY;
// 确保密钥长度为32字节 // 确保密钥长度为32字节
const getKey = (): Buffer => { const getKey = (): Buffer => {

View File

@ -2,16 +2,16 @@ import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server'; import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose'; import { jwtVerify } from 'jose';
// JWT 密钥 // JWT 密钥(必须通过环境变量配置)
const JWT_SECRET = new TextEncoder().encode( const JWT_SECRET = new TextEncoder().encode(
process.env.JWT_SECRET || 'lioncode-jwt-secret-key-2024' process.env.JWT_SECRET || ''
); );
// Cookie 名称 // Cookie 名称
const AUTH_COOKIE_NAME = 'lioncode_auth_token'; const AUTH_COOKIE_NAME = 'lioncode_auth_token';
// 需要登录才能访问的路由 // 需要登录才能访问的路由
const protectedRoutes = ['/', '/chat', '/settings']; const protectedRoutes = ['/', '/chat', '/settings', '/assistants', '/notes'];
// 公开路由(已登录用户访问会重定向到首页) // 公开路由(已登录用户访问会重定向到首页)
const publicRoutes = ['/login', '/register', '/reset-password']; const publicRoutes = ['/login', '/register', '/reset-password'];