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 Nov 6, 2024
1 parent 47555aa commit fc8e3b3
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions packages/suite-desktop-core/src/modules/trezor-connect.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,71 @@
import { ipcMain } from 'electron';
import { WebSocketServer } from 'ws';

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

import { Dependencies, mainThreadEmitter, ModuleInitBackground, ModuleInit } from './index';
import { app } from '../typed-electron';

export const SERVICE_NAME = '@trezor/connect';

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('app/show');
// @ts-expect-error
const response = await TrezorConnect[method](rest);
ws.send(JSON.stringify(response));
} finally {
// blur renderer window
// mainThreadEmitter.emit('');
}
});
});

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

export const initBackground: ModuleInitBackground = ({ store }: Pick<Dependencies, 'store'>) => {
const { logger } = global;
logger.info(SERVICE_NAME, `Starting service`);
Expand All @@ -28,6 +87,10 @@ export const initBackground: ModuleInitBackground = ({ store }: Pick<Dependencie
const response = await TrezorConnect[method](...params);
await setProxy(true);

if (app.commandLine.hasSwitch('expose-connect-ws') || isDevEnv) {
exposeConnectWs({ mainThreadEmitter });
}

return response;
}

Expand Down

0 comments on commit fc8e3b3

Please sign in to comment.