UNPKG

advanced-games-library

Version:

Advanced Gaming Library for React Native - Four Complete Games with iOS Compatibility Fixes

869 lines (734 loc) 25.9 kB
/** * Advanced Security System - מערכת אבטחה מתקדמת * מספקת הגנה מקיפה על נתונים, זיהוי איומים וניהול הרשאות */ export interface SecurityConfig { encryption: { algorithm: 'AES-256-GCM' | 'ChaCha20-Poly1305'; keyRotationInterval: number; // hours enableDataEncryption: boolean; enableTransmissionEncryption: boolean; }; authentication: { tokenExpiration: number; // minutes refreshTokenExpiration: number; // days maxLoginAttempts: number; lockoutDuration: number; // minutes requireBiometric: boolean; enableMFA: boolean; }; privacy: { dataRetentionDays: number; anonymizeData: boolean; consentRequired: boolean; gdprCompliant: boolean; ccpaCompliant: boolean; }; threatDetection: { enableAnomalyDetection: boolean; enableBehaviorAnalysis: boolean; enableBotDetection: boolean; suspiciousActivityThreshold: number; }; } export interface SecurityThreat { id: string; type: 'brute_force' | 'suspicious_behavior' | 'data_breach_attempt' | 'bot_activity' | 'injection_attack'; severity: 'low' | 'medium' | 'high' | 'critical'; timestamp: number; source: { ip?: string; userAgent?: string; playerId?: string; sessionId?: string; }; details: any; mitigated: boolean; mitigationStrategy?: string; } export interface SecurityAudit { timestamp: number; action: string; playerId?: string; resource: string; success: boolean; details: any; ipAddress?: string; userAgent?: string; } export interface PrivacyConsent { playerId: string; consentType: 'analytics' | 'marketing' | 'data_processing' | 'cookies'; granted: boolean; timestamp: number; version: string; ipAddress?: string; } export interface DataEncryption { encryptData(data: any, key?: string): Promise<string>; decryptData(encryptedData: string, key?: string): Promise<any>; generateKey(): Promise<string>; rotateKeys(): Promise<void>; } export interface ThreatDetector { analyzeRequest(request: any): Promise<SecurityThreat | null>; detectBotActivity(playerBehavior: any[]): Promise<boolean>; detectAnomalies(playerData: any): Promise<SecurityThreat[]>; updateThreatModels(): Promise<void>; } class AdvancedSecuritySystem { private config: SecurityConfig; private threats: SecurityThreat[] = []; private auditLog: SecurityAudit[] = []; private privacyConsents: Map<string, PrivacyConsent[]> = new Map(); private encryptionKeys: Map<string, string> = new Map(); private suspiciousActivities: Map<string, any[]> = new Map(); private botDetectionModel: any = null; private anomalyDetectionModel: any = null; constructor(config?: Partial<SecurityConfig>) { this.config = { encryption: { algorithm: 'AES-256-GCM', keyRotationInterval: 24, // 24 hours enableDataEncryption: true, enableTransmissionEncryption: true, ...config?.encryption }, authentication: { tokenExpiration: 60, // 1 hour refreshTokenExpiration: 7, // 7 days maxLoginAttempts: 5, lockoutDuration: 15, // 15 minutes requireBiometric: false, enableMFA: false, ...config?.authentication }, privacy: { dataRetentionDays: 90, anonymizeData: true, consentRequired: true, gdprCompliant: true, ccpaCompliant: true, ...config?.privacy }, threatDetection: { enableAnomalyDetection: true, enableBehaviorAnalysis: true, enableBotDetection: true, suspiciousActivityThreshold: 10, ...config?.threatDetection } }; this.initializeSecurity(); console.log('🔒 Advanced Security System initialized'); } /** * אתחול מערכת האבטחה */ private async initializeSecurity(): Promise<void> { // Initialize encryption await this.initializeEncryption(); // Initialize threat detection models await this.initializeThreatDetection(); // Start periodic security tasks this.startSecurityTasks(); // Setup audit logging this.setupAuditLogging(); } /** * אתחול הצפנה */ private async initializeEncryption(): Promise<void> { try { // Generate master key const masterKey = await this.generateMasterKey(); this.encryptionKeys.set('master', masterKey); // Generate session keys const sessionKey = await this.generateSessionKey(); this.encryptionKeys.set('session', sessionKey); console.log('🔐 Encryption initialized'); } catch (error) { console.error('Encryption initialization failed:', error); throw new Error('Security system initialization failed'); } } /** * אתחול זיהוי איומים */ private async initializeThreatDetection(): Promise<void> { if (this.config.threatDetection.enableBotDetection) { this.botDetectionModel = this.createBotDetectionModel(); } if (this.config.threatDetection.enableAnomalyDetection) { this.anomalyDetectionModel = this.createAnomalyDetectionModel(); } console.log('🛡️ Threat detection initialized'); } /** * התחלת משימות אבטחה תקופתיות */ private startSecurityTasks(): void { // Key rotation setInterval(() => { this.rotateEncryptionKeys(); }, this.config.encryption.keyRotationInterval * 60 * 60 * 1000); // Cleanup old audit logs setInterval(() => { this.cleanupAuditLogs(); }, 24 * 60 * 60 * 1000); // Daily // Threat analysis setInterval(() => { this.analyzeThreatPatterns(); }, 60 * 60 * 1000); // Hourly } /** * הגדרת רישום ביקורת */ private setupAuditLogging(): void { // Setup audit logging for critical actions console.log('📋 Audit logging configured'); } /** * הצפנת נתונים */ async encryptData(data: any, customKey?: string): Promise<string> { try { if (!this.config.encryption.enableDataEncryption) { return JSON.stringify(data); } const key = customKey || this.encryptionKeys.get('session') || ''; const jsonData = JSON.stringify(data); // Simplified encryption (in production, use Web Crypto API) const encrypted = this.simpleEncrypt(jsonData, key); this.logAudit('data_encryption', undefined, 'data', true, { dataSize: jsonData.length }); return encrypted; } catch (error) { this.logAudit('data_encryption', undefined, 'data', false, { error: error.message }); throw new Error('Data encryption failed'); } } /** * פענוח נתונים */ async decryptData(encryptedData: string, customKey?: string): Promise<any> { try { if (!this.config.encryption.enableDataEncryption) { return JSON.parse(encryptedData); } const key = customKey || this.encryptionKeys.get('session') || ''; // Simplified decryption const decrypted = this.simpleDecrypt(encryptedData, key); const data = JSON.parse(decrypted); this.logAudit('data_decryption', undefined, 'data', true, { dataSize: decrypted.length }); return data; } catch (error) { this.logAudit('data_decryption', undefined, 'data', false, { error: error.message }); throw new Error('Data decryption failed'); } } /** * זיהוי איומי אבטחה */ async detectThreats(request: { playerId?: string; sessionId?: string; action: string; data?: any; metadata?: any; }): Promise<SecurityThreat[]> { const threats: SecurityThreat[] = []; try { // Check for brute force attacks const bruteForceThreats = await this.detectBruteForce(request); threats.push(...bruteForceThreats); // Check for suspicious behavior if (this.config.threatDetection.enableBehaviorAnalysis) { const behaviorThreats = await this.detectSuspiciousBehavior(request); threats.push(...behaviorThreats); } // Check for bot activity if (this.config.threatDetection.enableBotDetection) { const botThreats = await this.detectBotActivity(request); threats.push(...botThreats); } // Check for injection attacks const injectionThreats = await this.detectInjectionAttacks(request); threats.push(...injectionThreats); // Log detected threats threats.forEach(threat => { this.threats.push(threat); this.handleThreat(threat); }); return threats; } catch (error) { console.error('Threat detection error:', error); return []; } } /** * זיהוי התקפות brute force */ private async detectBruteForce(request: any): Promise<SecurityThreat[]> { const threats: SecurityThreat[] = []; if (request.action === 'login_attempt' && request.metadata?.failed) { const playerId = request.playerId || 'unknown'; const attempts = this.getFailedLoginAttempts(playerId); if (attempts >= this.config.authentication.maxLoginAttempts) { threats.push({ id: `brute_force_${Date.now()}`, type: 'brute_force', severity: 'high', timestamp: Date.now(), source: { playerId, sessionId: request.sessionId, ip: request.metadata?.ip, userAgent: request.metadata?.userAgent }, details: { failedAttempts: attempts }, mitigated: false }); } } return threats; } /** * זיהוי התנהגות חשודה */ private async detectSuspiciousBehavior(request: any): Promise<SecurityThreat[]> { const threats: SecurityThreat[] = []; if (!request.playerId) return threats; const playerActivities = this.suspiciousActivities.get(request.playerId) || []; playerActivities.push({ action: request.action, timestamp: Date.now(), data: request.data }); // Keep only recent activities const recentActivities = playerActivities.filter( activity => Date.now() - activity.timestamp < 60 * 60 * 1000 // Last hour ); this.suspiciousActivities.set(request.playerId, recentActivities); // Analyze for suspicious patterns if (recentActivities.length > this.config.threatDetection.suspiciousActivityThreshold) { const isAnomalous = await this.analyzeActivityPattern(recentActivities); if (isAnomalous) { threats.push({ id: `suspicious_behavior_${Date.now()}`, type: 'suspicious_behavior', severity: 'medium', timestamp: Date.now(), source: { playerId: request.playerId }, details: { activityCount: recentActivities.length, pattern: 'high_frequency' }, mitigated: false }); } } return threats; } /** * זיהוי פעילות בוטים */ private async detectBotActivity(request: any): Promise<SecurityThreat[]> { const threats: SecurityThreat[] = []; if (!this.botDetectionModel || !request.playerId) return threats; const playerBehavior = this.suspiciousActivities.get(request.playerId) || []; const isBotLikely = await this.analyzeBotBehavior(playerBehavior); if (isBotLikely > 0.8) { // 80% confidence threshold threats.push({ id: `bot_activity_${Date.now()}`, type: 'bot_activity', severity: 'high', timestamp: Date.now(), source: { playerId: request.playerId }, details: { confidence: isBotLikely }, mitigated: false }); } return threats; } /** * זיהוי התקפות injection */ private async detectInjectionAttacks(request: any): Promise<SecurityThreat[]> { const threats: SecurityThreat[] = []; if (request.data && typeof request.data === 'string') { const suspiciousPatterns = [ /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, /('|(\\')|(;|:|\\x3B|\\u003B|\\u3B|%3B)|(\||\\x7C|\\u007C|\\u7C|%7C)|(\*|\\x2A|\\u002A|\\u2A|%2A))/gi, /(select|union|insert|delete|update|drop|create|alter|exec|execute)/gi ]; for (const pattern of suspiciousPatterns) { if (pattern.test(request.data)) { threats.push({ id: `injection_attack_${Date.now()}`, type: 'injection_attack', severity: 'critical', timestamp: Date.now(), source: { playerId: request.playerId, sessionId: request.sessionId }, details: { pattern: pattern.source, data: request.data }, mitigated: false }); break; } } } return threats; } /** * טיפול באיום שזוהה */ private async handleThreat(threat: SecurityThreat): Promise<void> { console.warn(`🚨 Security threat detected: ${threat.type} (${threat.severity})`); let mitigationStrategy = ''; switch (threat.type) { case 'brute_force': mitigationStrategy = await this.mitigateBruteForce(threat); break; case 'suspicious_behavior': mitigationStrategy = await this.mitigateSuspiciousBehavior(threat); break; case 'bot_activity': mitigationStrategy = await this.mitigateBotActivity(threat); break; case 'injection_attack': mitigationStrategy = await this.mitigateInjectionAttack(threat); break; } threat.mitigated = true; threat.mitigationStrategy = mitigationStrategy; // Log mitigation this.logAudit('threat_mitigation', threat.source.playerId, 'security', true, { threatId: threat.id, threatType: threat.type, strategy: mitigationStrategy }); } /** * מניעת התקפות brute force */ private async mitigateBruteForce(threat: SecurityThreat): Promise<string> { const playerId = threat.source.playerId; if (playerId) { // Lock account temporarily this.lockPlayerAccount(playerId, this.config.authentication.lockoutDuration); return `Account locked for ${this.config.authentication.lockoutDuration} minutes`; } return 'IP-based rate limiting applied'; } /** * מניעת התנהגות חשודה */ private async mitigateSuspiciousBehavior(threat: SecurityThreat): Promise<string> { const playerId = threat.source.playerId; if (playerId) { // Add to monitoring list this.addToSuspiciousPlayersList(playerId); return 'Player added to enhanced monitoring'; } return 'Increased monitoring applied'; } /** * מניעת פעילות בוטים */ private async mitigateBotActivity(threat: SecurityThreat): Promise<string> { const playerId = threat.source.playerId; if (playerId) { // Require additional verification this.requireAdditionalVerification(playerId); return 'Additional verification required'; } return 'CAPTCHA challenge issued'; } /** * מניעת התקפות injection */ private async mitigateInjectionAttack(threat: SecurityThreat): Promise<string> { // Block the request and sanitize input this.blockSuspiciousRequest(threat.source); return 'Request blocked and input sanitized'; } /** * ניהול הסכמות פרטיות */ async managePrivacyConsent( playerId: string, consentType: PrivacyConsent['consentType'], granted: boolean, version: string = '1.0' ): Promise<void> { const consent: PrivacyConsent = { playerId, consentType, granted, timestamp: Date.now(), version, ipAddress: this.getCurrentIP() }; if (!this.privacyConsents.has(playerId)) { this.privacyConsents.set(playerId, []); } this.privacyConsents.get(playerId)!.push(consent); this.logAudit('privacy_consent', playerId, 'consent', true, { type: consentType, granted, version }); console.log(`📋 Privacy consent updated: ${playerId} - ${consentType}: ${granted}`); } /** * בדיקת הסכמה לפרטיות */ hasPrivacyConsent(playerId: string, consentType: PrivacyConsent['consentType']): boolean { const consents = this.privacyConsents.get(playerId) || []; const latestConsent = consents .filter(c => c.consentType === consentType) .sort((a, b) => b.timestamp - a.timestamp)[0]; return latestConsent ? latestConsent.granted : false; } /** * אנונימיזציה של נתונים */ async anonymizePlayerData(playerId: string): Promise<void> { if (!this.config.privacy.anonymizeData) return; // Remove or hash personal identifiable information const anonymizedId = this.generateAnonymousId(playerId); this.logAudit('data_anonymization', playerId, 'privacy', true, { anonymizedId }); console.log(`🔒 Player data anonymized: ${playerId} → ${anonymizedId}`); } /** * מחיקת נתונים ישנים */ async purgeOldData(): Promise<void> { const cutoffDate = Date.now() - (this.config.privacy.dataRetentionDays * 24 * 60 * 60 * 1000); // Remove old audit logs this.auditLog = this.auditLog.filter(log => log.timestamp >= cutoffDate); // Remove old threats this.threats = this.threats.filter(threat => threat.timestamp >= cutoffDate); // Remove old consents (keep latest for each type) this.privacyConsents.forEach((consents, playerId) => { const latestConsents = new Map<string, PrivacyConsent>(); consents.forEach(consent => { const existing = latestConsents.get(consent.consentType); if (!existing || consent.timestamp > existing.timestamp) { latestConsents.set(consent.consentType, consent); } }); this.privacyConsents.set(playerId, Array.from(latestConsents.values())); }); console.log('🗑️ Old data purged according to retention policy'); } // Helper methods private async generateMasterKey(): Promise<string> { // In production, use proper cryptographic key generation return 'master_key_' + Math.random().toString(36).substring(2, 15); } private async generateSessionKey(): Promise<string> { return 'session_key_' + Math.random().toString(36).substring(2, 15); } private simpleEncrypt(data: string, key: string): string { // Simplified encryption - in production use Web Crypto API return btoa(data + key); } private simpleDecrypt(encryptedData: string, key: string): string { // Simplified decryption const decoded = atob(encryptedData); return decoded.substring(0, decoded.length - key.length); } private createBotDetectionModel(): any { // Simplified bot detection model return { analyze: (behavior: any[]) => { // Check for bot-like patterns const avgTimeBetweenActions = this.calculateAvgTimeBetweenActions(behavior); const actionVariability = this.calculateActionVariability(behavior); // Bots typically have very consistent timing and limited action variety if (avgTimeBetweenActions < 100 && actionVariability < 0.2) { return 0.9; // High probability of bot } return 0.1; // Low probability of bot } }; } private createAnomalyDetectionModel(): any { return { detect: (data: any) => { // Simplified anomaly detection return Math.random() > 0.9; // 10% chance of anomaly } }; } private calculateAvgTimeBetweenActions(behavior: any[]): number { if (behavior.length < 2) return 1000; const timeDiffs = []; for (let i = 1; i < behavior.length; i++) { timeDiffs.push(behavior[i].timestamp - behavior[i-1].timestamp); } return timeDiffs.reduce((a, b) => a + b, 0) / timeDiffs.length; } private calculateActionVariability(behavior: any[]): number { const actionTypes = new Set(behavior.map(b => b.action)); return actionTypes.size / Math.max(behavior.length, 1); } private async analyzeActivityPattern(activities: any[]): Promise<boolean> { // Simplified pattern analysis const uniqueActions = new Set(activities.map(a => a.action)); const actionRate = activities.length / (60 * 60); // Actions per second in last hour // Suspicious if too many actions or too few unique actions return actionRate > 10 || uniqueActions.size < 3; } private async analyzeBotBehavior(behavior: any[]): Promise<number> { if (!this.botDetectionModel || behavior.length < 5) return 0; return this.botDetectionModel.analyze(behavior); } private getFailedLoginAttempts(playerId: string): number { const recentAudits = this.auditLog.filter(log => log.playerId === playerId && log.action === 'login_attempt' && !log.success && Date.now() - log.timestamp < 60 * 60 * 1000 // Last hour ); return recentAudits.length; } private lockPlayerAccount(playerId: string, duration: number): void { // Implementation would integrate with authentication system console.log(`🔒 Account locked: ${playerId} for ${duration} minutes`); } private addToSuspiciousPlayersList(playerId: string): void { // Add to monitoring list console.log(`👁️ Player added to monitoring: ${playerId}`); } private requireAdditionalVerification(playerId: string): void { // Require CAPTCHA or other verification console.log(`🔐 Additional verification required: ${playerId}`); } private blockSuspiciousRequest(source: any): void { // Block the request console.log(`🚫 Request blocked from: ${JSON.stringify(source)}`); } private getCurrentIP(): string { return '127.0.0.1'; // Placeholder } private generateAnonymousId(playerId: string): string { // Simple hash-like anonymization return 'anon_' + btoa(playerId).replace(/[^a-zA-Z0-9]/g, '').substring(0, 10); } private async rotateEncryptionKeys(): Promise<void> { const newSessionKey = await this.generateSessionKey(); this.encryptionKeys.set('session', newSessionKey); this.logAudit('key_rotation', undefined, 'security', true, { timestamp: Date.now() }); console.log('🔄 Encryption keys rotated'); } private cleanupAuditLogs(): void { const cutoff = Date.now() - (30 * 24 * 60 * 60 * 1000); // 30 days this.auditLog = this.auditLog.filter(log => log.timestamp >= cutoff); console.log('🧹 Audit logs cleaned up'); } private async analyzeThreatPatterns(): Promise<void> { // Analyze threat patterns for intelligence const recentThreats = this.threats.filter( threat => Date.now() - threat.timestamp < 24 * 60 * 60 * 1000 ); if (recentThreats.length > 0) { console.log(`📊 Threat analysis: ${recentThreats.length} threats in last 24h`); } } private logAudit( action: string, playerId: string | undefined, resource: string, success: boolean, details: any ): void { const audit: SecurityAudit = { timestamp: Date.now(), action, playerId, resource, success, details, ipAddress: this.getCurrentIP(), userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : undefined }; this.auditLog.push(audit); } /** * Public API Methods */ /** * קבלת דוח אבטחה */ getSecurityReport(): { threats: SecurityThreat[]; auditSummary: any; privacyCompliance: any; recommendations: string[]; } { const recentThreats = this.threats.filter( threat => Date.now() - threat.timestamp < 24 * 60 * 60 * 1000 ); const auditSummary = { totalActions: this.auditLog.length, successRate: this.auditLog.filter(log => log.success).length / Math.max(this.auditLog.length, 1), uniquePlayers: new Set(this.auditLog.map(log => log.playerId).filter(Boolean)).size }; const privacyCompliance = { totalConsents: Array.from(this.privacyConsents.values()).flat().length, activeConsents: Array.from(this.privacyConsents.values()) .flat() .filter(consent => consent.granted).length, gdprCompliant: this.config.privacy.gdprCompliant, ccpaCompliant: this.config.privacy.ccpaCompliant }; const recommendations = this.generateSecurityRecommendations(recentThreats); return { threats: recentThreats, auditSummary, privacyCompliance, recommendations }; } private generateSecurityRecommendations(threats: SecurityThreat[]): string[] { const recommendations: string[] = []; if (threats.length > 10) { recommendations.push('Consider implementing additional rate limiting'); } const criticalThreats = threats.filter(t => t.severity === 'critical'); if (criticalThreats.length > 0) { recommendations.push('Review and strengthen input validation'); } if (threats.some(t => t.type === 'bot_activity')) { recommendations.push('Consider implementing CAPTCHA challenges'); } return recommendations; } /** * ניקוי משאבים */ dispose(): void { this.threats.length = 0; this.auditLog.length = 0; this.privacyConsents.clear(); this.encryptionKeys.clear(); this.suspiciousActivities.clear(); console.log('🔒 Advanced Security System disposed'); } } export default AdvancedSecuritySystem;