This repository has been archived by the owner on Jun 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
81 lines (75 loc) · 2.38 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
var aes = require('crypto-js').AES
var debug = require('debug')('secure-webrtc-swarm')
var enc = require('crypto-js').enc.Utf8
var randomstring = require('randomstring').generate
var Swarm = require('webrtc-swarm')
module.exports = Main
Main.WEBRTC_SUPPORT = Swarm.WEBRTC_SUPPORT
Main.createKey = randomstring
function Main (hub, opts) {
if (!hub) throw new Error('`signalhub` instance required, see: https://github.com/mafintosh/signalhub')
opts = opts || {}
this.sharedKeys = opts.sharedKeys || {}
this.keys = opts.keys || [randomstring(16)]
opts = Object.assign(opts, {
wrap: function (data, channel) {
if (!data.signal) return data
var key = this.sharedKeys[channel] || pickRandom(this.keys)
data.signal = JSON.stringify(data.signal)
data.signal = aes.encrypt(data.signal, key).toString()
return data
},
unwrap: function (data, channel) {
if (!data.signal) return data
var key = this.sharedKeys[data.from]
if (key) {
try {
data.signal = aes.decrypt(data.signal, key).toString(enc)
data.signal = JSON.parse(data.signal)
} catch (err) {
debug(swarm.me,
'Unable to decrypt message /w known key in channel:',
channel
)
}
debug(swarm.me, 'Decrypted data w/ known key:', key)
return data
}
debug(swarm.me, 'Trying to discover key out of', this.keys.length)
key = this.keys.find(function (key) {
try {
data.signal = aes.decrypt(data.signal, key).toString(enc)
data.signal = JSON.parse(data.signal)
} catch (err) {
return false
}
debug(swarm.me, 'Discoverd key', key)
return true
})
if (!key) {
debug(
swarm.me,
'No shared key found - trying again next time',
data.from
)
// we need to remove the remote otherwise `webrtc-swarm` won't try again
delete swarm.remotes[data.from]
return
}
Object.assign(this.sharedKeys, {
[data.from]: key
})
return data
}
})
var swarm = new Swarm(hub, opts)
Object.assign(swarm, this)
swarm.on('peer', function (peer, id) {
Object.assign(peer, {sharedKey: this.sharedKeys[id]})
})
return swarm
}
function pickRandom (obj) {
var props = Object.keys(obj)
return obj[props[props.length * Math.random() << 0]]
}