tl-enterprise-security-suite
v2.1.6
Published
Enterprise-grade security module for frontend and backend applications with comprehensive protection against XSS, CSRF, SQL injection, and other security vulnerabilities
Maintainers
Readme
TL Shared Security
Enterprise-grade security module for frontend and backend applications with comprehensive protection against XSS, CSRF, SQL injection, and other security vulnerabilities.
Features
- XSS Protection: Advanced XSS sanitization for both frontend and backend
- CSRF Protection: Modern CSRF protection with secure token handling
- SQL Injection Prevention: Input validation and sanitization guards
- Rate Limiting: Configurable rate limiting middleware
- Security Headers: Comprehensive security headers management
- Cryptography: Secure encryption, hashing, and JWT handling
- Session Security: Secure session management with configurable options
- Security Monitoring: Real-time security event monitoring and alerting
- Secrets Management: Secure secrets storage and rotation
- Content Security Policy: Configurable CSP with nonce support
Installation
npm install tl-shared-securityQuick Start
Backend (NestJS)
import { SecurityModule } from 'tl-shared-security/backend';
@Module({
imports: [
SecurityModule.forRoot({
enableHelmet: true,
enableXssSanitization: true,
enableCsrf: true,
enableRateLimiter: true,
enableSecurityMonitoring: true,
}),
],
})
export class AppModule {}Frontend
import { xssSanitizer, securityHeaders, cspConfig } from 'tl-shared-security/frontend';
// Sanitize user input
const cleanInput = xssSanitizer.sanitize(userInput);
// Apply security headers
securityHeaders.applyToDocument();
// Configure CSP
cspConfig.applyToDocument();Cryptography
import { cryptoService, jwtService } from 'tl-shared-security/crypto';
// Hash password
const hashedPassword = cryptoService.hashPassword('password123');
// Generate JWT
const token = jwtService.sign({ userId: '123' }, 'secret');
// Encrypt data
const encrypted = cryptoService.encrypt('sensitive data', 'password');Backend Components
Security Module
The main security module provides comprehensive protection:
SecurityModule.forRoot({
enableHelmet: true, // Security headers
enableXssSanitization: true, // XSS protection
enableCsrf: true, // CSRF protection
enableRateLimiter: true, // Rate limiting
enableSecurityMonitoring: true, // Security monitoring
enableSessionSecurity: true, // Session management
enableSecretsManager: true, // Secrets management
enableSecurityHealth: true, // Health endpoints
rateLimiterOptions: {
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
},
})Guards and Interceptors
import {
SqlInjectionGuard,
SanitizeInterceptor,
AuditLogInterceptor
} from 'tl-shared-security/backend';
@Controller('api')
@UseGuards(SqlInjectionGuard)
@UseInterceptors(SanitizeInterceptor, AuditLogInterceptor)
export class ApiController {}Security Monitoring
import { SecurityMonitoringService } from 'tl-shared-security/backend';
@Injectable()
export class MyService {
constructor(private securityMonitoring: SecurityMonitoringService) {}
logSecurityEvent() {
this.securityMonitoring.logSecurityEvent({
type: 'suspicious_activity',
severity: 'high',
ipAddress: '192.168.1.1',
userAgent: 'Mozilla/5.0...',
endpoint: '/api/sensitive',
details: { reason: 'Multiple failed attempts' }
});
}
}Frontend Components
XSS Sanitization
import { XssSanitizer, sanitizeInput } from 'tl-shared-security/frontend';
// Using default sanitizer
const clean = sanitizeInput('<script>alert("xss")</script>Hello');
// Custom sanitizer
const customSanitizer = new XssSanitizer({
whiteList: {
b: [],
i: [],
p: ['class'],
}
});
const result = customSanitizer.sanitize(userInput);Content Security Policy
import { CspConfig } from 'tl-shared-security/frontend';
const csp = new CspConfig({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'nonce-abc123'"],
styleSrc: ["'self'", "'unsafe-inline'"],
}
});
// Apply to document
csp.applyToDocument();
// Get headers for server-side
const headers = csp.getHeaders();Security Headers
import { SecurityHeaders } from 'tl-shared-security/frontend';
const headers = new SecurityHeaders({
xssProtection: true,
contentTypeOptions: true,
frameOptions: 'deny',
strictTransportSecurity: {
maxAge: 31536000,
includeSubDomains: true,
}
});
headers.applyToDocument();Cryptography
Password Hashing
import { cryptoService } from 'tl-shared-security/crypto';
// Hash password (recommended - uses bcrypt)
const hash = cryptoService.hashPassword('password123');
// Verify password
const isValid = cryptoService.verifyPassword('password123', hash);
// Async versions
const hashAsync = await cryptoService.hashPasswordAsync('password123');
const isValidAsync = await cryptoService.verifyPasswordAsync('password123', hashAsync);Encryption
import { cryptoService } from 'tl-shared-security/crypto';
// Encrypt data
const encrypted = cryptoService.encrypt('sensitive data', 'password');
// Decrypt data
const decrypted = cryptoService.decrypt(encrypted, 'password');
// Generate secure tokens
const token = cryptoService.generateToken(32);
const uuid = cryptoService.generateUUID();JWT Handling
import { jwtService } from 'tl-shared-security/crypto';
// Sign JWT
const token = jwtService.sign(
{ userId: '123', role: 'admin' },
'secret',
{ expiresIn: 3600 }
);
// Verify JWT
try {
const payload = jwtService.verify(token, 'secret');
console.log(payload.userId);
} catch (error) {
console.error('Invalid token');
}
// Decode without verification
const { header, payload } = jwtService.decode(token);Configuration
Environment Variables
# Secrets Manager
SECRETS_MASTER_KEY=your-master-key-here
# Session Security
SESSION_MAX_AGE=3600000
SESSION_STRICT_IP=true
# General
NODE_ENV=productionSecurity Best Practices
- Always validate input on both client and server side
- Use HTTPS in production environments
- Set strong CSP policies to prevent XSS attacks
- Implement rate limiting to prevent abuse
- Monitor security events and set up alerts
- Rotate secrets regularly using the secrets manager
- Use secure session configuration with appropriate timeouts
API Reference
Backend Exports
SecurityModule- Main security moduleSecurityConfigService- Configuration serviceSecurityMonitoringService- Security event monitoringSessionSecurityService- Session managementSecretsManagerService- Secrets managementSqlInjectionGuard- SQL injection protectionSanitizeInterceptor- Input sanitizationAuditLogInterceptor- Request loggingRateLimiterMiddleware- Rate limitingLoggerMiddleware- Request loggingCorsMiddleware- CORS handling
Frontend Exports
XssSanitizer- XSS sanitization classsanitizeInput- Quick sanitization functionCspConfig- Content Security PolicySecurityHeaders- Security headers managementSecureStorage- Secure local storageSecurityScanner- Security vulnerability scanner
Crypto Exports
CryptoService- Main cryptography serviceJwtService- JWT handlingPasswordPolicyService- Password validationcryptoService- Default crypto instancejwtService- Default JWT instance
License
MIT
Contributing
Please read our contributing guidelines and submit pull requests to help improve this package.
Security
If you discover a security vulnerability, please send an email to [email protected] instead of using the issue tracker.
