-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchelonia.ts
More file actions
2829 lines (2764 loc) · 104 KB
/
chelonia.ts
File metadata and controls
2829 lines (2764 loc) · 104 KB
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
import '@sbp/okturtles.eventqueue'
import '@sbp/okturtles.events'
import sbp from '@sbp/sbp'
import {
cloneDeep,
delay,
difference,
has,
intersection,
merge,
randomHexString,
randomIntFromRange
} from 'turtledash'
import { blake32Hash, createCID, multicodes, parseCID } from './functions.js'
import { Buffer } from 'buffer'
import { NOTIFICATION_TYPE, createClient } from './pubsub/index.js'
import type {
ProtoSPOpKeyRequestInnerV2,
SPKey,
SPKeyPurpose,
SPOpActionUnencrypted,
SPOpContract,
SPOpKeyAdd,
SPOpKeyDel,
SPOpKeyRequestSeen,
SPOpKeyShare,
SPOpKeyUpdate,
SPOpValue
} from './SPMessage.js'
import type { Key } from '@chelonia/crypto'
import {
EDWARDS25519SHA512BATCH,
deserializeKey,
keyId,
keygen,
serializeKey
} from '@chelonia/crypto'
import {
ChelErrorResourceGone,
ChelErrorUnexpected,
ChelErrorUnexpectedHttpResponseCode,
ChelErrorUnrecoverable
} from './errors.js'
import { CHELONIA_RESET, CONTRACTS_MODIFIED, CONTRACT_REGISTERED } from './events.js'
import { SPMessage } from './SPMessage.js'
import type { Secret } from './Secret.js'
import './chelonia-utils.js'
import type { EncryptedData } from './encryptedData.js'
import {
encryptedOutgoingData,
encryptedOutgoingDataWithRawKey,
isEncryptedData,
maybeEncryptedIncomingData,
unwrapMaybeEncryptedData
} from './encryptedData.js'
import './files.js'
import './internals.js'
import type { PublishOptions } from './internals.js'
import {
isSignedData,
type RawSignedData,
signedIncomingData,
signedOutgoingData,
signedOutgoingDataWithRawKey
} from './signedData.js'
import './time-sync.js'
import {
buildShelterAuthorizationHeader,
checkCanBeGarbageCollected,
clearObject,
collectEventStream,
deletionTokenFromHint,
eventsAfter,
findForeignKeysByContractID,
findKeyIdByName,
findRevokedKeyIdsByName,
findSuitableSecretKeyId,
freshDeletionToken,
getContractIDfromKeyId,
handleFetchResult,
reactiveClearObject
} from './utils.js'
import {
ChelContractKey,
ChelContractProcessMessageObject,
ChelContractSideeffectMutationObject,
ChelContractState,
ChelKvOnConflictCallback,
ChelRootState,
CheloniaConfig,
CheloniaContext,
CheloniaContractCtx,
JSONType,
ParsedEncryptedOrUnencryptedMessage
} from './types.js'
import type { Options as PubSubOptions, PubSubClient } from './pubsub/index.js'
// TODO: define ChelContractType for /defineContract
export type { PublishOptions }
export type ChelRegParams = {
contractName: string;
server?: string; // TODO: implement!
data: object;
signingKeyId: string;
actionSigningKeyId: string;
actionEncryptionKeyId?: string | null | undefined;
keys: (SPKey | EncryptedData<SPKey>)[];
namespaceRegistration?: string | null | undefined;
hooks?: {
prepublishContract?: (msg: SPMessage) => void;
postpublishContract?: (msg: SPMessage) => void;
preSendCheck?: (msg: SPMessage, state: ChelContractState) => void;
beforeRequest?: (msg1: SPMessage, msg2: SPMessage) => Promise<void> | void;
prepublish?: (msg: SPMessage) => Promise<void> | void;
postpublish?: (msg: SPMessage) => Promise<void> | void;
onprocessed?: (msg: SPMessage) => Promise<void> | void;
};
publishOptions?: PublishOptions;
};
export type ChelActionParams = {
action: string;
server?: string; // TODO: implement!
contractID: string;
data: object;
signingKeyId: string;
innerSigningKeyId: string;
encryptionKeyId?: string | null | undefined;
encryptionKey?: Key | null | undefined;
hooks?: {
prepublishContract?: (msg: SPMessage) => void;
prepublish?: (msg: SPMessage) => Promise<void> | void;
postpublish?: (msg: SPMessage) => Promise<void> | void;
};
publishOptions?: PublishOptions;
atomic: boolean;
};
export type ChelKeyAddParams = {
contractName: string;
contractID: string;
data: SPOpKeyAdd;
signingKeyId: string;
hooks?: {
prepublishContract?: (msg: SPMessage) => void;
prepublish?: (msg: SPMessage) => Promise<void> | void;
postpublish?: (msg: SPMessage) => Promise<void> | void;
};
publishOptions?: PublishOptions;
atomic: boolean;
// Usually `keyAdd` will ignore calls for keys that already exist in the
// contract, for convenience. In some cases, e.g., when using OP_KEY_DEL
// and OP_KEY_ADD inside of OP_ATOMIC, we might want to skip this check.
skipExistingKeyCheck?: boolean;
};
export type ChelKeyDelParams = {
contractName: string;
contractID: string;
data: SPOpKeyDel;
signingKeyId: string;
hooks?: {
prepublishContract?: (msg: SPMessage) => void;
prepublish?: (msg: SPMessage) => Promise<void>;
postpublish?: (msg: SPMessage) => Promise<void>;
};
publishOptions?: PublishOptions;
atomic: boolean;
};
export type ChelKeyUpdateParams = {
contractName: string;
contractID: string;
data: SPOpKeyUpdate;
signingKeyId: string;
hooks?: {
prepublishContract?: (msg: SPMessage) => void;
prepublish?: (msg: SPMessage) => Promise<void>;
postpublish?: (msg: SPMessage) => Promise<void>;
};
publishOptions?: PublishOptions;
atomic: boolean;
};
export type ChelKeyShareParams = {
originatingContractID?: string;
originatingContractName?: string;
contractID: string;
contractName: string;
data: SPOpKeyShare;
signingKeyId?: string;
signingKey?: Key;
hooks?: {
prepublishContract?: (msg: SPMessage) => void;
prepublish?: (msg: SPMessage) => Promise<void>;
postpublish?: (msg: SPMessage) => Promise<void>;
};
publishOptions?: PublishOptions;
atomic: boolean;
};
export type ChelKeyRequestParams = {
originatingContractID: string;
originatingContractName: string;
contractName: string;
contractID: string;
signingKeyId: string;
innerSigningKeyId: string;
encryptionKeyId: string;
innerEncryptionKeyId: string;
encryptKeyRequestMetadata?: boolean;
permissions?: '*' | string[];
allowedActions?: '*' | string[];
// Arbitrary data the requester can use as reference (e.g., the hash
// of the user-initiated action that triggered this key request)
reference?: string;
// Contract-defined string describing which keys are being requested
// The special value '*' (default) means that all 'shareable' keys will be
// shared. Otherwise, this value is passed on to a contract-defined handler
// for processing. For example, this string could be something like 'missing'
// or it could be a comma-separated list of key names to share.
request?: string;
// Use an existing #krrk key instead of creating a new one
keyRequestResponseId?: string;
// Mark request as not consuming invites (this will be enforced by the responder)
skipInviteAccounting?: boolean;
hooks?: {
prepublishContract?: (msg: SPMessage) => void;
prepublish?: (msg: SPMessage) => Promise<void>;
postpublish?: (msg: SPMessage) => Promise<void>;
};
publishOptions?: PublishOptions;
atomic: boolean;
};
export type ChelKeyRequestResponseParams = {
contractName: string;
contractID: string;
data: SPOpKeyRequestSeen;
signingKeyId: string;
hooks?: {
prepublishContract?: (msg: SPMessage) => void;
prepublish?: (msg: SPMessage) => Promise<void>;
postpublish?: (msg: SPMessage) => Promise<void>;
};
publishOptions?: PublishOptions;
atomic: boolean;
};
export type ChelAtomicParams = {
originatingContractID: string;
originatingContractName: string;
contractName: string;
contractID: string;
signingKeyId: string;
data: [sel: string, data: ChelActionParams | ChelKeyRequestParams | ChelKeyShareParams][];
hooks?: {
prepublishContract?: (msg: SPMessage) => void;
prepublish?: (msg: SPMessage) => Promise<void>;
postpublish?: (msg: SPMessage) => Promise<void>;
};
publishOptions?: PublishOptions;
};
export { SPMessage }
export const ACTION_REGEX: RegExp = /^((([\w.]+)\/([^/]+))(?:\/(?:([^/]+)\/)?)?)\w*/
// ACTION_REGEX.exec('gi.contracts/group/payment/process')
// 0 => 'gi.contracts/group/payment/process'
// 1 => 'gi.contracts/group/payment/'
// 2 => 'gi.contracts/group'
// 3 => 'gi.contracts'
// 4 => 'group'
// 5 => 'payment'
export default sbp('sbp/selectors/register', {
// https://www.wordnik.com/words/chelonia
// https://gitlab.okturtles.org/okturtles/group-income/-/wikis/E2E-Protocol/Framework.md#alt-names
'chelonia/_init': function (this: CheloniaContext) {
this.config = {
// TODO: handle connecting to multiple servers for federation
get connectionURL () {
throw new Error('Invalid use of connectionURL before initialization')
},
// override!
set connectionURL (value: string) {
Object.defineProperty(this, 'connectionURL', { value, writable: true })
},
stateSelector: 'chelonia/private/state', // override to integrate with, for example, vuex
contracts: {
defaults: {
modules: {}, // '<module name>' => resolved module import
exposedGlobals: {},
allowedDomains: [],
allowedSelectors: [],
preferSlim: false
},
overrides: {}, // override default values per-contract
manifests: {} // override! contract names => manifest hashes
},
whitelisted: (action: string): boolean => !!this.whitelistedActions[action],
reactiveSet: (obj, key, value) => {
obj[key] = value
return value
}, // example: set to Vue.set
fetch: (...args) => fetch(...args),
reactiveDel: (obj, key) => {
delete obj[key]
},
// acceptAllMessages disables checking whether we are expecting a message
// or not for processing
acceptAllMessages: false,
skipActionProcessing: false,
skipDecryptionAttempts: false,
skipSideEffects: false,
// Strict processing will treat all processing errors as unrecoverable
// This is useful, e.g., in the server, to prevent invalid messages from
// being added to the database
strictProcessing: false,
// Strict ordering will throw on past events with ChelErrorAlreadyProcessed
// Similarly, future events will not be reingested and will throw
// with ChelErrorDBBadPreviousHEAD
strictOrdering: false,
// Chelonia will store some information (e.g., date it was received) about
// messages. This is primarily useful in the server, and not so useful for
// clients, especially for lightweight clients that don't store messages.
saveMessageMetadata: false,
connectionOptions: {
maxRetries: Infinity, // See https://github.com/okTurtles/group-income/issues/1183
reconnectOnTimeout: true // can be enabled since we are not doing auth via web sockets
},
hooks: {
preHandleEvent: null, // async (message: SPMessage) => {}
postHandleEvent: null, // async (message: SPMessage) => {}
processError: null, // (e: Error, message: SPMessage) => {}
sideEffectError: null, // (e: Error, message: SPMessage) => {}
handleEventError: null, // (e: Error, message: SPMessage) => {}
syncContractError: null, // (e: Error, contractID: string) => {}
pubsubError: null // (e:Error, socket: Socket)
},
unwrapMaybeEncryptedData
}
// Used in publishEvent to cancel sending events after reset (logout)
this._instance = Object.create(null)
this.abortController = new AbortController()
this.state = {
contracts: {}, // contractIDs => { type, HEAD } (contracts we've subscribed to)
pending: [] // prevents processing unexpected data from a malicious server
}
this.manifestToContract = {}
this.whitelistedActions = {}
this.currentSyncs = Object.create(null)
this.postSyncOperations = Object.create(null)
this.sideEffectStacks = Object.create(null) // [contractID]: Array<unknown>
this.sideEffectStack = (contractID: string) => {
let stack = this.sideEffectStacks[contractID]
if (!stack) {
this.sideEffectStacks[contractID] = stack = []
}
return stack
}
// setPostSyncOp defines operations to be run after all recent events have
// been processed. This is useful, for example, when responding to
// OP_KEY_REQUEST, as we want to send an OP_KEY_SHARE only to yet-unanswered
// requests, which is information in the future (from the point of view of
// the event handler).
// We could directly enqueue the operations, but by using a map we avoid
// enqueueing more operations than necessary
// The operations defined here will be executed:
// (1) After a call to /sync or /syncContract; or
// (2) After an event has been handled, if it was received on a web socket
this.setPostSyncOp = (contractID: string, key: string, op: Parameters<typeof sbp>) => {
this.postSyncOperations[contractID] =
this.postSyncOperations[contractID] || Object.create(null)
this.postSyncOperations[contractID][key] = op
}
const secretKeyGetter = (o: Record<string, Key>, p: string) => {
if (has(o, p)) return o[p]
const rootState = sbp(this.config.stateSelector)
if (rootState?.secretKeys && has(rootState.secretKeys, p)) {
const key = deserializeKey(rootState.secretKeys[p])
o[p] = key
return key
}
}
const secretKeyList = (o: Record<string, Key>) => {
const rootState = sbp(this.config.stateSelector)
const stateKeys = Object.keys(rootState?.secretKeys || {})
return Array.from(new Set([...Object.keys(o), ...stateKeys]))
}
this.transientSecretKeys = new Proxy(Object.create(null), {
get: secretKeyGetter,
ownKeys: secretKeyList
})
this.ephemeralReferenceCount = Object.create(null)
// subscriptionSet includes all the contracts in state.contracts for which
// we can process events (contracts for which we have called /sync)
// The reason we can't use, e.g., Object.keys(state.contracts), is that
// when resetting the state (calling /reset, e.g., after logging out) we may
// still receive events for old contracts that belong to the old session.
// Those events must be ignored or discarded until the new session is set up
// (i.e., login has finished running) because we don't necessarily have
// all the information needed to process events in those contracts, such as
// secret keys.
// A concrete example is:
// 1. user1 logs in to the group and rotates the group keys, then logs out
// 2. user2 logs in to the group.
// 3. If an event came over the web socket for the group, we must not
// process it before we've processed the OP_KEY_SHARE containing the
// new keys, or else we'll build an incorrect state.
// The example above is simplified, but this is even more of an issue
// when there is a third contract (for example, a group chatroom) using
// those rotated keys as foreign keys.
this.subscriptionSet = new Set()
// pending includes contracts that are scheduled for syncing or in the
// process of syncing for the first time. After sync completes for the
// first time, they are removed from pending and added to subscriptionSet
this.pending = []
const rootState = sbp(this.config.stateSelector)
rootState.secretKeys = rootState.secretKeys || Object.create(null)
},
'chelonia/config': function (this: CheloniaContext) {
return {
...cloneDeep(this.config),
fetch: this.config.fetch,
reactiveSet: this.config.reactiveSet,
reactiveDel: this.config.reactiveDel
}
},
'chelonia/configure': async function (this: CheloniaContext, config: CheloniaConfig) {
merge(this.config, config)
// merge will strip the hooks off of config.hooks when merging from the root of the object
// because they are functions and cloneDeep doesn't clone functions
Object.assign(this.config.hooks, config.hooks || {})
// using Object.assign here instead of merge to avoid stripping away imported modules
if (config.contracts) {
Object.assign(this.config.contracts.defaults, config.contracts.defaults || {})
const manifests = this.config.contracts.manifests
console.debug('[chelonia] preloading manifests:', Object.keys(manifests))
for (const contractName in manifests) {
await sbp('chelonia/private/loadManifest', contractName, manifests[contractName])
}
}
if (has(config, 'skipDecryptionAttempts')) {
if (config.skipDecryptionAttempts) {
this.config.unwrapMaybeEncryptedData = (data) => {
if (data == null) return
if (!isEncryptedData(data)) {
return {
encryptionKeyId: null,
data
}
}
}
} else {
this.config.unwrapMaybeEncryptedData = unwrapMaybeEncryptedData
}
}
},
'chelonia/reset': async function (
this: CheloniaContext,
newState: ChelRootState | undefined,
postCleanupFn?: () => Promise<void> | void
) {
// Allow optional newState OR postCleanupFn
if (typeof newState === 'function' && typeof postCleanupFn === 'undefined') {
postCleanupFn = newState
newState = undefined
}
if (this.pubsub) {
sbp('chelonia/private/stopClockSync')
}
// wait for any pending sync operations to finish before saving
Object.keys(this.postSyncOperations).forEach((cID) => {
sbp('chelonia/private/enqueuePostSyncOps', cID)
})
await sbp('chelonia/contract/waitPublish')
await sbp('chelonia/contract/wait')
// do this again to catch operations that are the result of side-effects
// or post sync ops
Object.keys(this.postSyncOperations).forEach((cID) => {
sbp('chelonia/private/enqueuePostSyncOps', cID)
})
await sbp('chelonia/contract/waitPublish')
await sbp('chelonia/contract/wait')
const result = await postCleanupFn?.()
// The following are all synchronous operations
const rootState = sbp(this.config.stateSelector)
// Cancel all outgoing messages by replacing this._instance
this._instance = Object.create(null)
this.abortController.abort()
this.abortController = new AbortController()
// Remove all contracts, including all contracts from pending
reactiveClearObject(rootState, this.config.reactiveDel)
this.config.reactiveSet(rootState, 'contracts', Object.create(null))
this.config.reactiveSet(rootState, 'secretKeys', Object.create(null))
clearObject(this.ephemeralReferenceCount)
this.pending.splice(0)
clearObject(this.currentSyncs)
clearObject(this.postSyncOperations)
clearObject(this.sideEffectStacks)
const removedContractIDs = Array.from(this.subscriptionSet)
this.subscriptionSet.clear()
sbp('chelonia/clearTransientSecretKeys')
sbp('okTurtles.events/emit', CHELONIA_RESET)
sbp('okTurtles.events/emit', CONTRACTS_MODIFIED, Array.from(this.subscriptionSet), {
added: [],
removed: removedContractIDs
})
if (this.pubsub) {
sbp('chelonia/private/startClockSync')
}
if (newState) {
Object.entries(newState).forEach(([key, value]) => {
this.config.reactiveSet(rootState, key, value)
})
}
return result
},
'chelonia/storeSecretKeys': function (
this: CheloniaContext,
wkeys: Secret<{ key: Key | string; transient?: boolean }[]>
) {
const rootState = sbp(this.config.stateSelector)
if (!rootState.secretKeys) { this.config.reactiveSet(rootState, 'secretKeys', Object.create(null)) }
let keys = wkeys.valueOf()
if (!keys) return
if (!Array.isArray(keys)) keys = [keys]
keys.forEach(({ key, transient }) => {
if (!key) return
if (typeof key === 'string') {
key = deserializeKey(key)
}
const id = keyId(key)
// Store transient keys transientSecretKeys
if (!has(this.transientSecretKeys, id)) {
this.transientSecretKeys[id] = key
}
if (transient) return
// If the key is marked as persistent, write it to the state as well
if (!has(rootState.secretKeys, id)) {
this.config.reactiveSet(rootState.secretKeys, id, serializeKey(key, true))
}
})
},
'chelonia/clearTransientSecretKeys': function (this: CheloniaContext, ids?: string[]) {
if (Array.isArray(ids)) {
ids.forEach((id) => {
delete this.transientSecretKeys[id]
})
} else {
Object.keys(this.transientSecretKeys).forEach((id) => {
delete this.transientSecretKeys[id]
})
}
},
'chelonia/haveSecretKey': function (this: CheloniaContext, keyId: string, persistent?: boolean) {
if (!persistent && has(this.transientSecretKeys, keyId)) return true
const rootState = sbp(this.config.stateSelector)
return !!rootState?.secretKeys && has(rootState.secretKeys, keyId)
},
'chelonia/contract/isResyncing': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState
) {
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector)
contractIDOrState = rootState[contractIDOrState]
}
return (
!!(contractIDOrState as ChelContractState)?._volatile?.dirty ||
!!(contractIDOrState as ChelContractState)?._volatile?.resyncing
)
},
'chelonia/contract/hasKeyShareBeenRespondedBy': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState | null | undefined,
requestedToContractID: string,
reference?: string
): boolean {
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector)
contractIDOrState = rootState[contractIDOrState]
}
const result = Object.values(
(contractIDOrState as ChelContractState)?._vm.authorizedKeys || {}
).some((r) => {
return (
r?.meta?.keyRequest?.responded &&
r.meta.keyRequest.contractID === requestedToContractID &&
(!reference || r.meta.keyRequest.reference === reference)
)
})
return result
},
'chelonia/contract/waitingForKeyShareTo': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState,
requestingContractID?: string,
reference?: string
): null | string[] {
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector) as ChelRootState
contractIDOrState = rootState[contractIDOrState]
}
const result = (contractIDOrState as ChelContractState)._volatile?.pendingKeyRequests
?.filter((r) => {
return (
r &&
(!requestingContractID || r.contractID === requestingContractID) &&
(!reference || r.reference === reference)
)
})
?.map(({ name }) => name)
if (!result?.length) return null
return result
},
'chelonia/contract/successfulKeySharesByContractID': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState,
requestingContractID?: string
) {
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector)
contractIDOrState = rootState[contractIDOrState]
}
const keyShares = Object.values((contractIDOrState as ChelContractState)._vm.keyshares || {})
if (!keyShares?.length) return
const result = Object.create(null) as Record<string, { height: number; hash?: string }[]>
keyShares.forEach((kS) => {
if (!kS.success) return
if (requestingContractID && kS.contractID !== requestingContractID) return
if (!result[kS.contractID]) result[kS.contractID] = []
result[kS.contractID].push({ height: kS.height, hash: kS.hash })
})
Object.keys(result).forEach((cID) => {
result[cID].sort((a, b) => {
return b.height - a.height
})
})
return result
},
'chelonia/contract/hasKeysToPerformOperation': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState,
operation: string
) {
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector)
contractIDOrState = rootState[contractIDOrState]
}
const op = operation !== '*' ? [operation] : operation
return !!findSuitableSecretKeyId(contractIDOrState as ChelContractState, op, ['sig'])
},
// Did sourceContractIDOrState receive an OP_KEY_SHARE to perform the given
// operation on contractIDOrState?
'chelonia/contract/receivedKeysToPerformOperation': function (
this: CheloniaContext,
sourceContractIDOrState: string | ChelContractState,
contractIDOrState: string | ChelContractState,
operation: string
) {
const rootState = sbp(this.config.stateSelector)
if (typeof sourceContractIDOrState === 'string') {
sourceContractIDOrState = rootState[sourceContractIDOrState]
}
if (typeof contractIDOrState === 'string') {
contractIDOrState = rootState[contractIDOrState]
}
const op = operation !== '*' ? [operation] : operation
const keyId = findSuitableSecretKeyId(contractIDOrState as ChelContractState, op, ['sig'])
return (sourceContractIDOrState as ChelContractState)?._vm?.sharedKeyIds?.some(
(sK) => sK.id === keyId
)
},
'chelonia/contract/currentKeyIdByName': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState,
name: string,
requireSecretKey?: boolean
) {
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector)
contractIDOrState = rootState[contractIDOrState]
}
const currentKeyId = findKeyIdByName(contractIDOrState as ChelContractState, name)
if (requireSecretKey && !sbp('chelonia/haveSecretKey', currentKeyId)) {
return
}
return currentKeyId
},
'chelonia/contract/foreignKeysByContractID': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState,
foreignContractID: string
) {
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector)
contractIDOrState = rootState[contractIDOrState]
}
return findForeignKeysByContractID(contractIDOrState as ChelContractState, foreignContractID)
},
'chelonia/contract/historicalKeyIdsByName': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState,
name: string
) {
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector)
contractIDOrState = rootState[contractIDOrState]
}
const currentKeyId = findKeyIdByName(contractIDOrState as ChelContractState, name)
const revokedKeyIds = findRevokedKeyIdsByName(contractIDOrState as ChelContractState, name)
return currentKeyId ? [currentKeyId, ...revokedKeyIds] : revokedKeyIds
},
'chelonia/contract/suitableSigningKey': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState,
permissions: '*' | string[],
purposes: SPKeyPurpose[],
ringLevel?: number,
allowedActions?: '*' | string[]
) {
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector)
contractIDOrState = rootState[contractIDOrState]
}
const keyId = findSuitableSecretKeyId(
contractIDOrState as ChelContractState,
permissions,
purposes,
ringLevel,
allowedActions
)
return keyId
},
// setPendingKeyRevocation is meant to be called by contracts (or applications)
// to mark a set of keys as pending revocation / rotation (that is, adding the
// key to `_volatile.pendingKeyRevocations`).
// Keys that are marked as pending revocation can then be collected by key
// rotation logic (currently, 'gi.actions/out/rotateKeys') to rotate them or
// delete them.
// Calling this selector in itself doesn't revoke or rotate the key. It will
// just set a flag on that key for later handling. The flag is automatically
// cleared when the key is updated or deleted.
'chelonia/contract/setPendingKeyRevocation': function (
this: CheloniaContext,
contractIDOrState: string | ChelContractState,
names: string[],
keyIds?: string[]
) {
let state: ChelContractState
let contractID: string | undefined
if (typeof contractIDOrState === 'string') {
const rootState = sbp(this.config.stateSelector)
contractID = contractIDOrState
state = rootState[contractIDOrState]
} else {
state = contractIDOrState
}
if (!state._volatile) this.config.reactiveSet(state, '_volatile', Object.create(null))
if (!state._volatile!.pendingKeyRevocations) {
this.config.reactiveSet(state._volatile!, 'pendingKeyRevocations', Object.create(null))
}
for (const name of names) {
const keyId = findKeyIdByName(state, name)
if (keyId) {
if (keyIds && !keyIds.includes(keyId)) continue
this.config.reactiveSet(state._volatile!.pendingKeyRevocations!, keyId, true)
} else {
console.warn('[setPendingKeyRevocation] Unable to find keyId for name', {
contractID: contractID ?? '(unknown)',
name
})
}
}
},
'chelonia/shelterAuthorizationHeader' (this: CheloniaContext, contractID: string) {
return buildShelterAuthorizationHeader.call(this, contractID)
},
// The purpose of the 'chelonia/crypto/*' selectors is so that they can be called
// from contracts without including the crypto code (i.e., importing crypto.js)
// This function takes a function as a parameter that returns a string
// It does not a string directly to prevent accidentally logging the value,
// which is a secret
'chelonia/crypto/keyId': (inKey: Secret<Key | string>) => {
return keyId(inKey.valueOf())
},
// TODO: allow connecting to multiple servers at once
'chelonia/connect': function (
this: CheloniaContext,
options: Partial<PubSubOptions> = {}
): PubSubClient {
if (!this.config.connectionURL) throw new Error('config.connectionURL missing')
if (!this.config.connectionOptions) throw new Error('config.connectionOptions missing')
if (this.pubsub) {
this.pubsub.destroy()
}
let pubsubURL = this.config.connectionURL
if (process.env.NODE_ENV === 'development') {
// This is temporarily used in development mode to help the server improve
// its console output until we have a better solution. Do not use for auth.
pubsubURL += `?debugID=${randomHexString(6)}`
}
if (this.pubsub) {
sbp('chelonia/private/stopClockSync')
}
sbp('chelonia/private/startClockSync')
this.pubsub = createClient(pubsubURL, {
...this.config.connectionOptions,
handlers: {
...options.handlers,
// Every time we get a REQUEST_TYPE.SUB response, which happens for
// 'new' subscriptions as well as every time the connection is reset
'subscription-succeeded': function (event: CustomEvent<{ channelID: string }>) {
const { channelID } = event.detail
// The check below is needed because we could have unsubscribed since
// requesting a subscription from the server. In that case, we don't
// need to call `sync`.
if (this.subscriptionSet.has(channelID)) {
// For new subscriptions, some messages could have been lost
// between the time the subscription was requested and it was
// actually set up. In these cases, force sync contracts to get them
// updated.
sbp('chelonia/private/out/sync', channelID, { force: true }).catch((err: Error) => {
console.warn(`[chelonia] Syncing contract ${channelID} failed: ${err.message}`)
})
}
options.handlers?.['subscription-succeeded']?.call(this, event)
}
},
// Map message handlers to transparently handle encryption and signatures
messageHandlers: {
...Object.fromEntries(
Object.entries(options.messageHandlers || {}).map(([k, v]) => {
switch (k) {
case NOTIFICATION_TYPE.PUB:
return [
k,
(msg: {
data?: RawSignedData<{ height: string }>;
channelID: string;
}) => {
if (!msg.channelID) {
console.info('[chelonia] Discarding pub event without channelID')
return
}
if (!this.subscriptionSet.has(msg.channelID)) {
console.info(
`[chelonia] Discarding pub event for ${msg.channelID} because it's not in the current subscriptionSet`
)
return
}
sbp('chelonia/queueInvocation', msg.channelID, () => {
(
v as (
this: PubSubClient,
msg: ParsedEncryptedOrUnencryptedMessage<object>,
) => void
).call(
this.pubsub,
parseEncryptedOrUnencryptedMessage<{ channelID: string; data: JSONType }>(
this,
{
contractID: msg.channelID,
serializedData: msg.data!
}
)
)
}).catch((e: Error) => {
console.error(
`[chelonia] Error processing pub event for ${msg.channelID}`,
e
)
})
}
]
case NOTIFICATION_TYPE.KV:
return [
k,
(msg: { channelID: string; key: string; data: string }) => {
if (!msg.channelID || !msg.key) {
console.info('[chelonia] Discarding kv event without channelID or key')
return
}
if (!this.subscriptionSet.has(msg.channelID)) {
console.info(
`[chelonia] Discarding kv event for ${msg.channelID} because it's not in the current subscriptionSet`
)
return
}
sbp('chelonia/queueInvocation', msg.channelID, () => {
(
v as unknown as (
this: PubSubClient,
msg: [string, ParsedEncryptedOrUnencryptedMessage<object>],
) => void
).call(this.pubsub, [
msg.key,
parseEncryptedOrUnencryptedMessage<object>(this, {
contractID: msg.channelID,
meta: msg.key,
serializedData: JSON.parse(Buffer.from(msg.data).toString())
})
])
}).catch((e: unknown) => {
console.error(
`[chelonia] Error processing kv event for ${msg.channelID} and key ${msg.key}`,
msg,
e
)
})
}
]
case NOTIFICATION_TYPE.DELETION:
return [
k,
(msg: { data: unknown }) =>
(v as unknown as (this: PubSubClient, data: unknown) => void).call(
this.pubsub,
msg.data
)
]
default:
return [k, v]
}
})
),
[NOTIFICATION_TYPE.ENTRY] (msg) {
// We MUST use 'chelonia/private/in/enqueueHandleEvent' to ensure handleEvent()
// is called AFTER any currently-running calls to 'chelonia/private/out/sync'
// to prevent gi.db from throwing "bad previousHEAD" errors.
// Calling via SBP also makes it simple to implement 'test/backend.js'
const { contractID } = SPMessage.deserializeHEAD(msg.data as string)
sbp('chelonia/private/in/enqueueHandleEvent', contractID, msg.data)
}
}
})
if (!this.contractsModifiedListener) {
// Keep pubsub in sync (logged into the right "rooms") with 'state.contracts'
this.contractsModifiedListener = () => sbp('chelonia/pubsub/update')
sbp('okTurtles.events/on', CONTRACTS_MODIFIED, this.contractsModifiedListener)
}
return this.pubsub
},
// This selector is defined primarily for ingesting web push notifications,
// although it can be used as a general-purpose API to process events received
// from other external sources that are not managed by Chelonia itself (i.e. sources
// other than the Chelonia-managed websocket connection and RESTful API).
'chelonia/handleEvent': async function (event: string) {
const { contractID } = SPMessage.deserializeHEAD(event)
return await sbp('chelonia/private/in/enqueueHandleEvent', contractID, event)
},
'chelonia/defineContract': function (this: CheloniaContext, contract: CheloniaContractCtx) {
if (!ACTION_REGEX.exec(contract.name)) throw new Error(`bad contract name: ${contract.name}`)
if (!contract.metadata) contract.metadata = { validate () {}, create: () => ({}) }
if (!contract.getters) contract.getters = {}
contract.state = (contractID) => sbp(this.config.stateSelector)[contractID]
contract.manifest = this.defContractManifest
contract.sbp = this.defContractSBP
this.defContractSelectors = []
this.defContract = contract
this.defContractSelectors.push(
...sbp('sbp/selectors/register', {
// expose getters for Vuex integration and other conveniences
[`${contract.manifest}/${contract.name}/getters`]: () => contract.getters,
// 2 ways to cause sideEffects to happen: by defining a sideEffect function in the
// contract, or by calling /pushSideEffect w/async SBP call. Can also do both.
[`${contract.manifest}/${contract.name}/pushSideEffect`]: (
contractID: string,
asyncSbpCall: [string, ...unknown[]]
) => {
// if this version of the contract is pushing a sideEffect to a function defined by the
// contract itself, make sure that it calls the same version of the sideEffect
const [sel] = asyncSbpCall
if (sel.startsWith(contract.name + '/')) {
asyncSbpCall[0] = `${contract.manifest}/${sel}`
}
this.sideEffectStack(contractID).push(asyncSbpCall)
}
})
)
for (const action in contract.actions) {
contractNameFromAction(action) // ensure actions are appropriately named
this.whitelistedActions[action] = true
// TODO: automatically generate send actions here using `${action}/send`
// allow the specification of:
// - the optype (e.g. OP_ACTION_(UN)ENCRYPTED)
// - a localized error message
// - whatever keys should be passed in as well
// base it off of the design of encryptedAction()
this.defContractSelectors.push(
...(sbp('sbp/selectors/register', {