Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | const { validationResult, body, param, query } = require('express-validator');
const logger = require('../utils/logger');
// Validation error handler
const handleValidationErrors = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
logger.warn('Validation errors:', { errors: errors.array(), path: req.path });
return res.status(400).json({
error: 'Validation failed',
details: errors.array().map(err => ({
field: err.param,
message: err.msg
}))
});
}
next();
};
// Common validators
const validators = {
// User validators
walletAddress: () =>
body('walletAddress')
.trim()
.matches(/^0x[a-fA-F0-9]{40}$/)
.withMessage('Invalid Ethereum wallet address'),
email: () =>
body('email')
.optional()
.trim()
.isEmail()
.normalizeEmail()
.withMessage('Invalid email address'),
riskProfile: () =>
body('riskProfile')
.optional()
.isIn(['conservative', 'moderate', 'aggressive'])
.withMessage('Risk profile must be: conservative, moderate, or aggressive'),
// Trade validators
amount: (min = 0, max = Infinity) =>
body('amount')
.isFloat({ min, max })
.withMessage(`Amount must be between ${min} and ${max}`),
strategyType: () =>
body('strategyType')
.trim()
.notEmpty()
.isIn(['arbitrage', 'flashloan', 'mev', 'autotrading', 'grid', 'dca', 'copytrading', 'sniper'])
.withMessage('Invalid strategy type'),
// Query validators
limit: (defaultValue = 50, max = 100) =>
query('limit')
.optional()
.isInt({ min: 1, max })
.toInt()
.withMessage(`Limit must be between 1 and ${max}`),
offset: () =>
query('offset')
.optional()
.isInt({ min: 0 })
.toInt()
.withMessage('Offset must be a positive integer'),
days: (max = 365) =>
query('days')
.optional()
.isInt({ min: 1, max })
.toInt()
.withMessage(`Days must be between 1 and ${max}`),
// ID validators
uuid: (field = 'id') =>
param(field)
.isUUID()
.withMessage('Invalid ID format'),
// 2FA validators
token: () =>
body('token')
.trim()
.isLength({ min: 6, max: 6 })
.isNumeric()
.withMessage('2FA token must be 6 digits'),
// Security validators
password: () =>
body('password')
.isLength({ min: 8 })
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/)
.withMessage('Password must be at least 8 characters with uppercase, lowercase, number, and special character'),
signature: () =>
body('signature')
.trim()
.matches(/^0x[a-fA-F0-9]{130}$/)
.withMessage('Invalid signature format'),
};
// Sanitization middleware
const sanitizeInput = (req, res, next) => {
// Remove any potentially dangerous characters from strings
const sanitize = (obj) => {
for (let key in obj) {
if (typeof obj[key] === 'string') {
// Remove HTML tags
obj[key] = obj[key].replace(/<[^>]*>/g, '');
// Remove script tags
obj[key] = obj[key].replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
// Remove SQL injection patterns
obj[key] = obj[key].replace(/(\b(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC|EXECUTE)\b)/gi, '');
} else if (typeof obj[key] === 'object' && obj[key] !== null) {
sanitize(obj[key]);
}
}
};
sanitize(req.body);
sanitize(req.query);
sanitize(req.params);
next();
};
// CSRF protection
const csrfProtection = (req, res, next) => {
// Skip for API endpoints that use JWT
if (req.path.startsWith('/api/')) {
return next();
}
const token = req.headers['x-csrf-token'];
const sessionToken = req.session?.csrfToken;
if (!token || token !== sessionToken) {
return res.status(403).json({ error: 'Invalid CSRF token' });
}
next();
};
// IP whitelist middleware (for admin routes)
const ipWhitelist = (allowedIPs = []) => {
return (req, res, next) => {
const clientIP = req.ip || req.connection.remoteAddress;
if (allowedIPs.length > 0 && !allowedIPs.includes(clientIP)) {
logger.warn(`Blocked request from unauthorized IP: ${clientIP}`);
return res.status(403).json({ error: 'Access denied from this IP' });
}
next();
};
};
// SQL injection protection
const sqlInjectionProtection = (req, res, next) => {
const sqlPatterns = [
/(\b(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC|EXECUTE|UNION|DECLARE|CAST)\b)/gi,
/(--|;|\*|\/\*|\*\/|xp_|sp_)/gi,
/('|\"|`|;|<|>|\||&)/gi
];
const checkForSQLInjection = (obj) => {
for (let key in obj) {
if (typeof obj[key] === 'string') {
for (let pattern of sqlPatterns) {
if (pattern.test(obj[key])) {
logger.warn(`Potential SQL injection detected: ${obj[key]}`);
return true;
}
}
} else if (typeof obj[key] === 'object' && obj[key] !== null) {
if (checkForSQLInjection(obj[key])) {
return true;
}
}
}
return false;
};
if (checkForSQLInjection(req.body) ||
checkForSQLInjection(req.query) ||
checkForSQLInjection(req.params)) {
return res.status(400).json({ error: 'Invalid input detected' });
}
next();
};
module.exports = {
validators,
handleValidationErrors,
sanitizeInput,
csrfProtection,
ipWhitelist,
sqlInjectionProtection
};
|