Skip to content

Commit b3785af

Browse files
committed
feat(electron): launch plebbit rpc with auth key
1 parent 787184f commit b3785af

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

electron/start-plebbit-rpc.js

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
const tcpPortUsed = require('tcp-port-used')
22
const {PlebbitWsServer} = require('@plebbit/plebbit-js/rpc')
33
const path = require('path')
4-
const envPaths = require('env-paths').default('plebbit', { suffix: false });
4+
const envPaths = require('env-paths').default('plebbit', { suffix: false })
5+
const {randomBytes} = require('crypto')
6+
const fs = require('fs-extra')
57

68
let isDev = true
79
try {
@@ -18,6 +20,18 @@ const defaultPlebbitOptions = {
1820
pubsubHttpClientsOptions: ['http://localhost:5001/api/v0'],
1921
}
2022

23+
// generate plebbit rpc auth key if doesn't exist
24+
const plebbitRpcAuthKeyPath = path.join(defaultPlebbitOptions.dataPath, 'auth-key')
25+
let plebbitRpcAuthKey
26+
try {
27+
plebbitRpcAuthKey = fs.readFileSync(plebbitRpcAuthKeyPath, 'utf8')
28+
}
29+
catch (e) {
30+
plebbitRpcAuthKey = randomBytes(32).toString('base64').replace(/[/+=]/g, '').substring(0, 40)
31+
fs.ensureFileSync(plebbitRpcAuthKeyPath)
32+
fs.writeFileSync(plebbitRpcAuthKeyPath, plebbitRpcAuthKey)
33+
}
34+
2135
let pendingStart = false
2236
const start = async () => {
2337
if (pendingStart) {
@@ -29,14 +43,16 @@ const start = async () => {
2943
if (started) {
3044
return
3145
}
32-
const plebbitWebSocketServer = await PlebbitWsServer({port, plebbitOptions: defaultPlebbitOptions})
33-
console.log(`plebbit rpc: listening on port ${port}`)
46+
const plebbitWebSocketServer = await PlebbitWsServer({port, plebbitOptions: defaultPlebbitOptions, authKey: plebbitRpcAuthKey})
47+
48+
console.log(`plebbit rpc: listening on ws://localhost:${port} (local connections only)`)
49+
console.log(`plebbit rpc: listening on ws://localhost:${port}/${plebbitRpcAuthKey} (secret auth key for remote connections)`)
3450
plebbitWebSocketServer.ws.on('connection', (socket, request) => {
3551
console.log('plebbit rpc: new connection')
3652
// debug raw JSON RPC messages in console
37-
// if (isDev) {
53+
if (isDev) {
3854
socket.on('message', (message) => console.log(`plebbit rpc: ${message.toString()}`))
39-
// }
55+
}
4056
})
4157
}
4258
catch (e) {

0 commit comments

Comments
 (0)