-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
238 lines (183 loc) · 4.69 KB
/
index.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
'use strict'
const async = require('async')
const RPC = require('@hyperswarm/rpc')
const Base = require('bfx-facs-base')
const libKeys = require('hyper-cmd-lib-keys')
const DHT = require('hyperdht')
const Hyperswarm = require('hyperswarm')
const os = require('os')
class NetFacility extends Base {
constructor (caller, opts, ctx) {
super(caller, opts, ctx)
this.name = 'net'
this._hasConf = true
if (!this.opts.timeout) {
this.opts.timeout = 30000
}
if (!this.opts.poolLinger) {
this.opts.poolLinger = 300000
}
this.init()
}
parseInputJSON (data) {
data = data.toString()
try {
data = JSON.parse(data)
} catch (e) {
throw new Error('ERR_FACS_NET_DATA_FORMAT')
}
return data
}
handleInputError (data) {
if (typeof data !== 'string' && !(data instanceof String)) {
return
}
let isErr = false
if (data.slice(0, 15).includes('[HRPC_ERR]=')) {
isErr = true
}
if (!isErr) {
return
}
throw new Error(data)
}
toOutJSON (data) {
return Buffer.from(JSON.stringify(data))
}
toOut (data) {
return Buffer.from(data.toString())
}
async jRequest (key, method, data, opts = {}) {
if (!this.rpc) {
throw new Error('ERR_FACS_NET_RPC_NOTFOUND')
}
if (!opts.timeout) {
opts.timeout = this.opts.timeout
}
let res = await this.rpc.request(
Buffer.from(key, 'hex'), method,
this.toOutJSON(data), opts
)
res = this.parseInputJSON(res)
this.handleInputError(res)
return res
}
async jEvent (k, m, d) {
if (!this.rpc) {
throw new Error('ERR_FACS_NET_RPC_NOTFOUND')
}
await this.rpc.event(
Buffer.from(k, 'hex'), m,
this.toOutJSON(d)
)
}
async handleReply (met, data) {
try {
data = this.parseInputJSON(data)
} catch (e) {
return this.toOutJSON(`[HRPC_ERR]=${e.message}`)
}
try {
const res = await this.caller[met](data)
return this.toOutJSON(res)
} catch (e) {
return this.toOutJSON(`[HRPC_ERR]=${e.message}`)
}
}
async getSeed (name) {
const store = this.opts.fac_store || this.caller.store_s0
const confBee = await store.getBee(
{ name: 'storeConf' },
{ keyEncoding: 'utf-8' }
)
await confBee.ready()
let seed = await confBee.get(name)
if (seed) {
seed = seed.value
} else {
seed = libKeys.randomBytes(32)
await confBee.put(name, seed)
}
return seed
}
buildFirewall (allowed, allowLocal = false) {
// convert keys to Buffer if string
allowed = allowed?.map(k => typeof k === 'string' ? Buffer.from(k, 'hex') : k)
// if firewall enabled, allow from local ip
const localIp = allowLocal ? this.getLocalIPAddress() : null
return (remotePublicKey, remoteHandshakePayload) => {
if (allowed && !libKeys.checkAllowList(allowed, remotePublicKey)) {
if (allowLocal && localIp && remoteHandshakePayload?.addresses4) {
for (const remoteHost of remoteHandshakePayload.addresses4) {
if (remoteHost.host === localIp) return false
}
}
return true
}
return false
}
}
getLocalIPAddress () {
for (const devices of Object.values(os.networkInterfaces())) {
const device = devices.find(d => d.family === 'IPv4' && d.address !== '127.0.0.1' && !d.internal)
if (device) return device.address
}
return '127.0.0.1'
}
async startRpcServer () {
if (this.rpcServer) {
return
}
await this.startRpc()
const server = this.rpc.createServer({
firewall: this.buildFirewall(this.conf.allow, this.conf.allowLocal)
})
await server.listen()
this.rpcServer = server
}
async startRpc () {
if (this.rpc) {
return
}
const seed = await this.getSeed('seedRpc')
const rpc = new RPC({
seed,
dht: this.dht,
poolLinger: this.opts.poolLinger
})
this.rpc = rpc
}
async startSwarm () {
const seed = await this.getSeed('seedSwarm')
const swarm = new Hyperswarm({
seed,
dht: this.dht
})
this.swarm = swarm
}
_start (cb) {
async.series([
next => { super._start(next) },
async () => {
const seed = await this.getSeed('seedDht')
const keyPair = DHT.keyPair(seed)
this.dht = new DHT({ keyPair })
}
], cb)
}
_stop (cb) {
async.series([
next => { super._stop(next) },
async () => {
if (this.rpcServer) {
await this.rpcServer.close()
}
if (this.rpc) {
await this.rpc.destroy()
}
await this.dht.destroy()
}
], cb)
}
}
module.exports = NetFacility