-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrapi-lapi.js
More file actions
52 lines (34 loc) · 1.23 KB
/
rapi-lapi.js
File metadata and controls
52 lines (34 loc) · 1.23 KB
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
const BitFilament = require('./bit-filament')
const BitChaos = require('./bit-chaos')
module.exports = function rapi({ lapi, socket, ecdh, getState = () => {}, setState = () => {}}) {
return new Promise((ok, fail) => {
const filament = new BitFilament()
let secret = '', cipher
socket.binaryType = 'arraybuffer'
socket.addEventListener('message', ({ data }) => {
if(!secret) {
data = new Uint8Array(data)
const { key, api } = filament.untwist(data).shift()
secret = ecdh.computeSecret(key)
cipher = new BitChaos(secret)
const rapi = {}
api.forEach(method => rapi[method] = (...args) => {
const payload = filament.twist([method, ...args])
socket.send(cipher.encrypt(payload, 'bytearray'))
})
lapi = lapi(rapi, getState, setState)
rapi.key = key
ok(rapi)
} else {
const payload = cipher.decrypt(data, 'bytearray')
const [ method, ...args ] = filament.untwist(payload).shift()
if(typeof lapi[method] === 'function') lapi[method](...args);
}
})
const key = ecdh.getPublicKey()
// console.log('>>>', {key})
const payload = filament.twist({ key, api: Object.keys(lapi()) })
// console.log('>>>', {payload})
socket.send(Uint8Array.from(payload))
})
}