/
createSyncMachine.ts
1664 lines (1557 loc) · 63.1 KB
/
createSyncMachine.ts
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 type { KeyPair } from "libsodium-wrappers";
import {
AnyActorRef,
assertEvent,
assign,
forwardTo,
fromCallback,
fromPromise,
sendTo,
setup,
stopChild,
} from "xstate";
import { generateId } from "./crypto/generateId";
import { hash } from "./crypto/hash";
import { messageTypes } from "./ephemeralMessage/createEphemeralMessage";
import { createEphemeralSession } from "./ephemeralMessage/createEphemeralSession";
import { parseEphemeralMessage } from "./ephemeralMessage/parseEphemeralMessage";
import { verifyAndDecryptEphemeralMessage } from "./ephemeralMessage/verifyAndDecryptEphemeralMessage";
import { createInitialSnapshot } from "./snapshot/createInitialSnapshot";
import { createSnapshot } from "./snapshot/createSnapshot";
import { isValidAncestorSnapshot } from "./snapshot/isValidAncestorSnapshot";
import { parseSnapshot } from "./snapshot/parseSnapshot";
import { verifyAndDecryptSnapshot } from "./snapshot/verifyAndDecryptSnapshot";
import {
EphemeralMessage,
EphemeralMessagesSession,
OnDocumentUpdatedEventType,
Snapshot,
SnapshotInfoWithUpdateClocks,
SnapshotProofChainEntry,
SnapshotProofInfo,
SnapshotPublicData,
SyncMachineConfig,
Update,
} from "./types";
import { createUpdate } from "./update/createUpdate";
import { parseUpdate } from "./update/parseUpdate";
import { verifyAndDecryptUpdate } from "./update/verifyAndDecryptUpdate";
import { updateUpdateClocksEntry } from "./utils/updateUpdateClocksEntry";
import { websocketService } from "./utils/websocketService";
// The sync machine is responsible for syncing the document with the server.
// Specifically it is responsible for:
// - sending snapshots
// - sending updates
// - sending ephemeral messages
// - receiving snapshots
// - receiving updates
// - receiving ephemeral messages
//
// In general the first thing that happens is that a websocket connection is established.
// Once that's done the latest snapshot including it's related updates should be received.
//
// In order to process incoming and outgoing changes the sync machine uses three queues:
// - _incomingQueue: contains all incoming messages from the server
// - _customMessageQueue: contains all custom incoming messages from the server
// - _pendingChangesQueue: contains all outgoing messages that are not yet sent to the server
//
// How Queue processing works
// -------------------------
// 1. first handle all incoming custom messages
// 2. first handle all incoming message
// 3. then handle all pending updates
// Background: There might be a new snapshot and this way we avoid retries
//
// WebSockets reconnection logic:
// During the state connecting the sync machine will try to reconnect to the server.
// If no connection can be established after 5 seconds it will trigger a retry after a delay.
// The delay is based on the number of retries that have already been done using an exponential
// formula: (100 * 1.8 ** websocketRetries).
// The websocketRetries is capped at 13 so that the delay doesn't get too large.
//
// Handling outgoing messages
// -------------------------
// Once a change is added and the `_pendingChangesQueue` is processed it will collect all changes
// and depending on `shouldSendSnapshot` either send a snapshot or an update.
// In case a snapshot is sent `_pendingChangesQueue` is cleared and the `_snapshotInFlight` set to the snapshot ID.
// In case an update is sent the changes will be added to the `_updatesInFlight` and the `_updatesLocalClock` increased by one.
//
// If a snapshot saved event is received
// - it is added to the `_snapshotInfosWithUpdateClocks`
// - the `_snapshotInFlight` is cleared.
// Queue processing for sending messages is resumed.
//
// If an update saved event is received
// - the `updateClocks` in the related snapshot are updated for the current client
// - the update removed from the `_updatesInFlight` removed
//
// IF a snapshot failed to save
// - the snapshot and changes that came with the response are applied and another snapshot is created and sent. If there is a new snapshot and it has been received in the meantime
// the snapshot is ignored. If there are new updates and they already have been applied they
// are ignored as well.
//
// If an update failed to save
// - check if the update is in the `_updatesInFlight` - only if it's there a retry is necessary
// since we know it was not handled by a new snapshot or update
// - set the `_updatesLocalClock` to the `updateClocks` the active snapshot for the current client
// - all the changes from this failed and later updates plus the new pendingChanges are taken and a new update is created and
// sent with the clock set to the latest confirmed clock + 1
//
// When loading the initial document it's important to make sure these variables are correctly set:
// - `_updatesLocalClock` (same as `updateClocks` for the current Client in the latest snapshot)
// - `_snapshotInfosWithUpdateClocks`
// Otherwise you might try to send an update that the server will reject.
type UpdateInFlight = {
snapshotId: string;
clock: number;
changes: any[];
};
type SnapshotInFlight = SnapshotInfoWithUpdateClocks & {
parentSnapshotId: string;
changes: any[];
};
export type DocumentDecryptionState =
| "pending"
| "failed"
| "partial"
| "complete";
type ProcessQueueData =
| {
handledQueue: "customMessage" | "incoming" | "pending";
snapshotInFlight: SnapshotInFlight | null;
snapshotInfosWithUpdateClocks: SnapshotInfoWithUpdateClocks[];
updatesLocalClock: number;
updatesInFlight: UpdateInFlight[];
pendingChangesToRemoveCount: number;
pendingChangesToPrepend: any[];
ephemeralMessageReceivingErrors: Error[];
documentDecryptionState: DocumentDecryptionState;
ephemeralMessagesSession: EphemeralMessagesSession | null;
snapshotSaveFailedCounter: number;
errorNotCausingDocumentToFail: Error | null;
}
| {
handledQueue: "none";
snapshotSaveFailedCounter: number;
errorNotCausingDocumentToFail: Error | null;
};
export type InternalContextReset = {
_incomingQueue: any[];
_customMessageQueue: any[];
_snapshotInFlight: SnapshotInFlight | null;
_updatesInFlight: UpdateInFlight[];
_updatesLocalClock: number;
_documentDecryptionState: DocumentDecryptionState;
_ephemeralMessagesSession: EphemeralMessagesSession | null;
_snapshotSaveFailedCounter: number;
};
export type Context = SyncMachineConfig &
InternalContextReset & {
_websocketRetries: number;
_websocketActor?: AnyActorRef;
_websocketShouldReconnect: boolean;
_pendingChangesQueue: any[];
_snapshotInfosWithUpdateClocks: SnapshotInfoWithUpdateClocks[];
_snapshotAndUpdateErrors: Error[];
_ephemeralMessageReceivingErrors: Error[];
_ephemeralMessageAuthoringErrors: Error[];
logging: SyncMachineConfig["logging"];
};
const disconnectionContextReset: InternalContextReset = {
_incomingQueue: [],
_customMessageQueue: [],
_snapshotInFlight: null,
_updatesInFlight: [],
_updatesLocalClock: -1,
_documentDecryptionState: "pending",
_ephemeralMessagesSession: null,
_snapshotSaveFailedCounter: 0,
};
const scheduleRetry = fromCallback(
({
sendBack,
input,
}: {
input: { _websocketRetries: number; logging: SyncMachineConfig["logging"] };
sendBack: any;
}) => {
const delay = 100 * 1.8 ** input._websocketRetries;
if (input.logging === "debug") {
console.debug(
`schedule websocket connection #${input._websocketRetries} in `,
delay
);
}
setTimeout(() => {
sendBack({ type: "WEBSOCKET_RETRY" });
// calculating slow exponential back-off
}, delay);
}
);
const processQueues = fromPromise(
async ({
input,
}: {
input: { context: Context; event: any; parent: any };
self: any;
system: any;
}): Promise<ProcessQueueData> => {
const context = input.context;
const event = input.event;
// inspired by https://github.com/statelyai/xstate/discussions/4684
const parent = input.parent;
if (context.logging === "debug") {
console.debug("processQueues event", event);
console.debug("_incomingQueue", context._incomingQueue.length);
console.debug("_customMessageQueue", context._customMessageQueue.length);
console.debug(
"_pendingChangesQueue",
context._pendingChangesQueue.length
);
}
let handledQueue: "customMessage" | "incoming" | "pending" | "none" =
"none";
let snapshotInfosWithUpdateClocks = context._snapshotInfosWithUpdateClocks;
let activeSnapshotInfoWithUpdateClocks: SnapshotInfoWithUpdateClocks | null =
snapshotInfosWithUpdateClocks[snapshotInfosWithUpdateClocks.length - 1] ||
null;
let snapshotInFlight = context._snapshotInFlight;
let updatesLocalClock = context._updatesLocalClock;
let updatesInFlight = context._updatesInFlight;
let documentDecryptionState = context._documentDecryptionState;
let ephemeralMessagesSession = context._ephemeralMessagesSession;
let errorCausingDocumentToFail: Error | null = null;
let errorNotCausingDocumentToFail: Error | null = null;
let snapshotSaveFailedCounter = context._snapshotSaveFailedCounter;
let pendingChangesToRemoveCount = 0;
let pendingChangesToPrepend: any[] = [];
let ephemeralMessageReceivingErrors =
context._ephemeralMessageReceivingErrors;
const invokeOnDocumentUpdated = (type: OnDocumentUpdatedEventType) => {
try {
if (context.onDocumentUpdated) {
const snapshotInfosWithUpdateClocksEntry =
snapshotInfosWithUpdateClocks[
snapshotInfosWithUpdateClocks.length - 1
] || null;
context.onDocumentUpdated({
type,
knownSnapshotInfo: {
snapshotId: snapshotInfosWithUpdateClocksEntry.snapshotId,
parentSnapshotProof:
snapshotInfosWithUpdateClocksEntry.parentSnapshotProof,
snapshotCiphertextHash:
snapshotInfosWithUpdateClocksEntry.snapshotCiphertextHash,
updateClocks: snapshotInfosWithUpdateClocksEntry.updateClocks,
additionalPublicData:
snapshotInfosWithUpdateClocksEntry.additionalPublicData,
},
});
}
} catch (err) {
// logging anyway since this is a error by the developer implementing it
console.error(err);
}
};
try {
const createAndSendSnapshot = async () => {
try {
const newSnapshotId = generateId(context.sodium);
const snapshotData = await context.getNewSnapshotData({
id: newSnapshotId,
});
if (context.logging === "debug") {
console.log("createAndSendSnapshot", snapshotData);
}
// only if there is an entry we provide the object, and empty object is not
// desired as it would be inconsistent
const additionalPublicData =
Object.keys(snapshotData.publicData).length === 0
? undefined
: snapshotData.publicData;
// no snapshot exists so far
if (activeSnapshotInfoWithUpdateClocks === null) {
const publicData: SnapshotPublicData = {
...snapshotData.publicData,
snapshotId: newSnapshotId,
docId: context.documentId,
pubKey: context.sodium.to_base64(
context.signatureKeyPair.publicKey
),
parentSnapshotId: "",
parentSnapshotUpdateClocks: {},
};
const snapshot = createInitialSnapshot(
snapshotData.data,
publicData,
snapshotData.key,
context.signatureKeyPair,
context.sodium
);
pendingChangesToRemoveCount = context._pendingChangesQueue.length;
snapshotInFlight = {
updateClocks: {},
snapshotId: snapshot.publicData.snapshotId,
snapshotCiphertextHash: hash(snapshot.ciphertext, context.sodium),
parentSnapshotProof: snapshot.publicData.parentSnapshotProof,
parentSnapshotId: snapshot.publicData.parentSnapshotId,
changes: context._pendingChangesQueue,
additionalPublicData,
};
parent.send({
type: "SEND",
message: JSON.stringify({
...snapshot,
// Note: send a faulty message to test the error handling
// ciphertext: "lala",
additionalServerData: snapshotData.additionalServerData,
}),
});
} else {
const currentClientPublicKey = context.sodium.to_base64(
context.signatureKeyPair.publicKey
);
const publicData: SnapshotPublicData = {
...snapshotData.publicData,
snapshotId: newSnapshotId,
docId: context.documentId,
pubKey: currentClientPublicKey,
parentSnapshotId: activeSnapshotInfoWithUpdateClocks.snapshotId,
parentSnapshotUpdateClocks:
activeSnapshotInfoWithUpdateClocks.updateClocks || {},
};
const snapshot = createSnapshot(
snapshotData.data,
publicData,
snapshotData.key,
context.signatureKeyPair,
activeSnapshotInfoWithUpdateClocks.snapshotCiphertextHash,
activeSnapshotInfoWithUpdateClocks.parentSnapshotProof,
context.sodium
);
pendingChangesToRemoveCount = context._pendingChangesQueue.length;
snapshotInFlight = {
updateClocks: {},
snapshotId: snapshot.publicData.snapshotId,
snapshotCiphertextHash: hash(snapshot.ciphertext, context.sodium),
parentSnapshotProof: snapshot.publicData.parentSnapshotProof,
parentSnapshotId: snapshot.publicData.parentSnapshotId,
changes: context._pendingChangesQueue,
additionalPublicData,
};
parent.send({
type: "SEND",
message: JSON.stringify({
...snapshot,
// Note: send a faulty message to test the error handling
// ciphertext: "lala",
additionalServerData: snapshotData.additionalServerData,
}),
});
}
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_401");
}
};
const createAndSendUpdate = async (
changes: unknown[],
activeSnapshotInfo: SnapshotInfoWithUpdateClocks,
clock: number
) => {
try {
const key = await context.getSnapshotKey(activeSnapshotInfo);
const refSnapshotId = activeSnapshotInfo.snapshotId;
const update = context.serializeChanges(changes);
updatesLocalClock = clock + 1;
const publicData = {
refSnapshotId,
docId: context.documentId,
pubKey: context.sodium.to_base64(
context.signatureKeyPair.publicKey
),
};
const message = createUpdate(
update,
publicData,
key,
context.signatureKeyPair,
updatesLocalClock,
context.sodium
);
updatesInFlight.push({
snapshotId: refSnapshotId,
clock: updatesLocalClock,
changes,
});
parent.send({
type: "SEND",
message: JSON.stringify(message),
// Note: send a faulty message to test the error handling
// message: JSON.stringify({ ...message, ciphertext: "lala" }),
});
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_501");
}
};
const processSnapshot = async (
rawSnapshot: Snapshot,
snapshotProofChain: SnapshotProofChainEntry[],
knownSnapshotInfo?: SnapshotInfoWithUpdateClocks
) => {
try {
if (context.logging === "debug") {
console.debug("processSnapshot", rawSnapshot);
}
let snapshot: Snapshot;
let additionalPublicData: unknown;
try {
const parseSnapshotResult = parseSnapshot(
rawSnapshot,
context.additionalAuthenticationDataValidations?.snapshot
);
snapshot = parseSnapshotResult.snapshot;
additionalPublicData = parseSnapshotResult.additionalPublicData;
} catch (err) {
errorNotCausingDocumentToFail = new Error("SECSYNC_ERROR_110");
return;
}
try {
const isValidClient = await context.isValidClient(
snapshot.publicData.pubKey,
snapshot.publicData
);
if (!isValidClient) {
errorNotCausingDocumentToFail = new Error("SECSYNC_ERROR_114");
return;
}
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_104");
return;
}
const isAlreadyProcessedSnapshot =
knownSnapshotInfo?.snapshotId === snapshot.publicData.snapshotId &&
knownSnapshotInfo?.snapshotCiphertextHash ===
hash(snapshot.ciphertext, context.sodium) &&
knownSnapshotInfo?.parentSnapshotProof ===
snapshot.publicData.parentSnapshotProof;
if (isAlreadyProcessedSnapshot) {
return;
}
let isValidAncestor = false;
let parentSnapshotUpdateClock: number | undefined;
if (knownSnapshotInfo && snapshotProofChain.length > 0) {
isValidAncestor = isValidAncestorSnapshot({
knownSnapshotProofEntry: knownSnapshotInfo,
snapshotProofChain,
currentSnapshot: snapshot,
sodium: context.sodium,
});
parentSnapshotUpdateClock = undefined;
if (!isValidAncestor) {
errorNotCausingDocumentToFail = new Error("SECSYNC_ERROR_115");
return;
}
} else {
const parentSnapshotUpdateClocks = knownSnapshotInfo?.updateClocks;
if (parentSnapshotUpdateClocks) {
const currentClientPublicKey = context.sodium.to_base64(
context.signatureKeyPair.publicKey
);
parentSnapshotUpdateClock =
parentSnapshotUpdateClocks[currentClientPublicKey];
}
}
let snapshotKey: Uint8Array;
try {
snapshotKey = await context.getSnapshotKey({
snapshotId: snapshot.publicData.snapshotId,
parentSnapshotProof: snapshot.publicData.parentSnapshotProof,
snapshotCiphertextHash: hash(snapshot.ciphertext, context.sodium),
additionalPublicData,
});
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_103");
return;
}
// console.log("processSnapshot key", snapshotKey);
const decryptedSnapshotResult = verifyAndDecryptSnapshot(
snapshot,
snapshotKey,
context.documentId,
context.signatureKeyPair.publicKey,
context.sodium,
isValidAncestor ? undefined : knownSnapshotInfo,
isValidAncestor ? undefined : parentSnapshotUpdateClock
);
if (decryptedSnapshotResult.error) {
if (
decryptedSnapshotResult.error.message === "SECSYNC_ERROR_100" ||
decryptedSnapshotResult.error.message === "SECSYNC_ERROR_101" ||
decryptedSnapshotResult.error.message === "SECSYNC_ERROR_102"
) {
errorCausingDocumentToFail = decryptedSnapshotResult.error;
} else {
errorNotCausingDocumentToFail = decryptedSnapshotResult.error;
}
return;
}
try {
context.applySnapshot(decryptedSnapshotResult.content);
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_105");
return;
}
// can be inserted in the last position since verifyAndDecryptSnapshot already verified the parent
snapshotInfosWithUpdateClocks.push({
updateClocks: {},
snapshotId: snapshot.publicData.snapshotId,
snapshotCiphertextHash: hash(snapshot.ciphertext, context.sodium),
parentSnapshotProof: snapshot.publicData.parentSnapshotProof,
additionalPublicData,
});
// cleanup old snapshotInfosWithUpdateClocks entries and only keep the last 3 for debugging purposes
// cleaning them up to avoid a memory leak
snapshotInfosWithUpdateClocks =
snapshotInfosWithUpdateClocks.slice(-3);
updatesLocalClock = -1;
invokeOnDocumentUpdated("snapshot-received");
return additionalPublicData;
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_100");
}
};
const processUpdates = async (
rawUpdates: Update[],
relatedSnapshotInfo: SnapshotProofInfo
) => {
try {
let key: Uint8Array;
try {
key = await context.getSnapshotKey(relatedSnapshotInfo);
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_206");
return;
}
let changes: unknown[] = [];
for (let rawUpdate of rawUpdates) {
let update: Update;
try {
update = parseUpdate(
rawUpdate,
context.additionalAuthenticationDataValidations?.update
);
} catch (err) {
errorNotCausingDocumentToFail = new Error("SECSYNC_ERROR_211");
continue;
}
try {
const isValidClient = await context.isValidClient(
update.publicData.pubKey,
update.publicData
);
if (!isValidClient) {
errorNotCausingDocumentToFail = new Error("SECSYNC_ERROR_215");
continue;
}
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_205");
continue;
}
const unverifiedCurrentClock =
snapshotInfosWithUpdateClocks[
snapshotInfosWithUpdateClocks.length - 1
]?.updateClocks[update.publicData.pubKey];
const currentClock = Number.isInteger(unverifiedCurrentClock)
? unverifiedCurrentClock
: -1;
const decryptUpdateResult = verifyAndDecryptUpdate(
update,
key,
relatedSnapshotInfo.snapshotId,
currentClock,
context.sodium,
context.logging
);
if (decryptUpdateResult.error) {
const ignoreErrorList = [
"SECSYNC_ERROR_211",
"SECSYNC_ERROR_212",
"SECSYNC_ERROR_213",
"SECSYNC_ERROR_214",
"SECSYNC_ERROR_215",
];
if (ignoreErrorList.includes(decryptUpdateResult.error.message)) {
errorNotCausingDocumentToFail = decryptUpdateResult.error;
continue;
} else {
errorCausingDocumentToFail = decryptUpdateResult.error;
continue;
}
}
const { content, clock } = decryptUpdateResult;
snapshotInfosWithUpdateClocks = updateUpdateClocksEntry({
snapshotInfosWithUpdateClocks,
snapshotId: relatedSnapshotInfo.snapshotId,
clientPublicKey: update.publicData.pubKey,
newClock: clock,
});
if (
update.publicData.pubKey ===
context.sodium.to_base64(context.signatureKeyPair.publicKey)
) {
updatesLocalClock = update.publicData.clock;
}
try {
const additionalChanges = context.deserializeChanges(
context.sodium.to_string(content)
);
changes = changes.concat(additionalChanges);
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_204");
}
}
try {
context.applyChanges(changes);
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_203");
}
invokeOnDocumentUpdated("update-received");
} catch (err) {
if (context.logging === "debug" || context.logging === "error") {
console.error(err);
}
errorCausingDocumentToFail = new Error("SECSYNC_ERROR_200");
}
};
if (context._customMessageQueue.length > 0) {
handledQueue = "customMessage";
const event = context._customMessageQueue[0];
if (context.onCustomMessage) {
await context.onCustomMessage(event);
}
} else if (context._incomingQueue.length > 0) {
handledQueue = "incoming";
const event = context._incomingQueue[0];
switch (event.type) {
case "document":
documentDecryptionState = "failed";
if (
context.loadDocumentParams?.mode !== "delta" &&
!event.snapshot &&
event.updates &&
event.updates.length > 0
) {
if (context.logging === "debug" || context.logging === "error") {
console.error(
"Loading document mode was 'complete', but received updates without a snapshot"
);
}
throw new Error("SECSYNC_ERROR_100");
}
let snapshotAdditionalPublicDataOnDocumentLoad: any = undefined;
if (event.snapshot) {
snapshotAdditionalPublicDataOnDocumentLoad =
await processSnapshot(
event.snapshot,
event.snapshotProofChain || [],
context.loadDocumentParams?.knownSnapshotInfo
);
// if the initial snapshot fails the document can't be loaded
if (errorNotCausingDocumentToFail) {
errorCausingDocumentToFail = errorNotCausingDocumentToFail;
}
}
if (errorCausingDocumentToFail === null) {
documentDecryptionState = "partial";
if (event.updates) {
await processUpdates(
event.updates,
event.snapshot
? {
snapshotId: event.snapshot.publicData.snapshotId,
parentSnapshotProof:
event.snapshot.publicData.parentSnapshotProof,
snapshotCiphertextHash: hash(
event.snapshot.ciphertext,
context.sodium
),
additionalPublicData:
snapshotAdditionalPublicDataOnDocumentLoad,
}
: activeSnapshotInfoWithUpdateClocks
);
if (errorNotCausingDocumentToFail) {
errorCausingDocumentToFail = errorNotCausingDocumentToFail;
}
}
}
if (errorCausingDocumentToFail === null) {
documentDecryptionState = "complete";
}
break;
case "snapshot":
if (context.logging === "debug") {
console.log("snapshot", event);
}
await processSnapshot(
event.snapshot,
[],
activeSnapshotInfoWithUpdateClocks
? activeSnapshotInfoWithUpdateClocks
: undefined
);
break;
case "snapshot-saved":
if (context.logging === "debug") {
console.log("snapshot saved", event);
}
if (
// Ignore snapshot-saved for an event that is not in flight
snapshotInFlight &&
event.snapshotId === snapshotInFlight.snapshotId &&
// Ignore snapshot saved if there is an activeSnapshot and
// it doesn't match the currently active one.
// This can happen if another snapshot event has been received already.
(activeSnapshotInfoWithUpdateClocks === undefined ||
activeSnapshotInfoWithUpdateClocks === null ||
activeSnapshotInfoWithUpdateClocks.snapshotId ===
snapshotInFlight.parentSnapshotId)
) {
snapshotSaveFailedCounter = 0; // reset the counter since we got a positive save response
snapshotInfosWithUpdateClocks.push({
...snapshotInFlight,
updateClocks: {},
});
invokeOnDocumentUpdated("snapshot-saved");
snapshotInFlight = null;
updatesLocalClock = -1;
}
break;
case "snapshot-save-failed":
snapshotSaveFailedCounter += 1;
if (context.logging === "debug") {
console.log("snapshot saving failed", event);
}
let snapshotAdditionalPublicData: any = undefined;
if (event.snapshot) {
snapshotAdditionalPublicData = await processSnapshot(
event.snapshot,
event.snapshotProofChain || [],
activeSnapshotInfoWithUpdateClocks
);
}
if (event.updates) {
await processUpdates(
event.updates,
event.snapshot
? {
snapshotId: event.snapshot.publicData.snapshotId,
parentSnapshotProof:
event.snapshot.publicData.parentSnapshotProof,
snapshotCiphertextHash: hash(
event.snapshot.ciphertext,
context.sodium
),
additionalPublicData: snapshotAdditionalPublicData,
}
: activeSnapshotInfoWithUpdateClocks
);
}
// put changes from the failed snapshot back in the queue
pendingChangesToPrepend = snapshotInFlight?.changes || [];
snapshotInFlight = null;
if (context.logging === "debug") {
console.log("retry send snapshot");
}
// skip another try if there is a snapshot in flight
if (snapshotSaveFailedCounter < 5) {
await createAndSendSnapshot();
}
break;
case "update":
await processUpdates([event], activeSnapshotInfoWithUpdateClocks);
break;
case "update-saved":
if (context.logging === "debug") {
console.debug("update saved", event);
}
snapshotSaveFailedCounter = 0; // reset the counter since we got a positive save response
// only increases if the event.clock is larger since the server
// might have returned them out of order
snapshotInfosWithUpdateClocks = updateUpdateClocksEntry({
snapshotInfosWithUpdateClocks,
clientPublicKey: context.sodium.to_base64(
context.signatureKeyPair.publicKey
),
snapshotId: event.snapshotId,
newClock: event.clock,
});
updatesInFlight = updatesInFlight.filter(
(updateInFlight) =>
!(
updateInFlight.clock === event.clock &&
updateInFlight.snapshotId === event.snapshotId
)
);
invokeOnDocumentUpdated("update-saved");
break;
case "update-save-failed":
if (context.logging === "debug") {
console.log(
"update saving failed",
event,
" referencing active snapshot: ",
activeSnapshotInfoWithUpdateClocks.snapshotId ===
event.snapshotId
);
}
if (event.requiresNewSnapshot) {
await createAndSendSnapshot();
} else {
// collect all changes that are in flight and put them back into the queue
const changes = updatesInFlight.reduce(
(acc, updateInFlight) => acc.concat(updateInFlight.changes),
[] as any[]
);
updatesInFlight = [];
// put the changes from the failed updated and after back to the queue
pendingChangesToPrepend = changes;
const currentClientPublicKey = context.sodium.to_base64(
context.signatureKeyPair.publicKey
);
const unverifiedCurrentClock =
snapshotInfosWithUpdateClocks[
snapshotInfosWithUpdateClocks.length - 1
]?.updateClocks[currentClientPublicKey];
updatesLocalClock = Number.isInteger(unverifiedCurrentClock)
? unverifiedCurrentClock
: -1;
}
break;
case "ephemeral-message":
// used so we can do early return
const handleEphemeralMessage = async () => {
try {
let ephemeralMessage: EphemeralMessage;
try {
ephemeralMessage = parseEphemeralMessage(
event,
context.additionalAuthenticationDataValidations
?.ephemeralMessage
);
} catch (err) {
if (context.logging === "error") {
console.error(err);
}
ephemeralMessageReceivingErrors.unshift(
new Error("SECSYNC_ERROR_307")
);
return;
}
const key = await context.getSnapshotKey(
activeSnapshotInfoWithUpdateClocks
);
let isValidClient: boolean;
try {
isValidClient = await context.isValidClient(
ephemeralMessage.publicData.pubKey,
ephemeralMessage.publicData
);
} catch (err) {
if (context.logging === "error") {
console.error(err);
}
isValidClient = false;
}
if (!isValidClient) {
ephemeralMessageReceivingErrors.unshift(
new Error("SECSYNC_ERROR_304")
);
return;
}
if (ephemeralMessagesSession === null) {
if (
context.logging === "error" ||
context.logging === "debug"
) {
console.error(
"context._ephemeralMessagesSession is not defined"
);
}
return;
}
const ephemeralMessageResult = verifyAndDecryptEphemeralMessage(
ephemeralMessage,
key,