funnycode
Version:
obfuscation {js,ts,cjs,mjs} code
86 lines (83 loc) • 2.71 kB
JavaScript
import { promises } from 'fs';
import { exit } from 'node:process';
import path from 'path';
import fg from 'fast-glob';
import CryptoJS from 'crypto-js';
import JavaScriptObfuscator from 'javascript-obfuscator';
import ts from 'typescript';
import JSON5 from 'json5';
import { loadCache, isUnixBashShellPath, isDir, winPath, cwd, CACHE_PATH } from './utils.mjs';
const cache = loadCache();
async function encode(entry, key) {
let files = [];
if (typeof entry === "string") {
files = await getFiles(entry);
} else {
for (const i of entry)
files.push(await getFiles(i));
}
await transform(files, key);
await save();
}
async function getFiles(entry) {
if (isUnixBashShellPath(entry) || !isDir(winPath(path.join(cwd, entry))))
return await fg(entry);
else
return await fg(`${entry}/**/*.{js,ts,cjs,mjs}`);
}
async function transform(files, key) {
for (const file of files) {
if (Array.isArray(file)) {
await transform(file, key);
} else {
const absolutePath = winPath(path.join(cwd, file));
let code = await promises.readFile(absolutePath, "utf8");
if (/funnycode/.test(code)) {
console.error(`${file} already encoded , Please decode first.`);
} else {
cache[file] = crypto(code, key);
const isTs = path.extname(file) === ".ts";
if (isTs)
code = await toJavascript(code);
let funnycode = obfuscator(code);
funnycode = `/** funnycode symbol */
${funnycode}`;
if (isTs) {
funnycode = `/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
${funnycode}`;
}
funnycode = `/* eslint-disable eslint-comments/no-unlimited-disable */
/* eslint-disable */
${funnycode}`;
await promises.writeFile(absolutePath, funnycode);
console.log(`done ${file}`);
}
}
}
}
function crypto(code, key) {
return CryptoJS.AES.encrypt(code, key).toString();
}
function obfuscator(code) {
const obfuscationResult = JavaScriptObfuscator.obfuscate(code);
return obfuscationResult.getObfuscatedCode();
}
async function toJavascript(code) {
const configPath = ts.findConfigFile(
cwd,
ts.sys.fileExists,
"tsconfig.json"
);
if (!configPath)
throw new Error("Could not find a valid 'tsconfig.json'.");
const tsconfig = await promises.readFile(configPath, "utf8");
const { compilerOptions = {} } = JSON5.parse(tsconfig);
const { outputText } = ts.transpileModule(code, { compilerOptions: { module: compilerOptions.module } });
return outputText;
}
async function save() {
await promises.writeFile(CACHE_PATH, JSON.stringify(cache, null, 2));
exit(0);
}
export { encode as default };