1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-30 15:13:32 +00:00

[PM-7846] Implement a rust based native messaging proxy and IPC system

This commit is contained in:
Daniel García
2024-06-20 18:11:24 +02:00
parent d92e1b3eca
commit 0a83b8ddaf
26 changed files with 961 additions and 358 deletions

View File

@@ -1,35 +1,4 @@
import { NativeMessagingProxy } from "./proxy/native-messaging-proxy";
import { Main } from "./main";
// We need to import the other dependencies using `require` since `import` will
// generate `Error: Cannot find module 'electron'`. The cause of this error is
// due to native messaging setting the ELECTRON_RUN_AS_NODE env flag on windows
// which removes the electron module. This flag is needed for stdin/out to work
// properly on Windows.
if (
process.argv.some((arg) => arg.indexOf("chrome-extension://") !== -1 || arg.indexOf("{") !== -1)
) {
if (process.platform === "darwin") {
// eslint-disable-next-line
const app = require("electron").app;
app.on("ready", () => {
app.dock.hide();
});
}
process.stdout.on("error", (e) => {
if (e.code === "EPIPE") {
process.exit(0);
}
});
const proxy = new NativeMessagingProxy();
proxy.run();
} else {
// eslint-disable-next-line
const Main = require("./main").Main;
const main = new Main();
main.bootstrap();
}
const main = new Main();
main.bootstrap();

View File

@@ -214,6 +214,7 @@ export class Main {
this.windowMain,
app.getPath("userData"),
app.getPath("exe"),
app.getAppPath(),
);
this.desktopAutofillSettingsService = new DesktopAutofillSettingsService(stateProvider);

View File

