js-confuser-vm 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runtimeObf.ts CHANGED
@@ -3,16 +3,21 @@ import { generate } from "@babel/generator";
3
3
  import { parse } from "@babel/parser";
4
4
  import traverseImport from "@babel/traverse";
5
5
  import { ok } from "assert";
6
- import { choice, shuffle } from "./random.ts";
6
+ import { shuffle } from "./random.ts";
7
7
  import type { Options } from "./options.ts";
8
- import { escapeRegex } from "./utilts.ts";
9
8
  import { minify } from "./minify.ts";
10
- const traverse = traverseImport.default;
9
+ const traverse = (traverseImport.default ||
10
+ traverseImport) as typeof traverseImport.default;
11
11
 
12
12
  export async function obfuscateRuntime(runtime: string, options: Options) {
13
- const ast = parse(runtime, {
14
- sourceType: "unambiguous",
15
- });
13
+ let ast: t.File;
14
+ try {
15
+ ast = parse(runtime, {
16
+ sourceType: "unambiguous",
17
+ });
18
+ } catch (error) {
19
+ throw new Error("VM-Runtime final parsing failed", { cause: error });
20
+ }
16
21
 
17
22
  // shuffle order of opcode handlers
18
23
 
@@ -38,10 +43,19 @@ export async function obfuscateRuntime(runtime: string, options: Options) {
38
43
  switchStatement.cases = shuffle(switchStatement.cases);
39
44
  }
40
45
 
41
- let generated = generate(ast).code;
46
+ let generated: string;
47
+ try {
48
+ generated = generate(ast).code;
49
+ } catch (error) {
50
+ throw new Error("VM-Runtime final generation failed", { cause: error });
51
+ }
42
52
 
43
53
  if (options.minify) {
44
- generated = await minify(generated);
54
+ try {
55
+ generated = await minify(generated);
56
+ } catch (error) {
57
+ throw new Error("VM-Runtime final minification failed", { cause: error });
58
+ }
45
59
  }
46
60
 
47
61
  return generated;
@@ -0,0 +1,30 @@
1
+ import { Instruction } from "../types.ts";
2
+
3
+ interface BasicBlock {
4
+ label: string;
5
+ body: Instruction;
6
+ jumpLabels?: Set<string>;
7
+ }
8
+
9
+ /**
10
+ * Breaks functions into DAGs (Directed Acyclic Graphs)
11
+ *
12
+ * - 1. Break bytecode into chunks
13
+ * - 2. Shuffle chunks but remember their original position
14
+ * - 3. Create an effectively Switch statement inside a While loop, each case is a chunk, and the while loops exits on the last transition.
15
+ *
16
+ * The Switch statement:
17
+ *
18
+ * - 1. The state variable controls which case will run next
19
+ * - 2. At the end of each case, the state variable is updated to the next block of code.
20
+ * - 3. The while loop continues until the the state variable is the end state.
21
+ */
22
+ export async function controlFlowFlattening(bytecode: Instruction) {
23
+ // break bytecode into basic blocks
24
+ // 1. read bytecode and track the current label from the IR-instruction "defineLabel"
25
+ // 2. track any potential jumps inside this block using the IR-instruction operand "label"
26
+ // at this stage in the passing process, may still use these IR-instruction labels for jumps, meaning no effort is required to maintain absolute PCs
27
+ // create a bare CFF implementation of a simple switch dispatch loop effectively
28
+ // This CFF implementation should only apply to "easy jumps" such as conditional jump (if-statement)
29
+ // the complex and specific jumps for for..in shouldn't get flattened
30
+ }
@@ -0,0 +1,42 @@
1
+ import type { Bytecode, Instruction } from "../types.ts";
2
+ import { SOURCE_NODE_SYM } from "../compiler.ts";
3
+
4
+ // Resolve all {type:"constant", value} operands to integer indices into the
5
+ // constants pool. Returns both the resolved bytecode and the constants array
6
+ // so the Serializer can use it for comment generation and output.
7
+ export function resolveConstants(bc: Bytecode): {
8
+ bytecode: Bytecode;
9
+ constants: any[];
10
+ } {
11
+ const constants: any[] = [];
12
+ const constantsMap = new Map<any, number>();
13
+
14
+ function intern(value: any): number {
15
+ let idx = constantsMap.get(value);
16
+ if (typeof idx !== "number") {
17
+ idx = constants.length;
18
+ constantsMap.set(value, idx);
19
+ constants.push(value);
20
+ }
21
+ return idx;
22
+ }
23
+
24
+ const resolved: Bytecode = [];
25
+ for (const instr of bc) {
26
+ const [op, operand] = instr;
27
+ if (
28
+ operand !== undefined &&
29
+ operand !== null &&
30
+ typeof operand === "object" &&
31
+ (operand as any).type === "constant"
32
+ ) {
33
+ const newInstr: Instruction = [op, intern((operand as any).value)];
34
+ (newInstr as any)[SOURCE_NODE_SYM] = (instr as any)[SOURCE_NODE_SYM];
35
+ resolved.push(newInstr);
36
+ } else {
37
+ resolved.push(instr);
38
+ }
39
+ }
40
+
41
+ return { bytecode: resolved, constants };
42
+ }
@@ -0,0 +1,83 @@
1
+ // --- Label IR ---
2
+ // During compilation, jump targets are symbolic labels instead of hard-coded
3
+ // PC numbers. Two IR "pseudo operands" carry the label information:
4
+ //
5
+ // defineLabel operand : [null, {type:"defineLabel", label:"FN_ENTRY_1"}]
6
+ // Marks a position in the bytecode array.
7
+ // resolveLabels() strips these out entirely.
8
+ //
9
+ // label ref operand : [OP.JUMP, {type:"label", label:"FN_ENTRY_1"}]
10
+ // Used as the operand of any jump instruction. resolveLabels() replaces
11
+ // it with the integer PC that the corresponding defineLabel resolves to.
12
+
13
+ import type { Instruction } from "../types.ts";
14
+ import { Compiler } from "../compiler.ts";
15
+
16
+ // Resolve symbolic labels to absolute PC indices within a bytecode array.
17
+ // defineLabel pseudo-instructions are stripped; label-ref operands become ints.
18
+ // Mutates `bc` in place so callers holding a reference see the resolved result.
19
+ export function resolveLabels(
20
+ bc: Instruction[],
21
+ compiler: Compiler,
22
+ ): {
23
+ bytecode: Instruction[];
24
+ } {
25
+ // Pass 1 – walk the array and record each label's real PC, counting only
26
+ // real instructions (defineLabel pseudo-ops don't occupy a PC slot).
27
+ const labelToPc = new Map<string, number>();
28
+ let realPc = 0;
29
+ for (const instr of bc) {
30
+ const op = instr[0];
31
+ const operand = instr[1];
32
+ if (
33
+ op === null &&
34
+ operand !== null &&
35
+ typeof operand === "object" &&
36
+ operand.type === "defineLabel"
37
+ ) {
38
+ labelToPc.set(operand.label, realPc);
39
+ } else {
40
+ realPc++;
41
+ }
42
+ }
43
+
44
+ // Pass 2 – build the resolved instruction list.
45
+ const resolved: any[] = [];
46
+ for (const instr of bc) {
47
+ const op = instr[0];
48
+ const operand = instr[1];
49
+
50
+ // Strip defineLabel pseudo-ops.
51
+ if (
52
+ op === null &&
53
+ typeof operand === "object" &&
54
+ operand?.type === "defineLabel"
55
+ ) {
56
+ continue;
57
+ }
58
+
59
+ // Replace label-ref operands with integer PCs.
60
+ if (
61
+ operand !== undefined &&
62
+ operand !== null &&
63
+ typeof operand === "object" &&
64
+ operand.type === "label"
65
+ ) {
66
+ const pc = labelToPc.get(operand.label);
67
+ if (pc === undefined)
68
+ throw new Error(`Undefined label: ${operand.label}`);
69
+ resolved.push([op, pc + (operand.offset ?? 0)]);
70
+ } else {
71
+ resolved.push(instr);
72
+ }
73
+ }
74
+
75
+ // Patch each function descriptor's startPc now that labels are resolved.
76
+ for (const desc of compiler.fnDescriptors) {
77
+ desc.startPc = labelToPc.get(desc.startLabel);
78
+ }
79
+
80
+ return {
81
+ bytecode: resolved,
82
+ };
83
+ }
@@ -0,0 +1,124 @@
1
+ import type { Bytecode, Instruction } from "../types.ts";
2
+ import { Compiler } from "../compiler.ts";
3
+
4
+ export function selfModifying(
5
+ bc: Bytecode,
6
+ compiler: Compiler,
7
+ ): { bytecode: Bytecode } {
8
+ // Walk the bytecode looking for "defineLabel" pseudo-ops, which start basic
9
+ // blocks. For each block we collect the body (instructions between the label
10
+ // and the next label/jump terminator), move it to the end of the bytecode
11
+ // under a fresh "patch_LXX" label, and replace it in-place with:
12
+ //
13
+ // defineLabel ("originalLabel") ← kept as-is (pseudo-op)
14
+ // LOAD_INT { label: patch_LXX, offset: N } ← push slice-end PC
15
+ // LOAD_INT { label: patch_LXX } ← push slice-start PC
16
+ // PATCH { label: originalLabel, offset: 3 } ← destPc = L+3
17
+ // LOAD_INT 0 × N ← N placeholder instructions
18
+ //
19
+ // PATCH pops (start, end) from the stack and copies bytecode[start..end) to
20
+ // bytecode[destPc..]. Since destPc = L+3 = first placeholder, the body is
21
+ // written exactly over the placeholder region on the first call. Subsequent
22
+ // calls are idempotent (same bytes written again). Execution falls through
23
+ // from PATCH into the freshly-patched body at L+3, then continues naturally
24
+ // to whatever terminator (JUMP/RETURN) follows at L+3+N.
25
+
26
+ const { OP, JUMP_OPS } = compiler;
27
+
28
+ const result: Bytecode = [];
29
+ const appended: Bytecode = [];
30
+ let patchCount = 0;
31
+
32
+ let i = 0;
33
+ while (i < bc.length) {
34
+ const instr = bc[i];
35
+ const [op, operand] = instr;
36
+
37
+ // Detect a defineLabel pseudo-op — start of a new basic block.
38
+ if (
39
+ op === null &&
40
+ operand !== null &&
41
+ typeof operand === "object" &&
42
+ (operand as any).type === "defineLabel"
43
+ ) {
44
+ const originalLabel = (operand as any).label as string;
45
+ result.push(instr); // keep the defineLabel marker
46
+ i++;
47
+
48
+ // Collect body: everything after the label until the next terminator.
49
+ let j = i;
50
+ while (j < bc.length) {
51
+ const [nextOp, nextOperand] = bc[j];
52
+
53
+ // Another defineLabel = boundary of the next block.
54
+ if (
55
+ nextOp === null &&
56
+ typeof nextOperand === "object" &&
57
+ (nextOperand as any)?.type === "defineLabel"
58
+ ) {
59
+ break;
60
+ }
61
+
62
+ // Jump instructions, RETURN, and DATA (function header words) all
63
+ // terminate the body without being included in it.
64
+ if (
65
+ nextOp !== null &&
66
+ (JUMP_OPS.has(nextOp) || nextOp === OP.RETURN || nextOp === OP.DATA)
67
+ ) {
68
+ break;
69
+ }
70
+
71
+ j++;
72
+ }
73
+
74
+ const body = bc.slice(i, j);
75
+ const N = body.length;
76
+
77
+ if (N === 0) {
78
+ // Nothing to transform — label is immediately followed by a terminator.
79
+ continue;
80
+ }
81
+
82
+ const patchLabel = `patch_${originalLabel}_${patchCount++}`;
83
+
84
+ // ── Stub (3 real instructions) ──────────────────────────────────────
85
+ // LOAD_INT pushes the end-index of the body slice (patchLabel_pc + N).
86
+ // LOAD_INT pushes the start-index (patchLabel_pc).
87
+ // Stack before PATCH: [end (bottom), start (top)].
88
+ // PATCH: slice(pop()=start, pop()=end) copies the body to destPc = L+3.
89
+ result.push([
90
+ OP.LOAD_INT as number,
91
+ { type: "label", label: patchLabel, offset: N },
92
+ ]);
93
+ result.push([
94
+ OP.LOAD_INT as number,
95
+ { type: "label", label: patchLabel },
96
+ ]);
97
+ result.push([
98
+ OP.PATCH as number,
99
+ { type: "label", label: originalLabel, offset: 3 },
100
+ ]);
101
+
102
+ // ── Placeholders (N instructions) ───────────────────────────────────
103
+ // These are overwritten by PATCH on the first execution. They never
104
+ // execute as LOAD_INT 0 in a correct run.
105
+ for (let p = 0; p < N; p++) {
106
+ result.push([OP.LOAD_INT as number, 0]);
107
+ }
108
+
109
+ // ── Append real body at end ─────────────────────────────────────────
110
+ appended.push([null, { type: "defineLabel", label: patchLabel }]);
111
+ for (const bodyInstr of body) {
112
+ appended.push(bodyInstr);
113
+ }
114
+
115
+ i = j; // skip over the original body in the input array
116
+ continue;
117
+ }
118
+
119
+ result.push(instr);
120
+ i++;
121
+ }
122
+
123
+ return { bytecode: [...result, ...appended] };
124
+ }
package/src/types.ts ADDED
@@ -0,0 +1,24 @@
1
+ // Bytecode supports both real instructions and IR pseudo-instructions
2
+ // Real instruction: [OP.ADD, 5]
3
+ // IR instruction: [null, { type: "defineLabel", label: "FN_ENTRY_1" }]
4
+
5
+ // IR instructions are used to hold symbolic information during compilation
6
+ // All "null" instructions are dropped before assembly time
7
+ export type Instruction = [
8
+ number | null,
9
+ (
10
+ | number
11
+ | { type: "label"; label: string; offset?: number }
12
+ | { type: "defineLabel"; label: string }
13
+ | { type: "constant"; value: any }
14
+ )?,
15
+ ];
16
+
17
+ export type Bytecode = Instruction[];
18
+
19
+ export function constantOperand(value: any): Instruction[1] {
20
+ return {
21
+ type: "constant",
22
+ value: value,
23
+ };
24
+ }
@@ -1,4 +0,0 @@
1
- var window = {};
2
- var global = {};
3
- var atob = {};
4
- var performance;