You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Never hardcode tokensconsttoken=process.env.DISCORD_TOKEN;// ✅ Goodconsttoken='your_token_here';// ❌ Bad// Use .env filerequire('dotenv').config();
Token Rotation
// Implement token rotationasyncfunctionrotateToken(){// Generate new tokenconstnewToken=awaitgenerateNewToken();// Update environmentprocess.env.DISCORD_TOKEN=newToken;// Restart bot with new tokenprocess.exit(0);}
Permission Management
Principle of Least Privilege
// Only request necessary intentsconstclient=newClient({intents: [GatewayIntentBits.Guilds,GatewayIntentBits.GuildMessages,GatewayIntentBits.MessageContent]});// Check permissions before actionsasyncfunctionkickUser(member,targetMember){if(!member.permissions.has('KickMembers')){thrownewError('Insufficient permissions');}awaittargetMember.kick();}
// Sanitize user inputfunctionsanitizeInput(input){returninput.replace(/[<>]/g,'')// Remove HTML tags.replace(/[^\w\s]/g,'')// Remove special characters.trim().substring(0,100);// Limit length}// Validate command argumentsfunctionvalidateCommand(args,expectedTypes){if(args.length!==expectedTypes.length){thrownewError('Invalid number of arguments');}for(leti=0;i<args.length;i++){if(typeofargs[i]!==expectedTypes[i]){thrownewError(`Argument ${i} must be ${expectedTypes[i]}`);}}}
SQL Injection Prevention
// Use parameterized queriesconstdb=require('better-sqlite3')('bot.db');// ✅ Good - parameterized queryconstuser=db.prepare('SELECT * FROM users WHERE id = ?').get(userId);// ❌ Bad - string concatenationconstuser=db.prepare(`SELECT * FROM users WHERE id = ${userId}`).get();
Rate Limiting
Command Cooldowns
// Implement command cooldownsconstcooldowns=newMap();functionisOnCooldown(userId,command,cooldownTime){constkey=`${userId}-${command}`;constnow=Date.now();if(cooldowns.has(key)){constlastUsed=cooldowns.get(key);if(now-lastUsed<cooldownTime){returntrue;}}cooldowns.set(key,now);returnfalse;}// Apply cooldown to commandif(isOnCooldown(interaction.user.id,'ping',5000)){awaitinteraction.reply('Command is on cooldown!',{ephemeral: true});return;}
API Rate Limiting
// Implement API rate limitingconstrateLimiter=newMap();asyncfunctionmakeAPICall(endpoint,data){constkey=endpoint;constnow=Date.now();if(rateLimiter.has(key)){constlastCall=rateLimiter.get(key);consttimeDiff=now-lastCall;if(timeDiff<1000){// 1 second cooldownawaitnewPromise(resolve=>setTimeout(resolve,1000-timeDiff));}}rateLimiter.set(key,now);// Make API callreturnawaitfetch(endpoint,data);}
Error Handling
Secure Error Messages
// Don't expose sensitive informationtry{awaitdangerousOperation();}catch(error){console.error('Error:',error);// Log full error// Send generic error to userawaitinteraction.reply('An error occurred. Please try again later.');}
constcrypto=require('crypto');functionverifyWebhookSignature(payload,signature,secret){constexpectedSignature=crypto.createHmac('sha256',secret).update(payload).digest('hex');returnsignature===expectedSignature;}// Use in webhook handlerapp.post('/webhook',(req,res)=>{constsignature=req.headers['x-signature'];constpayload=JSON.stringify(req.body);if(!verifyWebhookSignature(payload,signature,process.env.WEBHOOK_SECRET)){returnres.status(401).send('Unauthorized');}// Process webhook});