-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol.js
1107 lines (948 loc) · 35.7 KB
/
protocol.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This module implements the Seif Protocol Version 0 in two functions,
// 'connect' and 'listen'. These functions are similar to a party's methods, but
// they do not use a store.
// This implementation deviates slightly from the specification, which contains
// a mistake:
// Seif uses AES-256 in GCM mode to encrypt the communication stream. Since
// the channel will look exactly the same for an identical stream, the
// protocol modulates the channel with a random stream of numbers. The
// random stream is generated using Xorshift+ Random Number Generator
// (RNG).
// Wrong! Two identical streams of plaintext will never yield the same stream of
// ciphertext in GCM mode, unless an IV were reused. But reuse of an IV
// jeopardises the secrecy of the key, and is easy to avoid because a unique
// symmetric key is negotiated for each Seif session. In order to simplify
// implementation, WebSeif omits this modulation.
// ABOUT TRANSPORTS
// The 'transport_connect' and 'transport_listen' parameters are functions
// providing an ordered, reliable and persistent connection for binary data.
// Both functions take these four parameters:
// address
// The address to connect or listen on. Different kinds of transports may
// format their address differently.
// on_open(connection)
// A function that is called when a connection is opened. The 'connection'
// parameter is an object with two methods:
// connection.send(chunk)
// Send a chunk of binary data down the connection. The 'chunk' is
// a Uint8Array.
// connection.close()
// Close the connection.
// on_receive(connection, chunk)
// A function that is called with each 'chunk' that arrives over a
// connection. The chunk is a Uint8Array.
// on_close(connection, reason)
// A function that is called when a connection is closed. If the connection
// failed, the 'reason' parameter should explain why.
// The 'transport_connect' function returns a 'close' function, which closes the
// connection. The 'transport_listen' funtion returns a 'stop' function, which
// closes every connection and stops listening. Once a transport is closed or
// stopped, the 'on_open', 'on_receive' and 'on_close' callbacks must not be
// called again.
/*jslint browser, node, deno, global, bitwise */
import hex from "./hex.js";
import elliptic from "./elliptic.js";
function concat_bytes(a, b) {
let array = new Uint8Array(a.byteLength + b.byteLength);
array.set(a, 0);
array.set(b, a.byteLength);
return array;
}
function encode_json(value) {
return new TextEncoder().encode(JSON.stringify(value));
}
function decode_json(bytes) {
return JSON.parse(new TextDecoder().decode(bytes));
}
function iv(fixed_field) {
// The 'iv' function returns a generator that produces sequential 96-bit
// initialization vectors, suitable for use with AES-GCM. The AES-GCM
// specification states that IVs must never be reused for a given key,
// otherwise it's game over.
// Exactly two parties share a key. If each party maintains its own counter,
// then we just need to make sure they never encrypt anything using the same
// IV. This is accomplished by concatenating the counter with the 'fixed_field',
// which should be either 0 (for messages originating from initiating parties)
// or 1 (for messages destined for initiating parties).
let counter = 0;
return function iv_generator() {
if (counter > Number.MAX_SAFE_INTEGER) {
throw new Error("Counter exhausted.");
}
const bytes = new Uint8Array(12);
// Use a DataView to ensure a uniform endianness within the IVs, regardless of
// the machine's architecture.
const view = new DataView(bytes.buffer);
view.setUint32(0, fixed_field);
view.setUint32(4, Math.floor(counter / (2 ** 32)));
view.setUint32(8, counter % (2 ** 32));
counter += 1;
return bytes;
};
}
function make_record(identifier, message, encrypt_bytes) {
// The 'make_record' function constructs a Seif record, consisting of a binary
// length field, an identifier, and any number of blobs. The returned Promise
// resolves to a Uint8Array, intended to be put on the wire.
// Properties found on the 'identifier' object are included in the record's
// identifier.
// The 'message' parameter is an object containing the values for the record's
// blobs. The name of each property is the blob ID, and each value is either a
// Uint8Array or a JSON-encodable value.
// The 'encrypt_bytes' function takes a plaintext Uint8Array and returns a
// Promise that resolves to the ciphertext Uint8Array.
if (typeof message !== "object") {
throw new Error("Bad message.");
}
identifier.blobs = [];
let blob_byte_arrays = Object.keys(
message
).filter(function (id) {
return message[id] !== undefined;
}).map(function (id) {
let bytes;
let blob_type;
// Determine whether the blob should be transmitted as binary or structured
// data.
if (message[id]?.constructor === Uint8Array) {
bytes = message[id];
blob_type = "Buffer";
} else {
bytes = encode_json(message[id]);
blob_type = "JSON";
}
// Include information about the blob in the identifier, sent ahead of the
// blobs. We include the length of the plaintext blob, rather than the length of
// the ciphertext. This is because the blob buffers must be encrypted after the
// identifier, due to the irreversible nature of AES-GCM.
identifier.blobs.push({
id,
type: blob_type,
length: bytes.length
});
return bytes;
});
// Serialize and encrypt the identifier, then each of the blob buffers.
const identifier_bytes = encode_json(identifier);
if (identifier_bytes.length >= 2 ** 16) {
throw new Error("Identifier too big.");
}
return Promise.all(
[identifier_bytes, ...blob_byte_arrays].map(encrypt_bytes)
).then(function (encrypted_byte_arrays) {
// The record begins with the identifier length field, which is a big-endian
// integer sent in the clear.
let length_bytes = new Uint8Array(2);
let length_view = new DataView(length_bytes.buffer);
length_view.setUint16(0, encrypted_byte_arrays[0].length);
// Finally, we stuff all of the bytes into one big buffer and return that as the
// record.
const record_byte_arrays = [length_bytes, ...encrypted_byte_arrays];
return record_byte_arrays.reduce(concat_bytes);
});
}
// The symmetric encryption operations. We use the 256 bit AES-GCM cipher, as
// per the Seif Protocol specification.
// The 'aes' object contains the following methods:
// generate_key()
// Generates a new symmetric key. The returned Promise resolves to a
// CryptoKey.
// encrypt(plaintext, key, iv)
// Encrypt a plaintext Uint8Array with a CryptoKey and an initialization
// vector. The returned Promise resolves to the ciphertext Uint8Array.
// decrypt(ciphertext, key, iv)
// Decrypt a ciphertext Uint8Array with the same CryptoKey and
// initialization vector that were used to encrypt it. The returned
// Promise resolves to the plaintext Uint8Array.
// derive_key(public_key, private_key)
// Derives a symmetric key from a public and private key using the
// Diffie-Hellman key exchange protocol (ECDH). The public and private
// keys should not form a keypair. The returned Promise resolves to the
// shared secret, a CryptoKey instance.
const aes = Object.freeze({
generate_key() {
return crypto.subtle.generateKey(
{name: "AES-GCM", length: 256},
true,
["encrypt", "decrypt"]
);
},
encrypt(plaintext, key, iv) {
return crypto.subtle.encrypt(
{name: "AES-GCM", iv},
key,
plaintext
).then(function (buffer) {
return new Uint8Array(buffer);
});
},
decrypt(ciphertext, key, iv) {
return crypto.subtle.decrypt(
{name: "AES-GCM", iv},
key,
ciphertext
).then(function (buffer) {
return new Uint8Array(buffer);
});
},
derive_key(public_key, private_key) {
return crypto.subtle.deriveKey(
{
name: "ECDH",
public: public_key
},
private_key,
{name: "AES-GCM", length: 256},
true,
["encrypt", "decrypt"]
);
}
});
function hello(
initiator_public_key,
receiver_public_key,
encryption_iv,
connection_info,
hello_value
) {
// The 'hello' function produces some values that are required to initiate a
// Seif handshake. It takes the following parameters:
// initiator_public_key: The public key of the initiator, as a CryptoKey.
// receiver_public_key: The public key of the receiver, as a CryptoKey.
// encryption_iv: An IV to be used for a single encryption.
// connection_info: An optional JSON-serializable value, sent in the clear.
// hello_value: A JSON-serializable value to include with the hello data.
// The returned Promise resolves to an object with these properties:
// hello_record: The Hello record as a Uint8Array.
// handshake_key: The generated handshake key, as a CryptoKey.
// We begin by generating an ephemeral keypair and immediately use it to derive
// the handshake key. This handshake key is used to encrypt the "hello data",
// which contains our public key.
return elliptic.generate_keypair().then(function (ephemeral) {
return Promise.all([
aes.derive_key(receiver_public_key, ephemeral.privateKey),
elliptic.export_public_key(initiator_public_key),
elliptic.export_public_key(ephemeral.publicKey)
]).then(function ([
handshake_key,
initiator_public_key_buffer,
ephemeral_public_key_buffer
]) {
return aes.encrypt(
encode_json({
initiatorPublicKey: hex.encode(initiator_public_key_buffer),
value: hello_value
}),
handshake_key,
encryption_iv
).then(function (encrypted_hello_data_buffer) {
// The Seif Protocol specification states that a Hello record's "handshakeKey"
// property contains the handshake key encrypted by the receiver's public key.
// But because we derived the handshake key via ECDH, this is simply the
// ephemeral public key.
return make_record(
{type: "Hello"},
{
version: 0,
handshakeKey: ephemeral_public_key_buffer,
helloData: encrypted_hello_data_buffer,
connectionInfo: connection_info
},
function encrypt(bytes) {
// The sensitive parts of the Hello record have already been encrypted, so we
// can skip this step.
return bytes;
}
);
}).then(function (hello_record) {
return {hello_record, handshake_key};
});
});
});
}
function auth_hello(
hello_message,
private_key,
next_decryption_iv,
next_encryption_iv
) {
// The 'auth_hello' function produces some values that are required to complete
// a Seif handshake. It takes the following parameters:
// hello_message: The Hello message as an object.
// private_key: The listener's private key, as a CryptoKey.
// next_decryption_iv: An IV generator for decryption.
// next_encryption_iv: An IV generator for encryption.
// The returned Promise resolves to an object with the following properties:
// auth_hello_record: A Uint8Array containing the AuthHello record.
// session_key: The negotiated session key, as a CryptoKey.
// hello_value: The value sent with the Hello message.
// initiator_public_key: The initiating party's public key, as a CryptoKey.
if (hello_message.version !== 0) {
return Promise.reject(new Error("Unsupported Seif version."));
}
// The Hello message contains the ephemeral public key of the handshake key
// exchange, and the initiator's public key encrypted by the handshake key. We
// derive and decrypt, and if it looks good we construct a response that
// initiates the session key exchange.
let hello_value;
let session_key;
let initiator_public_key;
return elliptic.import_public_key(
hello_message.handshakeKey
).then(function (ephemeral_public_key) {
return aes.derive_key(ephemeral_public_key, private_key);
}).then(function (handshake_key) {
return aes.decrypt(
hello_message.helloData,
handshake_key,
next_decryption_iv()
).then(function (hello_buffer) {
const {initiatorPublicKey, value} = decode_json(hello_buffer);
hello_value = value;
// Generate the ephemeral keypair for the session key exchange, and import the
// initiator's public key so that it can be used to derive the session key.
return Promise.all([
elliptic.generate_keypair(),
elliptic.import_public_key(hex.decode(initiatorPublicKey))
]);
}).then(function ([ephemeral, the_initiator_public_key]) {
initiator_public_key = the_initiator_public_key;
return Promise.all([
aes.derive_key(initiator_public_key, ephemeral.privateKey),
elliptic.export_public_key(ephemeral.publicKey)
]);
}).then(function ([the_session_key, ephemeral_public_key_buffer]) {
// Construct the AuthHello record.
session_key = the_session_key;
return make_record(
{type: "AuthHello"},
{sessionKey: ephemeral_public_key_buffer},
function encrypt(bytes) {
return aes.encrypt(
bytes,
handshake_key,
next_encryption_iv()
);
}
);
});
}).then(function (auth_hello_record) {
return {
auth_hello_record,
session_key,
hello_value,
initiator_public_key
};
});
}
function make_consumer(
transport_connection, // The underlying transport connection.
private_key, // Our private key.
next_encryption_iv, // Returns the next encryption IV.
next_decryption_iv, // Returns the next decryption IV.
on_open, // Called with each new Seif connection.
on_message, // Called with each new Seif message.
on_close, // Called when a Seif connection is closed.
on_redirect, // Called with Seif redirection info.
handshake_key // The symmetric key used during handshake.
) {
// A "consumer" does most of the work in setting up and communicating over a
// Seif connection. It is complex because it must tease messages out of an
// incoming byte stream.
let session_key; // The symmetric key, to encrypt traffic.
let seif_connection; // The interface for the Seif connection.
// Incoming state. Bytes are added to the end of a 'buffer', and periodically
// consumed from the start (unless 'busy' is true).
let buffer = new Uint8Array(0); // The incoming bytes left to process.
let busy = false; // Busy decrypting.
let identifier; // The parsed Seif record identifier.
let identifier_length; // The identifier's length in bytes.
let blob_buffers = []; // Decrypted blob buffers.
// Outgoing state. Tasks are then'd to a 'queue', which is a Promise that
// resolves whenever the queue is emptied.
let queue = Promise.resolve(); // Outgoing message queue.
let pending_acks = []; // Pending acknowledgement callbacks.
function encrypt(plain) {
return aes.encrypt(
plain,
session_key,
next_encryption_iv()
);
}
function decrypt(cipher) {
return aes.decrypt(
cipher,
session_key ?? handshake_key,
next_decryption_iv()
);
}
function destroy(reason, situation_option) {
// The value of 'situation_option' may be one of:
// undefined: There was a problem.
// true: The connection is no longer required.
// false: The connection has already been closed.
if (transport_connection !== undefined) {
// Inform the waiting senders that no more acknowledgements are forthcoming.
pending_acks.forEach(function (pending) {
pending.reject(reason);
});
if (situation_option !== false) {
transport_connection.close();
}
if (situation_option === undefined) {
on_close(seif_connection, reason);
}
transport_connection = undefined;
}
}
function enqueue(callback) {
// Adds a callback function to the outoing message queue. The callback should
// return a Promise that resolves to a record.
queue = queue.then(function () {
if (transport_connection !== undefined) {
return callback().then(function (record) {
if (transport_connection !== undefined) {
transport_connection.send(record);
}
});
}
}).catch(
destroy
);
}
function redirect(address, public_key, permanent, redirect_context) {
// Redirect the initiating party to another listening party.
enqueue(function () {
return elliptic.export_public_key(
public_key
).then(function (public_key_bytes) {
return make_record(
{type: "Redirect"},
{
address,
publicKey: hex.encode(public_key_bytes),
permanent,
redirectContext: redirect_context
},
encrypt
);
});
});
}
function send(message) {
// Send a message with the expectation that its delivery will be acknowledged.
return new Promise(function (resolve, reject) {
return enqueue(function () {
pending_acks.push({resolve, reject});
return make_record({type: "Send"}, message, encrypt);
});
});
}
function status_send(message) {
// Send a message with no delivery acknowledgement.
enqueue(function () {
return make_record({type: "StatusSend"}, message, encrypt);
});
}
function take(nr_bytes) {
// Remove some bytes from the start of the incoming buffer and return them.
const bytes = buffer.slice(0, nr_bytes);
buffer = buffer.slice(nr_bytes);
return bytes;
}
function receive() {
// The identifier and blobs of an incoming record are available. Parse them into
// a message and reset the incoming state, ready for the next record.
let {type} = identifier;
let message = {};
try {
identifier.blobs.forEach(function (blob, blob_nr) {
message[blob.id] = (
blob.type === "JSON"
? decode_json(blob_buffers[blob_nr])
: blob_buffers[blob_nr]
);
});
} catch (exception) {
return destroy(exception);
}
identifier = undefined;
identifier_length = undefined;
blob_buffers = [];
// Handle the message. Is the handshake still in progress?
if (session_key === undefined) {
if (handshake_key === undefined) {
// We have received the Hello message. Respond with an AuthHello message.
busy = true;
return auth_hello(
message,
private_key,
// Our IV generators are used for both the session and handshake keys. This is
// not a problem, because they remain unique for each key.
next_decryption_iv,
next_encryption_iv
).then(function (result) {
if (transport_connection === undefined) {
return;
}
transport_connection.send(result.auth_hello_record);
session_key = result.session_key;
seif_connection = Object.freeze({
send,
status_send,
redirect,
close(reason) {
return destroy(reason, true);
}
});
on_open(
seif_connection,
result.initiator_public_key,
result.hello_value,
message.connectionInfo
);
busy = false;
}).catch(
destroy
);
}
// We have received the AuthHello message. Derive the session key using the
// ephemeral public key plus our private key.
busy = true;
return elliptic.import_public_key(
message.sessionKey
).then(function (ephemeral_public_key) {
return aes.derive_key(ephemeral_public_key, private_key);
}).then(function (the_session_key) {
session_key = the_session_key;
seif_connection = Object.freeze({
send,
status_send,
close(reason) {
return destroy(reason, true);
}
});
on_open(seif_connection);
busy = false;
}).catch(
destroy
);
}
// The message is not part of the handshake. Handle it with respect to its type.
if (type === "Redirect") {
busy = true;
return elliptic.import_public_key(
hex.decode(message.publicKey)
).then(function (public_key) {
on_redirect(
seif_connection,
message.address,
public_key,
message.permanent,
message.redirectContext
);
busy = false;
}).catch(
destroy
);
}
if (type === "Send") {
enqueue(function () {
return make_record({type: "Acknowledge"}, {}, encrypt);
});
on_message(seif_connection, message);
return consume();
}
if (type === "Acknowledge") {
const pending = pending_acks.shift();
if (pending === undefined) {
return destroy("Unexpected acknowledgement.");
}
pending.resolve();
return consume();
}
if (type === "StatusSend") {
on_message(seif_connection, message);
return consume();
}
return destroy("Unrecognized message type.");
}
function consume() {
// The 'consume' function processes incoming messages as they become available.
// It recurses, working it way thru the 'buffer' until it needs to wait for more
// bytes.
if (transport_connection === undefined || busy) {
return;
}
if (identifier === undefined) {
// We are at the start of a record, which encodes a Seif message. A record
// is segmented like [identifier_length, identifier, ...blob_buffers].
if (identifier_length === undefined) {
if (buffer.length < 2) {
return;
}
// Read the first two bytes to get the length of the identifier. The Seif
// specification does not specify endianness, so big-endian it is.
identifier_length = new DataView(take(2).buffer).getUint16(0);
}
if (buffer.length < identifier_length) {
return;
}
if (session_key === undefined && handshake_key === undefined) {
// The Hello record is unique in that it sends its identifier in the clear.
try {
identifier = decode_json(take(identifier_length));
} catch (exception) {
return destroy(exception);
}
return consume();
}
// Decrypt and parse the identifier.
busy = true;
return decrypt(take(identifier_length)).then(
function (identifier_bytes) {
identifier = decode_json(identifier_bytes);
busy = false;
return consume();
}
).catch(
destroy
);
}
// Now for the blobs.
if (blob_buffers.length < identifier.blobs.length) {
// Decrypt the next blob, if it has arrived.
const blob = identifier.blobs[blob_buffers.length];
if (session_key === undefined && handshake_key === undefined) {
// We are receving a Hello record, which arrives in the clear.
if (buffer.length < blob.length) {
return;
}
blob_buffers.push(take(blob.length));
return consume();
}
// A ciphertext is always 16 bytes longer than a plaintext, due to the AES-GCM
// authentication tag.
const ciphertext_length = blob.length + 16;
if (buffer.length < ciphertext_length) {
return;
}
busy = true;
return decrypt(
take(ciphertext_length)
).then(function (decrypted_bytes) {
blob_buffers.push(decrypted_bytes);
busy = false;
return consume();
}).catch(
destroy
);
}
// The record's identifier and all of its blobs have now arrived and been
// decrypted. Parse it into a message.
return receive();
}
return Object.freeze({
consume(chunk) {
buffer = concat_bytes(buffer, chunk);
consume();
},
get_seif_connection() {
return seif_connection;
},
transport_closed(reason) {
destroy(reason, false);
}
});
}
function listen({
keypair,
transport_listen,
address,
on_open,
on_message,
on_close
}) {
let consumer_map = new Map();
function on_transport_open(transport_connection) {
consumer_map.set(
transport_connection,
make_consumer(
transport_connection,
keypair.privateKey,
iv(1),
iv(0),
on_open,
on_message,
function on_consumer_close(...args) {
consumer_map.delete(transport_connection);
return on_close(...args);
}
)
);
}
function on_transport_receive(transport_connection, chunk) {
const consumer = consumer_map.get(transport_connection);
if (consumer !== undefined) {
return consumer.consume(chunk);
}
}
function on_transport_close(transport_connection, reason) {
const consumer = consumer_map.get(transport_connection);
if (consumer !== undefined) {
consumer.transport_closed(reason);
consumer_map.delete(transport_connection);
return on_close(consumer.get_seif_connection(), reason);
}
}
const stop_transport = transport_listen(
address,
on_transport_open,
on_transport_receive,
on_transport_close
);
return function stop(reason) {
stop_transport();
consumer_map.forEach(function (consumer) {
consumer.transport_closed(reason);
});
consumer_map = new Map();
};
}
function connect({
keypair,
transport_connect,
address,
remote_public_key,
hello_value,
connection_info,
on_open,
on_message,
on_close
}) {
let transport_connection;
let consumer;
let close_transport;
let on_redirect;
function on_transport_receive(_, chunk) {
if (consumer !== undefined) {
return consumer.consume(chunk);
}
close_transport();
return on_close(undefined, "Unexpected chunk.");
}
function on_transport_close(_, reason) {
transport_connection = undefined;
if (consumer !== undefined) {
consumer.transport_closed(reason);
return on_close(consumer.get_seif_connection(), reason);
}
return on_close(undefined, reason);
}
function on_transport_open(the_transport_connection) {
transport_connection = the_transport_connection;
// Initiate the handshake.
const next_encryption_iv = iv(0);
const next_decryption_iv = iv(1);
return hello(
keypair.publicKey,
remote_public_key,
next_encryption_iv(),
connection_info,
hello_value
).then(
function ({hello_record, handshake_key}) {
if (transport_connection === undefined) {
return;
}
consumer = make_consumer(
transport_connection,
keypair.privateKey,
next_encryption_iv,
next_decryption_iv,
on_open,
on_message,
function on_consumer_close(...args) {
transport_connection = undefined;
return on_close(...args);
},
on_redirect,
handshake_key
);
transport_connection.send(hello_record);
}
).catch(
function (reason) {
close_transport();
on_close(undefined, reason);
}
);
}
on_redirect = function (
connection,
address,
public_key,
permanent,
redirect_context
) {
// We have been redirected. Close the current connection and connect to the
// specified party instead.
close_transport();
consumer.transport_closed("Redirected.");
consumer = undefined;
transport_connection = undefined;
on_close(
connection,
undefined,
address,
public_key,
permanent,
redirect_context
);
// Update some of the parameters and start over.
remote_public_key = public_key;
connection_info = redirect_context;
close_transport = transport_connect(
address,
on_transport_open,
on_transport_receive,
on_transport_close
);
};
close_transport = transport_connect(
address,
on_transport_open,
on_transport_receive,
on_transport_close
);
return function close(reason) {
transport_connection = undefined;
if (consumer !== undefined) {
consumer.transport_closed(reason);
}
return close_transport();
};
}
import mock_transport from "./transport/mock_transport.js";
const transport = mock_transport(0.01);
const bob_address = "bob";
const carol_address = "carol";
// import websock_transport from "./transport/websockets_transport.js";
// const transport = websock_transport();
// const bob_address = "ws://127.0.0.1:6666";
// const carol_address = "ws://127.0.0.1:5555";
// import tcp_transport from "./transport/deno_tcp_transport.js";
// const transport = tcp_transport();
// const bob_address = "127.0.0.1:6666";
// const carol_address = "127.0.0.1:5555";
let stop_alice;
let stop_bob;
let stop_carol;
const trace = globalThis.console.log;
const dummy_message = {
json: "some text",
age: 0,
bar: hex.decode("FF0C01")