ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Electron中使用bytenode保护nodejs代码实践

2022-01-06 16:32:06  阅读:302  来源: 互联网

标签:preload const nodejs js Electron background path bytenode


网上也看了不少把node javascript转换为bytecode的文章,但是实操起来总有些问题,特别是对preload.js部分怎么把preload.js转换为bytecode,说得不那么详尽;我把我自己实践过程详细的描述一下,希望可以帮到有需要的朋友;

1.我是在一个开源项目上简单修改一下,https://gitee.com/chiugi/vue3-electron-serialport

Home.vue

/* eslint-disable no-bitwise */
<template>
  <div>
    <el-form>
      <el-form-item>
         渲染进程
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
/* eslint-disable */
import {
  reactive, ref, onUnmounted, watch, computed, nextTick,
} from 'vue';
import funtest1 from '../funtest1'
const toHexString = bytes =>
  bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '')+' ';
funtest1('call by Home');
const getForm = () => {    
    
  return {
  
  };
}

export default {
  name: 'Home',  
  setup() {
    return {
      ...getForm(),      
    };
  },
  methods: {
  }
};
</script>

 background.js

import {
  app, protocol, BrowserWindow, session, ipcMain,
} from 'electron';
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer';
const path = require('path');

const isDevelopment = process.env.NODE_ENV !== 'production';

app.allowRendererProcessReuse = false;
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } },
]);


// 测试 Node API
// const bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// const buf = Buffer.from(bytes);
// console.log('backgroud,buf', buf);

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true,
      preload: path.join(__dirname, '/preload.js'),
    },
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol('app');
    // Load the index.html when not in development
    win.loadURL('app://./index.html');
  }
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    // try {
    //   await installExtension(VUEJS_DEVTOOLS);
    //   session.defaultSession.loadExtension(
    //     path.resolve(__dirname, '../../vue-devtools/shells/chrome'), // 这个是刚刚build好的插件目录
    //   );
    // } catch (e) {
    //   console.error('Vue Devtools failed to install:', e.toString());
    // }

    // 记得预先安装 npm install vue-devtools
    const ses = session.fromPartition('persist:name');
    try {
      // The path to the extension in 'loadExtension' must be absolute
      await ses.loadExtension(path.resolve('node_modules/vue-devtools/vender'));
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString());
    }
  }
  createWindow();
});

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit();
      }
    });
  } else {
    process.on('SIGTERM', () => {
      app.quit();
    });
  }
}

preload.js

const funtest1 = require('./funtest1');
const bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const buf = Buffer.from(bytes);
console.log('preload,buf', buf);
funtest1('call by preload');

funtest1.js

