UNPKG

1.75 kBJavaScriptView Raw
1var SHS = require('secret-handshake')
2var pull = require('pull-stream')
3
4function isString(s) {
5 return 'string' === typeof s
6}
7
8module.exports = function (opts) {
9 var keys = SHS.toKeys(opts.keys || opts.seed)
10 var appKey = isString(opts.appKey) ? Buffer.from(opts.appKey, 'base64') : opts.appKey
11
12 var server = SHS.createServer(
13 keys, opts.auth || opts.authenticate, appKey, opts.timeout
14 )
15 var client = SHS.createClient(
16 keys, appKey, opts.timeout
17 )
18
19 return {
20 name: 'shs',
21 create: function (_opts) {
22 return function (stream, cb) {
23 function _cb (err, stream) {
24 if(err) {
25 //shs is designed so that we do not _know_ who is connecting if it fails,
26 //so we probably can't add the connecting address. (unless it was client unauthorized)
27 err.address = 'shs:'
28 return cb(err)
29 }
30 stream.address = 'shs:'+stream.remote.toString('base64')
31 cb(null, stream)
32 }
33 pull(
34 stream.source,
35 _opts && _opts.key ? client(_opts.key, _opts.seed, _cb) : server(_cb),
36 stream.sink
37 )
38 }
39 },
40 parse: function (str) {
41 var ary = str.split(':')
42 if(ary[0] !== 'shs') return null
43 var seed = undefined
44
45 //seed of private key to connect with, optional.
46
47 if(ary.length > 2) {
48 seed = Buffer.from(ary[2], 'base64')
49 if(seed.length !== 32) return null
50 }
51 var key = Buffer.from(ary[1], 'base64')
52 if(key.length !== 32) return null
53
54 return {key: key, seed: seed}
55 },
56 stringify: function () {
57 if(!keys) return
58 return 'shs:'+keys.publicKey.toString('base64')
59 },
60 publicKey: keys && keys.publicKey
61 }
62}
63
64
65
66
67