feat: 修复测试套件问题并添加Woodpecker CI配置

- 修复API测试认证问题:创建全局认证设置,更新Playwright配置
- 优化回归测试稳定性:增加超时时间到15秒,修复定位器
- 创建Woodpecker CI工作流:CI、部署和质量门禁配置
- 添加Jest配置和测试脚本
- 移除登录页面的默认账号密码显示(安全问题修复)
This commit is contained in:
张翔
2026-03-09 10:26:02 +08:00
parent 96c96fe75d
commit 6d92024b63
68 changed files with 5584 additions and 167 deletions
+59
View File
@@ -0,0 +1,59 @@
import { db } from '@/db';
import { auditLogs } from '@/db/schema';
import { nanoid } from 'nanoid';
export type AuditAction = 'create' | 'update' | 'delete' | 'publish' | 'login' | 'logout' | 'upload';
export interface AuditLogData {
userId?: string;
action: AuditAction;
resourceType: string;
resourceId?: string;
details?: Record<string, any>;
ipAddress?: string;
userAgent?: string;
}
export async function createAuditLog(data: AuditLogData) {
try {
await db.insert(auditLogs).values({
id: nanoid(),
userId: data.userId || null,
action: data.action,
resourceType: data.resourceType,
resourceId: data.resourceId || null,
details: data.details || null,
ipAddress: data.ipAddress || null,
userAgent: data.userAgent || null,
timestamp: new Date(),
});
} catch (error) {
console.error('创建审计日志失败:', error);
}
}
export function getActionLabel(action: AuditAction): string {
const labels: Record<AuditAction, string> = {
create: '创建',
update: '更新',
delete: '删除',
publish: '发布',
login: '登录',
logout: '登出',
upload: '上传',
};
return labels[action];
}
export function getActionColor(action: AuditAction): string {
const colors: Record<AuditAction, string> = {
create: 'bg-green-100 text-green-800',
update: 'bg-blue-100 text-blue-800',
delete: 'bg-red-100 text-red-800',
publish: 'bg-purple-100 text-purple-800',
login: 'bg-cyan-100 text-cyan-800',
logout: 'bg-gray-100 text-gray-800',
upload: 'bg-yellow-100 text-yellow-800',
};
return colors[action];
}
+13 -46
View File
@@ -1,15 +1,11 @@
import { NextAuthOptions } from 'next-auth';
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import EmailProvider from 'next-auth/providers/email';
import { Resend } from 'resend';
import { db } from '@/db';
import { users } from '@/db/schema';
import { eq } from 'drizzle-orm';
import bcrypt from 'bcryptjs';
const resend = new Resend(process.env.RESEND_API_KEY);
export const authOptions: NextAuthOptions = {
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
CredentialsProvider({
name: '邮箱密码',
@@ -22,19 +18,20 @@ export const authOptions: NextAuthOptions = {
return null;
}
const user = await db
const userResult = await db
.select()
.from(users)
.where(eq(users.email, credentials.email))
.where(eq(users.email, credentials.email as string))
.limit(1);
if (user.length === 0) {
const user = userResult[0];
if (!user) {
return null;
}
const isValid = await bcrypt.compare(
credentials.password,
user[0].passwordHash || ''
credentials.password as string,
user.passwordHash || ''
);
if (!isValid) {
@@ -42,43 +39,13 @@ export const authOptions: NextAuthOptions = {
}
return {
id: user[0].id,
email: user[0].email,
name: user[0].name,
role: user[0].role,
id: user.id,
email: user.email,
name: user.name,
role: user.role,
};
},
}),
EmailProvider({
server: {},
from: process.env.EMAIL_FROM || 'noreply@novalon.cn',
sendVerificationRequest: async ({ identifier: email, url }) => {
try {
await resend.emails.send({
from: process.env.EMAIL_FROM || 'noreply@novalon.cn',
to: email,
subject: '睿新致遠 - 登录验证链接',
html: `
<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
<h2 style="color: #C41E3A;">睿新致遠管理后台登录</h2>
<p>您好!</p>
<p>您收到这封邮件是因为您请求登录睿新致遠管理后台。</p>
<p>请点击下方按钮完成登录:</p>
<a href="${url}" style="display: inline-block; padding: 12px 24px; background-color: #C41E3A; color: white; text-decoration: none; border-radius: 6px; margin: 16px 0;">
立即登录
</a>
<p style="color: #666; font-size: 14px;">如果您没有请求此链接,请忽略此邮件。</p>
<hr style="margin: 24px 0; border: none; border-top: 1px solid #eee;" />
<p style="color: #999; font-size: 12px;">四川睿新致远科技有限公司</p>
</div>
`,
});
} catch (error) {
console.error('发送邮件失败:', error);
throw new Error('发送邮件失败');
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
@@ -103,4 +70,4 @@ export const authOptions: NextAuthOptions = {
session: {
strategy: 'jwt',
},
};
});
+2 -3
View File
@@ -1,12 +1,11 @@
import { getServerSession } from 'next-auth';
import { authOptions } from '../auth';
import { auth } from '../auth';
import { hasPermission, Role, Resource, Action } from './permissions';
export async function checkPermission(
resource: Resource,
action: Action
): Promise<{ allowed: boolean; userId?: string; role?: Role }> {
const session = await getServerSession(authOptions);
const session = await auth();
if (!session || !session.user) {
return { allowed: false };
+10 -13
View File
@@ -20,11 +20,11 @@ function hexToRgb(hex: string): ColorRGB {
function getLuminance(rgb: ColorRGB): number {
const { r, g, b } = rgb;
const a = [r, g, b].map(v => {
v /= 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
const values = [r, g, b].map(v => {
const normalized = v / 255;
return normalized <= 0.03928 ? normalized / 12.92 : Math.pow((normalized + 0.055) / 1.055, 2.4);
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
return values[0]! * 0.2126 + values[1]! * 0.7152 + values[2]! * 0.0722;
}
export function calculateContrastRatio(foreground: string, background: string): number {
@@ -43,21 +43,18 @@ export function calculateContrastRatio(foreground: string, background: string):
export function meetsWCAGStandard(
foreground: string,
background: string,
level: 'AA' | 'AAA',
textSize: 'normal' | 'large'
level: 'AA' | 'AAA' = 'AA',
textSize: 'normal' | 'large' = 'normal'
): ContrastResult {
const ratio = calculateContrastRatio(foreground, background);
let requiredRatio: number;
if (level === 'AA') {
requiredRatio = textSize === 'normal' ? 4.5 : 3;
} else {
requiredRatio = textSize === 'normal' ? 7 : 4.5;
}
const requiredRatio = level === 'AAA'
? (textSize === 'large' ? 4.5 : 7)
: (textSize === 'large' ? 3 : 4.5);
return {
passes: ratio >= requiredRatio,
ratio,
requiredRatio
requiredRatio,
};
}
+190
View File
@@ -0,0 +1,190 @@
import { writeFile, mkdir, stat } from 'fs/promises';
import { existsSync } from 'fs';
import path from 'path';
import { nanoid } from 'nanoid';
export interface UploadOptions {
maxSize?: number;
allowedTypes?: string[];
type: 'image' | 'document';
userId?: string;
}
export interface UploadResult {
id: string;
name: string;
size: number;
type: string;
url: string;
path: string;
uploadedAt: Date;
uploadedBy?: string;
}
const FILE_SIGNATURES: Record<string, Buffer> = {
'image/jpeg': Buffer.from([0xFF, 0xD8, 0xFF]),
'image/png': Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]),
'image/gif': Buffer.from([0x47, 0x49, 0x46, 0x38]),
'image/webp': Buffer.from([0x52, 0x49, 0x46, 0x46]),
'application/pdf': Buffer.from([0x25, 0x50, 0x44, 0x46]),
};
const ALLOWED_TYPES: Record<string, string[]> = {
image: ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'],
document: ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
};
const MAX_FILE_SIZES: Record<string, number> = {
image: 5 * 1024 * 1024, // 5MB
document: 10 * 1024 * 1024, // 10MB
};
const DANGEROUS_EXTENSIONS = ['.exe', '.bat', '.cmd', '.sh', '.php', '.jsp', '.asp', '.aspx', '.js'];
export function getFileExtension(mimeType: string): string {
const extensions: Record<string, string> = {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
'image/webp': '.webp',
'image/svg+xml': '.svg',
'application/pdf': '.pdf',
'application/msword': '.doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
};
return extensions[mimeType] || '';
}
export function isAllowedType(mimeType: string, type: 'image' | 'document'): boolean {
return ALLOWED_TYPES[type]?.includes(mimeType) || false;
}
export function validateFileSignature(buffer: Buffer, mimeType: string): boolean {
if (mimeType === 'image/svg+xml') {
return true;
}
const signature = FILE_SIGNATURES[mimeType];
if (!signature) {
return true;
}
for (let i = 0; i < signature.length; i++) {
if (buffer[i] !== signature[i]) {
return false;
}
}
return true;
}
export function sanitizeFileName(fileName: string): string {
return fileName
.replace(/[^a-zA-Z0-9\u4e00-\u9fa5._-]/g, '_')
.replace(/\.{2,}/g, '.')
.toLowerCase();
}
export function isDangerousFile(fileName: string): boolean {
const ext = path.extname(fileName).toLowerCase();
return DANGEROUS_EXTENSIONS.includes(ext);
}
export function getDatePath(): string {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}/${month}/${day}`;
}
export async function uploadFile(
file: File,
options: UploadOptions
): Promise<UploadResult> {
const {
type = 'image',
maxSize = MAX_FILE_SIZES[type] || 5 * 1024 * 1024,
allowedTypes = ALLOWED_TYPES[type] || [],
userId
} = options;
if (file.size > maxSize) {
throw new Error(`文件大小超过限制 (最大 ${Math.round(maxSize / 1024 / 1024)}MB)`);
}
if (!allowedTypes.includes(file.type)) {
throw new Error(`不支持的文件类型: ${file.type}`);
}
if (isDangerousFile(file.name)) {
throw new Error('不允许上传此类型的文件');
}
const bytes = await file.arrayBuffer();
const buffer = Buffer.from(bytes);
if (!validateFileSignature(buffer, file.type)) {
throw new Error('文件内容与声明类型不匹配');
}
const uploadBaseDir = process.env.UPLOAD_DIR || './uploads';
const datePath = getDatePath();
const uploadDir = path.join(process.cwd(), uploadBaseDir, type, datePath);
if (!existsSync(uploadDir)) {
await mkdir(uploadDir, { recursive: true });
}
const fileId = nanoid();
const extension = getFileExtension(file.type);
const sanitizedOriginalName = sanitizeFileName(file.name);
const fileName = `${fileId}${extension}`;
const filePath = path.join(uploadDir, fileName);
await writeFile(filePath, buffer);
const publicUrl = `/uploads/${type}/${datePath}/${fileName}`;
return {
id: fileId,
name: sanitizedOriginalName,
size: file.size,
type: file.type,
url: publicUrl,
path: filePath,
uploadedAt: new Date(),
uploadedBy: userId,
};
}
export async function deleteFile(fileUrl: string): Promise<boolean> {
try {
const filePath = path.join(process.cwd(), 'public', fileUrl);
if (!existsSync(filePath)) {
return false;
}
const { unlink } = await import('fs/promises');
await unlink(filePath);
return true;
} catch (error) {
console.error('删除文件失败:', error);
return false;
}
}
export async function getFileInfo(filePath: string) {
try {
const stats = await stat(filePath);
return {
size: stats.size,
createdAt: stats.birthtime,
modifiedAt: stats.mtime,
};
} catch (error) {
return null;
}
}