File size: 4,989 Bytes
b1b7091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126f77a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1b7091
126f77a
 
 
b1b7091
 
 
 
 
 
 
 
 
 
 
 
 
126f77a
 
b1b7091
 
 
126f77a
b1b7091
 
 
 
 
 
 
 
 
 
 
 
 
126f77a
 
 
 
 
 
 
b1b7091
126f77a
 
 
 
 
 
 
 
 
 
 
 
b1b7091
 
 
b92316a
b1b7091
b92316a
 
b1b7091
b92316a
b1b7091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use strict'

const fs = require('fs')
const path = require('path')
const JavaScriptObfuscator = require('javascript-obfuscator')
const bytenode = require('bytenode')

const WEB_DIR = 'web'
const ROOT_TARGETS = ['main.js', 'preload.js']

function listWebJsFiles(appDir) {
  const webDir = path.join(appDir, WEB_DIR)
  if (!fs.existsSync(webDir)) return []

  const out = []
  const stack = [webDir]

  while (stack.length > 0) {
    const dir = stack.pop()
    const entries = fs.readdirSync(dir, { withFileTypes: true })
    for (const ent of entries) {
      const abs = path.join(dir, ent.name)
      if (ent.isDirectory()) {
        stack.push(abs)
        continue
      }
      if (ent.isFile() && ent.name.toLowerCase().endsWith('.js')) {
        out.push(abs)
      }
    }
  }

  return out
}

function obfuscateOne(absPath) {
  const original = fs.readFileSync(absPath, 'utf8')
  if (!original.trim()) return false

  const result = JavaScriptObfuscator.obfuscate(original, {
    compact: true,
    target: 'node',
    controlFlowFlattening: true,
    controlFlowFlatteningThreshold: 0.75,
    deadCodeInjection: false,
    disableConsoleOutput: false,
    identifierNamesGenerator: 'hexadecimal',
    renameGlobals: false,
    selfDefending: true,
    stringArray: true,
    stringArrayEncoding: ['base64'],
    stringArrayThreshold: 1,
    transformObjectKeys: true,
    unicodeEscapeSequence: false
  })

  fs.writeFileSync(absPath, result.getObfuscatedCode(), 'utf8')
  return true
}

// Workspace source root — two levels up from scripts/
const WORKSPACE_ROOT = path.resolve(__dirname, '..')

function assertNotSourceDir(appDir) {
  const resolved = path.resolve(appDir)
  if (
    resolved === WORKSPACE_ROOT ||
    resolved.startsWith(WORKSPACE_ROOT + path.sep)
  ) {
    throw new Error(
      `[bytecode] SAFETY GUARD: appDir "${resolved}" is inside the workspace source!\n` +
      `Aborting to prevent source file corruption.\n` +
      `appDir must be an electron-builder staging (temp) directory.`
    )
  }
}

async function compileRootToBytecode(appDir, relPath) {
  // Safety: must never operate on workspace source files
  assertNotSourceDir(appDir)

  const jsPath = path.join(appDir, relPath)
  if (!fs.existsSync(jsPath)) return false

  const parsed = path.parse(jsPath)
  const jscPath = path.join(parsed.dir, `${parsed.name}.jsc`)

  await bytenode.compileFile({
    filename: jsPath,
    output: jscPath,
    electron: true,
    compileAsModule: true
  })

  // Both main.js and preload.js are Electron entry points (not require()'d by anyone).
  // The correct loader is just require() — NOT module.exports = require().
  const loader = [
    "'use strict'",
    "require('bytenode')",
    `require('./${parsed.name}.jsc')`,
    ''
  ].join('\n')

  fs.writeFileSync(jsPath, loader, 'utf8')
  return true
}

module.exports = async (context) => {
  if (process.env.SKIP_OBFUSCATION === '1') {
    console.log('[obfuscation] skipped via SKIP_OBFUSCATION=1')
    return
  }

  const bytecodeRequested = process.env.ENABLE_BYTECODE === '1'
  const bytecodeAllowed = process.env.ALLOW_V8_BYTECODE === '1'
  const enableBytecode = bytecodeRequested && bytecodeAllowed

  if (bytecodeRequested && !bytecodeAllowed) {
    console.log('[bytecode] requested but blocked (set ALLOW_V8_BYTECODE=1 to enable)')
  }

  // electron-builder v26+ exposes appOutDir in BeforePackContext.
  // We only proceed when a reliable appDir is provided to avoid touching workspace source files.
  if (!context || !context.appDir) {
    console.log('[obfuscation] skipped: context.appDir is missing (builder context format changed)')
    return
  }
  const appDir = context.appDir

  // Safety: double-check appDir is NOT inside the workspace source
  if (enableBytecode) {
    assertNotSourceDir(appDir)
  }
  const targets = []

  if (enableBytecode) {
    const bytecodeResults = await Promise.all(ROOT_TARGETS.map(rel => compileRootToBytecode(appDir, rel)))
    let compiled = 0
    for (const [i, ok] of bytecodeResults.entries()) {
      if (ok) {
        compiled += 1
        console.log(`[bytecode] ${ROOT_TARGETS[i]} -> ${path.parse(ROOT_TARGETS[i]).name}.jsc`)
      }
    }
    console.log(`[bytecode] completed (${compiled} files)`)
  }

  if (!enableBytecode) {
    for (const rel of ROOT_TARGETS) {
      const abs = path.join(appDir, rel)
      if (fs.existsSync(abs)) targets.push(abs)
    }
  }

  targets.push(...listWebJsFiles(appDir))

  let changed = 0
  for (const file of targets) {
    try {
      if (obfuscateOne(file)) {
        changed += 1
        console.log(`[obfuscation] ${path.relative(appDir, file)}`)
      }
    } catch (err) {
      throw new Error(`Failed to obfuscate ${file}: ${err.message}`)
    }
  }

  console.log(`[obfuscation] completed (${changed} files)`)
}