-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1636 lines (1527 loc) · 67.6 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2023 the cable-core.js authors
//
// SPDX-License-Identifier: AGPL-3.0-or-later
// node core dependencies
const EventEmitter = require('events').EventEmitter
// external dependencies
const b4a = require("b4a")
const { LRUCache } = require("lru-cache")
const coredebug = require("debug")("core:core")
const livedebug = require("debug")("core:live")
// internal dependencies (deps made by us :)
const cable = require("cable.js")
const crypto = require("cable.js/cryptography.js")
const constants = require("cable.js/constants.js")
const util = require("./util.js")
const CableStore = require("./store.js")
const EventsManager = require("./events-manager.js")
const Swarm = require("./peers.js").Swarm
const LiveQueries = require("./live-queries.js")
const { ModerationRoles, ModerationSystem } = require("./moderation.js")
// aliases
const TEXT_POST = cable.TEXT_POST
const DELETE_POST = cable.DELETE_POST
const INFO_POST = cable.INFO_POST
const TOPIC_POST = cable.TOPIC_POST
const JOIN_POST = cable.JOIN_POST
const LEAVE_POST = cable.LEAVE_POST
const ROLE_POST = cable.ROLE_POST
const MODERATION_POST = cable.MODERATION_POST
const BLOCK_POST = cable.BLOCK_POST
const UNBLOCK_POST = cable.UNBLOCK_POST
class CableCore extends EventEmitter {
#moderationReady
constructor(level, opts) {
super()
if (!opts) { opts = {} }
if (!opts.storage) { coredebug("no storage passed in") }
if (!opts.network) { coredebug("no network transports passed in; will use transport shim") }
if (!opts.port) { opts.port = 13331 }
coredebug("opts", opts)
// i.e. the network of connections with other cab[a]l[e] peers
this.swarm = new Swarm(opts.key, opts)
this.swarm.on("data", (data) => {
this._handleIncomingMessage(data)
coredebug("incoming swarm data", data)
})
// TODO (2023-08-14): dedupe and cancel previous requests for the same channel if a new request comes in; basically
// superceding requests
//
// make sure it doesn't conflict if multiple different peers create a request
//
this.swarm.on("new-peer", (peer) => {
const ongoingRequests = []
for (let [reqid, entry] of this.requestsMap) { ongoingRequests.push(entry.binary) }
coredebug("new peer, sending %d ongoing requests", ongoingRequests.length)
ongoingRequests.forEach(req => {
const obj = cable.parseMessage(req)
coredebug("[%s] requesting %s (%O)", util.hex(obj.reqid), util.humanizeMessageType(cable.peekMessage(req)), req)
})
ongoingRequests.forEach(req => { this.swarm.broadcast(req) })
})
// assert if we are passed a keypair while starting lib and if format is correct (if not we generate a new kp)
// TODO (2023-09-01): also persist keypair in e.g. cable-client/cli
const validKeypair = (
opts.keypair && opts.keypair.publicKey && opts.keypair.secretKey &&
b4a.isBuffer(opts.keypair.publicKey) &&
opts.keypair.publicKey.length === constants.PUBLICKEY_SIZE &&
b4a.isBuffer(opts.keypair.secretKey) &&
opts.keypair.secretKey.length === constants.SECRETKEY_SIZE
)
if (validKeypair) {
this.kp = opts.keypair
coredebug("using opts.keypair as keypair")
} else {
this.kp = crypto.generateKeypair()
coredebug("generated new keypair")
}
this.events = new EventsManager()
this.store = new CableStore(level, this.kp.publicKey, { storage: opts.storage })
/* used as:
* store a join message:
* store.join(buf)
*/
// keeps tracks of each set of head per channel (or context in case of posts w/o channel info)
this.heads = new Map()
this.store.linksView.api.getAllKnownHeads((err, headsMap) => {
if (err) {
coredebug("experienced an error getting known heads: %O", err)
return
}
this.heads = headsMap
})
// tracks still ongoing requests
this.requestsMap = new Map()
// tracks which hashes we have explicitly requested in a 'request for hash' request
this.requestedHashes = new Set()
this._defaultTTL = 3
this.live = new LiveQueries(this)
// call rolesComputer.analyze(<all relevant post/role operations>) to receive a map of which users have which roles
// in what channels (or on the cabal itself) for the entire cabal
this.rolesComputer = new ModerationRoles(this.kp.publicKey)
// `this.activeRoles = rolesComputer.analyze(operations)` i.e. analyze's output will be stored in `this.activeRoles`
this.activeRoles = new Map()
// `this.moderationActions` keeps track of moderation actions (post/moderation, post/block, post/unblock) across channel contexts with methods to get state regarding
// users, posts, and channels
this.moderationActions = new ModerationSystem()
this.#moderationReady = new util.Ready("moderation")
this.#moderationReady.increment()
// get the latest moderation state and apply it
this.store.rolesView.api.getRelevantRoleHashes((err, hashes) => {
if (err || hashes.length === 0) {
// if we have no roles set let's operate on nothing to set the local user as a default admin in all known
// channels
this.activeRoles = this.rolesComputer.analyze([])
return this.#moderationReady.decrement()
}
this._getData(hashes, (err, bufs) => {
const ops = bufs.map(cable.parsePost)
this.activeRoles = this.rolesComputer.analyze(ops)
this.#moderationReady.decrement()
})
})
// get the latest roles and compute the final roles applied for the local user's pov
this.#moderationReady.increment()
this.store.actionsView.api.getAllApplied((err, hashes) => {
if (err || hashes.length === 0) {
return this.#moderationReady.decrement()
}
this._getData(hashes, (err, bufs) => {
const ops = bufs.map(cable.parsePost)
this.moderationActions.process(ops)
this.#moderationReady.decrement()
})
})
this.#moderationReady.call(() => {
// event `moderation/init` signals that anything and everything moderation has finished initializing and can be
// relied on :]
this._emitModeration("init")
})
// the set of hex-encoded public keys known to currently be blocking the local user
this.blockedBy = new Set()
this.store.blockedView.api.getUsersBlockingKey(this.kp.publicKey, (err, blocks) => {
if (err) { return }
blocks.forEach(pubkey => this.blockedBy.add(util.hex(pubkey)))
})
// use an lru cache in _emitStoredPost as a map to prevent multiple display of the same post in cli
this.seen = new LRUCache({ max: 5000, ttl: 1000 * 60 * 120 })
const _emitStoredPost = (obj, hash) => {
const hashHex = util.hex(hash)
if (this.seen.get(hashHex)) {
return
}
this.seen.set(hashHex, true)
// TODO (2023-08-18): how to know when:
// * a new user joined?
// * a new channel was added?
const publicKey = util.hex(obj.publicKey)
let recipients
// emit contextual events depending on what type of post was stored
switch (obj.postType) {
case constants.TEXT_POST:
this._emitChat("add", { channel: obj.channel, publicKey, hash: util.hex(hash), post: obj })
break
case constants.DELETE_POST:
this._emitChat("remove", { channel: obj.channel, publicKey, hash: util.hex(hash) })
break
case constants.INFO_POST:
if (obj.info.has("name")) {
this._emitUsers("name-changed", {publicKey, name: obj.info.get("name")})
} else {
coredebug("store-post: unknown key for post/info (keys: %O)", [...obj.info.keys()])
}
break
case constants.TOPIC_POST:
this._emitChannels("topic", { channel: obj.channel, topic: obj.topic, publicKey })
break
case constants.JOIN_POST:
this._emitChannels("join", { channel: obj.channel, publicKey })
break
case constants.LEAVE_POST:
this._emitChannels("leave", { channel: obj.channel, publicKey })
break
case constants.ROLE_POST:
this._emitModeration("role", { publicKey, role: obj.role, recipient: util.hex(obj.recipient), reason: obj.reason,
channel: obj.channel || constants.CABAL_CONTEXT })
break
case constants.MODERATION_POST:
this._emitModeration("action", { publicKey, action: obj.action, recipients: obj.recipients.map(util.hex),
reason: obj.reason, channel: obj.channel || constants.CABAL_CONTEXT })
break
case constants.BLOCK_POST:
recipients = obj.recipients.map(util.hex)
// update blocks in case they changed
if (recipients.includes(util.hex(this.kp.publicKey))) {
this.blockedBy.add(publicKey)
}
this._emitModeration("block", { publicKey, recipients, reason: obj.reason })
break
case constants.UNBLOCK_POST:
recipients = obj.recipients.map(util.hex)
if (recipients.includes(util.hex(this.kp.publicKey))) {
this.blockedBy.delete(publicKey)
}
this._emitModeration("unblock", { publicKey, recipients, reason: obj.reason })
break
default:
coredebug("store-post: unknown post type %d", obj.postType)
}
}
// obj is the json encoded post/role, with isAdmin attached
this.events.register("store", this.store, "roles-update", ({ recipient, channel, role }) => {
// we want to be able to:
// * diff what the user's current (prev) role is (i.e. their representation in this.rolesComputer) with their new role
// * discern which context the change happened in: cabal context or a channel
const updateRolesComputer = () => {
this.store.rolesView.api.getRelevantRoleHashes((err, hashes) => {
coredebug("update roles computer %d hashes returned", hashes.length)
if (hashes.length === 0) { return }
this._getData(hashes, (err, bufs) => {
const ops = bufs.map(cable.parsePost)
this.activeRoles = this.rolesComputer.analyze(ops)
this._emitModeration("roles-update", util.transformUserRoleMapScheme(this.activeRoles))
})
})
}
let performDemote = false
const context = channel.length ? constants.CABAL_CONTEXT : channel
// .get(recipient) returns { role: integer, since: timestamp, [precedence] }
if (this.activeRoles.get(context)?.has(recipient)) {
const prev = this.activeRoles.get(constants.CABAL_CONTEXT).get(recipient)
performDemote = prev.role === constants.ADMIN_FLAG && prev.role > role
}
if (performDemote) { // -- full update incoming
this.store.rolesView.api.demoteAdmin(demotedKey, context, updateRolesComputer)
} else {
// TODO (2024-03-11): replace full replacement with more efficient (but potentially error-prone) in-place patching
updateRolesComputer()
}
// // -- in place patching of activeRoles!
// const newRoleTs = { role, since: timestamp, precedence: b4a.equals(authorKey, this.kp.publicKey) }
//
// if (context === constants.CABAL_CONTEXT && role === constants.ADMIN_FLAG) {
// for (const chan of this.activeRoles) {
// if (this.activeRoles.has(recipient)) {
// this.activeRoles.get(context).set(recipient, newRoleTs)
// }
// }
// }
//
// if (this.activeRoles.has(context)) {
// if (this.activeRoles.get(context).has(recipient)) {
// this.activeRoles.get(context).set(recipient, newRoleTs)
// }
// }
// }
// determine if full update of `this.rolesComputer` is required or if a simple patch will do
// (e.g. adding a new admin is a patch as it has no far-reaching consequences yet; removing an admin has consequences)
//
// patch situations:
// * user without any assigned roles is made an mod|admin
// * user that is a mod is made an admin
// * note: adding an admin on the cabal context requires patching all channels of rolesComputer
// * ? mod (mod->user) is demoted?
//
// full update situations:
// * an admin is demoted (admin->mod; admin->user)
// - should we detect this here? and then perform the sequence:
// -- store.rolesView.demoteAdmin, AND THEN, once that is done
// -- store.rolesView.getRelevantRoleHashes() -> resolveHashes, and finally perform
// -- rolesComputer.analyze(ops)
// * note: it may be the case that it's only when an admin is demoted that requires a full update; test this
// thought
//
// TODO (2024-03-07): test situation where a mod at time T_1 does some moderation actions and then later at T_2 they are
// elevated to being an admin. their previous actions should remain applied, despite having a "newer" timestamp of
// when they acceded their latest role
})
this.events.register("store", this.store, "actions-update", (action) => {
this.moderationActions.process([action])
this._emitModeration("actions-update", action)
// in core we are required to be able to track:
//
// * dropped {users, posts, channels} for knowing how to handle incoming posts
// * blocked users
//
// i.e. we don't need necessarily need to maintain a list of hide operations at the core level; we just need to be
// able to respond to clients with that information
})
this.events.register("store", this.store, "channel-state-replacement", ({ channel, postType, hash }) => {
livedebug("channel-state-replacement evt (channel: %s, postType %i, hash %O)", channel, postType, hash)
// set timestamp to -1 because we don't have it when producing a channel-state-replacement,
// and timestamp only matters for correctly sending hash responses for channel time range requests
// (i.e. not applicable for channel state requests)
this.live.sendLiveHashResponse(channel, postType, [hash], -1)
// TODO (2023-09-07): also emit the newly reindexed post?
this.resolveHashes([hash], (err, results) => {
const obj = results[0]
if (obj === null) {
coredebug("channel-state-replacement: tried to fetch post using %O; nothing in store", hash)
return
}
_emitStoredPost(obj, hash)
})
})
this.events.register("store", this.store, "store-post", ({ obj, channel, timestamp, hash, postType }) => {
coredebug("store post evt [%s], %s, hash %s", channel, util.humanizePostType(postType), util.hex(hash))
this.live.sendLiveHashResponse(channel, postType, [hash], timestamp)
_emitStoredPost(obj, hash)
})
this.events.register("live", this.live, "live-request-ended", (reqidHex) => {
livedebug("[%s] live query concluded", reqidHex)
this._sendConcludingHashResponse(b4a.from(reqidHex, "hex"))
})
}
_emitUsers(eventName, obj) {
this.emit(`users/${eventName}`, obj)
}
_emitChannels(eventName, obj) {
this.emit(`channels/${eventName}`, obj)
}
_emitChat(eventName, obj) {
this.emit(`chat/${eventName}`, obj)
}
_emitModeration(eventName, obj) {
this.emit(`moderation/${eventName}`, obj)
}
/* event sources */
// users events:
// name-changed - emit(pubkey, name)
// new-user - emit(pubkey, [joinedChannels?])
// chat events:
// add - emit(channel, post, hash)
// remove - emit(channel, hash)
// channels events:
// add - emit(channel)
// join - emit(channel, pubkey)
// leave - emit(channel, pubkey)
// topic - emit(channel, topic)
// archive - emit(channel)
// network events:
// connection
// join - emit(peer)
// leave - emit(peer)
// data - emit(data, {address, data})
_sendConcludingHashResponse (reqid) {
// a concluding hash response is a signal to others that we've finished with this request, and regard it as ended on
// our side
const response = cable.HASH_RESPONSE.create(reqid, [])
coredebug("[%s] send concluding hash response", util.hex(reqid))
this.dispatchResponse(response)
this._removeRequest(reqid)
}
hash (buf) {
if (b4a.isBuffer(buf)) {
return crypto.hash(buf)
}
return null
}
// get the latest links for the given context. with `links` peers have a way to partially order message history
// without relying on claimed timestamps
_links(channel) {
if (!channel) {
coredebug("_links() called without channel info - what context do we use?")
return []
}
if (this.heads.has(channel)) {
return this.heads.get(channel)
}
// no links -> return an empty array
return []
}
/* methods that produce cablegrams, and which we store in our database */
_updateNewestHeads(channel, buf, done) {
const bufHash = this.hash(buf)
// we're storing a new post we have *just* created -> we *know* this is our latest heads for the specified channel
this.store.linksView.api.setNewHeads(channel, [bufHash], () => {
// update the newest heads
this.heads.set(channel, [bufHash])
done()
})
}
getReverseLinks(hashes, done) {
if (!done) { return }
const promises = []
const rlinks = new Map()
for (const hash of hashes) {
promises.push(new Promise((res, rej) => {
this.store.linksView.api.getReverseLinks(hash, (err, retLinks) => {
if (retLinks) {
rlinks.set(hash, retLinks.map(h => util.hex(h)))
res()
}
})
}))
}
Promise.all(promises).then(() => {
done(null, rlinks)
})
}
// post/text
postText(channel, text, done) {
if (!done) { done = util.noop }
// TODO (2023-09-06): current behaviour links to e.g. post/join and not only post/text
const links = this._links(channel)
const buf = TEXT_POST.create(this.kp.publicKey, this.kp.secretKey, links, channel, util.timestamp(), text)
this.store.text(buf, () => { this._updateNewestHeads(channel, buf, done) })
return buf
}
// post/info key=name
setName(name, done) {
if (!done) { done = util.noop }
// TODO (2023-06-11): decide what to do wrt context for post/info
const links = this._links()
// TODO (2024-03-05): get / use the local user's currently set `accept-role` (if any!) and, if set, pass it along to `INFO_POST.create`
const buf = INFO_POST.create(this.kp.publicKey, this.kp.secretKey, links, util.timestamp(), [["name", name]])
this.store.info(buf, done)
return buf
}
// post/topic
setTopic(channel, topic, done) {
if (!done) { done = util.noop }
const links = this._links(channel)
const buf = TOPIC_POST.create(this.kp.publicKey, this.kp.secretKey, links, channel, util.timestamp(), topic)
this.store.topic(buf, () => { this._updateNewestHeads(channel, buf, done) })
return buf
}
// post/join
join(channel, done) {
coredebug("join channel %s", channel)
if (!done) { done = util.noop }
const links = this._links(channel)
const buf = JOIN_POST.create(this.kp.publicKey, this.kp.secretKey, links, channel, util.timestamp())
this.store.join(buf, () => { this._updateNewestHeads(channel, buf, done) })
return buf
}
// post/leave
leave(channel, done) {
if (!done) { done = util.noop }
const links = this._links(channel)
const buf = LEAVE_POST.create(this.kp.publicKey, this.kp.secretKey, links, channel, util.timestamp())
this.store.leave(buf, () => { this._updateNewestHeads(channel, buf, done) })
return buf
}
// post/delete
// note: we store the deleted hash to keep track of hashes we don't want to sync.
// we also store which channel the post was in, to fulfill channel state requests
//
// q: should we have a flag that is like `persistDelete: true`? enables for deleting for storage reasons, but not
// blocking reasons. otherwise all deletes are permanent and not reversible
del(hash, done) {
if (!done) { done = util.noop }
// TODO (2023-06-11): decide what do with links for post/delete (lacking channel info)
const links = this._links()
const buf = DELETE_POST.create(this.kp.publicKey, this.kp.secretKey, links, util.timestamp(), [hash])
this.store.del(buf, done)
return buf
}
delMany(hashes, done) {
if (!done) { done = util.noop }
// TODO (2023-06-11): decide what do with links for post/delete (lacking channel info)
const links = this._links()
const buf = DELETE_POST.create(this.kp.publicKey, this.kp.secretKey, links, util.timestamp(), hashes)
this.store.del(buf, done)
return buf
}
assignRole(recipient, channel, timestamp, role, reason, privacy, done) {
if (!done) { done = util.noop }
const links = [] /*this._links(channel)*/
const buf = cable.ROLE_POST.create(this.kp.publicKey, this.kp.secretKey, links, channel, timestamp, b4a.from(recipient, "hex"), role, reason, privacy)
this.store.role(buf, util.isAdmin(this.kp, buf, this.activeRoles), done)
return buf
}
moderatePosts (postids, action, reason, privacy, timestamp, done) {
if (!done) { done = util.noop }
switch (action) {
case constants.ACTION_HIDE_POST:
case constants.ACTION_UNHIDE_POST:
case constants.ACTION_DROP_POST:
case constants.ACTION_UNDROP_POST:
break
default:
throw new Error("`action` was not related to acting on a post")
}
const channel = ""
const recipients = postids.map(pid => b4a.from(pid, "hex"))
const links = [] /*this._links(channel)*/
const buf = cable.MODERATION_POST.create(this.kp.publicKey, this.kp.secretKey, links, channel, timestamp, recipients, action, reason, privacy)
this.store.moderation(buf, util.isApplicable(this.kp, buf, this.activeRoles), done)
return buf
}
moderateChannel (channel, action, reason, privacy, timestamp, done) {
if (!done) { done = util.noop }
switch (action) {
case constants.ACTION_DROP_CHANNEL:
case constants.ACTION_UNDROP_CHANNEL:
break
default:
throw new Error("`action` was not related to acting on a channel")
}
const recipients = []
const links = [] /*this._links(channel)*/
const buf = cable.MODERATION_POST.create(this.kp.publicKey, this.kp.secretKey, links, channel, timestamp, recipients, action, reason, privacy)
this.store.moderation(buf, util.isApplicable(this.kp, buf, this.activeRoles), done)
return buf
}
blockUsers (recipients, drop, notify, reason, privacy, timestamp, done) {
if (!done) { done = util.noop }
const links = [] /*this._links(channel)*/
const recipientsBufs = recipients.map(uid => b4a.from(uid, "hex"))
const buf = cable.BLOCK_POST.create(this.kp.publicKey, this.kp.secretKey, links, timestamp, recipientsBufs, drop, notify, reason, privacy)
this.store.block(buf, util.isApplicable(this.kp, buf, this.activeRoles), done)
return buf
}
unblockUsers (recipients, undrop, reason, privacy, timestamp, done) {
if (!done) { done = util.noop }
const links = [] /*this._links(channel)*/
const recipientsBufs = recipients.map(uid => b4a.from(uid, "hex"))
const buf = cable.UNBLOCK_POST.create(this.kp.publicKey, this.kp.secretKey, links, timestamp, recipientsBufs, undrop, reason, privacy)
this.store.unblock(buf, util.isApplicable(this.kp, buf, this.activeRoles), done)
return buf
}
moderateUsers (recipients, channel, action, reason, privacy, timestamp, done) {
if (!done) { done = util.noop }
switch (action) {
case constants.ACTION_HIDE_USER:
case constants.ACTION_UNHIDE_USER:
break
default:
throw new Error("`action` was not related to hiding/unhiding a user")
}
const recipientsBufs = recipients.map(uid => b4a.from(uid, "hex"))
const links = [] /*this._links(channel)*/
const buf = cable.MODERATION_POST.create(this.kp.publicKey, this.kp.secretKey, links, channel, timestamp, recipientsBufs, action, reason, privacy)
this.store.moderation(buf, util.isApplicable(this.kp, buf, this.activeRoles), done)
return buf
}
/* methods to get data we already have locally */
getChat(channel, start, end, limit, cb) {
coredebug(channel, start, end, limit, cb)
this.store.getChannelTimeRange(channel, start, end, limit, (err, hashes) => {
if (err) { return cb(err) }
this.resolveHashes(hashes, cb)
})
}
// gets the local user's most recently set nickname
getName(cb) {
this.store.userInfoView.api.getLatestInfoHash(this.kp.publicKey, (err, hash) => {
if (err) { return cb(err) }
this.resolveHashes([hash], (err, results) => {
if (err) { return cb(err) }
const obj = results[0]
let name = constants.INFO_DEFAULT_NAME
if (obj.info.has("name")) {
name = obj.info.get("name")
}
cb(null, name)
})
})
}
// gets the string topic of a particular channel
getTopic(channel, cb) {
this.store.getTopic(channel, cb)
}
// returns a list of channel names, sorted lexicographically
getChannels(cb) {
this.store.channelMembershipView.api.getChannelNames(0, 0, (err, channels) => {
cb(err, channels)
})
}
// returns a list of channel names the user has joined, sorted lexicographically
getJoinedChannels(cb) {
this.store.channelMembershipView.api.getJoinedChannels(this.kp.publicKey, (err, channels) => {
cb(err, channels)
})
}
// returns a Map mapping user public key (as a hex string) to their current nickname. if they don't have a nickname
// set, what is returned is the hex-encoded public key
getUsers(cb) {
if (!cb) { return }
coredebug("get users")
this.store.authorView.api.getUniquePublicKeys((err, publicKeys) => {
coredebug("err %O", err)
coredebug("public keys %O", publicKeys)
const users = new Map()
// set placeholder defaults for all known public keys
publicKeys.forEach(publicKey => {
users.set(util.hex(publicKey), { name: "", acceptRole: constants.INFO_DEFAULT_ACCEPT_ROLE })
})
this.store.userInfoView.api.getLatestInfoHashAllUsers((err, latestInfoHashes) => {
if (err) return cb(err)
this.resolveHashes(latestInfoHashes, (err, posts) => {
// TODO (2023-09-06): handle post/info deletion and storing null?
posts.filter(post => post !== null).forEach(post => {
if (post.postType !== constants.INFO_POST) { return }
// prepare default values
let nameValue = constants.INFO_DEFAULT_NAME
let acceptRoleValue = constants.INFO_DEFAULT_ACCEPT_ROLE
if (post.info.has("name")) {
nameValue = post.info.get("name")
}
if (post.info.has("accept-role")) {
acceptRoleValue = post.info.get("accept-role")
}
users.set(post.publicKey, { name: nameValue, acceptRole: acceptRoleValue })
// public key had a post/info:name -> use it
})
cb(null, users)
})
})
})
}
getUsersInChannel(channel, cb) {
if (!cb) { return }
// first get the pubkeys currently in channel
this.store.channelMembershipView.api.getUsersInChannel(channel, (err, pubkeys) => {
if (err) return cb(err)
const channelUsers = new Map()
// filter all known users down to only users in the queried channel
this.getUsers((err, users) => {
users.forEach((value, key) => {
if (pubkeys.includes(key)) {
channelUsers.set(key, value)
}
})
cb(null, channelUsers)
})
})
}
getRoles(channel, cb) {
this.#moderationReady.call(() => {
const context = channel === "" ? constants.CABAL_CONTEXT : channel
const emptyRoles = new Map()
if (this.activeRoles.has(context)) {
return cb(null, this.activeRoles.get(context))
}
return cb(null, emptyRoles)
})
}
getAllRoles(cb) {
if (!cb) return
// returns a map with the scheme: Map[pubkey] => Map[channel] -> role
this.#moderationReady.call(() => {
const userMap = util.transformUserRoleMapScheme(this.activeRoles)
return cb(null, userMap)
})
}
getAllModerationActions(cb) {
if (!cb) return
this.#moderationReady.call(() => {
cb(null, this.moderationActions)
})
}
// get all relevant roles + get all relevant actions (used for answering requests)
getRelevantModerationHashes(ts, channels, cb) {
// TODO (2024-03-25): when handling a moderation state request and fashioning a responce, verify the conformance of
// requirements for moderation state request wrt "belonging to at least one channel"
// query the actions view to get all matching moderation actions
const promises = []
promises.push(new Promise((res, rej) => {
this.store.actionsView.api.getRelevantByContextsSince(ts, channels, (err, hashes) => {
if (err) return rej(err)
return res(hashes)
})
}))
// query the roles view to get all matching roles
promises.push(new Promise((res, rej) => {
this.store.rolesView.api.getAllByContextsSinceTime(ts, channels, (err, hashes) => {
if (err) return rej(err)
return res(hashes)
})
}))
// wait until both view calls have returned their results, collect them and pass to the callback
Promise.all(promises).then((results) => {
cb(results.flatMap(h => h))
})
}
// resolves hashes into post objects. note: all post objects that are returned from cable-core will have their buffer
// instances be converted to hex strings
resolveHashes(hashes, cb) {
this._getData(hashes, (err, bufs) => {
const posts = []
bufs.forEach((buf, index) => {
if (buf !== null) {
const post = cable.parsePost(buf)
// deviating from spec-defined fields!
// 1. add a 'postHash' key to each resolved hash.
// this allows downstream clients to refer to a particular post and act on it
post["postHash"] = util.hex(hashes[index])
// 2. convert to hex string instead of buffer instance
post.links = post.links.map(l => util.hex(l))
post.publicKey = util.hex(post.publicKey)
post.signature = util.hex(post.signature)
posts.push(post)
} else {
posts.push(null)
}
})
cb(null, posts)
})
}
_getData(hashes, cb) {
this.store.blobs.api.getMany(hashes, (err, bufs) => {
if (err) { return cb(err) }
coredebug("getData bufs %O", bufs)
const posts = []
bufs.forEach(buf => {
if (typeof buf === "undefined") {
posts.push(null)
return
}
posts.push(buf)
})
cb(null, posts)
})
}
getChannelState(channel, cb) {
// resolve the hashes into cable posts and return them
this.store.channelMembershipView.api.getHistoricUsers(channel, (err, pubkeys) => {
this.getChannelStateHashes(pubkeys, channel, (err, hashes) => {
if (err) { return cb(err) }
this.resolveHashes(hashes, cb)
})
})
}
getChannelStateHashes(channel, cb) {
// get historic membership of channel
this.store.channelMembershipView.api.getHistoricUsers(channel, (err, pubkeys) => {
// get the latest state (topic, membership, info hashes) of the channel
const statePromise = new Promise((res, reject) => {
this.store.channelStateView.api.getLatestState(pubkeys, channel, (err, hashes) => {
if (err) return reject(err)
res(hashes)
})
})
// resolve promises to get at the hashes
statePromise.then(hashes => {
// collapse results into a single array, deduplicate via set and get the list of hashes
const filteredHashes = hashes.filter(item => typeof item !== "undefined")
cb(null, filteredHashes)
})
})
}
/* methods that control requests to peers, causing responses to stream in (or stop) */
// cancel request
cancelRequest(cancelid) {
// the cancel id is the request to cancel (stop)
const reqid = crypto.generateReqID()
// set ttl to 0 as it's is unused in cancel req
const req = cable.CANCEL_REQUEST.create(reqid, 0, cancelid)
// signal to others to forget about the canceled request id
this.dispatchRequest(req)
this._removeRequest(cancelid)
return req
}
_removeRequest(reqid) {
const reqidHex = util.hex(reqid)
coredebug("[%s] _removeRequest: ceasing tracking request", reqidHex)
// cancel any potential ongoing live requests
this.live.cancelLiveStateRequest(reqidHex)
// forget the targeted request id locally
this.requestsMap.delete(reqidHex)
}
// <-> getChannels
requestChannels(ttl, offset, limit) {
const reqid = crypto.generateReqID()
const req = cable.CHANNEL_LIST_REQUEST.create(reqid, ttl, offset, limit)
this.dispatchRequest(req)
return req
}
// <-> getRelevantModerationHashes
requestModeration(ttl, channels, future, oldest) {
const reqid = crypto.generateReqID()
const req = cable.MODERATION_STATE_REQUEST.create(reqid, ttl, channels, future, oldest)
this.dispatchRequest(req)
return req
}
// <-> getChat
requestPosts(channel, start, end, ttl, limit) {
const reqid = crypto.generateReqID()
coredebug("[%s] request posts for %s", util.hex(reqid), channel)
const req = cable.TIME_RANGE_REQUEST.create(reqid, ttl, channel, start, end, limit)
this.dispatchRequest(req)
return req
}
// -> request post/topic, post/join, post/leave, post/info
// future is either 0 or 1, 1 if we want to request future posts
requestState(channel, ttl, future) {
const reqid = crypto.generateReqID()
const req = cable.CHANNEL_STATE_REQUEST.create(reqid, ttl, channel, future)
this.dispatchRequest(req)
return req
}
_reqEntryTemplate (obj) {
const entry = {
obj, // `obj` is the full JSON encoded cable message representing the request being mapped
"resType": -1,
"recipients": [],
"origin": false,
"binary": null
}
const reqType = obj.msgType
switch (reqType) {
case constants.POST_REQUEST:
entry.resType = constants.POST_RESPONSE
break
case constants.CANCEL_REQUEST:
break
case constants.TIME_RANGE_REQUEST:
entry.resType = constants.HASH_RESPONSE
break
case constants.CHANNEL_STATE_REQUEST:
entry.resType = constants.HASH_RESPONSE
break
case constants.CHANNEL_LIST_REQUEST:
entry.resType = constants.CHANNEL_LIST_RESPONSE
break
case constants.MODERATION_STATE_REQUEST:
entry.resType = constants.HASH_RESPONSE
break
default:
throw new Error(`make request: unknown reqType (${reqType})`)
}
return entry
}
_registerRequest(reqid, origin, type, obj, buf) {
const reqidHex = util.hex(reqid)
if (this._isReqidKnown(reqid)) {
coredebug(`[%s] request map already registered request`, reqidHex)
return
}
// TODO (2023-03-23): handle recipients at some point
// entry.recipients.push(peer)
const entry = this._reqEntryTemplate(obj)
entry.origin = origin
entry.binary = buf
this.requestsMap.set(reqidHex, entry)
}
// register a request that is originating from the local node, sets origin to true
_registerLocalRequest(reqid, reqType, buf) {
const reqidHex = util.hex(reqid)
const obj = cable.parseMessage(buf)
coredebug("register local %O", obj)
// before proceeding: investigate if we have prior a live request for the target channel.
// requests that can be considered live: channel time range with time_end = 0 or channel state with future = 1
const contexts = []
switch (reqType) {
case constants.TIME_RANGE_REQUEST:
case constants.CHANNEL_STATE_REQUEST:
contexts.push(obj.channel)
coredebug("register local: had channel state request or time range request with target %s", obj.channel)
break
case constants.MODERATION_STATE_REQUEST:
// need to handle moderation state request differently as it targets many channels and implicitly also the
// entire cabal
contexts.push(constants.CABAL_CONTEXT)
obj.channels.forEach(channel => contexts.push(channel))
coredebug("register local: had moderation state request with targets %s", obj.channels)
break
default:
// pass; no other requests can be considered 'live' as of writing
this._registerRequest(reqid, true, reqType, obj, buf)
return
}
// find out if we already have such requests for this channel(s) in flight and alive
const localLiveRequests = []
for (const entry of this.requestsMap.values()) {
// we only want to operate on our own requests for the given channel
coredebug("stored msgtype", entry.obj.msgType, "incoming msgtype", reqType, "origin", entry.origin)
if (reqType === 8 && entry.obj.msgType === reqType) {
coredebug("stored request info", entry)
coredebug("incoming request", obj)
coredebug(reqType === constants.MODERATION_STATE_REQUEST && contexts.some(c1 => entry.obj.channels.some(c2 => c1 === c2)) || contexts.includes(entry.obj.channel))
}
if (entry.obj.msgType === reqType && entry.origin) {
if ((reqType === constants.MODERATION_STATE_REQUEST && contexts.some(c1 => entry.obj.channels.some(c2 => c1 === c2))) || contexts.includes(entry.obj.channel)) {
coredebug("register local entry %O", entry)
localLiveRequests.push(util.hex(entry.obj.reqid))
}
}
}
// if we have found any local live requests, this will send a request to cancel them
localLiveRequests.forEach(liveid => {
coredebug("canceling prior live request [%s] since it has been superceded by [%s]", liveid, reqidHex)
this.cancelRequest(b4a.from(liveid, "hex"))
})
// finally register the new request (do this last so we don't accidentally iterate over it while looking at live
// requests, and cancel it :)
this._registerRequest(reqid, true, reqType, obj, buf)
}
// keeping track of requests
// * live requests (future=1, time_end = 0)
// * in progress requests, waiting for their response
// * local requests which are to succeed any live request currently made on the same channel
// register a request that originates from a remote node, sets origin to false
_registerRemoteRequest(reqid, reqType, buf) {
const obj = cable.parseMessage(buf)
this._registerRequest(reqid, false, reqType, obj, buf)
}
/* methods that deal with responding to requests */
// TODO (2023-08-15): wherever we clearly conclude a received request - make sure it is removed from requestsMap /
// this._removeRequest(reqid) is called
handleRequest(req, done) {
if (!done) { done = util.noop }
const reqType = cable.peekMessage(req)
const reqid = cable.peekReqid(req)
const reqidHex = util.hex(reqid)
// check if message is a request or a response
if (!this._messageIsRequest(reqType)) {
coredebug("[%s] message is not a request (msgType %d)", reqidHex, reqType)
return done()
}
// deduplicate the request: if we already know about it, we don't need to process it any further
/* from spec: To prevent request loops in the network, an incoming request with a known req_id MUST be discarded. */
if (this._isReqidKnown(reqid)) {
coredebug("[%s] already knew about request - returning early", reqidHex)
return done()
}
const obj = cable.parseMessage(req)
coredebug("[%s] request obj", reqidHex, obj)
this._registerRemoteRequest(reqid, reqType, req)
if (obj.ttl > 0) { this.forwardRequest(req) }