js-deobfuscator 2.0.0

Universal JavaScript deobfuscator built on OXC
Documentation
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! String array decoder (obfuscator.io pattern).
//!
//! Locked module: runs once, decodes all strings, then convergence loop handles the rest.
//!
//! ## Pattern
//!
//! ```javascript
//! function _0xarr() { var a = ["encoded1", ...]; _0xarr = function(){return a;}; return _0xarr(); }
//! function _0xget(i) { return _0xarr()[i - 0x1a3]; }
//! (function(arr, check) { /* push/shift rotation */ })(_0xarr, 0x44598);
//! console.log(_0xget(0x1a5)); // → decoded string
//! ```
//!
//! ## Pipeline
//!
//! 1. Detect shuffler IIFE (push/shift + parseInt pattern)
//! 2. Collect component source (array function + accessor function)
//! 3. Collect all accessor calls with literal args
//! 4. Execute in Node.js: setup array + accessor + shuffler, batch eval all calls
//! 5. Inline decoded strings at call sites

use rustc_hash::{FxHashMap, FxHashSet};

use oxc::allocator::Allocator;
use oxc::ast::ast::*;
use oxc::ast_visit::{Visit, walk};
use oxc::semantic::{Scoping, SymbolId};
use oxc::span::SPAN;

use oxc_traverse::{Traverse, TraverseCtx, traverse_mut};

use crate::ast::{codegen, create, query};
use crate::engine::error::Result;
use crate::engine::module::{Module, TransformResult};
use crate::eval::node::NodeProcess;
use crate::scope::resolve;

/// String array decoder module. Intended as a **locked** module.
#[derive(Default)]
pub struct StringArrayDecoder {
    node: Option<NodeProcess>,
}

impl Module for StringArrayDecoder {
    fn name(&self) -> &'static str { "StringArrayDecoder" }
    fn changes_symbols(&self) -> bool { true }

    fn transform<'a>(
        &mut self,
        allocator: &'a Allocator,
        program: &mut Program<'a>,
        scoping: Scoping,
    ) -> Result<TransformResult> {
        // Phase 1: Detect shuffler IIFEs
        let mut detector = ShufflerDetector::default();
        let scoping = traverse_mut(&mut detector, allocator, program, scoping, ());

        if detector.systems.is_empty() {
            return Ok(TransformResult { modifications: 0, scoping });
        }

        let mut total_mods = 0;
        let mut scoping = scoping;

        // Phase 2: Collect component source code
        let mut component_symbols: Vec<SymbolId> = Vec::new();
        for sys in &detector.systems {
            component_symbols.push(sys.array_symbol_id);
            component_symbols.push(sys.accessor_symbol_id);
        }
        let mut component_collector = ComponentCollector::new(component_symbols);
        scoping = traverse_mut(&mut component_collector, allocator, program, scoping, ());

        for sys in &detector.systems {
            // Phase 3: Collect all accessor calls with literal args
            let mut call_collector = CallCollector::new(sys.accessor_symbol_id);
            scoping = traverse_mut(&mut call_collector, allocator, program, scoping, ());

            let calls: Vec<String> = call_collector.calls.into_iter().collect();
            if calls.is_empty() { continue; }

            // Phase 4: Execute in Node.js
            let array_code = component_collector.code_map.get(&sys.array_symbol_id)
                .map(|s| s.as_str()).unwrap_or("");
            let accessor_code = component_collector.code_map.get(&sys.accessor_symbol_id)
                .map(|s| s.as_str()).unwrap_or("");

            let decoded = match self.execute(array_code, accessor_code, &sys.shuffler_code, &calls) {
                Some(d) => d,
                None => {
                    tracing::warn!("string array decode failed for system");
                    continue;
                }
            };

            // Phase 5: Inline decoded strings
            let mut inliner = StringInliner::new(sys.accessor_symbol_id, decoded);
            scoping = traverse_mut(&mut inliner, allocator, program, scoping, ());
            total_mods += inliner.modifications;
        }

        Ok(TransformResult { modifications: total_mods, scoping })
    }
}

impl StringArrayDecoder {
    fn ensure_node(&mut self) -> Option<&mut NodeProcess> {
        if self.node.is_none() {
            self.node = NodeProcess::spawn().ok();
        }
        self.node.as_mut()
    }

