perf: add rate limiting, validation, logging, and error handling
- Add express-rate-limit with tiered rate limits per endpoint - Add express-validator for input validation on all API routes - Add winston + morgan for structured logging - Add node-cache for lottery result caching (5min TTL, 1000 max keys) - Convert OCR to async task queue with max 2 concurrent jobs - Add global error handler middleware - Add React ErrorBoundary for client-side error handling - Fix memory leaks in OCR task queue and lottery cache - Add per-item error handling in batch ticket updates - Fix SQL UPDATE to include user_id in WHERE clause Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
7b1073e23b
commit
335f0fb8dc
@@ -0,0 +1,24 @@
|
||||
const logger = require('../services/logger');
|
||||
|
||||
function errorHandler(err, req, res, next) {
|
||||
logger.error('Unhandled error', {
|
||||
error: err.message,
|
||||
stack: err.stack,
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
ip: req.ip
|
||||
});
|
||||
|
||||
if (err.type === 'entity.parse.failed') {
|
||||
return res.status(400).json({ error: '无效的JSON格式' });
|
||||
}
|
||||
|
||||
// express-validator 验证失败时直接返回400,不会抛到这里
|
||||
// 此检查保留作为其他验证库的安全网
|
||||
|
||||
res.status(err.status || 500).json({
|
||||
error: process.env.NODE_ENV === 'production' ? '服务器内部错误' : err.message
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = errorHandler;
|
||||
@@ -0,0 +1,39 @@
|
||||
const rateLimit = require('express-rate-limit');
|
||||
|
||||
// 通用限流器 - 100请求/分钟
|
||||
const standardLimiter = rateLimit({
|
||||
windowMs: 60 * 1000,
|
||||
max: 100,
|
||||
message: { error: '请求过于频繁,请稍后再试' },
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
// 认证限流器 - 10请求/分钟 (防止暴力攻击)
|
||||
const authLimiter = rateLimit({
|
||||
windowMs: 60 * 1000,
|
||||
max: 10,
|
||||
message: { error: '登录尝试过于频繁,请稍后再试' },
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
// OCR限流器 - 5请求/分钟 (OCR是重操作)
|
||||
const ocrLimiter = rateLimit({
|
||||
windowMs: 60 * 1000,
|
||||
max: 5,
|
||||
message: { error: 'OCR处理请求过于频繁,请稍后再试' },
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
// 彩票刷新限流器 - 10请求/分钟
|
||||
const refreshLimiter = rateLimit({
|
||||
windowMs: 60 * 1000,
|
||||
max: 10,
|
||||
message: { error: '刷新请求过于频繁,请稍后再试' },
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
module.exports = { standardLimiter, authLimiter, ocrLimiter, refreshLimiter };
|
||||
@@ -0,0 +1,64 @@
|
||||
const { body, query, param, validationResult } = require('express-validator');
|
||||
|
||||
// 验证结果处理
|
||||
function validate(req, res, next) {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
error: '输入验证失败',
|
||||
details: errors.array().map(e => ({ field: e.path, message: e.msg }))
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
// 注册验证
|
||||
const registerRules = [
|
||||
body('username')
|
||||
.trim()
|
||||
.isLength({ min: 3, max: 20 }).withMessage('用户名3-20个字符')
|
||||
.matches(/^[a-zA-Z0-9_]+$/).withMessage('用户名只能包含字母、数字、下划线'),
|
||||
body('password')
|
||||
.isLength({ min: 6 }).withMessage('密码至少6个字符'),
|
||||
];
|
||||
|
||||
// 登录验证
|
||||
const loginRules = [
|
||||
body('username').trim().notEmpty().withMessage('用户名不能为空'),
|
||||
body('password').notEmpty().withMessage('密码不能为空'),
|
||||
];
|
||||
|
||||
// 彩票创建验证
|
||||
const ticketCreateRules = [
|
||||
body('type').isIn(['welfare', 'sports']).withMessage('无效的彩票类型'),
|
||||
body('game').isString().notEmpty().withMessage('游戏类型不能为空'),
|
||||
body('cost').isFloat({ min: 0 }).withMessage('金额必须为正数'),
|
||||
body('issue').optional().matches(/^\d{5,}$/).withMessage('期号格式不正确'),
|
||||
body('numbers').optional().isArray().withMessage('号码必须是数组'),
|
||||
body('bet_count').optional().isInt({ min: 1 }).withMessage('注数必须大于0'),
|
||||
body('multiple').optional().isInt({ min: 1, max: 99 }).withMessage('倍数必须在1-99之间'),
|
||||
];
|
||||
|
||||
// 彩票更新验证
|
||||
const ticketUpdateRules = [
|
||||
body('type').optional().isIn(['welfare', 'sports']).withMessage('无效的彩票类型'),
|
||||
body('game').optional().isString().notEmpty().withMessage('游戏类型不能为空'),
|
||||
body('cost').optional().isFloat({ min: 0 }).withMessage('金额必须为正数'),
|
||||
body('issue').optional().matches(/^\d{5,}$/).withMessage('期号格式不正确'),
|
||||
body('bet_count').optional().isInt({ min: 1 }).withMessage('注数必须大于0'),
|
||||
body('multiple').optional().isInt({ min: 1, max: 99 }).withMessage('倍数必须在1-99之间'),
|
||||
body('status').optional().isIn(['pending', 'won', 'lost']).withMessage('状态无效'),
|
||||
];
|
||||
|
||||
// 开奖查询验证
|
||||
const lotteryQueryRules = [
|
||||
query('game').isString().notEmpty().withMessage('彩票类型不能为空'),
|
||||
query('issue').matches(/^\d{5,}$/).withMessage('期号格式不正确'),
|
||||
];
|
||||
|
||||
// ID参数验证
|
||||
const idParamRule = [
|
||||
param('id').isInt({ min: 1 }).withMessage('无效的ID'),
|
||||
];
|
||||
|
||||
module.exports = { validate, registerRules, loginRules, ticketCreateRules, ticketUpdateRules, lotteryQueryRules, idParamRule };
|
||||
Reference in New Issue
Block a user