79 lines
2.7 KiB
TypeScript
79 lines
2.7 KiB
TypeScript
import {
|
|
registerDecorator,
|
|
ValidationOptions,
|
|
ValidationArguments,
|
|
} from 'class-validator';
|
|
|
|
// Decorator para sanitizar strings e prevenir SQL/NoSQL injection
|
|
export function IsSanitized(validationOptions?: ValidationOptions) {
|
|
return function (object: object, propertyName: string) {
|
|
registerDecorator({
|
|
name: 'isSanitized',
|
|
target: object.constructor,
|
|
propertyName: propertyName,
|
|
options: validationOptions,
|
|
validator: {
|
|
validate(value: any, args: ValidationArguments) {
|
|
if (typeof value !== 'string') return true; // Skip non-string values
|
|
|
|
const sqlInjectionRegex =
|
|
/('|"|;|--|\/\*|\*\/|@@|@|char|nchar|varchar|nvarchar|alter|begin|cast|create|cursor|declare|delete|drop|end|exec|execute|fetch|insert|kill|open|select|sys|sysobjects|syscolumns|table|update|xp_)/i;
|
|
if (sqlInjectionRegex.test(value)) {
|
|
return false;
|
|
}
|
|
|
|
// Check for NoSQL injection patterns (MongoDB)
|
|
const noSqlInjectionRegex =
|
|
/(\$where|\$ne|\$gt|\$lt|\$gte|\$lte|\$in|\$nin|\$or|\$and|\$regex|\$options|\$elemMatch|\{.*\:.*\})/i;
|
|
if (noSqlInjectionRegex.test(value)) {
|
|
return false;
|
|
}
|
|
|
|
// Check for XSS attempts
|
|
const xssRegex =
|
|
/(<script|javascript:|on\w+\s*=|<%=|<img|<iframe|alert\(|window\.|document\.)/i;
|
|
if (xssRegex.test(value)) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
},
|
|
defaultMessage(args: ValidationArguments) {
|
|
return 'A entrada contém caracteres inválidos ou padrões potencialmente maliciosos';
|
|
},
|
|
},
|
|
});
|
|
};
|
|
}
|
|
|
|
// Decorator para validar IDs seguros (evita injeção em IDs)
|
|
export function IsSecureId(validationOptions?: ValidationOptions) {
|
|
return function (object: object, propertyName: string) {
|
|
registerDecorator({
|
|
name: 'isSecureId',
|
|
target: object.constructor,
|
|
propertyName: propertyName,
|
|
options: validationOptions,
|
|
validator: {
|
|
validate(value: any, args: ValidationArguments) {
|
|
if (typeof value !== 'string' && typeof value !== 'number')
|
|
return false;
|
|
|
|
if (typeof value === 'string') {
|
|
// Permitir apenas: letras, números, hífens, underscores e GUIDs
|
|
return /^[a-zA-Z0-9\-_]+$|^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
|
value,
|
|
);
|
|
}
|
|
|
|
// Se for número, deve ser positivo
|
|
return value > 0;
|
|
},
|
|
defaultMessage(args: ValidationArguments) {
|
|
return 'O ID fornecido não é seguro ou está em formato inválido';
|
|
},
|
|
},
|
|
});
|
|
};
|
|
}
|