-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobfuscator.ts
More file actions
executable file
·217 lines (183 loc) · 6.69 KB
/
obfuscator.ts
File metadata and controls
executable file
·217 lines (183 loc) · 6.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/env bun
import yargs from 'yargs/yargs';
import { hideBin } from 'yargs/helpers';
import * as fs from 'node:fs';
import * as path from 'node:path';
import JavaScriptObfuscator from 'javascript-obfuscator';
import * as cheerio from 'cheerio';
import { minify } from 'html-minifier-terser';
// --- 1. 定义命令行参数 ---
const argv = yargs(hideBin(process.argv))
.usage('用法: $0 --input <文件路径> --output <文件路径>')
.option('input', {
alias: 'i',
type: 'string',
description: '输入的 HTML 或 JS 文件路径',
demandOption: true, // 必需参数
})
.option('output', {
alias: 'o',
type: 'string',
description: '输出文件路径',
demandOption: true, // 必需参数
})
.help()
.alias('help', 'h')
.argv as { input: string; output: string };
// --- 2. 定义混淆器配置 ---
// JavaScriptObfuscator 的配置,可以根据需要调整
const jsObfuscatorOptions = {
compact: true, // 压缩代码
controlFlowFlattening: true, // 控制流扁平化
controlFlowFlatteningThreshold: 0.75,
deadCodeInjection: true, // 注入死代码
deadCodeInjectionThreshold: 0.4,
debugProtection: false, // 调试保护(会阻止在控制台调试)
debugProtectionInterval: 0,
disableConsoleOutput: true, // 禁用 console.log
identifierNamesGenerator: 'hexadecimal', // 标识符名生成方式
log: false,
numbersToExpressions: true,
renameGlobals: false,
selfDefending: true, // 自我保护,防止代码被格式化
simplify: true,
splitStrings: true,
splitStringsChunkLength: 10,
stringArray: true, // 字符串数组
stringArrayCallsTransform: true,
stringArrayEncoding: ['base64'], // 字符串数组编码
stringArrayIndexShift: true,
stringArrayRotate: true,
stringArrayShuffle: true,
stringArrayWrappersCount: 2,
stringArrayWrappersChainedCalls: true,
stringArrayWrappersParametersMaxCount: 4,
stringArrayWrappersType: 'function',
stringArrayThreshold: 0.75,
transformObjectKeys: true,
unicodeEscapeSequence: false,
};
// HTML 压缩器配置
const htmlMinifyOptions = {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
minifyJS: true, // 也压缩内联JS
minifyCSS: true, // 也压缩内联CSS
};
// --- 3. 核心混淆函数 ---
/**
* 混淆 JavaScript 代码
* @param code JS 源码
* @returns 混淆后的代码
*/
function obfuscateJs(code: string): string {
const obfuscated = JavaScriptObfuscator.obfuscate(code, jsObfuscatorOptions);
return obfuscated.getObfuscatedCode();
}
/**
* 处理 HTML 文件
* @param htmlContent HTML 源码
* @param inputDir 输入文件的目录,用于解析相对路径
* @param outputDir 输出文件的目录,用于写入混淆后的外部JS
* @returns 处理并压缩后的 HTML 内容
*/
async function processHtml(htmlContent: string, inputDir: string, outputDir: string): Promise<string> {
const $ = cheerio.load(htmlContent);
// 遍历所有 <script> 标签
for (const script of $('script').toArray()) {
const $script = $(script);
// 只处理真正的 JS 脚本,跳过 JSON-LD 等其他类型
const typeAttr = ($script.attr('type') || '').toLowerCase();
const isJsType =
!typeAttr || // 默认不写 type 时当成 text/javascript
typeAttr === 'text/javascript' ||
typeAttr === 'application/javascript' ||
typeAttr === 'module' ||
typeAttr === 'text/ecmascript' ||
typeAttr === 'application/ecmascript';
if (!isJsType) {
// 对于 application/ld+json 等非 JS 类型,直接跳过
continue;
}
// 情况1: 处理内联 JS
if (!$script.attr('src')) {
const inlineCode = $script.html() || '';
if (inlineCode.trim()) {
try {
const obfuscatedCode = obfuscateJs(inlineCode);
$script.html(obfuscatedCode);
} catch (err) {
console.error('❌ 混淆内联 JS 失败,已跳过该 <script>:', err);
}
}
}
// 情况2: 处理外部 JS 文件
else {
const src = $script.attr('src')!;
const externalJsPath = path.resolve(inputDir, src);
// 确定外部JS文件的输出路径,保持目录结构
const outputJsPath = path.resolve(outputDir, src);
const outputJsDir = path.dirname(outputJsPath);
try {
// 读取外部JS文件
const externalJsCode = await fs.promises.readFile(externalJsPath, 'utf-8');
// 混淆JS代码
const obfuscatedCode = obfuscateJs(externalJsCode);
// 确保输出目录存在
await fs.promises.mkdir(outputJsDir, { recursive: true });
// 将混淆后的JS写入新文件
await fs.promises.writeFile(outputJsPath, obfuscatedCode);
console.log(`✅ 已混淆并写入外部JS文件: ${outputJsPath}`);
// 注意:HTML中的src路径不需要修改,因为我们保持了相对路径结构
} catch (err) {
console.error(`❌ 处理外部JS文件失败: ${externalJsPath}`, err);
}
}
}
// 获取处理后的HTML
const processedHtml = $.html();
// 压缩HTML
const minifiedHtml = await minify(processedHtml, htmlMinifyOptions);
return minifiedHtml;
}
// --- 4. 主函数 ---
async function main() {
try {
const { input: inputPath, output: outputPath } = argv;
console.log(`🚀 开始处理文件: ${inputPath}`);
// 检查输入文件是否存在
if (!fs.existsSync(inputPath)) {
throw new Error(`输入文件不存在: ${inputPath}`);
}
// 读取输入文件内容
const inputContent = await fs.promises.readFile(inputPath, 'utf-8');
const ext = path.extname(inputPath).toLowerCase();
// 确保输出目录存在
const outputDir = path.dirname(outputPath);
await fs.promises.mkdir(outputDir, { recursive: true });
let finalContent: string;
// 根据文件扩展名执行不同逻辑
if (ext === '.js') {
console.log('🔧 检测到 JS 文件,执行混淆...');
finalContent = obfuscateJs(inputContent);
} else if (ext === '.html') {
console.log('🔧 检测到 HTML 文件,执行处理...');
const inputDir = path.dirname(inputPath);
finalContent = await processHtml(inputContent, inputDir, outputDir);
} else {
throw new Error('不支持的文件类型。请输入 .js 或 .html 文件。');
}
// 写入最终文件
await fs.promises.writeFile(outputPath, finalContent);
console.log(`✅ 处理完成!输出文件: ${outputPath}`);
} catch (error) {
console.error('❌ 发生错误:', error);
process.exit(1); // 非零退出码表示错误
}
}
// 运行主函数
main();