Files
.gitignore
index.js
package.json
Code
3 379
index.js
const {
Client,
GatewayIntentBits,
SlashCommandBuilder,
EmbedBuilder,
REST,
Routes
} = require('discord.js');
const JavaScriptObfuscator = require('javascript-obfuscator');
const acorn = require('acorn');
const path = require('node:path');
require('dotenv').config();
const MAX_INPUT_BYTES = 256 * 1024;
const MAX_MAXIMUM_PRESET_BYTES = 64 * 1024;
const OBFUSCATION_COOLDOWN_MS = 15_000;
const cooldowns = new Map();
const commands = [
new SlashCommandBuilder()
.setName('obfuscate')
.setDescription('Obfuscate a JavaScript file and get the result as an attachment.')
.addAttachmentOption(option =>
option.setName('file').setDescription('A .js, .mjs, or .cjs file').setRequired(true)
)
.addStringOption(option =>
option
.setName('preset')
.setDescription('Choose the obfuscation strength')
.setRequired(true)
.addChoices(
{ name: 'Balanced', value: 'balanced' },
{ name: 'Strong', value: 'strong' },
{ name: 'Maximum', value: 'maximum' }
)
),
new SlashCommandBuilder()
.setName('analyze')
.setDescription('Check JavaScript syntax and view basic source statistics.')
.addAttachmentOption(option =>
option.setName('file').setDescription('A .js, .mjs, or .cjs file').setRequired(true)
),
new SlashCommandBuilder()
.setName('presets')
.setDescription('Compare the available obfuscation presets.'),
new SlashCommandBuilder()
.setName('help')
.setDescription('Show the bot commands and usage.')
];
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
function getObfuscatorOptions(preset) {
const common = {
compact: true,
simplify: true,
stringArray: true,
stringArrayThreshold: 0.65,
identifierNamesGenerator: 'hexadecimal',
renameGlobals: false
};
if (preset === 'strong') {
return {
...common,
stringArrayEncoding: ['base64'],
stringArrayThreshold: 0.8,
controlFlowFlattening: true,
controlFlowFlatteningThreshold: 0.35,
deadCodeInjection: true,
deadCodeInjectionThreshold: 0.08
};
}
if (preset === 'maximum') {
return {
...common,
stringArrayEncoding: ['rc4'],
stringArrayThreshold: 1,
controlFlowFlattening: true,
controlFlowFlatteningThreshold: 0.65,
deadCodeInjection: true,
deadCodeInjectionThreshold: 0.2,
numbersToExpressions: true,
transformObjectKeys: true,
selfDefending: true
};
}
return common;
}
function validateJavaScriptAttachment(attachment) {
const extension = path.extname(attachment.name).toLowerCase();
if (!['.js', '.mjs', '.cjs'].includes(extension)) {
throw new Error('Upload a JavaScript file ending in .js, .mjs, or .cjs.');
}
return extension;
}
async function downloadAttachment(attachment, maxBytes) {
if (attachment.size > maxBytes) {
throw new Error(`That file is too large. The limit for this command is ${Math.floor(maxBytes / 1024)} KB.`);
}
const url = new URL(attachment.url);
if (!['cdn.discordapp.com', 'media.discordapp.net'].includes(url.hostname)) {
throw new Error('The attachment URL is not a supported Discord file URL.');
}
const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(15_000) });
if (!response.ok || !response.body) {
throw new Error('Could not download that attachment from Discord.');
}
const contentLength = Number(response.headers.get('content-length'));
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
throw new Error(`That file is too large. The limit for this command is ${Math.floor(maxBytes / 1024)} KB.`);
}
const reader = response.body.getReader();
const chunks = [];
let totalBytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.byteLength;
if (totalBytes > maxBytes) {
await reader.cancel();
throw new Error(`That file is too large. The limit for this command is ${Math.floor(maxBytes / 1024)} KB.`);
}
chunks.push(Buffer.from(value));
}
} finally {
reader.releaseLock();
}
return Buffer.concat(chunks, totalBytes).toString('utf8');
}
function acquireObfuscationCooldown(userId) {
const now = Date.now();
for (const [id, expiresAt] of cooldowns) {
if (expiresAt <= now) cooldowns.delete(id);
}
const expiresAt = cooldowns.get(userId);
if (expiresAt && expiresAt > now) {
return Math.ceil((expiresAt - now) / 1000);
}
cooldowns.set(userId, now + OBFUSCATION_COOLDOWN_MS);
return 0;
}
function parseJavaScript(source) {
try {
return acorn.parse(source, {
ecmaVersion: 'latest',
sourceType: 'module',
allowHashBang: true
});
} catch (moduleError) {
try {
return acorn.parse(source, {
ecmaVersion: 'latest',
sourceType: 'script',
allowHashBang: true,
allowReturnOutsideFunction: true
});
} catch (scriptError) {
throw new Error(`JavaScript syntax error: ${scriptError.message || moduleError.message}`);
}
}
}
function collectSyntaxStats(node, stats) {
if (!node || typeof node !== 'object') return;
if (Array.isArray(node)) {
for (const child of node) collectSyntaxStats(child, stats);
return;
}
if (typeof node.type === 'string') {
if (['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'].includes(node.type)) {
stats.functions += 1;
}
if (node.type === 'ImportDeclaration') stats.imports += 1;
if (node.type.startsWith('Export')) stats.exports += 1;
}
for (const [key, value] of Object.entries(node)) {
if (key !== 'start' && key !== 'end' && key !== 'loc' && value && typeof value === 'object') {
collectSyntaxStats(value, stats);
}
}
}