'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)`) }