forked from ssbc/ssb-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (87 loc) · 2.76 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
'use strict'
var path = require('path')
var ssbKeys = require('ssb-keys')
var explain = require('explain-error')
var path = require('path')
var fs = require('fs')
var MultiServer = require('multiserver')
var WS = require('multiserver/plugins/ws')
var Net = require('multiserver/plugins/net')
var Onion = require('multiserver/plugins/onion')
var Shs = require('multiserver/plugins/shs')
var muxrpc = require('muxrpc')
var pull = require('pull-stream')
var fixBlobsAdd = require('./blobs')
function toSodiumKeys(keys) {
if(!keys || !keys.public) return null
return {
publicKey:
new Buffer(keys.public.replace('.ed25519',''), 'base64'),
secretKey:
new Buffer(keys.private.replace('.ed25519',''), 'base64'),
}
}
var createConfig = require('ssb-config/inject')
module.exports = function (keys, opts, cb) {
var config
if (typeof keys == 'function') {
cb = keys
keys = null
opts = null
}
else if (typeof opts == 'function') {
cb = opts
opts = keys
keys = null
}
if(typeof opts === 'string' || opts == null || !keys)
config = createConfig((typeof opts === 'string' ? opts : null) || process.env.ssb_appname)
else if(opts && 'object' === typeof opts)
config = opts
keys = keys || ssbKeys.loadOrCreateSync(path.join(config.path, 'secret'))
opts = opts || {}
var appKey = new Buffer(config.caps.shs, 'base64')
var remote
if(opts.remote)
remote = opts.remote
else {
var host = opts.host || 'localhost'
var port = opts.port || config.port || 8008
var key = opts.key || keys.id
var protocol = 'net:'
if (host.endsWith(".onion"))
protocol = 'onion:'
remote = protocol+host+':'+port+'~shs:'+key.substring(1).replace('.ed25519', '')
}
var manifest = opts.manifest || (function () {
try {
return JSON.parse(fs.readFileSync(
path.join(config.path, 'manifest.json')
))
} catch (err) {
throw explain(err, 'could not load manifest file')
}
})()
var shs = Shs({
keys: toSodiumKeys(keys),
appKey: appKey,
//no client auth. we can't receive connections anyway.
auth: function (cb) { cb(null, false) },
timeout: config.timers && config.timers.handshake || 3000
})
var ms = MultiServer([
[Net({}), shs],
[Onion({}), shs],
[WS({}), shs]
])
ms.client(remote, function (err, stream) {
if(err) return cb(explain(err, 'could not connect to sbot'))
var sbot = muxrpc(manifest, false)()
sbot.id = '@'+stream.remote.toString('base64')+'.ed25519'
// fix blobs.add. (see ./blobs.js)
if (sbot.blobs && sbot.blobs.add)
sbot.blobs.add = fixBlobsAdd(sbot.blobs.add)
pull(stream, sbot.createStream(), stream)
cb(null, sbot, config)
})
}