Electron 防脱壳转二进制 JSC 打包过程以及踩坑记录

发布于:2025-06-14 ⋅ 阅读:(20) ⋅ 点赞:(0)

背景

在调研Electron客户端时,发现对方的源代码的后缀名为 .jsc,之前 helloworld 采用 Uglify / Obfuscator 是比较容易破解的,毕竟源代码可以反编译过来,代码信息并没有损失性编码,而二进制打包的方式是损失性编码,即原来的代码结构在二进制层面都是破坏的,甚至包括变量名也会进行破坏式修改,转为二进制直接运行,这种代码反编译难度极大,基本上是没办法抄袭的。

同理,我们的代码也是辛辛苦苦开发出来的,若被对方直接抄袭源码,对我们的造成损失也很大,为此,我们也需要加固自己的代码。

二进制打包原理

  1. JavaScript代码通过V8的解析器生成抽象语法树(AST)。

  2. Ignition解释器将AST转换为字节码,存储在内存中或缓存文件中(例如.jsc文件)

  3. bytenode利用V8的vm.Script接口,通过produceCachedData生成字节码缓冲区(buffer)。

const bytenode = require('bytenode');
let bytecode = bytenode.compileCode('console.log("Hello World!");');

打包关键

  1. 本地所使用的 node.js 版本一定要和 electron 内置的 node.js 版本一致,否则打包出来的 jsc 无法在 electron 版本中运行,我的 electron 内置版本是 16.20.2

webpack 5 打包方式

  1. 写一个插件,在代码打包完成输出到指定路径下时,派生状态时,做 bytecode 处理

    1. 派生状态时代码刚刚构建在一个文件里,还没有进行混淆和压缩,回填进去的资源还会经过TerserPlugin 插件进一步压缩

const Module = require('module');
const bytenode = require('bytenode');
const fs = require('fs').promises;
const path = require('path');

// 从 Webpack 获取 Compilation 类,用于访问 stage 常量
const { Compilation } = require('webpack');

class BytenodeWebpackPlugin {
    // constructor 部分保持不变
    constructor(options = {}) {
        const { bytecodeTemplate, ...otherOptions } = options;

        if (!bytecodeTemplate) {
            throw new Error(
                "BytenodeWebpackPlugin: 'bytecodeTemplate' 选项是必需的,请提供 bytecode loader 模板文件的路径。"
            );
        }

        this.options = {
            compileAsModule: true,
            keepSource: false,
            ...otherOptions,
            bytecodeTemplate: path.resolve(process.cwd(), bytecodeTemplate),
        };
    }

    apply(compiler) {
        // --- 核心改动:从 emit 迁移到 processAssets ---

        // 1. 使用 thisCompilation 钩子来获取每次编译的 compilation 对象
        compiler.hooks.thisCompilation.tap('BytenodeWebpackPlugin', (compilation) => {

            // 2. 在 compilation 对象上,使用新的 processAssets 钩子
            compilation.hooks.processAssets.tapPromise(
                {
                    name: 'BytenodeWebpackPlugin',
                    // 3. 指定一个合适的阶段
                    // PROCESS_ASSETS_STAGE_DERIVED 用于从现有资源派生出新资源,非常适合此场景
                    stage: Compilation.PROCESS_ASSETS_STAGE_DERIVED,
                },
                // 4. 这个钩子会直接提供 assets 对象,我们在这个函数内完成所有资源的修改
                async (assets) => {
                    // ----> 以下是原有的核心逻辑,原封不动地迁移至此 <----

                    let entryJsName = null;
                    const entrypoints = compilation.entrypoints;
                    if (entrypoints.size === 0) {
                        return;
                    }
                    const entryPoint = entrypoints.get(entrypoints.keys().next().value);
                    entryJsName = entryPoint.getFiles().find(file => file.endsWith('.js'));

                    if (!entryJsName) {
                        return;
                    }

                    if (!assets[entryJsName]) {
                        return;
                    }

                    let source = assets[entryJsName].source();
                    if (this.options.compileAsModule) {
                        source = Module.wrap(source);
                    }

                    const bytecode = await bytenode.compileElectronCode(source);
                    const entryJscName = entryJsName.replace(/\.js$/, '.jsc');

                    // 直接在传入的 assets 对象上进行操作
                    assets[entryJscName] = {
                        source: () => bytecode,
                        size: () => bytecode.length,
                    };

                    try {
                        const bytecodeLoaderContent = await fs.readFile(this.options.bytecodeTemplate);
                        assets['bytecode-loader.js'] = {
                            source: () => bytecodeLoaderContent,
                            size: () => bytecodeLoaderContent.length,
                        };
                    } catch (error) {
                        compilation.errors.push(new Error(`BytenodeWebpackPlugin: 无法从路径 ${this.options.bytecodeTemplate} 读取 bytecode 模板文件。错误: ${error.message}`));
                        return;
                    }

                    const newEntryJsContent = `'use strict';require('./bytecode-loader.js');require('./${entryJscName}');`.trim();

                    assets[entryJsName] = {
                        source: () => Buffer.from(newEntryJsContent),
                        size: () => Buffer.from(newEntryJsContent).length,
                    };
                }
            );
        });
    }
}

module.exports = BytenodeWebpackPlugin;
  1. 在配置文件中引入该插件即可,传入运行 jsc 的解码模板即可,这里其实就是一个拷贝动作,后续需要文件输出时,移动调整替换文件的操作均可在这个插件中实现

踩坑过程

  1. electron-bytenode-example 基于 @herberttn/bytenode-webpack-plugin 来运行

  2. @herberttn/bytenode-webpack-plugin 这个又依赖于 @vercel/webpack-asset-relocator-loader

  3. 但 @vercel/webpack-asset-relocator-loader 装上之后,build 时就会卡死

  4. 又发现 csdn 有一篇 Electron-bytenode-webpack-plugin NPM | npm.io 安装后可以打包出来 jsc 文件了,且将 bytecode-loader.js 拷贝过来后,发现可以运行了,说明这里打包成功了

  5. 看完这个插件的源代码发现特别简单,只是基于 bytecode 库在文件导出时,让 bytecode 构建一遍即可

  6. 基于 5,我就让 AI 在这个插件的基础上开始改造,将 bytecode-loader.js 拷贝到指定目录下即可,同时创建入口文件 main.js,打包后正常运行。

  7. electron源码保护_electron 加密-CSDN博客 评论区说现在有成熟框架来帮助你进行二进制打包,看回复是 源代码保护 | electron-vite

  8. 后续会迁移代码到 electron-vite 脚手架上来