    fn execute(
        &mut self,
        array_code: &str,
        accessor_code: &str,
        shuffler_code: &str,
        calls: &[String],
    ) -> Option<FxHashMap<String, String>> {
        if calls.is_empty() { return Some(FxHashMap::default()); }

        let node = self.ensure_node()?;

        // Setup: define array + accessor + run shuffler
        let setup = format!("{array_code}\n{accessor_code}\n{shuffler_code}");
        node.eval(&setup)?;

        // Batch eval all calls
        let mut script = String::from("(function() { var r = {};\n");
        for (i, call) in calls.iter().enumerate() {
            script.push_str(&format!("try {{ r[{i}] = {call}; }} catch(e) {{ r[{i}] = null; }}\n"));
        }
        script.push_str("return JSON.stringify(r); })()");

        let result = node.eval(&script)?;
        let result_str = result.as_str()?;
        let obj: serde_json::Value = serde_json::from_str(result_str).ok()?;

        let mut decoded = FxHashMap::default();
        for (i, call) in calls.iter().enumerate() {
            if let Some(s) = obj.get(i.to_string()).and_then(|v| v.as_str()) {
                decoded.insert(call.clone(), s.to_string());
            }
        }
        Some(decoded)
    }
}

// ============================================================================
// Phase 1: Detect shuffler IIFEs
// ============================================================================

struct DetectedSystem {
    array_symbol_id: SymbolId,
    accessor_symbol_id: SymbolId,
    shuffler_code: String,
}

#[derive(Default)]
struct ShufflerDetector {
    systems: Vec<DetectedSystem>,
}

impl<'a> Traverse<'a, ()> for ShufflerDetector {
    fn exit_statement(&mut self, stmt: &mut Statement<'a>, ctx: &mut TraverseCtx<'a, ()>) {
        let Statement::ExpressionStatement(expr_stmt) = stmt else { return; };

        if let Some(sys) = detect_shuffler_in_expr(&expr_stmt.expression, ctx.scoping()) {
            self.systems.push(sys);
            *stmt = ctx.ast.statement_empty(SPAN);
        }
    }
}

fn detect_shuffler_in_expr(expr: &Expression, scoping: &Scoping) -> Option<DetectedSystem> {
    // Match: (function(arr, check) { ... })(_0xarr, 0x44598)
    // Or: !function(arr, check) { ... }(_0xarr, 0x44598)
    let call = match expr {
        Expression::CallExpression(c) if is_iife(c) => c,
        Expression::UnaryExpression(u) => {
            if let Expression::CallExpression(c) = &u.argument {
                if is_iife(c) { c } else { return None; }
            } else { return None; }
        }
        Expression::SequenceExpression(seq) => {
            // Try each sub-expression
            for sub in &seq.expressions {
                if let Some(sys) = detect_shuffler_in_expr(sub, scoping) {
                    return Some(sys);
                }
            }
            return None;
        }
        Expression::ParenthesizedExpression(p) => {
            return detect_shuffler_in_expr(&p.expression, scoping);
        }
        _ => return None,
    };

    // First argument must be an identifier → array function
    let first_expr = call.arguments.first()?.as_expression()?;
    let Expression::Identifier(array_id) = first_expr else { return None; };
    let array_symbol_id = resolve::get_reference_symbol(scoping, array_id)?;

    // Validate body: count push/shift and parseInt
    let callee = unwrap_parens(&call.callee);
    let Expression::FunctionExpression(func) = callee else { return None; };
    let body = func.body.as_ref()?;

    let mut validator = ShufflerValidator::new(scoping, array_symbol_id);
    // Register local symbols
    for param in &func.params.items {
        if let Some(b) = param.pattern.get_binding_identifier() {
            if let Some(sym) = b.symbol_id.get() { validator.local_symbols.insert(sym); }
        }
    }
    for stmt in &body.statements {
        if let Statement::FunctionDeclaration(f) = stmt {
            if let Some(id) = &f.id {
                if let Some(sym) = id.symbol_id.get() { validator.local_symbols.insert(sym); }
            }
        }
        if let Statement::VariableDeclaration(vd) = stmt {
            for decl in &vd.declarations {
                if let Some(b) = decl.id.get_binding_identifier() {
                    if let Some(sym) = b.symbol_id.get() { validator.local_symbols.insert(sym); }
                }
            }
        }
    }
    validator.visit_function_body(body);

    if validator.push_shift_count < 1 || validator.parse_int_count < 2 {
        return None;
    }

    // Find accessor: external function that isn't the array function
    let accessor_symbol_id = validator.external_calls.iter()
        .find(|s| **s != array_symbol_id)
        .copied()?;

    // Capture shuffler source for Node.js execution
    let shuffler_code = codegen::expr_to_code(expr);

    Some(DetectedSystem { array_symbol_id, accessor_symbol_id, shuffler_code })
}

fn is_iife(call: &CallExpression) -> bool {
    matches!(unwrap_parens(&call.callee), Expression::FunctionExpression(_))
}

fn unwrap_parens<'a>(expr: &'a Expression<'a>) -> &'a Expression<'a> {
    match expr {
        Expression::ParenthesizedExpression(p) => unwrap_parens(&p.expression),
        e => e,
    }
}

// ============================================================================
// Shuffler validator (uses Visit, not Traverse)
// ============================================================================

