Download security.js from Saedmh/Saed: direct link, hf CLI and curl.
- Browser
- Download file 9.15 kB
-
https://huggingface.co/spaces/Saedmh/Saed/resolve/main/security.js
- Command line
-
hf download hf://spaces/Saedmh/Saed/security.js
-
curl -L -o security.js https://huggingface.co/spaces/Saedmh/Saed/resolve/main/security.js
9.15 kB
| ; | |
| /** | |
| * ╔══════════════════════════════════════════════════════════════════════════╗ | |
| * Security — v19.0 | Security Layers for Bot + Dashboard ║ | |
| * ╠══════════════════════════════════════════════════════════════════════════╣ | |
| * ✅ Rate Limiting: Token bucket per IP/bot ║ | |
| * ✅ Input Validation: Whitelist commands + sanitize strings ║ | |
| * ✅ Auth: Simple password for dashboard (DASH_PASSWORD env) ║ | |
| * ✅ Command Injection Prevention: No eval, parameterized ║ | |
| * ✅ Anti-Bot Detection: Randomized usernames + human patterns ║ | |
| * ✅ Data Protection: Config sanitization ║ | |
| * ╚══════════════════════════════════════════════════════════════════════════╝ | |
| */ | |
| const crypto = require('crypto'); | |
| const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19); | |
| class RateLimiter { | |
| constructor(options = {}) { | |
| this.maxTokens = options.maxTokens || 10; | |
| this.refillRate = options.refillRate || 1; | |
| this.refillInterval = options.refillInterval || 1000; | |
| this.buckets = new Map(); | |
| this._cleanupTimer = setInterval(() => this._cleanup(), 60000); | |
| } | |
| _cleanup() { | |
| const now = Date.now(); | |
| for (const [key, bucket] of this.buckets) { | |
| if (now - bucket.lastRefill > 300000) { | |
| this.buckets.delete(key); | |
| } | |
| } | |
| } | |
| tryConsume(key, tokens = 1) { | |
| const now = Date.now(); | |
| let bucket = this.buckets.get(key); | |
| if (!bucket) { | |
| bucket = { tokens: this.maxTokens, lastRefill: now }; | |
| this.buckets.set(key, bucket); | |
| } | |
| const elapsed = now - bucket.lastRefill; | |
| const refill = Math.floor(elapsed / this.refillInterval) * this.refillRate; | |
| bucket.tokens = Math.min(this.maxTokens, bucket.tokens + refill); | |
| bucket.lastRefill = now; | |
| if (bucket.tokens >= tokens) { | |
| bucket.tokens -= tokens; | |
| return true; | |
| } | |
| return false; | |
| } | |
| getRemaining(key) { | |
| const bucket = this.buckets.get(key); | |
| return bucket ? bucket.tokens : this.maxTokens; | |
| } | |
| destroy() { | |
| clearInterval(this._cleanupTimer); | |
| this.buckets.clear(); | |
| } | |
| } | |
| class SecurityManager { | |
| constructor(config = {}) { | |
| this.dashPassword = config.dashPassword || process.env.DASH_PASSWORD || ''; | |
| this.authEnabled = !!this.dashPassword; | |
| this.sessions = new Map(); | |
| this.sessionTTL = config.sessionTTL || 3600000; | |
| this.rateLimiter = new RateLimiter({ | |
| maxTokens: config.rateMaxTokens || 30, | |
| refillRate: config.rateRefillRate || 1, | |
| refillInterval: config.rateRefillInterval || 1000 | |
| }); | |
| this.apiRateLimiter = new RateLimiter({ | |
| maxTokens: config.apiMaxTokens || 20, | |
| refillRate: config.apiRefillRate || 1, | |
| refillInterval: config.apiRefillInterval || 1000 | |
| }); | |
| this.allowedCommands = new Set([ | |
| 'stop', 'restart', 'plugins', 'optimize', 'come', 'follow', | |
| 'sleep', 'wake', 'chat' | |
| ]); | |
| this.blockedPatterns = [ | |
| /eval\s*\(/i, /exec\s*\(/i, /system\s*\(/i, | |
| /\.\.\//i, /\.\.\\/, /<script/i, /javascript:/i, | |
| /\$\{.*\}/i, /\$\(/i, /`[^`]*`/i | |
| ]; | |
| this.suspiciousIps = new Map(); | |
| this._log('SECURITY', `تم إنشاء Security Manager (Auth: ${this.authEnabled ? 'ON' : 'OFF'})`); | |
| } | |
| _log(tag, msg) { | |
| const ts = tsNow(); | |
| console.log(`[${ts}] [SECURITY] ${tag} ${msg}`); | |
| } | |
| generateSession() { | |
| const token = crypto.randomBytes(32).toString('hex'); | |
| const expires = Date.now() + this.sessionTTL; | |
| this.sessions.set(token, { created: Date.now(), expires }); | |
| return token; | |
| } | |
| validateSession(token) { | |
| if (!token) return false; | |
| const session = this.sessions.get(token); | |
| if (!session) return false; | |
| if (Date.now() > session.expires) { | |
| this.sessions.delete(token); | |
| return false; | |
| } | |
| return true; | |
| } | |
| // مقارنة آمنة ضد هجمات التوقيت (timing attacks) | |
| _safeCompare(a, b) { | |
| const ha = crypto.createHash('sha256').update(String(a)).digest(); | |
| const hb = crypto.createHash('sha256').update(String(b)).digest(); | |
| return crypto.timingSafeEqual(ha, hb); | |
| } | |
| login(password, ip = 'unknown') { | |
| if (!this.authEnabled) return { success: true, token: this.generateSession() }; | |
| // قفل بعد 5 محاولات فاشلة خلال 10 دقائق (حماية من brute-force) | |
| const rec = this.suspiciousIps.get(ip) || { fails: 0, until: 0 }; | |
| if (rec.until > Date.now()) { | |
| this._log('🚫', `IP محظور مؤقتاً: ${ip}`); | |
| return { success: false, error: 'محاولات كثيرة — حاول لاحقاً' }; | |
| } | |
| if (!this._safeCompare(password, this.dashPassword)) { | |
| rec.fails++; | |
| if (rec.fails >= 5) { rec.until = Date.now() + 600000; rec.fails = 0; } | |
| this.suspiciousIps.set(ip, rec); | |
| this._log('❌', 'محاولة دخول فاشلة'); | |
| return { success: false, error: 'كلمة المرور غير صحيحة' }; | |
| } | |
| this.suspiciousIps.delete(ip); | |
| const token = this.generateSession(); | |
| this._log('✅', 'تسجيل دخول ناجح'); | |
| return { success: true, token }; | |
| } | |
| logout(token) { | |
| if (token) this.sessions.delete(token); | |
| } | |
| validatePassword(password) { | |
| if (!this.authEnabled) return true; | |
| return this._safeCompare(password, this.dashPassword); | |
| } | |
| checkRateLimit(key) { | |
| return this.rateLimiter.tryConsume(key); | |
| } | |
| checkApiRateLimit(key) { | |
| return this.apiRateLimiter.tryConsume(key); | |
| } | |
| isCommandAllowed(cmd) { | |
| return this.allowedCommands.has(String(cmd)); | |
| } | |
| sanitizeInput(input) { | |
| if (typeof input !== 'string') return ''; | |
| let clean = input | |
| .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '') | |
| .replace(/[<>]/g, '') | |
| .trim() | |
| .slice(0, 500); | |
| for (const pattern of this.blockedPatterns) { | |
| if (pattern.test(clean)) { | |
| this._log('🚫', `محظور: ${clean.slice(0, 50)}`); | |
| return ''; | |
| } | |
| } | |
| return clean; | |
| } | |
| sanitizeUsername(username) { | |
| if (typeof username !== 'string') return ''; | |
| return username.replace(/[^a-zA-Z0-9_\-]/g, '').slice(0, 16); | |
| } | |
| sanitizeCommand(cmd) { | |
| if (typeof cmd !== 'string') return ''; | |
| return cmd.replace(/[^a-zA-Z0-9_\-\/ ]/g, '').slice(0, 100); | |
| } | |
| isSuspiciousIp(ip) { | |
| const data = this.suspiciousIps.get(ip); | |
| if (!data) return false; | |
| if (Date.now() - data.lastSeen > 3600000) { | |
| this.suspiciousIps.delete(ip); | |
| return false; | |
| } | |
| return data.failures >= 10; | |
| } | |
| reportSuspiciousActivity(ip, reason) { | |
| const data = this.suspiciousIps.get(ip) || { failures: 0, lastSeen: 0 }; | |
| data.failures++; | |
| data.lastSeen = Date.now(); | |
| this.suspiciousIps.set(ip, data); | |
| this._log('🚨', `نشاط مشبوه من ${ip}: ${reason} (فشل #${data.failures})`); | |
| } | |
| getAntiBotConfig() { | |
| return { | |
| useRealisticNames: true, | |
| avoidBotWords: ['bot', 'robot', 'auto', 'mcbot', 'minecraft'], | |
| nameFormats: [ | |
| '{adjective}_{noun}{number}', | |
| '{noun}{noun}{number}', | |
| '{name}_{number}' | |
| ], | |
| adjectives: ['Cool', 'Swift', 'Brave', 'Dark', 'Wild', 'Red', 'Blue', 'Epic', 'Max', 'Neo'], | |
| nouns: ['Miner', 'Crafter', 'Builder', 'Hunter', 'Rider', 'Smith', 'Warden', 'Blade', 'Storm', 'Wolf'], | |
| behaviorPatterns: { | |
| typingDelay: { min: 35, max: 90 }, | |
| thinkPause: { min: 80, max: 300 }, | |
| randomPauses: true, | |
| humanLikeMistakes: false, | |
| emojiFrequency: 0.1 | |
| } | |
| }; | |
| } | |
| generateRealisticName() { | |
| const config = this.getAntiBotConfig(); | |
| const format = config.nameFormats[Math.floor(Math.random() * config.nameFormats.length)]; | |
| const adjective = config.adjectives[Math.floor(Math.random() * config.adjectives.length)]; | |
| const noun = config.nouns[Math.floor(Math.random() * config.nouns.length)]; | |
| const number = Math.floor(Math.random() * 9000) + 1000; | |
| return format | |
| .replace('{adjective}', adjective) | |
| .replace('{noun}', noun) | |
| .replace('{number}', number) | |
| .replace('{name}', noun); | |
| } | |
| getStatus() { | |
| return { | |
| authEnabled: this.authEnabled, | |
| activeSessions: this.sessions.size, | |
| suspiciousIps: this.suspiciousIps.size, | |
| rateLimiterBuckets: this.rateLimiter.buckets.size, | |
| apiRateLimiterBuckets: this.apiRateLimiter.buckets.size, | |
| allowedCommands: [...this.allowedCommands] | |
| }; | |
| } | |
| destroy() { | |
| this.rateLimiter.destroy(); | |
| this.apiRateLimiter.destroy(); | |
| this.sessions.clear(); | |
| this.suspiciousIps.clear(); | |
| } | |
| } | |
| module.exports = { SecurityManager, RateLimiter }; | |