git ssb

2+

Dominic / ssb-client



Tree: 4cf3f7ee96faaf9556ede729fc6fe0ad1fb9aa18

Files: 4cf3f7ee96faaf9556ede729fc6fe0ad1fb9aa18 / index.js

2693 bytesRaw
1'use strict'
2var path = require('path')
3var ssbKeys = require('ssb-keys')
4var explain = require('explain-error')
5var path = require('path')
6var fs = require('fs')
7
8var MultiServer = require('multiserver')
9var WS = require('multiserver/plugins/ws')
10var Net = require('multiserver/plugins/net')
11var Onion = require('multiserver/plugins/onion')
12var Shs = require('multiserver/plugins/shs')
13
14var muxrpc = require('muxrpc')
15var pull = require('pull-stream')
16
17function toSodiumKeys(keys) {
18 if(!keys || !keys.public) return null
19 return {
20 publicKey:
21 new Buffer(keys.public.replace('.ed25519',''), 'base64'),
22 secretKey:
23 new Buffer(keys.private.replace('.ed25519',''), 'base64'),
24 }
25}
26
27var cap =
28 new Buffer('1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s=', 'base64')
29
30var createConfig = require('ssb-config/inject')
31
32module.exports = function (keys, opts, cb) {
33 var config
34 if (typeof keys == 'function') {
35 cb = keys
36 keys = null
37 opts = null
38 }
39 else if (typeof opts == 'function') {
40 cb = opts
41 opts = keys
42 keys = null
43 }
44 if(typeof opts === 'string' || opts == null || !keys)
45 config = createConfig((typeof opts === 'string' ? opts : null) || process.env.ssb_appname)
46 else if(opts && 'object' === typeof opts)
47 config = opts
48
49 keys = keys || ssbKeys.loadOrCreateSync(path.join(config.path, 'secret'))
50 opts = opts || {}
51
52 var remote
53 if(opts.remote)
54 remote = opts.remote
55 else {
56 var host = opts.host || 'localhost'
57 var port = opts.port || config.port || 8008
58 var key = opts.key || keys.id
59
60 var protocol = 'net:'
61 if (host.endsWith(".onion"))
62 protocol = 'onion:'
63 remote = protocol+host+':'+port+'~shs:'+key.substring(1).replace('.ed25519', '')
64 }
65
66 var manifest = opts.manifest || (function () {
67 try {
68 return JSON.parse(fs.readFileSync(
69 path.join(config.path, 'manifest.json')
70 ))
71 } catch (err) {
72 throw explain(err, 'could not load manifest file')
73 }
74 })()
75
76 var shs = Shs({
77 keys: toSodiumKeys(keys),
78 appKey: opts.appKey || cap,
79
80 //no client auth. we can't receive connections anyway.
81 auth: function (cb) { cb(null, false) },
82 timeout: config.timers && config.timers.handshake || 3000
83 })
84
85 var ms = MultiServer([
86 [Net({}), shs],
87 [Onion({}), shs],
88 [WS({}), shs]
89 ])
90
91 ms.client(remote, function (err, stream) {
92 if(err) return cb(explain(err, 'could not connect to sbot'))
93 var sbot = muxrpc(manifest, false)()
94 sbot.id = '@'+stream.remote.toString('base64')+'.ed25519'
95 pull(stream, sbot.createStream(), stream)
96 cb(null, sbot)
97 })
98}
99
100

Built with git-ssb-web