1+ const fs = require ( 'fs' ) ;
2+ const parser = require ( '@babel/parser' ) ;
3+ const generator = require ( '@babel/generator' ) ;
4+ const traverse = require ( '@babel/traverse' ) . default ;
5+ const types = require ( '@babel/types' ) ;
6+ const { StringLiteral} = require ( "@babel/generator/lib/generators/types" ) ;
7+ const { assertSourceType} = require ( "@babel/core/lib/config/validation/option-assertions" ) ;
8+
9+ // ------------------------------------------------ 依赖函数 ------------------------------------------------------------
10+
11+ /**
12+ * 把字符串转为code point数组
13+ *
14+ * @param str
15+ * @returns {number[] }
16+ */
17+ function stringToCodePointArray ( str ) {
18+ return Array . from ( str , function ( char ) {
19+ return char . codePointAt ( 0 ) ;
20+ } ) ;
21+ }
22+
23+ /**
24+ * 把babel里的字符串替换为计算code point实时生成字符串的代码,用于隐藏字面值常量
25+ *
26+ * @param stringLiteral
27+ * @returns {ParseResult<Expression> }
28+ */
29+ function stringLiteralToCodePointCode ( stringLiteral ) {
30+ const valueCodePointArray = stringToCodePointArray ( stringLiteral ) ;
31+ // 替换字符串
32+ const code = `String.fromCodePoint(${ valueCodePointArray . join ( ', ' ) } )` ;
33+ return parser . parseExpression ( code ) ;
34+ }
35+
36+ /**
37+ * 生成随机名称,用于对变量名称进行混淆
38+ *
39+ * @returns {string }
40+ */
41+ function generateRandomName ( ) {
42+ return `v_${ Math . random ( ) . toString ( 36 ) . substr ( 2 , 8 ) } ` ;
43+ }
44+
45+ // ---------------------------------------------------------------------------------------------------------------------
46+
47+
48+ // 读取 submit-form-code.js 文件内容,对其进行一些基础的混淆
49+ const code = fs . readFileSync ( 'submit-form-code.js' , 'utf8' ) ;
50+
51+ // 使用 Babel 解析代码
52+ const ast = parser . parse ( code , {
53+ sourceType : 'module' ,
54+ plugins : [ '*' ]
55+ } ) ;
56+
57+ // 遍历 AST 并替换所有的字符串
58+ traverse ( ast , {
59+ // 直接的字面值常量
60+ StringLiteral ( path ) {
61+ path . parent . value = stringLiteralToCodePointCode ( path . node . value ) ;
62+ } ,
63+ // 函数调用的实参字符串也进行编码
64+ CallExpression ( path ) {
65+ const args = path . node . arguments ;
66+ for ( let i = 0 ; i < args . length ; i ++ ) {
67+ const arg = args [ i ] ;
68+ if ( types . isStringLiteral ( arg ) ) {
69+ args [ i ] = stringLiteralToCodePointCode ( arg . value ) ;
70+ }
71+ }
72+ }
73+ } ) ;
74+
75+ // 重命名变量
76+ traverse ( ast , {
77+ // 遍历所有的变量声明
78+ VariableDeclarator ( path ) {
79+ const id = path . node . id ;
80+ if ( types . isIdentifier ( id ) ) {
81+ // 生成新名称
82+ const newName = generateRandomName ( ) ;
83+ // 重命名变量
84+ path . scope . rename ( id . name , newName ) ;
85+ }
86+ }
87+ } ) ;
88+
89+ // 将修改后的 AST 转换回代码
90+ const output = generator . default ( ast , { // 配置选项,例如文件名、代码格式等
91+ sourceMaps : true ,
92+ retainLines : true ,
93+ comments : false ,
94+ minified : false ,
95+ } , code ) ;
96+
97+ // 输出结果
98+ console . log ( output . code ) ;
0 commit comments