function stringToUint8Array(str){
  var arr = [];
  for (var i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
 
  var tmpUint8Array = new Uint8Array(arr);
  return tmpUint8Array
}

function funtest1(str) {
  console.log("str",str);
  const buf = Buffer.from(str);
  //const buf = stringToUint8Array(str);
  console.log("buf:",buf);
}

module.exports = funtest1;

执行

npm run electron:serve

在console里面看日志,可以发现那个 Buffer.from 返回的对象在preload.js 里面跟在 Home.vue里面返回的对象类型是不一样的,在 Node.js 中,Buffer 类是随 Node 内核一起发布的核心库,在普通的Web里面的Javascript环境是调用不了的,

我这个是使用 Electron13.6.2版本,在渲染进程里面能使用Buffer.from,感觉应该跟早期版本渲染进程可以直接调用Nodejs API有关系,虽然新版在渲染进程中不能通过require调用Node API,但是调用Node核心库好像没有问题;我说这个跟下面的内容是有关系的,先做个铺垫;

下面来说说如何使用bytenode;先安装

npm install --save bytenode

修改下package.json,在  scripts 里面增加

"pack": "vue-cli-service electron:build --skipBundle"

在 vue.config.js里面的增加

 electronBuilder: {
      preload: 'src/preload.js',
     builderOptions: {
     ...

这样build的时候才会把 preload.js 打包进去;

执行打包

npm run electron:build

在 dist_electron\win-unpacked\resources\app 目录下可以看到,跟   dist_electron\bundled  是一样的

 

下面的使用bytenode的方法是学习自 https://gitee.com/qjh_2413/vue-electron-bytenode.git

1.在bundled里面把 backgroud.js 重命名为 backgroud.src.js,把 preload.js重命名为 preload.src.js,新建 background.bytenode.js和 preload.bytenode.js

background.bytenode.js

'use strict';

const bytenode = require('bytenode');
const fs = require('fs');
const v8 = require('v8');
const path = require('path');

v8.setFlagsFromString('--no-lazy');

if (!fs.existsSync(path.join(__dirname, './background.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './background.src.js'),path.join(__dirname,  './background.jsc'));
}

require(path.join(__dirname,'./background.jsc'));

preload.bytenode.js

'use strict';

const bytenode = require('bytenode');
const fs = require('fs');
const v8 = require('v8');
const path = require('path');

v8.setFlagsFromString('--no-lazy');

if (!fs.existsSync(path.join(__dirname, './preload.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './preload.src.js'),path.join(__dirname,  './preload.jsc'));
}

require(path.join(__dirname,'./preload.jsc'));

把 background.bytenode.js 复制一份为 backgroud.js,把 preload.bytenode.js复制为 preload.js,

网上有说用 electron .\background.js ,但是经常有人碰到错误,其实就是因为你调用的electron版本跟当前项目的版本不一致;你可以直接使用 .\node_modules\electron\dist\electron.exe .\dist_electron\bundled\background.js   ,用当前项目的electron来执行background.js;

另一种更简单,在 dist_electron\win-unpacked\resources\app 执行跟上面一样的步骤(electronbuilder里面的 asar 先设为 false),然后执行 dist_electron\win-unpacked\(项目).exe,然后把 backgroud.jsc,background.js,preload.jsc,preload.js复制到 bundled 目录里面;

然后执行打包

npm run pack

但是你会发现

 preload.js里面调用 Buffer.from 报错,因为 preload.js 生成preload.jsc时是在渲染进程执行的,普通的浏览器javascript环境是调用不了 Buffer.from 这个 Nodejs API的。要解决这个问题,把生成 preload.jsc这个步骤放到 background.js执行,

修改 background.js

'use strict';

const bytenode = require('bytenode');
const fs = require('fs');
const v8 = require('v8');
const path = require('path');

v8.setFlagsFromString('--no-lazy');

if (!fs.existsSync(path.join(__dirname, './background.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './background.src.js'),path.join(__dirname,  './background.jsc'));
}

if (!fs.existsSync(path.join(__dirname, './preload.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './preload.src.js'),path.join(__dirname,  './preload.jsc'));
}

require(path.join(__dirname,'./background.jsc'));

然后在 preload.js里面把生成 preload.jsc 这段代码注释掉,你发现可以正确执行,调用Buffer.from 也不报错了;

我也实验了一下 在 preload.js 里面生成 background.jsc,

修改 preload.js

'use strict';

const bytenode = require('bytenode');
const fs = require('fs');
const v8 = require('v8');
const path = require('path');

v8.setFlagsFromString('--no-lazy');

if (!fs.existsSync(path.join(__dirname, './preload.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './preload.src.js'),path.join(__dirname,  './preload.jsc'));
}

if (!fs.existsSync(path.join(__dirname, './background.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './background.src.js'),path.join(__dirname,  './background.jsc'));
}

require(path.join(__dirname,'./preload.jsc'));

我说下结果吧,如果 background.js 里面不调用 Buffer.from,生成的 background.jsc执行没有报错,background.js里面通过require引用Nodejs API都没有问题,如果我在background.js加上

 const bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 const buf = Buffer.from(bytes);
 console.log('backgroud,buf', buf);

启动就会报错,

应用启动不起来;

 总结:background.js,preload.js这些要转换成bytecode还是在主线程里面执行比较好;

标签:preload,const,nodejs,js,Electron,background,path,bytenode
来源: https://www.cnblogs.com/cfqdbt/p/15771666.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有