chahuadev-framework-en / modules /security-logger.js
chahuadev
Update README
857cdcf
/**
* Security Logger - ระบบบันทึกเหตุการณ์ความปลอดภัย
* Chahua Development Thailand
* CEO: Saharath C.
*
* Purpose: บันทึกและตรวจสอบเหตุการณ์ด้านความปลอดภัย
*/
const fs = require('fs');
const path = require('path');
class SecurityLogger {
constructor(options = {}) {
this.config = {
logPath: options.logPath || './logs/security',
maxLogSize: options.maxLogSize || 10 * 1024 * 1024, // 10MB
maxLogFiles: options.maxLogFiles || 5,
alertThreshold: options.alertThreshold || 10, // Alert after 10 events
enableRealTimeAlerts: options.enableRealTimeAlerts || true,
sensitiveFields: options.sensitiveFields || ['password', 'token', 'secret', 'key']
};
this.securityEvents = [];
this.alertCount = 0;
this.blockedIPs = new Set();
this.suspiciousActivities = new Map();
this.ensureLogDirectory();
console.log('Security Logger initialized');
}
ensureLogDirectory() {
try {
if (!fs.existsSync(this.config.logPath)) {
fs.mkdirSync(this.config.logPath, { recursive: true });
}
} catch (error) {
console.warn('Warning: Could not create security log directory:', error.message);
}
}
async logSecurityEvent(eventData) {
const timestamp = new Date().toISOString();
const eventId = this.generateEventId();
const securityEvent = {
id: eventId,
timestamp,
type: eventData.type || 'UNKNOWN',
severity: eventData.severity || 'medium',
details: this.sanitizeDetails(eventData),
ip: eventData.ip || 'unknown',
userAgent: eventData.userAgent || 'unknown',
source: eventData.source || 'system'
};
// Add to memory
this.securityEvents.push(securityEvent);
// Maintain max events in memory
if (this.securityEvents.length > 1000) {
this.securityEvents.shift();
}
// Write to file
this.writeToLogFile(securityEvent);
// Check for alerts
this.checkForAlerts(securityEvent);
// Update suspicious activity tracking
this.updateSuspiciousActivity(securityEvent);
console.log(`Security Event [${securityEvent.severity.toUpperCase()}]: ${securityEvent.type} - ${eventId}`);
return eventId;
}
logAuthFailure(ip, username, details = {}) {
return this.logSecurityEvent({
type: 'AUTH_FAILURE',
ip,
username,
severity: 'high',
...details
});
}
logAuthSuccess(ip, username, details = {}) {
return this.logSecurityEvent({
type: 'AUTH_SUCCESS',
ip,
username,
severity: 'low',
...details
});
}
logSuspiciousAccess(ip, endpoint, details = {}) {
return this.logSecurityEvent({
type: 'SUSPICIOUS_ACCESS',
ip,
endpoint,
severity: 'high',
...details
});
}
logRateLimitExceeded(ip, endpoint, details = {}) {
return this.logSecurityEvent({
type: 'RATE_LIMIT_EXCEEDED',
ip,
endpoint,
severity: 'medium',
...details
});
}
logDataBreach(source, details = {}) {
return this.logSecurityEvent({
type: 'DATA_BREACH',
source,
severity: 'critical',
...details
});
}
logUnauthorizedAccess(ip, resource, details = {}) {
return this.logSecurityEvent({
type: 'UNAUTHORIZED_ACCESS',
ip,
resource,
severity: 'high',
...details
});
}
logSystemAnomaly(anomalyType, details = {}) {
return this.logSecurityEvent({
type: 'SYSTEM_ANOMALY',
anomalyType,
severity: 'medium',
...details
});
}
sanitizeDetails(details) {
const sanitized = { ...details };
// Remove sensitive fields
for (const field of this.config.sensitiveFields) {
if (sanitized[field]) {
sanitized[field] = '***REDACTED***';
}
}
return sanitized;
}
writeToLogFile(event) {
try {
const logFileName = `security-${new Date().toISOString().split('T')[0]}.log`;
const logFilePath = path.join(this.config.logPath, logFileName);
const logEntry = JSON.stringify(event) + '\n';
// Check file size and rotate if needed
if (fs.existsSync(logFilePath)) {
const stats = fs.statSync(logFilePath);
if (stats.size > this.config.maxLogSize) {
this.rotateLogFile(logFilePath);
}
}
fs.appendFileSync(logFilePath, logEntry);
} catch (error) {
console.error('Error writing security log:', error.message);
}
}
rotateLogFile(logFilePath) {
try {
const logDir = path.dirname(logFilePath);
const baseName = path.basename(logFilePath, '.log');
// Rotate existing files
for (let i = this.config.maxLogFiles - 1; i > 0; i--) {
const oldFile = path.join(logDir, `${baseName}.${i}.log`);
const newFile = path.join(logDir, `${baseName}.${i + 1}.log`);
if (fs.existsSync(oldFile)) {
if (i === this.config.maxLogFiles - 1) {
fs.unlinkSync(oldFile); // Delete oldest
} else {
fs.renameSync(oldFile, newFile);
}
}
}
// Move current file to .1
const rotatedFile = path.join(logDir, `${baseName}.1.log`);
fs.renameSync(logFilePath, rotatedFile);
console.log(`Security log rotated: ${logFilePath}`);
} catch (error) {
console.error('Error rotating security log:', error.message);
}
}
checkForAlerts(event) {
if (!this.config.enableRealTimeAlerts) return;
// Count events from same IP in last hour
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
const recentEvents = this.securityEvents.filter(e =>
e.ip === event.ip &&
new Date(e.timestamp) > oneHourAgo
);
if (recentEvents.length >= this.config.alertThreshold) {
this.triggerAlert(event.ip, recentEvents);
}
// Immediate alert for critical events
if (event.severity === 'critical') {
this.triggerCriticalAlert(event);
}
}
triggerAlert(ip, events) {
this.alertCount++;
console.warn(`SECURITY ALERT: Multiple events from IP ${ip} (${events.length} events)`);
// Block IP after multiple alerts
if (events.length >= this.config.alertThreshold * 2) {
this.blockedIPs.add(ip);
console.warn(`IP ${ip} has been blocked due to suspicious activity`);
}
// In a real system, you might send email/SMS alerts here
}
triggerCriticalAlert(event) {
console.error(`CRITICAL SECURITY ALERT: ${event.type} - ${event.id}`);
// In a real system, you might trigger immediate notifications
}
updateSuspiciousActivity(event) {
const key = `${event.ip}_${event.type}`;
const count = this.suspiciousActivities.get(key) || 0;
this.suspiciousActivities.set(key, count + 1);
}
isIPBlocked(ip) {
return this.blockedIPs.has(ip);
}
unblockIP(ip) {
if (this.blockedIPs.delete(ip)) {
console.log(`IP ${ip} has been unblocked`);
return true;
}
return false;
}
getSecurityReport(timeRange = '24h') {
const hours = timeRange === '24h' ? 24 : parseInt(timeRange);
const startTime = new Date(Date.now() - hours * 60 * 60 * 1000);
const relevantEvents = this.securityEvents.filter(e =>
new Date(e.timestamp) > startTime
);
const report = {
timeRange: `${hours} hours`,
totalEvents: relevantEvents.length,
eventTypes: {},
severityBreakdown: {},
topIPs: {},
blockedIPs: Array.from(this.blockedIPs),
alertsTriggered: this.alertCount
};
// Analyze events
relevantEvents.forEach(event => {
// Event types
report.eventTypes[event.type] = (report.eventTypes[event.type] || 0) + 1;
// Severity breakdown
report.severityBreakdown[event.severity] = (report.severityBreakdown[event.severity] || 0) + 1;
// Top IPs
report.topIPs[event.ip] = (report.topIPs[event.ip] || 0) + 1;
});
// Sort top IPs
report.topIPs = Object.entries(report.topIPs)
.sort(([,a], [,b]) => b - a)
.slice(0, 10)
.reduce((obj, [ip, count]) => {
obj[ip] = count;
return obj;
}, {});
return report;
}
exportSecurityLogs(startDate, endDate) {
try {
const events = this.securityEvents.filter(e => {
const eventDate = new Date(e.timestamp);
return eventDate >= startDate && eventDate <= endDate;
});
const exportData = {
exportDate: new Date().toISOString(),
dateRange: { start: startDate, end: endDate },
totalEvents: events.length,
events: events
};
return exportData;
} catch (error) {
console.error('Error exporting security logs:', error.message);
return null;
}
}
generateEventId() {
return `sec_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
}
getStats() {
return {
totalEvents: this.securityEvents.length,
alertsTriggered: this.alertCount,
blockedIPs: this.blockedIPs.size,
suspiciousActivities: this.suspiciousActivities.size
};
}
}
module.exports = SecurityLogger;