struct ShufflerValidator<'s> {
    scoping: &'s Scoping,
    push_shift_count: usize,
    parse_int_count: usize,
    external_calls: FxHashSet<SymbolId>,
    local_symbols: FxHashSet<SymbolId>,
    array_symbol_id: SymbolId,
}

impl<'s> ShufflerValidator<'s> {
    fn new(scoping: &'s Scoping, array_symbol_id: SymbolId) -> Self {
        Self {
            scoping, push_shift_count: 0, parse_int_count: 0,
            external_calls: FxHashSet::default(),
            local_symbols: FxHashSet::default(),
            array_symbol_id,
        }
    }
}

impl<'a> Visit<'a> for ShufflerValidator<'_> {
    fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
        // Detect push(shift()) pattern
        let is_push = match &call.callee {
            Expression::StaticMemberExpression(m) => m.property.name == "push",
            _ => false,
        };
        if is_push {
            if let Some(Expression::CallExpression(inner_call)) = call.arguments.first().and_then(|a| a.as_expression()) {
                if matches!(&inner_call.callee, Expression::StaticMemberExpression(m) if m.property.name == "shift") {
                    self.push_shift_count += 1;
                }
            }
        }

        // Count parseInt
        if let Expression::Identifier(id) = &call.callee {
            if id.name == "parseInt" { self.parse_int_count += 1; }
        }

        // Track external function calls
        if let Expression::Identifier(id) = &call.callee {
            if let Some(sym) = resolve::get_reference_symbol(self.scoping, id) {
                if sym != self.array_symbol_id && !self.local_symbols.contains(&sym) {
                    self.external_calls.insert(sym);
                }
            }
        }

        walk::walk_call_expression(self, call);
    }
}

// ============================================================================
// Phase 2: Component source collector
// ============================================================================

struct ComponentCollector {
    targets: Vec<SymbolId>,
    code_map: FxHashMap<SymbolId, String>,
}

impl ComponentCollector {
    fn new(targets: Vec<SymbolId>) -> Self {
        Self { targets, code_map: FxHashMap::default() }
    }
}

impl<'a> Traverse<'a, ()> for ComponentCollector {
    fn enter_statement(&mut self, stmt: &mut Statement<'a>, _ctx: &mut TraverseCtx<'a, ()>) {
        if let Statement::FunctionDeclaration(func) = stmt {
            if let Some(id) = &func.id {
                if let Some(sym) = id.symbol_id.get() {
                    if self.targets.contains(&sym) {
                        self.code_map.insert(sym, codegen::stmt_to_code(stmt));
                    }
                }
            }
        }
    }
}

// ============================================================================
// Phase 3: Call collector
// ============================================================================

struct CallCollector {
    accessor_symbol_id: SymbolId,
    calls: FxHashSet<String>,
}

impl CallCollector {
    fn new(accessor_symbol_id: SymbolId) -> Self {
        Self { accessor_symbol_id, calls: FxHashSet::default() }
    }
}

impl<'a> Traverse<'a, ()> for CallCollector {
    fn exit_expression(&mut self, expr: &mut Expression<'a>, ctx: &mut TraverseCtx<'a, ()>) {
        let Expression::CallExpression(call) = &*expr else { return; };
        let Expression::Identifier(id) = &call.callee else { return; };
        let Some(sym) = resolve::get_reference_symbol(ctx.scoping(), id) else { return; };
        if sym != self.accessor_symbol_id { return; }

        // Only collect calls with all-literal arguments
        if !call.arguments.iter().all(|a| a.as_expression().is_some_and(query::is_literal)) {
            return;
        }
        self.calls.insert(codegen::expr_to_code(expr));
    }
}

// ============================================================================
// Phase 5: String inliner
// ============================================================================

struct StringInliner {
    accessor_symbol_id: SymbolId,
    decoded: FxHashMap<String, String>,
    modifications: usize,
}

impl StringInliner {
    fn new(accessor_symbol_id: SymbolId, decoded: FxHashMap<String, String>) -> Self {
        Self { accessor_symbol_id, decoded, modifications: 0 }
    }
}

impl<'a> Traverse<'a, ()> for StringInliner {
    fn exit_expression(&mut self, expr: &mut Expression<'a>, ctx: &mut TraverseCtx<'a, ()>) {
        let Expression::CallExpression(call) = &*expr else { return; };
        let Expression::Identifier(id) = &call.callee else { return; };
        let Some(sym) = resolve::get_reference_symbol(ctx.scoping(), id) else { return; };
        if sym != self.accessor_symbol_id { return; }

        let code = codegen::expr_to_code(expr);
        if let Some(decoded_str) = self.decoded.get(&code) {
            *expr = create::make_string(decoded_str, &ctx.ast);
            self.modifications += 1;
        }
    }
}