-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinternals.cjs
More file actions
2444 lines (2442 loc) · 133 KB
/
internals.cjs
File metadata and controls
2444 lines (2442 loc) · 133 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
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const sbp_1 = __importStar(require("@sbp/sbp"));
const functions_js_1 = require("./functions.cjs");
const turtledash_1 = require("turtledash");
const SPMessage_js_1 = require("./SPMessage.cjs");
const Secret_js_1 = require("./Secret.cjs");
const constants_js_1 = require("./constants.cjs");
const crypto_1 = require("@chelonia/crypto");
require("./db.cjs");
const encryptedData_js_1 = require("./encryptedData.cjs");
const errors_js_1 = require("./errors.cjs");
const events_js_1 = require("./events.cjs");
const utils_js_1 = require("./utils.cjs");
const signedData_js_1 = require("./signedData.cjs");
// Used for temporarily storing the missing decryption key IDs in a given
// message
const missingDecryptionKeyIdsMap = new WeakMap();
const getMsgMeta = function (message, contractID, state, index) {
const signingKeyId = message.signingKeyId();
let innerSigningKeyId = null;
const config = this.config;
const result = {
signingKeyId,
get signingContractID() {
return (0, utils_js_1.getContractIDfromKeyId)(contractID, signingKeyId, state);
},
get innerSigningKeyId() {
if (innerSigningKeyId === null) {
const value = message.message();
const data = config.unwrapMaybeEncryptedData(value);
if (data?.data && (0, signedData_js_1.isSignedData)(data.data)) {
innerSigningKeyId = data.data.signingKeyId;
}
else {
innerSigningKeyId = undefined;
}
return innerSigningKeyId;
}
},
get innerSigningContractID() {
return (0, utils_js_1.getContractIDfromKeyId)(contractID, result.innerSigningKeyId, state);
},
index
};
return result;
};
const keysToMap = function (keys_, height, signingKeyId, authorizedKeys) {
// Using cloneDeep to ensure that the returned object is serializable
// Keys in a SPMessage may not be serializable (i.e., supported by the
// structured clone algorithm) when they contain encryptedIncomingData
const keys = keys_
.map((key) => {
const data = this.config.unwrapMaybeEncryptedData(key);
if (!data)
return undefined;
if (data.encryptionKeyId) {
data.data._private = data.encryptionKeyId;
}
return data.data;
})
// eslint-disable-next-line no-use-before-define
.filter(Boolean);
const keysCopy = (0, turtledash_1.cloneDeep)(keys);
return Object.fromEntries(keysCopy.map((key) => {
key._notBeforeHeight = height;
key._addedByKeyId = signingKeyId;
if (authorizedKeys?.[key.id]) {
if (authorizedKeys[key.id]._notAfterHeight == null) {
throw new errors_js_1.ChelErrorKeyAlreadyExists(`Cannot set existing unrevoked key: ${key.id}`);
}
// If the key was get previously, preserve its _notBeforeHeight
// NOTE: (SECURITY) This may allow keys for periods for which it wasn't
// supposed to be active. This is a trade-off for simplicity, instead of
// considering discrete periods, which is the correct solution
// Discrete ranges *MUST* be implemented because they impact permissions
key._notBeforeHeight = Math.min(height, authorizedKeys[key.id]._notBeforeHeight ?? 0);
}
else {
key._notBeforeHeight = height;
}
delete key._notAfterHeight;
return [key.id, key];
}));
};
const keyRotationHelper = (contractID, state, config, updatedKeysMap, requiredPermissions, outputSelector, outputMapper, internalSideEffectStack) => {
if (!internalSideEffectStack || !Array.isArray(state._volatile?.watch))
return;
const rootState = (0, sbp_1.default)(config.stateSelector);
const watchMap = Object.create(null);
state._volatile.watch.forEach(([name, cID]) => {
if (!updatedKeysMap[name] || watchMap[cID] === null) {
return;
}
if (!watchMap[cID]) {
if (!rootState.contracts[cID]?.type ||
!(0, utils_js_1.findSuitableSecretKeyId)(rootState[cID], [SPMessage_js_1.SPMessage.OP_KEY_UPDATE], ['sig'])) {
watchMap[cID] = null;
return;
}
watchMap[cID] = [];
}
watchMap[cID].push(name);
});
Object.entries(watchMap).forEach(([cID, names]) => {
if (!Array.isArray(names) || !names.length)
return;
const [keyNamesToUpdate, signingKeyId] = names
.map((name) => {
const foreignContractKey = rootState[cID]?._vm?.authorizedKeys?.[updatedKeysMap[name].oldKeyId];
if (!foreignContractKey)
return undefined;
const signingKeyId = (0, utils_js_1.findSuitableSecretKeyId)(rootState[cID], requiredPermissions, ['sig'], foreignContractKey.ringLevel);
if (signingKeyId) {
return [
[name, foreignContractKey.name],
signingKeyId,
rootState[cID]._vm.authorizedKeys[signingKeyId].ringLevel
];
}
return undefined;
})
.filter(Boolean)
.reduce((acc, [name, signingKeyId, ringLevel]) => {
acc[0].push(name);
return ringLevel < acc[2] ? [acc[0], signingKeyId, ringLevel] : acc;
}, [[], undefined, Number.POSITIVE_INFINITY]);
if (!signingKeyId)
return;
// Send output based on keyNamesToUpdate, signingKeyId
const contractName = rootState.contracts[cID]?.type;
internalSideEffectStack?.push(() => {
// We can't await because it'll block on a different contract, which
// is possibly waiting on this current contract.
(0, sbp_1.default)(outputSelector, {
contractID: cID,
contractName,
data: keyNamesToUpdate.map(outputMapper).map((v) => {
return v;
}),
signingKeyId
}).catch((e) => {
console.warn(`Error mirroring key operation (${outputSelector}) from ${contractID} to ${cID}: ${e?.message || e}`);
});
});
});
};
// export const FERAL_FUNCTION = Function
exports.default = (0, sbp_1.default)('sbp/selectors/register', {
// DO NOT CALL ANY OF THESE YOURSELF!
'chelonia/private/state': function () {
return this.state;
},
'chelonia/private/invoke': function (instance, invocation) {
// If this._instance !== instance (i.e., chelonia/reset was called)
if (this._instance !== instance) {
console.info("['chelonia/private/invoke] Not proceeding with invocation as Chelonia was restarted", { invocation });
return;
}
if (Array.isArray(invocation)) {
return (0, sbp_1.default)(...invocation);
}
else if (typeof invocation === 'function') {
return invocation();
}
else {
throw new TypeError(`[chelonia/private/invoke] Expected invocation to be an array or a function. Saw ${typeof invocation} instead.`);
}
},
'chelonia/private/queueEvent': function (queueName, invocation) {
return (0, sbp_1.default)('okTurtles.eventQueue/queueEvent', queueName, [
'chelonia/private/invoke',
this._instance,
invocation
]);
},
'chelonia/private/verifyManifestSignature': function (contractName, manifestHash, manifest) {
// We check that the manifest contains a 'signature' field with the correct
// shape
if (!(0, turtledash_1.has)(manifest, 'signature') ||
typeof manifest.signature.keyId !== 'string' ||
typeof manifest.signature.value !== 'string') {
throw new Error(`Invalid or missing signature field for manifest ${manifestHash} (named ${contractName})`);
}
// Now, start the signature verification process
const rootState = (0, sbp_1.default)(this.config.stateSelector);
if (!(0, turtledash_1.has)(rootState, 'contractSigningKeys')) {
this.config.reactiveSet(rootState, 'contractSigningKeys', Object.create(null));
}
// Because `contractName` comes from potentially unsafe sources (for
// instance, from `processMessage`), the key isn't used directly because
// it could overlap with current or future 'special' key names in JavaScript,
// such as `prototype`, `__proto__`, etc. We also can't guarantee that the
// `contractSigningKeys` always has a null prototype, and, because of the
// way we manage state, neither can we use `Map`. So, we use prefix for the
// lookup key that's unlikely to ever be part of a special JS name.
const contractNameLookupKey = `name:${contractName}`;
// If the contract name has been seen before, validate its signature now
let signatureValidated = false;
if (process.env.UNSAFE_TRUST_ALL_MANIFEST_SIGNING_KEYS !== 'true' &&
(0, turtledash_1.has)(rootState.contractSigningKeys, contractNameLookupKey)) {
console.info(`[chelonia] verifying signature for ${manifestHash} with an existing key`);
if (!(0, turtledash_1.has)(rootState.contractSigningKeys[contractNameLookupKey], manifest.signature.keyId)) {
console.error(`The manifest with ${manifestHash} (named ${contractName}) claims to be signed with a key with ID ${manifest.signature.keyId}, which is not trusted. The trusted key IDs for this name are:`, Object.keys(rootState.contractSigningKeys[contractNameLookupKey]));
throw new Error(`Invalid or missing signature in manifest ${manifestHash} (named ${contractName}). It claims to be signed with a key with ID ${manifest.signature.keyId}, which has not been authorized for this contract before.`);
}
const signingKey = rootState.contractSigningKeys[contractNameLookupKey][manifest.signature.keyId];
(0, crypto_1.verifySignature)(signingKey, manifest.body + manifest.head, manifest.signature.value);
console.info(`[chelonia] successful signature verification for ${manifestHash} (named ${contractName}) using the already-trusted key ${manifest.signature.keyId}.`);
signatureValidated = true;
}
// Otherwise, when this is a yet-unseen contract, we parse the body to
// see its allowed signers to trust on first-use (TOFU)
const body = JSON.parse(manifest.body);
// If we don't have a list of authorized signatures yet, verify this
// contract's signature and set the auhorized signing keys
if (!signatureValidated) {
console.info(`[chelonia] verifying signature for ${manifestHash} (named ${contractName}) for the first time`);
if (!(0, turtledash_1.has)(body, 'signingKeys') || !Array.isArray(body.signingKeys)) {
throw new Error(`Invalid manifest file ${manifestHash} (named ${contractName}). Its body doesn't contain a 'signingKeys' list'`);
}
let contractSigningKeys;
try {
contractSigningKeys = Object.fromEntries(body.signingKeys.map((serializedKey) => {
return [(0, crypto_1.keyId)(serializedKey), serializedKey];
}));
}
catch (e) {
console.error(`[chelonia] Error parsing the public keys list for ${manifestHash} (named ${contractName})`, e);
throw e;
}
if (!(0, turtledash_1.has)(contractSigningKeys, manifest.signature.keyId)) {
throw new Error(`Invalid or missing signature in manifest ${manifestHash} (named ${contractName}). It claims to be signed with a key with ID ${manifest.signature.keyId}, which is not listed in its 'signingKeys' field.`);
}
(0, crypto_1.verifySignature)(contractSigningKeys[manifest.signature.keyId], manifest.body + manifest.head, manifest.signature.value);
console.info(`[chelonia] successful signature verification for ${manifestHash} (named ${contractName}) using ${manifest.signature.keyId}. The following key IDs will now be trusted for this contract name`, Object.keys(contractSigningKeys));
signatureValidated = true;
rootState.contractSigningKeys[contractNameLookupKey] = contractSigningKeys;
}
// If verification was successful, return the parsed body to make the newly-
// loaded contract available
return body;
},
'chelonia/private/loadManifest': async function (contractName, manifestHash) {
if (!contractName || typeof contractName !== 'string') {
throw new Error('Invalid or missing contract name');
}
if (this.manifestToContract[manifestHash]) {
console.warn('[chelonia]: already loaded manifest', manifestHash);
return;
}
const manifestSource = await (0, sbp_1.default)('chelonia/out/fetchResource', manifestHash, {
code: functions_js_1.multicodes.SHELTER_CONTRACT_MANIFEST
});
const manifest = JSON.parse(manifestSource);
const body = (0, sbp_1.default)('chelonia/private/verifyManifestSignature', contractName, manifestHash, manifest);
if (body.name !== contractName) {
throw new Error(`Mismatched contract name. Expected ${contractName} but got ${body.name}`);
}
const contractInfo = (this.config.contracts.defaults.preferSlim && body.contractSlim) || body.contract;
console.info(`[chelonia] loading contract '${contractInfo.file}'@'${body.version}' from manifest: ${manifestHash}`);
const source = await (0, sbp_1.default)('chelonia/out/fetchResource', contractInfo.hash, {
code: functions_js_1.multicodes.SHELTER_CONTRACT_TEXT
});
const reduceAllow = (acc, v) => {
acc[v] = true;
return acc;
};
const allowedSels = [
'okTurtles.events/on',
'chelonia/defineContract',
'chelonia/out/keyRequest'
]
.concat(this.config.contracts.defaults.allowedSelectors)
.reduce(reduceAllow, {});
const allowedDoms = this.config.contracts.defaults.allowedDomains.reduce(reduceAllow, {});
const contractSBP = (selector, ...args) => {
const domain = (0, sbp_1.domainFromSelector)(selector);
if (selector.startsWith(contractName + '/')) {
selector = `${manifestHash}/${selector}`;
}
if (allowedSels[selector] || allowedDoms[domain]) {
return (0, sbp_1.default)(selector, ...args);
}
else {
console.error('[chelonia] selector not on allowlist', {
selector,
allowedSels,
allowedDoms
});
throw new Error(`[chelonia] selector not on allowlist: '${selector}'`);
}
};
// const saferEval: Function = new FERAL_FUNCTION(`
// eslint-disable-next-line no-new-func
const saferEval = new Function(`
return function (globals) {
// almost a real sandbox
// stops (() => this)().fetch
// needs additional step of locking down Function constructor to stop:
// new (()=>{}).constructor("console.log(typeof this.fetch)")()
globals.self = globals
globals.globalThis = globals
with (new Proxy(globals, {
get (o, p) { return o[p] },
has (o, p) { /* console.log('has', p); */ return true }
})) {
(function () {
'use strict'
${source}
})()
}
}
`)();
// TODO: lock down Function constructor! could just use SES lockdown()
// or do our own version of it.
// https://github.com/endojs/endo/blob/master/packages/ses/src/tame-function-constructors.js
this.defContractSBP = contractSBP;
this.defContractManifest = manifestHash;
// contracts will also be signed, so even if sandbox breaks we still have protection
saferEval({
// pass in globals that we want access to by default in the sandbox
// note: you can undefine these by setting them to undefined in exposedGlobals
crypto: {
getRandomValues: (v) => globalThis.crypto.getRandomValues(v)
},
...(typeof window === 'object' &&
window && {
alert: window.alert.bind(window),
confirm: window.confirm.bind(window),
prompt: window.prompt.bind(window)
}),
isNaN,
console,
Object,
Error,
TypeError,
RangeError,
Math,
Symbol,
Date,
Array,
BigInt,
Boolean,
String,
Number,
Int8Array,
Int16Array,
Int32Array,
Uint8Array,
Uint16Array,
Uint32Array,
Float32Array,
Float64Array,
ArrayBuffer,
JSON,
RegExp,
parseFloat,
parseInt,
Promise,
Function,
Map,
WeakMap,
...this.config.contracts.defaults.exposedGlobals,
require: (dep) => {
return dep === '@sbp/sbp' ? contractSBP : this.config.contracts.defaults.modules[dep];
},
sbp: contractSBP,
fetchServerTime: async (fallback = true) => {
// If contracts need the current timestamp (for example, for metadata 'createdDate')
// they must call this function so that clients are kept synchronized to the server's
// clock, for consistency, so that if one client's clock is off, it doesn't conflict
// with other client's clocks.
// See: https://github.com/okTurtles/group-income/issues/531
try {
const response = await this.config.fetch(`${this.config.connectionURL}/time`, {
signal: this.abortController.signal
});
return (0, utils_js_1.handleFetchResult)('text')(response);
}
catch (e) {
console.warn('[fetchServerTime] Error', e);
if (fallback) {
return new Date((0, sbp_1.default)('chelonia/time')).toISOString();
}
throw new errors_js_1.ChelErrorFetchServerTimeFailed('Can not fetch server time. Please check your internet connection.');
}
}
});
if (contractName !== this.defContract.name) {
throw new Error(`Invalid contract name for manifest ${manifestHash}. Expected ${contractName} but got ${this.defContract.name}`);
}
this.defContractSelectors.forEach((s) => {
allowedSels[s] = true;
});
this.manifestToContract[manifestHash] = {
slim: contractInfo === body.contractSlim,
info: contractInfo,
contract: this.defContract
};
},
// Warning: avoid using this unless you know what you're doing. Prefer using /remove.
'chelonia/private/removeImmediately': function (contractID, params) {
const state = (0, sbp_1.default)(this.config.stateSelector);
const contractName = state.contracts[contractID]?.type;
if (!contractName) {
console.error('[chelonia/private/removeImmediately] Missing contract name for contract', {
contractID
});
return;
}
const manifestHash = this.config.contracts.manifests[contractName];
if (manifestHash) {
const destructor = `${manifestHash}/${contractName}/_cleanup`;
// Check if a destructor is defined
if ((0, sbp_1.default)('sbp/selectors/fn', destructor)) {
// And call it
try {
(0, sbp_1.default)(destructor, { contractID, resync: !!params?.resync, state: state[contractID] });
}
catch (e) {
console.error(`[chelonia/private/removeImmediately] Error at destructor for ${contractID}`, e);
}
}
}
if (params?.resync) {
// If re-syncing, keep the reference count
Object.keys(state.contracts[contractID])
.filter((k) => k !== 'references')
.forEach((k) => this.config.reactiveDel(state.contracts[contractID], k));
// If re-syncing, keep state._volatile.watch
Object.keys(state[contractID])
.filter((k) => k !== '_volatile')
.forEach((k) => this.config.reactiveDel(state[contractID], k));
if (state[contractID]._volatile) {
Object.keys(state[contractID]._volatile)
.filter((k) => k !== 'watch')
.forEach((k) => this.config.reactiveDel(state[contractID]._volatile, k));
}
}
else {
delete this.ephemeralReferenceCount[contractID];
if (params?.permanent) {
// Keep a 'null' state to remember permanently-deleted contracts
// (e.g., when they've been removed from the server)
this.config.reactiveSet(state.contracts, contractID, null);
}
else {
this.config.reactiveDel(state.contracts, contractID);
}
this.config.reactiveDel(state, contractID);
}
this.subscriptionSet.delete(contractID);
// calling this will make pubsub unsubscribe for events on `contractID`
(0, sbp_1.default)('okTurtles.events/emit', events_js_1.CONTRACTS_MODIFIED, Array.from(this.subscriptionSet), {
added: [],
removed: [contractID],
permanent: params?.permanent,
resync: params?.resync
});
},
// used by, e.g. 'chelonia/contract/wait'
'chelonia/private/noop': function () { },
'chelonia/private/out/sync': function (contractIDs, params) {
const listOfIds = typeof contractIDs === 'string' ? [contractIDs] : contractIDs;
const forcedSync = !!params?.force;
return Promise.all(listOfIds.map((contractID) => {
// If this isn't a forced sync and we're already subscribed to the contract,
// only wait on the event queue (as events should come over the subscription)
if (!forcedSync && this.subscriptionSet.has(contractID)) {
const rootState = (0, sbp_1.default)(this.config.stateSelector);
// However, if the contract has been marked as dirty (meaning its state
// could be wrong due to newly received encryption keys), sync it anyhow
// (i.e., disregard the force flag and proceed to sync the contract)
if (!rootState[contractID]?._volatile?.dirty) {
return (0, sbp_1.default)('chelonia/private/queueEvent', contractID, ['chelonia/private/noop']);
}
}
// enqueue this invocation in a serial queue to ensure
// handleEvent does not get called on contractID while it's syncing,
// but after it's finished. This is used in tandem with
// queuing the 'chelonia/private/in/handleEvent' selector, defined below.
// This prevents handleEvent getting called with the wrong previousHEAD for an event.
return (0, sbp_1.default)('chelonia/private/queueEvent', contractID, [
'chelonia/private/in/syncContract',
contractID,
params
]).catch((err) => {
console.error(`[chelonia] failed to sync ${contractID}:`, err);
throw err; // re-throw the error
});
}));
},
'chelonia/private/out/publishEvent': function (entry, { maxAttempts = 5, headers, billableContractID, bearer, disableAutoDedup } = {}, hooks) {
const contractID = entry.contractID();
const originalEntry = entry;
return (0, sbp_1.default)('chelonia/private/queueEvent', `publish:${contractID}`, async () => {
let attempt = 1;
let lastAttemptedHeight;
// prepublish is asynchronous to allow for cleanly sending messages to
// different contracts
await hooks?.prepublish?.(entry);
const onreceivedHandler = (_contractID, message) => {
if (entry.hash() === message.hash()) {
(0, sbp_1.default)('okTurtles.events/off', events_js_1.EVENT_HANDLED, onreceivedHandler);
hooks.onprocessed(entry);
}
};
if (typeof hooks?.onprocessed === 'function') {
(0, sbp_1.default)('okTurtles.events/on', events_js_1.EVENT_HANDLED, onreceivedHandler);
}
// auto resend after short random delay
// https://github.com/okTurtles/group-income/issues/608
while (true) {
// Queued event to ensure that we send the event with whatever the
// 'latest' state may be for that contract (in case we were receiving
// something over the web socket)
// This also ensures that the state doesn't change while reading it
lastAttemptedHeight = entry.height();
const newEntry = await (0, sbp_1.default)('chelonia/private/queueEvent', contractID, async () => {
const rootState = (0, sbp_1.default)(this.config.stateSelector);
const state = rootState[contractID];
const isFirstMessage = entry.isFirstMessage();
if (!state && !isFirstMessage) {
console.info(`[chelonia] Not sending message as contract state has been removed: ${entry.description()}`);
return;
}
if (hooks?.preSendCheck) {
if (!(await hooks.preSendCheck(entry, state))) {
console.info(`[chelonia] Not sending message as preSendCheck hook returned non-truish value: ${entry.description()}`);
return;
}
}
// Process message to ensure that it is valid. Should this throw,
// we propagate the error. Calling `processMessage` will perform
// validation by checking signatures, well-formedness and, in the case
// of actions, by also calling both the `validate` method (which
// doesn't mutate the state) and the `process` method (which could
// mutate the state).
// `SPMessage` objects have an implicit `direction` field that's set
// based on how the object was constructed. For messages that will be
// sent to the server (this case), `direction` is set to `outgoing`.
// This `direction` affects how certain errors are reported during
// processing, and is also exposed to contracts (which could then
// alter their behavior based on this) to support some features (such
// as showing users that a certain message is 'pending').
// Validation ensures that we don't write messages known to be invalid.
// Although those invalid messages will be ignored if sent anyhow,
// sending them is wasteful.
// The only way to know for sure if a message is valid or not is using
// the same logic that would be used if the message was received,
// hence the call to `processMessage`. Validation requires having the
// state and all mutations that would be applied. For example, when
// joining a chatroom, this is usually done by sending an OP_ATOMIC
// that contains OP_KEY_ADD and OP_ACTION_ENCRYPTED. Correctly
// validating this operation requires applying the OP_KEY_ADD to the
// state in order to know whether OP_ACTION_ENCRYPTED has a valid
// signature or not.
// We also rely on this logic to keep different contracts in sync
// when there are side-effects. For example, the side-effect in a
// group for someone joining a chatroom can call the `join` action
// on the chatroom unconditionally, since validation will prevent
// the message from being sent.
// Because of this, 'chelonia/private/in/processMessage' SHOULD NOT
// change the global Chelonia state and it MUST NOT call any
// side-effects or change the global state in a way that affects
// the meaning of any future messages or successive invocations.
// Note: mutations to the contract state, if any, are immediately
// discarded (see the temporary object created using `cloneDeep`).
await (0, sbp_1.default)('chelonia/private/in/processMessage', entry, (0, turtledash_1.cloneDeep)(state || {}));
// if this isn't the first event (i.e., OP_CONTRACT), recreate and
// resend message
// This is mainly to set height and previousHEAD. For the first event,
// this doesn't need to be done because previousHEAD is always undefined
// and height is always 0.
// We always call recreateEvent because we may have received new events
// in the web socket
if (!isFirstMessage) {
return (0, utils_js_1.recreateEvent)(entry, state, rootState.contracts[contractID], disableAutoDedup);
}
return entry;
});
// If there is no event to send, return
if (!newEntry)
return;
await hooks?.beforeRequest?.(newEntry, entry);
entry = newEntry;
const r = await this.config.fetch(`${this.config.connectionURL}/event`, {
method: 'POST',
body: entry.serialize(),
headers: {
...headers,
...(bearer && {
Authorization: `Bearer ${bearer}`
}),
...(billableContractID && {
Authorization: utils_js_1.buildShelterAuthorizationHeader.call(this, billableContractID)
}),
'Content-Type': 'text/plain'
},
signal: this.abortController.signal
});
if (r.ok) {
await hooks?.postpublish?.(entry);
return entry;
}
try {
if (r.status === 409) {
if (attempt + 1 > maxAttempts) {
console.error(`[chelonia] failed to publish ${entry.description()} after ${attempt} attempts`, entry);
throw new Error(`publishEvent: ${r.status} - ${r.statusText}. attempt ${attempt}`);
}
// create new entry
const randDelay = (0, turtledash_1.randomIntFromRange)(0, 1500);
console.warn(`[chelonia] publish attempt ${attempt} of ${maxAttempts} failed. Waiting ${randDelay} msec before resending ${entry.description()}`);
attempt += 1;
await (0, turtledash_1.delay)(randDelay); // wait randDelay ms before sending it again
// TODO: The [pubsub] code seems to miss events that happened between
// a call to sync and the subscription time. This is a temporary measure
// to handle this until [pubsub] is updated.
if (!entry.isFirstMessage() && entry.height() === lastAttemptedHeight) {
await (0, sbp_1.default)('chelonia/private/out/sync', contractID, { force: true });
}
}
else {
const message = (await r.json())?.message;
console.error(`[chelonia] ERROR: failed to publish ${entry.description()}: ${r.status} - ${r.statusText}: ${message}`, entry);
throw new Error(`publishEvent: ${r.status} - ${r.statusText}: ${message}`);
}
}
catch (e) {
(0, sbp_1.default)('okTurtles.events/off', events_js_1.EVENT_HANDLED, onreceivedHandler);
throw e;
}
}
})
.then((entry) => {
(0, sbp_1.default)('okTurtles.events/emit', events_js_1.EVENT_PUBLISHED, {
contractID,
message: entry,
originalMessage: originalEntry
});
return entry;
})
.catch((e) => {
(0, sbp_1.default)('okTurtles.events/emit', events_js_1.EVENT_PUBLISHING_ERROR, {
contractID,
message: entry,
originalMessage: originalEntry,
error: e
});
throw e;
});
},
'chelonia/private/out/latestHEADinfo': function (contractID) {
return this.config
.fetch(`${this.config.connectionURL}/latestHEADinfo/${contractID}`, {
cache: 'no-store',
signal: this.abortController.signal
})
.then((0, utils_js_1.handleFetchResult)('json'));
},
'chelonia/private/postKeyShare': function (contractID, previousVolatileState, signingKey) {
const cheloniaState = (0, sbp_1.default)(this.config.stateSelector);
const targetState = cheloniaState[contractID];
if (!targetState)
return;
if (previousVolatileState && (0, turtledash_1.has)(previousVolatileState, 'watch')) {
if (!targetState._volatile) {
this.config.reactiveSet(targetState, '_volatile', Object.create(null));
}
if (!targetState._volatile.watch) {
this.config.reactiveSet(targetState._volatile, 'watch', previousVolatileState.watch);
}
else if (targetState._volatile.watch !== previousVolatileState.watch) {
previousVolatileState.watch.forEach((pWatch) => {
if (!targetState._volatile.watch.some((tWatch) => {
return tWatch[0] === pWatch[0] && tWatch[1] === pWatch[1];
})) {
targetState._volatile.watch.push(pWatch);
}
});
}
}
if (!Array.isArray(targetState._volatile?.pendingKeyRequests))
return;
this.config.reactiveSet(targetState._volatile, 'pendingKeyRequests', targetState._volatile.pendingKeyRequests.filter((pkr) => pkr?.name !== signingKey.name));
},
'chelonia/private/operationHook': function (contractID, message, state) {
if (this.config.skipActionProcessing)
return;
const rootState = (0, sbp_1.default)('chelonia/rootState');
const contractName = rootState.contracts[contractID]?.type || state._vm?.type;
if (!contractName)
return;
const manifestHash = message.manifest();
const hook = `${manifestHash}/${contractName}/hook/${message.opType()}`;
// Check if a hook is defined
if ((0, sbp_1.default)('sbp/selectors/fn', hook)) {
// And call it
try {
// Note: Errors here should not stop processing, since running these
// hooks is optionl (for example, they aren't run on the server)
(0, sbp_1.default)(hook, { contractID, message, state });
}
catch (e) {
console.error(`[${hook}] hook error for message ${message.hash()} on contract ${contractID}:`, e);
}
}
},
'chelonia/private/in/processMessage': async function (message, state, internalSideEffectStack, contractName) {
const [opT, opV] = message.op();
const hash = message.hash();
const height = message.height();
const contractID = message.contractID();
const manifestHash = message.manifest();
const signingKeyId = message.signingKeyId();
const direction = message.direction();
const config = this.config;
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
const opName = Object.entries(SPMessage_js_1.SPMessage).find(([, y]) => y === opT)?.[0];
console.debug('PROCESSING OPCODE:', opName, 'to', contractID);
if (state?._volatile?.dirty) {
console.debug('IGNORING OPCODE BECAUSE CONTRACT STATE IS MARKED AS DIRTY.', 'OPCODE:', opName, 'CONTRACT:', contractID);
return;
}
if (!state._vm)
state._vm = Object.create(null);
const opFns = {
/*
There are two types of "errors" that we need to consider:
1. "Ignoring" errors
2. "Failure" errors
Example: OP_KEY_ADD
1. IGNORING: an error is thrown because we wanted to add a key but the
key we wanted to add is already there. This is not a hard error, it's an
ignoring error. We don't care that the operation failed in this case because the intent was accomplished.
2. FAILURE: an error is thrown while attempting to add a key that doesn't exist.
Example: OP_ACTION_ENCRYPTED
1. IGNORING: An error is thrown because we don't have the key to decrypt the action. We ignore it.
2. FAILURE: An error is thrown by the process function during processing.
Handling these in OP_ATOMIC
• ALL errors of class "IGNORING" should be ignored. They should not
impact our ability to process the rest of the operations in the OP_ATOMIC.
No matter how many of these are thrown, it doesn't affect the rest of the operations.
• ANY error of class "FAILURE" will call the rest of the operations to
fail and the state to be reverted to prior to the OP_ATOMIC. No side-effects should be run. Because an intention failed.
*/
async [SPMessage_js_1.SPMessage.OP_ATOMIC](v) {
for (let i = 0; i < v.length; i++) {
const u = v[i];
try {
if (u[0] === SPMessage_js_1.SPMessage.OP_ATOMIC)
throw new Error('Cannot nest OP_ATOMIC');
if (!(0, utils_js_1.validateKeyPermissions)(message, config, state, signingKeyId, u[0], u[1])) {
throw new Error('Inside OP_ATOMIC: no matching signing key was defined');
}
await opFns[u[0]](u[1]);
}
catch (e_) {
const e = e_;
if (e && typeof e === 'object') {
if (e.name === 'ChelErrorDecryptionKeyNotFound') {
console.warn(`[chelonia] [OP_ATOMIC] WARN '${e.name}' in processMessage for ${message.description()}: ${e.message}`, e, message.serialize());
if (e.cause) {
const missingDecryptionKeyIds = missingDecryptionKeyIdsMap.get(message);
if (missingDecryptionKeyIds) {
missingDecryptionKeyIds.add(e.cause);
}
else {
missingDecryptionKeyIdsMap.set(message, new Set([e.cause]));
}
}
continue;
}
else {
(0, utils_js_1.logEvtError)(message, `[chelonia] [OP_ATOMIC] ERROR '${e.name}' in processMessage for ${message.description()}: ${e.message || e}`, e, message.serialize());
}
console.warn(`[chelonia] [OP_ATOMIC] Error processing ${message.description()}: ${message.serialize()}. Any side effects will be skipped!`);
if (config.strictProcessing) {
throw e;
}
config.hooks.processError?.(e, message, getMsgMeta.call(self, message, contractID, state));
if (e.name === 'ChelErrorWarning')
continue;
}
else {
(0, utils_js_1.logEvtError)(message, 'Inside OP_ATOMIC: Non-object or null error thrown', contractID, message, i, e);
}
throw e;
}
}
},
[SPMessage_js_1.SPMessage.OP_CONTRACT](v) {
state._vm.type = v.type;
const keys = keysToMap.call(self, v.keys, height, signingKeyId);
state._vm.authorizedKeys = keys;
// Loop through the keys in the contract and try to decrypt all of the private keys
// Example: in the identity contract you have the IEK, IPK, CSK, and CEK.
// When you login you have the IEK which is derived from your password, and you
// will use it to decrypt the rest of the keys which are encrypted with that.
// Specifically, the IEK is used to decrypt the CSKs and the CEKs, which are
// the encrypted versions of the CSK and CEK.
utils_js_1.keyAdditionProcessor.call(self, message, hash, v.keys, state, contractID, signingKey, internalSideEffectStack);
},
[SPMessage_js_1.SPMessage.OP_ACTION_ENCRYPTED](v) {
if (config.skipActionProcessing) {
if (!config.skipDecryptionAttempts) {
console.log('OP_ACTION_ENCRYPTED: skipped action processing');
}
return;
}
return opFns[SPMessage_js_1.SPMessage.OP_ACTION_UNENCRYPTED](v.valueOf());
},
async [SPMessage_js_1.SPMessage.OP_ACTION_UNENCRYPTED](v) {
if (!config.skipActionProcessing) {
let innerSigningKeyId;
if ((0, signedData_js_1.isSignedData)(v)) {
innerSigningKeyId = v.signingKeyId;
v = v.valueOf();
}
const { data, meta, action } = v;
if (!config.whitelisted(action)) {
throw new Error(`chelonia: action not whitelisted: '${action}'`);
}
await (0, sbp_1.default)(`${manifestHash}/${action}/process`, {
data,
meta,
hash,
height,
contractID,
direction: message.direction(),
signingKeyId,
get signingContractID() {
return (0, utils_js_1.getContractIDfromKeyId)(contractID, signingKeyId, state);
},
innerSigningKeyId,
get innerSigningContractID() {
return (0, utils_js_1.getContractIDfromKeyId)(contractID, innerSigningKeyId, state);
}
}, state);
}
},
[SPMessage_js_1.SPMessage.OP_KEY_SHARE](wv) {
// TODO: Prompt to user if contract not in pending
const data = config.unwrapMaybeEncryptedData(wv);
if (!data)
return;
const v = data.data;
for (const key of v.keys) {
if (key.id && key.meta?.private?.content) {
if (!(0, turtledash_1.has)(state._vm, 'sharedKeyIds'))
state._vm.sharedKeyIds = [];
if (!state._vm.sharedKeyIds.some((sK) => sK.id === key.id)) {
state._vm.sharedKeyIds.push({
id: key.id,
contractID: v.contractID,
height,
keyRequestHash: v.keyRequestHash,
keyRequestHeight: v.keyRequestHeight
});
}
}
}
// If this is a response to an OP_KEY_REQUEST (marked by the
// presence of the keyRequestHash attribute), then we'll mark the
// key request as completed
// TODO: Verify that the keyRequestHash is what we expect (on the
// other contact's state, we should have a matching structure in
// state._volatile.pendingKeyRequests = [
// { contractID: "this", name: "name of this signingKeyId", reference: "this reference", hash: "KA" }, ..., but we don't
// have a copy of the keyRequestHash (this would need a new
// message to ourselves in the KR process), so for now we trust
// that if it has keyRequestHash, it's a response to a request
// we sent.
// For similar reasons, we can't check pendingKeyRequests, because
// depending on how and in which order events are processed, it may
// not be available.
// ]
if ((0, turtledash_1.has)(v, 'keyRequestHash') && state._vm.authorizedKeys[signingKeyId].meta?.keyRequest) {
state._vm.authorizedKeys[signingKeyId].meta.keyRequest.responded = hash;
}
internalSideEffectStack?.push(async () => {
delete self.postSyncOperations[contractID]?.['pending-keys-for-' + v.contractID];
const cheloniaState = (0, sbp_1.default)(self.config.stateSelector);
const targetState = cheloniaState[v.contractID];
const missingDecryptionKeyIds = cheloniaState.contracts[v.contractID]?.missingDecryptionKeyIds;
let newestEncryptionKeyHeight = Number.POSITIVE_INFINITY;
for (const key of v.keys) {
if (key.id && key.meta?.private?.content) {
// Outgoing messages' keys are always transient
const transient = direction === 'outgoing' || key.meta.private.transient;
if (!(0, sbp_1.default)('chelonia/haveSecretKey', key.id, !transient)) {
try {
const decrypted = key.meta.private.content.valueOf();
(0, sbp_1.default)('chelonia/storeSecretKeys', new Secret_js_1.Secret([
{
key: (0, crypto_1.deserializeKey)(decrypted),
transient
}
]));
// If we've just received a known missing key (i.e., a key
// that previously resulted in a decryption error), we know
// our state is outdated and we need to re-sync the contract
if (missingDecryptionKeyIds?.includes(key.id)) {
newestEncryptionKeyHeight = Number.NEGATIVE_INFINITY;
}
else if (
// Otherwise, we make an educated guess on whether a re-sync
// is needed based on the height.
targetState?._vm?.authorizedKeys?.[key.id]?._notBeforeHeight != null &&
Array.isArray(targetState._vm.authorizedKeys[key.id].purpose) &&
targetState._vm.authorizedKeys[key.id].purpose.includes('enc')) {
newestEncryptionKeyHeight = Math.min(newestEncryptionKeyHeight, targetState._vm.authorizedKeys[key.id]._notBeforeHeight);
}
}
catch (e_) {
const e = e_;
if (e?.name === 'ChelErrorDecryptionKeyNotFound') {
console.warn(`OP_KEY_SHARE (${hash} of ${contractID}) missing secret key: ${e.message}`, e);
}
else {
// Using console.error instead of logEvtError because this
// is a side-effect and not relevant for outgoing messages
console.error(`OP_KEY_SHARE (${hash} of ${contractID}) error '${e.message || e}':`, e);
}
}
}
}
}
// If an encryption key has been shared with _notBefore lower than the
// current height, then the contract must be resynced.
const mustResync = !!(newestEncryptionKeyHeight < cheloniaState.contracts[v.contractID]?.height);
if (mustResync) {
if (!(0, turtledash_1.has)(targetState, '_volatile')) {
config.reactiveSet(targetState, '_volatile', Object.create(null));
}
config.reactiveSet(targetState._volatile, 'dirty', true);
if (!Object.keys(targetState).some((k) => k !== '_volatile')) {
// If the contract only has _volatile state, we don't force sync it
return;
}
// Mark contracts that have foreign keys that have been received
// as dirty
// First, we group watched keys by key and contracts
const keyDict = Object.create(null);
targetState._volatile?.watch?.forEach(([keyName, contractID]) => {
if (!keyDict[keyName]) {
keyDict[keyName] = [contractID];
return;
}
keyDict[keyName].push(contractID);
});
// Then, see which of those contracts need to be updated
const contractIdsToUpdate = Array.from(new Set(Object.entries(keyDict).flatMap(([keyName, contractIDs]) => {
const keyId = (0, utils_js_1.findKeyIdByName)(targetState, keyName);
if (
// Does the key exist? (i.e., is it a current key)
keyId &&
// Is it an encryption key? (signing keys don't build up a
// potentially invalid state because the private key isn't
// required for validation; however, missing encryption keys
// prevent message processing)
targetState._vm.authorizedKeys[keyId].purpose.includes('enc') &&
// Is this a newly set key? (avoid re-syncing contracts that
// haven't been affected by the `OP_KEY_SHARE`)