-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·91 lines (73 loc) · 2.47 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env node
const b4a = require('b4a')
const goodbye = require('graceful-goodbye')
const idEncoding = require('hypercore-id-encoding')
const pino = require('pino')
const { ProxyServer } = require('./index')
function loadConfig () {
const rawBootstrap = process.env.P2PROXY_BOOTSTRAP
const bootstrap = rawBootstrap
? [{
host: rawBootstrap.split(':')[0],
port: parseInt(rawBootstrap.split(':')[1])
}]
: null
if (!process.env.P2PROXY_PORT) {
console.error('P2PROXY_PORT must be set to the port you wish to proxy')
process.exit(1)
}
const port = parseInt(process.env.P2PROXY_PORT)
const rawSeed = process.env.P2PROXY_SEED
if (!rawSeed || !idEncoding.isValid(rawSeed)) {
console.error('P2PROXY_SEED must be set to a valid seed')
process.exit(1)
}
const seed = idEncoding.decode(rawSeed)
const config = {
port,
seed,
bootstrap,
keepAlive: 5000,
host: '127.0.0.1',
logLevel: 'info'
}
return config
}
async function main () {
const config = loadConfig()
const logger = pino({ level: config.logLevel })
const { port, seed, bootstrap, keepAlive, host } = config
if (bootstrap) {
logger.warn(`Using non-default bootstrap: ${bootstrap[0].host}:${bootstrap[0].port}`)
}
const proxy = new ProxyServer(
seed, port, host, { logger, keepAlive, bootstrap }
)
setupLogging(proxy, logger)
goodbye(async () => {
logger.info('Shutting down')
if (proxy.opened) await proxy.close()
logger.info('Shut down')
})
logger.info('Starting proxy')
await proxy.ready()
logger.info('The proxy server is listening. Connect by running a client with the same seed.')
const address = proxy.address
logger.info(`Public key: ${b4a.toString(address.publicKey, 'hex')}`)
logger.info(`DHT address: ${address.host}:${address.port}`)
logger.info(`Proxying to ${host}:${port}`)
}
function setupLogging (proxy, logger) {
proxy.on('connection', ({ id, remotePublicKey }) => {
logger.info(`Opened connection ${id} with ${b4a.toString(remotePublicKey, 'hex')}`)
})
proxy.on('connection-close', ({ id, remotePublicKey }) => {
logger.info(`Closed connection ${id} with ${b4a.toString(remotePublicKey, 'hex')}`)
})
proxy.on('firewall-block', ({ remotePublicKey, address }) => {
const src = `${address?.host}:${address?.port}`
const pubKey = b4a.toString(remotePublicKey, 'hex')
logger.info(`Firewall blocked connection attempt from ${src} (public key ${pubKey})`)
})
}
main()