@@ -1,27 +1,27 @@
import { existsSync, promises as fs } from "fs";
import { Socket } from "net";
import { homedir, userInfo } from "os";
import * as path from "path";
import * as util from "util";
import { ipcMain } from "electron";
import * as ipc from "node-ipc";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { ipc } from "@bitwarden/desktop-napi";
import { getIpcSocketRoot } from "../proxy/ipc";
import { isDev } from "../utils";
import { WindowMain } from "./window.main";
export class NativeMessagingMain {
private connected: Socket[] = [];
private socket: any;
private ipcServer: ipc.IpcServer | null;
private connected: number[] = [];
constructor(
private logService: LogService,
private windowMain: WindowMain,
private userPath: string,
private exePath: string,
private appPath: string,
) {
ipcMain.handle(
"nativeMessaging.manifests",
@@ -73,55 +73,46 @@ export class NativeMessagingMain {
}
listen() {
ipc.config.id = "bitwarden";
ipc.config.retry = 1500;
const ipcSocketRoot = getIpcSocketRoot();
if (ipcSocketRoot != null) {
ipc.config.socketRoot = ipcSocketRoot;
if (this.ipcServer) {
this.ipcServer.stop();
}
ipc.serve(() => {
ipc.server.on("message", (data: any, socket: any) => {
this.socket = socket;
this.windowMain.win.webContents.send("nativeMessaging", data);
});
this.ipcServer = ipc.IpcServer.listen("bitwarden", (error, msg) => {
switch (msg.kind) {
case ipc.IpcMessageType.Connected:
this.connected.push(msg.clientId);
break;
case ipc.IpcMessageType.Disconnected: {
const index = this.connected.indexOf(msg.clientId);
if (index > -1) {
this.connected.splice(index, 1);
}
ipcMain.on("nativeMessagingReply", (event, msg) => {
if (this.socket != null && msg != null) {
this.send(msg, this.socket);
this.logService.info("client " + index + " has disconnected!");
break;
}
});
ipc.server.on("connect", (socket: Socket) => {
this.connected.push(socket);
});
ipc.server.on("socket.disconnected", (socket, destroyedSocketID) => {
const index = this.connected.indexOf(socket);
if (index > -1) {
this.connected.splice(index, 1);
}
this.socket = null;
ipc.log("client " + destroyedSocketID + " has disconnected!");
});
case ipc.IpcMessageType.Message:
this.logService.debug("received nativeMessaging message: " + msg.message);
this.windowMain.win.webContents.send("nativeMessaging", JSON.parse(msg.message));
break;
}
});
ipc.server.start();
}
stop() {
ipc.server.stop();
// Kill all existing connections
this.connected.forEach((socket) => {
if (!socket.destroyed) {
socket.destroy();
ipcMain.on("nativeMessagingReply", (event, msg) => {
if (msg != null) {
this.send(msg);
}
});
}
send(message: object, socket: any) {
ipc.server.emit(socket, "message", message);
stop() {
this.ipcServer?.stop();
}
send(message: object) {
const msg = JSON.stringify(message);
this.logService.debug("sent nativeMessaging message of length", msg.length, message);
this.ipcServer?.send(msg);
}
async generateManifests() {
@@ -331,6 +322,10 @@ export class NativeMessagingMain {
}
private binaryPath() {
if (isDev()) {
return path.join(this.appPath, "..", "desktop_native", "target", "release", "desktop_proxy");
}
if (process.platform === "win32") {
return path.join(path.dirname(this.exePath), "resources", "native-messaging.bat");
}

View File

@@ -1,78 +0,0 @@
/* eslint-disable no-console */
import { createHash } from "crypto";
import { existsSync, mkdirSync } from "fs";
import { homedir } from "os";
import { join as path_join } from "path";
import * as ipc from "node-ipc";
export function getIpcSocketRoot(): string | null {
let socketRoot = null;
switch (process.platform) {
case "darwin": {
const ipcSocketRootDir = path_join(homedir(), "tmp");
if (!existsSync(ipcSocketRootDir)) {
mkdirSync(ipcSocketRootDir);
}
socketRoot = ipcSocketRootDir + "/";
break;
}
case "win32": {
// Let node-ipc use a unique IPC pipe //./pipe/xxxxxxxxxxxxxxxxx.app.bitwarden per user.
// Hashing prevents problems with reserved characters and file length limitations.
socketRoot = createHash("sha1").update(homedir()).digest("hex") + ".";
}
}
return socketRoot;
}
ipc.config.id = "proxy";
ipc.config.retry = 1500;
ipc.config.logger = console.warn; // Stdout is used for native messaging
const ipcSocketRoot = getIpcSocketRoot();
if (ipcSocketRoot != null) {
ipc.config.socketRoot = ipcSocketRoot;
}
export default class IPC {
onMessage: (message: object) => void;
private connected = false;
connect() {
ipc.connectTo("bitwarden", () => {
ipc.of.bitwarden.on("connect", () => {
this.connected = true;
console.error("## connected to bitwarden desktop ##");
// Notify browser extension, connection is established to desktop application.
this.onMessage({ command: "connected" });
});
ipc.of.bitwarden.on("disconnect", () => {
this.connected = false;
console.error("disconnected from world");
// Notify browser extension, no connection to desktop application.
this.onMessage({ command: "disconnected" });
});
ipc.of.bitwarden.on("message", (message: any) => {
this.onMessage(message);
});
ipc.of.bitwarden.on("error", (err: any) => {
console.error("error", err);
});
});
}
isConnected(): boolean {
return this.connected;
}
send(json: object) {
ipc.of.bitwarden.emit("message", json);
}
}

View File

@@ -1,23 +0,0 @@
import IPC from "./ipc";
import NativeMessage from "./nativemessage";
// Proxy is a lightweight application which provides bi-directional communication
// between the browser extension and a running desktop application.
//
// Browser extension <-[native messaging]-> proxy <-[ipc]-> desktop
export class NativeMessagingProxy {
private ipc: IPC;
private nativeMessage: NativeMessage;
constructor() {
this.ipc = new IPC();
this.nativeMessage = new NativeMessage(this.ipc);
}
run() {
this.ipc.connect();
this.nativeMessage.listen();
this.ipc.onMessage = this.nativeMessage.send;
}
}

View File

@@ -1,95 +0,0 @@
/* eslint-disable no-console */
import IPC from "./ipc";
// Mostly based on the example from MDN,
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging
export default class NativeMessage {
ipc: IPC;
constructor(ipc: IPC) {
this.ipc = ipc;
}
send(message: object) {
const messageBuffer = Buffer.from(JSON.stringify(message));
const headerBuffer = Buffer.alloc(4);
headerBuffer.writeUInt32LE(messageBuffer.length, 0);
process.stdout.write(Buffer.concat([headerBuffer, messageBuffer]));
}
listen() {
let payloadSize: number = null;
// A queue to store the chunks as we read them from stdin.
// This queue can be flushed when `payloadSize` data has been read
const chunks: any = [];
// Only read the size once for each payload
const sizeHasBeenRead = () => Boolean(payloadSize);
// All the data has been read, reset everything for the next message
const flushChunksQueue = () => {
payloadSize = null;
chunks.splice(0);
};
const processData = () => {
// Create one big buffer with all all the chunks
const stringData = Buffer.concat(chunks);
console.error(stringData);
// The browser will emit the size as a header of the payload,
// if it hasn't been read yet, do it.
// The next time we'll need to read the payload size is when all of the data
// of the current payload has been read (ie. data.length >= payloadSize + 4)
if (!sizeHasBeenRead()) {
try {
payloadSize = stringData.readUInt32LE(0);
} catch (e) {
console.error(e);
return;
}
}
// If the data we have read so far is >= to the size advertised in the header,
// it means we have all of the data sent.
// We add 4 here because that's the size of the bytes that old the payloadSize
if (stringData.length >= payloadSize + 4) {
// Remove the header
const contentWithoutSize = stringData.slice(4, payloadSize + 4).toString();
// Reset the read size and the queued chunks
flushChunksQueue();
const json = JSON.parse(contentWithoutSize);
// Forward to desktop application
this.ipc.send(json);
}
};
process.stdin.on("readable", () => {
// A temporary variable holding the nodejs.Buffer of each
// chunk of data read off stdin
let chunk = null;
// Read all of the available data
// tslint:disable-next-line:no-conditional-assignment
while ((chunk = process.stdin.read()) !== null) {
chunks.push(chunk);
}
try {
processData();
} catch (e) {
console.error(e);
}
});
process.stdin.on("end", () => {
process.exit(0);
});
}
}