Skip to content

obfuscation

什么是 obfuscation

obfuscation 是代码混淆的意思。虽然 JS 都是明文存放,但混淆后的代码会变得很难阅读和调试,可以保护核心代码不外泄。我们使用 javascript-obfuscator 这个库进行代码混淆,内置配置如下:

typescript
let obfuscationResult = JavaScriptObfuscator.obfuscate(content, {
  compact: true,
  controlFlowFlattening: true,
  controlFlowFlatteningThreshold: 1,
  numbersToExpressions: true,
  simplify: true,

  stringArray: true,
  stringArrayCallsTransform: true,
  stringArrayEncoding: ["base64", "rc4"],
  stringArrayIndexShift: true,
  stringArrayRotate: true,
  stringArrayShuffle: true,
  stringArrayWrappersCount: 3,
  stringArrayWrappersChainedCalls: true,
  stringArrayWrappersParametersMaxCount: 2,
  stringArrayWrappersType: "variable",
  stringArrayThreshold: 1,

  splitStrings: true,
  unicodeEscapeSequence: true,
});
let obfuscationResult = JavaScriptObfuscator.obfuscate(content, {
  compact: true,
  controlFlowFlattening: true,
  controlFlowFlatteningThreshold: 1,
  numbersToExpressions: true,
  simplify: true,

  stringArray: true,
  stringArrayCallsTransform: true,
  stringArrayEncoding: ["base64", "rc4"],
  stringArrayIndexShift: true,
  stringArrayRotate: true,
  stringArrayShuffle: true,
  stringArrayWrappersCount: 3,
  stringArrayWrappersChainedCalls: true,
  stringArrayWrappersParametersMaxCount: 2,
  stringArrayWrappersType: "variable",
  stringArrayThreshold: 1,

  splitStrings: true,
  unicodeEscapeSequence: true,
});

看看一段代码混淆前后的区别:

混淆前

img_1.png

混淆后(你可以直接放弃阅读了)

img.png

如何配置

传入 obfuscation,类型为 Array<"injects" | "transformers">,只支持对 injectScript 和 transformers 进行混淆,因为核心代码只在这两类文件中。

typescript
import { defineConfig } from "vite";

export default defineConfig({
  //  ...
  plugins: [
    //    ...
    //    在这里你可以配置所有 webextkits 提供的 vite 插件
    ViteWebExtKits({
      extensionId: extId,
      obfuscation: ["injects", "transformers"],
    }),
  ],
});
import { defineConfig } from "vite";

export default defineConfig({
  //  ...
  plugins: [
    //    ...
    //    在这里你可以配置所有 webextkits 提供的 vite 插件
    ViteWebExtKits({
      extensionId: extId,
      obfuscation: ["injects", "transformers"],
    }),
  ],
});

WARNING

混淆只在打包时 pnpm run build 才会生效,开发环境不会混淆(避免影响编译速度)

Powered by Vitepress