-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.js
353 lines (311 loc) · 10.5 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
var kappa = require('kappa-core')
var events = require('events')
var inherits = require('inherits')
var level = require('level-mem')
var thunky = require('thunky')
var { box } = require('./lib/crypto')
var timestamp = require('monotonic-timestamp')
var sublevel = require('subleveldown')
var crypto = require('hypercore-crypto')
var createChannelView = require('./views/channels')
var createMembershipsView = require('./views/channel-membership')
var createMessagesView = require('./views/messages')
var createTopicsView = require('./views/topics')
var createUsersView = require('./views/users')
var createModerationView = require('./views/moderation')
var createArchivingView = require('./views/channel-archiving')
var createPrivateMessagesView = require('./views/private-messages')
var swarm = require('./swarm')
var DATABASE_VERSION = 1
var CHANNELS = 'c'
var MEMBERSHIPS = 'j' // j for joined memberships..? :3
var MESSAGES = 'm'
var TOPICS = 't'
var USERS = 'u'
var MODERATION_AUTH = 'mx'
var MODERATION_INFO = 'my'
var ARCHIVES = 'a'
var PRIVATE_MESSAGES = 'p'
module.exports = Cabal
module.exports.databaseVersion = DATABASE_VERSION
/**
* Create a new cabal. This is the object handling all
* local nickname -> mesh interactions for a single user.
* @constructor
* @param {string|function} storage - A hyperdb compatible storage function, or a string representing the local data path.
* @param {string|Buffer} key - a hypercore public key
*/
function Cabal (storage, key, opts) {
if (!(this instanceof Cabal)) return new Cabal(storage, key, opts)
if (!opts) opts = {}
events.EventEmitter.call(this)
this.setMaxListeners(Infinity)
var json = {
encode: function (obj) {
return Buffer.from(JSON.stringify(obj))
},
decode: function (buf) {
var str = buf.toString('utf8')
try { var obj = JSON.parse(str) } catch (err) { return {} }
return obj
},
buffer: true
}
this.maxFeeds = opts.maxFeeds
this.modKeys = opts.modKeys || []
this.adminKeys = opts.adminKeys || []
this.preferredPort = opts.preferredPort || 13331
if (!key) this.key = generateKeyHex()
else {
if (Buffer.isBuffer(key)) key = key.toString('hex')
if (!key.startsWith('cabal://')) key = 'cabal://' + key
this.key = sanitizeKey(key)
}
if (!isHypercoreKey(this.key)) throw new Error('invalid cabal key')
this.db = opts.db || level()
this.kcore = kappa(storage, {
valueEncoding: json,
encryptionKey: isHypercoreKey(this.key) ? this.key : null
})
// Create (if needed) and open local write feed
var self = this
this.feed = thunky(function (cb) {
self.kcore.ready(function () {
self.kcore.writer('local', function (err, feed) {
cb(feed)
})
})
})
// views
this.kcore.use('memberships', createMembershipsView(
sublevel(this.db, MEMBERSHIPS, { valueEncoding: json })))
this.kcore.use('channels', createChannelView(
sublevel(this.db, CHANNELS, { valueEncoding: json })))
this.kcore.use('messages', createMessagesView(
sublevel(this.db, MESSAGES, { valueEncoding: json })))
this.kcore.use('topics', createTopicsView(
sublevel(this.db, TOPICS, { valueEncoding: json })))
this.kcore.use('users', createUsersView(
sublevel(this.db, USERS, { valueEncoding: json })))
this.kcore.use('moderation', 2, createModerationView(
this,
sublevel(this.db, MODERATION_AUTH, { valueEncoding: json }),
sublevel(this.db, MODERATION_INFO, { valueEncoding: json })
))
this.kcore.use('archives', createArchivingView(
this,
sublevel(this.db, ARCHIVES, { valueEncoding: json })))
/* define a mechanism for asynchronously initializing parts of initial state (e.g. kappa views) */
this._init = () => {
let callQueue = []
let pending = 0
// fn is the function being initialized, finish is the function to call after all functions are initialized
return (fn, finish) => {
if (finish) { callQueue.push(finish) }
// done runs after fn is done, effectively pops the state by one.
// if all pending operations have been run we invoke callQueue's saved callbacks
const done = () => {
pending--
// we're done
if (pending <= 0) {
callQueue.forEach(cb => cb())
callQueue = [] // reset call queue
}
}
pending++
if (!fn) { return done() }
// the passed-in function `fn` has been initialized when our callback `done` is invoked
fn(done)
}
}
this._initializeAsync = this._init()
// curried syntax sugarr (rename to make more sense in cabal-core.ready)
this._waitForInit = (finish) => { this._initializeAsync(null, finish) }
// initialize private messages view
this._initializeAsync(done => {
if (!done) done = noop
if (this.privateMessages) { return done() } // private messages are already setup
this.feed(feed => {
self.kcore.use('privateMessages', createPrivateMessagesView(
{ public: feed.key, private: feed.secretKey },
sublevel(self.db, PRIVATE_MESSAGES, { valueEncoding: json })
))
this.privateMessages = this.kcore.api.privateMessages
done()
})
})
this.messages = this.kcore.api.messages
this.channels = this.kcore.api.channels
this.memberships = this.kcore.api.memberships
this.topics = this.kcore.api.topics
this.users = this.kcore.api.users
this.moderation = this.kcore.api.moderation
this.archives = this.kcore.api.archives
}
inherits(Cabal, events.EventEmitter)
Cabal.prototype.getDatabaseVersion = function (cb) {
if (!cb) cb = noop
process.nextTick(cb, DATABASE_VERSION)
}
/**
* Get information about a user that they've volunteered about themselves.
* @param {String} key - The hex key of the user.
*/
Cabal.prototype.getUser = function (key, cb) {
if (typeof key === 'function') {
cb = key
key = null
}
var self = this
this.feed(function (feed) {
if (!key) key = feed.key.toString('hex')
self.kcore.api.users.get(key, cb)
})
}
/**
* Publish a message to your feed.
* @param {String} message - The message to publish.
* @param {Object} opts - Options
* @param {function} cb - When message has been successfully added.
*/
Cabal.prototype.publish = function (message, opts, cb) {
if (!cb) cb = noop
if (!message) return cb()
if (typeof opts === 'function') return this.publish(message, null, opts)
if (!opts) opts = {}
this.feed(function (feed) {
message.timestamp = message.timestamp || timestamp()
feed.append(message, function (err) {
cb(err, err ? null : message)
})
})
}
/**
* Publish a message to your feed, encrypted to a specific recipient's key.
* @param {Object} message - The message to publish.
* @param {String|Buffer[32]) recipientKey - A recipient's public key to encrypt the message to.
* @param {function} cb - When the message has been successfully written.
*/
Cabal.prototype.publishPrivate = function (message, recipientKey, cb) {
if (!cb) cb = noop
if (typeof message !== 'object') return process.nextTick(cb, new Error('message must be an object'))
if (!isHypercoreKey(recipientKey)) return process.nextTick(cb, new Error('recipientKey must be a 32-byte hypercore key'))
if (typeof recipientKey === 'string') recipientKey = Buffer.from(recipientKey, 'hex')
this.feed(function (feed) {
message.timestamp = message.timestamp || timestamp()
// attach a bit of metadata signaling that this message is private
// (in a somewhat safe way that doesn't assume any particular pre-existing structure)
message.private = true
const msg = Object.assign({ timestamp: timestamp() }, message)
// Note: we encrypt the message to the recipient, but also to ourselves (so that we can read our part of the convo!)
const ciphertext = box(Buffer.from(JSON.stringify(msg)), [recipientKey, feed.key]).toString('base64')
const encryptedMessage = {
type: 'encrypted',
content: ciphertext
}
feed.append(encryptedMessage, function (err) {
cb(err, err ? null : encryptedMessage)
})
})
}
Cabal.prototype.publishNick = function (nick, cb) {
// TODO: sanity checks on reasonable names
if (!cb) cb = noop
if (!nick) return cb()
this.feed(function (feed) {
var msg = {
type: 'about',
content: {
name: nick
},
timestamp: timestamp()
}
feed.append(msg, cb)
})
}
Cabal.prototype.publishChannelTopic = function (channel, topic, cb) {
if (!cb) cb = noop
if (!channel || typeof channel !== 'string') return cb()
if (!topic || typeof topic !== 'string') return cb()
this.feed(function (feed) {
var msg = {
type: 'chat/topic',
content: {
channel: channel,
text: topic
},
timestamp: timestamp()
}
feed.append(msg, cb)
})
}
Cabal.prototype.getLocalKey = function (cb) {
if (!cb) return
this.feed(function (feed) {
cb(null, feed.key.toString('hex'))
})
}
Cabal.prototype.getMessage = function (feedAtSeq, cb) {
if (typeof feedAtSeq === 'string') {
var p = feedAtSeq.split('@')
feedAtSeq = { key: p[0], seq: Number(p[1]) }
}
this.kcore._logs.feed(feedAtSeq.key).get(feedAtSeq.seq, cb)
}
Cabal.prototype.swarm = function (opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
if (!cb) cb = noop
const self = this
swarm(this, opts, function (err, swarm) {
if (err) return cb(err)
self._swarm = swarm
cb(null, swarm)
})
}
Cabal.prototype.replicate = function (isInitiator, opts) {
opts = opts || {}
opts = Object.assign({}, {
live: true,
maxFeeds: 1024
}, opts)
return this.kcore.replicate(isInitiator, opts)
}
Cabal.prototype.ready = function (cb) {
this._waitForInit(() => {
this.kcore.ready(cb)
})
}
Cabal.prototype._addConnection = function (key) {
this.emit('peer-added', key)
}
Cabal.prototype._removeConnection = function (key) {
this.emit('peer-dropped', key)
}
Cabal.prototype.close = async function (cb) {
const self = this
if (this._swarm) await this._swarm.__shutdown()
close()
function close () {
self.kcore.pause(function () {
self.kcore._logs.close(cb)
})
}
}
function generateKeyHex () {
return crypto.keyPair().publicKey.toString('hex')
}
function isHypercoreKey (key) {
if (typeof key === 'string') return /^[0-9A-Fa-f]{64}$/.test(key)
else if (Buffer.isBuffer(key)) return key.length === 32
}
module.exports.isHypercoreKey = isHypercoreKey
// Ensures 'key' is a hex string
function sanitizeKey (key) {
const match = key.match(/^cabal:\/\/([0-9A-Fa-f]{64})/)
if (match === null) return undefined
return match[1]
}
function noop () {}