Skip to content

Commit

Permalink
feat(suite-desktop): add option to expose connect interface publicly …
Browse files Browse the repository at this point in the history
…over websocket
  • Loading branch information
mroz22 committed Oct 29, 2024
1 parent 80806fa commit 174c355
Showing 1 changed file with 67 additions and 2 deletions.
69 changes: 67 additions & 2 deletions packages/suite-desktop-core/src/modules/trezor-connect.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,74 @@
import { ipcMain } from 'electron';
import { WebSocketServer } from 'ws';

import { isDevEnv } from '@suite-common/suite-utils';
import TrezorConnect from '@trezor/connect';
import { createIpcProxyHandler, IpcProxyHandlerOptions } from '@trezor/ipc-proxy';
import { app } from '../typed-electron';

import type { Module } from './index';
import type { Dependencies, Module } from './index';

export const SERVICE_NAME = '@trezor/connect';

export const init: Module = ({ store }) => {
const exposeConnectWsFlag = app.commandLine.hasSwitch('expose-connect-ws');

const exposeConnectWs = ({
mainThreadEmitter,
}: {
mainThreadEmitter: Dependencies['mainThreadEmitter'];
}) => {
const { logger } = global;

const wss = new WebSocketServer({
port: 8090,
});

wss.on('listening', () => {
logger.info(`${SERVICE_NAME}-ws`, 'Listening on ws://localhost:8090');
});

wss.on('connection', function connection(ws) {
ws.on('error', err => {
logger.error(`${SERVICE_NAME}-ws`, err.message);
});

ws.on('message', async function message(data) {
let message;
try {
message = JSON.parse(data.toString());
} catch (err) {
message = data.toString();
}
try {
if (message === 'handshake') {
ws.send('handshake');
return;
}
if (typeof message !== 'object' || !message.payload || !message.payload.method) {
logger.error(`${SERVICE_NAME}-ws`, 'invalid message');
return;
}

const { method, ...rest } = message.payload;
// focus renderer window
mainThreadEmitter.emit('focus-window');
// @ts-expect-error
const response = await TrezorConnect[method](rest);
ws.send(JSON.stringify(response));
} finally {
// blur renderer window
mainThreadEmitter.emit('blur-window');
}
});
});

// todo: hmmm am I allowed to use app here directly?
app.on('before-quit', () => {
wss.close();
});
};

export const init: Module = ({ store, mainThreadEmitter }) => {
const { logger } = global;
logger.info(SERVICE_NAME, `Starting service`);

Expand All @@ -28,6 +89,10 @@ export const init: Module = ({ store }) => {
const response = await TrezorConnect[method](...params);
await setProxy(true);

if (exposeConnectWsFlag || isDevEnv) {
exposeConnectWs({ mainThreadEmitter });
}

return response;
}

Expand Down

0 comments on commit 174c355

Please sign in to comment.