/
index.js
2300 lines (2039 loc) · 84 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2018-2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
/**
* @module crypto
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.verificationMethods = undefined;
exports.isCryptoAvailable = isCryptoAvailable;
exports.default = Crypto;
var _bluebird = require('bluebird');
var _bluebird2 = _interopRequireDefault(_bluebird);
var _events = require('events');
var _logger = require('../logger');
var _logger2 = _interopRequireDefault(_logger);
var _randomstring = require('../randomstring');
var _OutgoingRoomKeyRequestManager = require('./OutgoingRoomKeyRequestManager');
var _OutgoingRoomKeyRequestManager2 = _interopRequireDefault(_OutgoingRoomKeyRequestManager);
var _indexeddbCryptoStore = require('./store/indexeddb-crypto-store');
var _indexeddbCryptoStore2 = _interopRequireDefault(_indexeddbCryptoStore);
var _QRCode = require('./verification/QRCode');
var _SAS = require('./verification/SAS');
var _SAS2 = _interopRequireDefault(_SAS);
var _Error = require('./verification/Error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const anotherjson = require('another-json');
const utils = require("../utils");
const OlmDevice = require("./OlmDevice");
const olmlib = require("./olmlib");
const algorithms = require("./algorithms");
const DeviceInfo = require("./deviceinfo");
const DeviceVerification = DeviceInfo.DeviceVerification;
const DeviceList = require('./DeviceList').default;
const defaultVerificationMethods = {
[_QRCode.ScanQRCode.NAME]: _QRCode.ScanQRCode,
[_QRCode.ShowQRCode.NAME]: _QRCode.ShowQRCode,
[_SAS2.default.NAME]: _SAS2.default
};
/**
* verification method names
*/
const verificationMethods = exports.verificationMethods = {
QR_CODE_SCAN: _QRCode.ScanQRCode.NAME,
QR_CODE_SHOW: _QRCode.ShowQRCode.NAME,
SAS: _SAS2.default.NAME
};
function isCryptoAvailable() {
return Boolean(global.Olm);
}
const MIN_FORCE_SESSION_INTERVAL_MS = 60 * 60 * 1000;
const KEY_BACKUP_KEYS_PER_REQUEST = 200;
/**
* Cryptography bits
*
* This module is internal to the js-sdk; the public API is via MatrixClient.
*
* @constructor
* @alias module:crypto
*
* @internal
*
* @param {module:base-apis~MatrixBaseApis} baseApis base matrix api interface
*
* @param {module:store/session/webstorage~WebStorageSessionStore} sessionStore
* Store to be used for end-to-end crypto session data
*
* @param {string} userId The user ID for the local user
*
* @param {string} deviceId The identifier for this device.
*
* @param {Object} clientStore the MatrixClient data store.
*
* @param {module:crypto/store/base~CryptoStore} cryptoStore
* storage for the crypto layer.
*
* @param {RoomList} roomList An initialised RoomList object
*
* @param {Array} verificationMethods Array of verification methods to use.
* Each element can either be a string from MatrixClient.verificationMethods
* or a class that implements a verification method.
*/
function Crypto(baseApis, sessionStore, userId, deviceId, clientStore, cryptoStore, roomList, verificationMethods) {
this._baseApis = baseApis;
this._sessionStore = sessionStore;
this._userId = userId;
this._deviceId = deviceId;
this._clientStore = clientStore;
this._cryptoStore = cryptoStore;
this._roomList = roomList;
this._verificationMethods = new Map();
if (verificationMethods) {
for (const method of verificationMethods) {
if (typeof method === "string") {
if (defaultVerificationMethods[method]) {
this._verificationMethods.set(method, defaultVerificationMethods[method]);
}
} else if (method.NAME) {
this._verificationMethods.set(method.NAME, method);
}
}
}
// track whether this device's megolm keys are being backed up incrementally
// to the server or not.
// XXX: this should probably have a single source of truth from OlmAccount
this.backupInfo = null; // The info dict from /room_keys/version
this.backupKey = null; // The encryption key object
this._checkedForBackup = false; // Have we checked the server for a backup we can use?
this._sendingBackups = false; // Are we currently sending backups?
this._olmDevice = new OlmDevice(cryptoStore);
this._deviceList = new DeviceList(baseApis, cryptoStore, this._olmDevice);
// the last time we did a check for the number of one-time-keys on the
// server.
this._lastOneTimeKeyCheck = null;
this._oneTimeKeyCheckInProgress = false;
// EncryptionAlgorithm instance for each room
this._roomEncryptors = {};
// map from algorithm to DecryptionAlgorithm instance, for each room
this._roomDecryptors = {};
this._supportedAlgorithms = utils.keys(algorithms.DECRYPTION_CLASSES);
this._deviceKeys = {};
this._globalBlacklistUnverifiedDevices = false;
this._outgoingRoomKeyRequestManager = new _OutgoingRoomKeyRequestManager2.default(baseApis, this._deviceId, this._cryptoStore);
// list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations
// we received in the current sync.
this._receivedRoomKeyRequests = [];
this._receivedRoomKeyRequestCancellations = [];
// true if we are currently processing received room key requests
this._processingRoomKeyRequests = false;
// controls whether device tracking is delayed
// until calling encryptEvent or trackRoomDevices,
// or done immediately upon enabling room encryption.
this._lazyLoadMembers = false;
// in case _lazyLoadMembers is true,
// track if an initial tracking of all the room members
// has happened for a given room. This is delayed
// to avoid loading room members as long as possible.
this._roomDeviceTrackingState = {};
// The timestamp of the last time we forced establishment
// of a new session for each device, in milliseconds.
// {
// userId: {
// deviceId: 1234567890000,
// },
// }
this._lastNewSessionForced = {};
this._verificationTransactions = new Map();
}
utils.inherits(Crypto, _events.EventEmitter);
/**
* Initialise the crypto module so that it is ready for use
*
* Returns a promise which resolves once the crypto module is ready for use.
*/
Crypto.prototype.init = async function () {
_logger2.default.log("Crypto: initialising Olm...");
await global.Olm.init();
_logger2.default.log("Crypto: initialising Olm device...");
await this._olmDevice.init();
_logger2.default.log("Crypto: loading device list...");
await this._deviceList.load();
// build our device keys: these will later be uploaded
this._deviceKeys["ed25519:" + this._deviceId] = this._olmDevice.deviceEd25519Key;
this._deviceKeys["curve25519:" + this._deviceId] = this._olmDevice.deviceCurve25519Key;
_logger2.default.log("Crypto: fetching own devices...");
let myDevices = this._deviceList.getRawStoredDevicesForUser(this._userId);
if (!myDevices) {
myDevices = {};
}
if (!myDevices[this._deviceId]) {
// add our own deviceinfo to the cryptoStore
_logger2.default.log("Crypto: adding this device to the store...");
const deviceInfo = {
keys: this._deviceKeys,
algorithms: this._supportedAlgorithms,
verified: DeviceVerification.VERIFIED,
known: true
};
myDevices[this._deviceId] = deviceInfo;
this._deviceList.storeDevicesForUser(this._userId, myDevices);
this._deviceList.saveIfDirty();
}
_logger2.default.log("Crypto: checking for key backup...");
this._checkAndStartKeyBackup();
};
/**
* Check the server for an active key backup and
* if one is present and has a valid signature from
* one of the user's verified devices, start backing up
* to it.
*/
Crypto.prototype._checkAndStartKeyBackup = async function () {
_logger2.default.log("Checking key backup status...");
if (this._baseApis.isGuest()) {
_logger2.default.log("Skipping key backup check since user is guest");
this._checkedForBackup = true;
return null;
}
let backupInfo;
try {
backupInfo = await this._baseApis.getKeyBackupVersion();
} catch (e) {
_logger2.default.log("Error checking for active key backup", e);
if (e.httpStatus / 100 === 4) {
// well that's told us. we won't try again.
this._checkedForBackup = true;
}
return null;
}
this._checkedForBackup = true;
const trustInfo = await this.isKeyBackupTrusted(backupInfo);
if (trustInfo.usable && !this.backupInfo) {
_logger2.default.log("Found usable key backup v" + backupInfo.version + ": enabling key backups");
this._baseApis.enableKeyBackup(backupInfo);
} else if (!trustInfo.usable && this.backupInfo) {
_logger2.default.log("No usable key backup: disabling key backup");
this._baseApis.disableKeyBackup();
} else if (!trustInfo.usable && !this.backupInfo) {
_logger2.default.log("No usable key backup: not enabling key backup");
} else if (trustInfo.usable && this.backupInfo) {
// may not be the same version: if not, we should switch
if (backupInfo.version !== this.backupInfo.version) {
_logger2.default.log("On backup version " + this.backupInfo.version + " but found " + "version " + backupInfo.version + ": switching.");
this._baseApis.disableKeyBackup();
this._baseApis.enableKeyBackup(backupInfo);
} else {
_logger2.default.log("Backup version " + backupInfo.version + " still current");
}
}
return { backupInfo, trustInfo };
};
Crypto.prototype.setTrustedBackupPubKey = async function (trustedPubKey) {
// This should be redundant post cross-signing is a thing, so just
// plonk it in localStorage for now.
this._sessionStore.setLocalTrustedBackupPubKey(trustedPubKey);
await this.checkKeyBackup();
};
/**
* Forces a re-check of the key backup and enables/disables it
* as appropriate.
*
* @return {Object} Object with backup info (as returned by
* getKeyBackupVersion) in backupInfo and
* trust information (as returned by isKeyBackupTrusted)
* in trustInfo.
*/
Crypto.prototype.checkKeyBackup = async function () {
this._checkedForBackup = false;
const returnInfo = await this._checkAndStartKeyBackup();
return returnInfo;
};
/**
* @param {object} backupInfo key backup info dict from /room_keys/version
* @return {object} {
* usable: [bool], // is the backup trusted, true iff there is a sig that is valid & from a trusted device
* sigs: [
* valid: [bool || null], // true: valid, false: invalid, null: cannot attempt validation
* deviceId: [string],
* device: [DeviceInfo || null],
* ]
* }
*/
Crypto.prototype.isKeyBackupTrusted = async function (backupInfo) {
const ret = {
usable: false,
trusted_locally: false,
sigs: []
};
if (!backupInfo || !backupInfo.algorithm || !backupInfo.auth_data || !backupInfo.auth_data.public_key || !backupInfo.auth_data.signatures) {
_logger2.default.info("Key backup is absent or missing required data");
return ret;
}
const trustedPubkey = this._sessionStore.getLocalTrustedBackupPubKey();
if (backupInfo.auth_data.public_key === trustedPubkey) {
_logger2.default.info("Backup public key " + trustedPubkey + " is trusted locally");
ret.trusted_locally = true;
}
const mySigs = backupInfo.auth_data.signatures[this._userId] || [];
for (const keyId of Object.keys(mySigs)) {
const keyIdParts = keyId.split(':');
if (keyIdParts[0] !== 'ed25519') {
_logger2.default.log("Ignoring unknown signature type: " + keyIdParts[0]);
continue;
}
const sigInfo = { deviceId: keyIdParts[1] }; // XXX: is this how we're supposed to get the device ID?
const device = this._deviceList.getStoredDevice(this._userId, sigInfo.deviceId);
if (device) {
sigInfo.device = device;
try {
await olmlib.verifySignature(this._olmDevice,
// verifySignature modifies the object so we need to copy
// if we verify more than one sig
Object.assign({}, backupInfo.auth_data), this._userId, device.deviceId, device.getFingerprint());
sigInfo.valid = true;
} catch (e) {
_logger2.default.info("Bad signature from key ID " + keyId + " userID " + this._userId + " device ID " + device.deviceId + " fingerprint: " + device.getFingerprint(), backupInfo.auth_data, e);
sigInfo.valid = false;
}
} else {
sigInfo.valid = null; // Can't determine validity because we don't have the signing device
_logger2.default.info("Ignoring signature from unknown key " + keyId);
}
ret.sigs.push(sigInfo);
}
ret.usable = ret.sigs.some(s => s.valid && s.device.isVerified()) || ret.trusted_locally;
return ret;
};
/**
*/
Crypto.prototype.enableLazyLoading = function () {
this._lazyLoadMembers = true;
};
/**
* Tell the crypto module to register for MatrixClient events which it needs to
* listen for
*
* @param {external:EventEmitter} eventEmitter event source where we can register
* for event notifications
*/
Crypto.prototype.registerEventHandlers = function (eventEmitter) {
const crypto = this;
eventEmitter.on("RoomMember.membership", function (event, member, oldMembership) {
try {
crypto._onRoomMembership(event, member, oldMembership);
} catch (e) {
_logger2.default.error("Error handling membership change:", e);
}
});
eventEmitter.on("toDeviceEvent", function (event) {
crypto._onToDeviceEvent(event);
});
};
/** Start background processes related to crypto */
Crypto.prototype.start = function () {
this._outgoingRoomKeyRequestManager.start();
};
/** Stop background processes related to crypto */
Crypto.prototype.stop = function () {
this._outgoingRoomKeyRequestManager.stop();
this._deviceList.stop();
};
/**
* @return {string} The version of Olm.
*/
Crypto.getOlmVersion = function () {
return OlmDevice.getOlmVersion();
};
/**
* Get the Ed25519 key for this device
*
* @return {string} base64-encoded ed25519 key.
*/
Crypto.prototype.getDeviceEd25519Key = function () {
return this._olmDevice.deviceEd25519Key;
};
/**
* Set the global override for whether the client should ever send encrypted
* messages to unverified devices. This provides the default for rooms which
* do not specify a value.
*
* @param {boolean} value whether to blacklist all unverified devices by default
*/
Crypto.prototype.setGlobalBlacklistUnverifiedDevices = function (value) {
this._globalBlacklistUnverifiedDevices = value;
};
/**
* @return {boolean} whether to blacklist all unverified devices by default
*/
Crypto.prototype.getGlobalBlacklistUnverifiedDevices = function () {
return this._globalBlacklistUnverifiedDevices;
};
/**
* Upload the device keys to the homeserver.
* @return {object} A promise that will resolve when the keys are uploaded.
*/
Crypto.prototype.uploadDeviceKeys = function () {
const crypto = this;
const userId = crypto._userId;
const deviceId = crypto._deviceId;
const deviceKeys = {
algorithms: crypto._supportedAlgorithms,
device_id: deviceId,
keys: crypto._deviceKeys,
user_id: userId
};
return crypto._signObject(deviceKeys).then(() => {
crypto._baseApis.uploadKeysRequest({
device_keys: deviceKeys
}, {
// for now, we set the device id explicitly, as we may not be using the
// same one as used in login.
device_id: deviceId
});
});
};
/**
* Stores the current one_time_key count which will be handled later (in a call of
* onSyncCompleted). The count is e.g. coming from a /sync response.
*
* @param {Number} currentCount The current count of one_time_keys to be stored
*/
Crypto.prototype.updateOneTimeKeyCount = function (currentCount) {
if (isFinite(currentCount)) {
this._oneTimeKeyCount = currentCount;
} else {
throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number");
}
};
// check if it's time to upload one-time keys, and do so if so.
function _maybeUploadOneTimeKeys(crypto) {
// frequency with which to check & upload one-time keys
const uploadPeriod = 1000 * 60; // one minute
// max number of keys to upload at once
// Creating keys can be an expensive operation so we limit the
// number we generate in one go to avoid blocking the application
// for too long.
const maxKeysPerCycle = 5;
if (crypto._oneTimeKeyCheckInProgress) {
return;
}
const now = Date.now();
if (crypto._lastOneTimeKeyCheck !== null && now - crypto._lastOneTimeKeyCheck < uploadPeriod) {
// we've done a key upload recently.
return;
}
crypto._lastOneTimeKeyCheck = now;
// We need to keep a pool of one time public keys on the server so that
// other devices can start conversations with us. But we can only store
// a finite number of private keys in the olm Account object.
// To complicate things further then can be a delay between a device
// claiming a public one time key from the server and it sending us a
// message. We need to keep the corresponding private key locally until
// we receive the message.
// But that message might never arrive leaving us stuck with duff
// private keys clogging up our local storage.
// So we need some kind of enginering compromise to balance all of
// these factors.
// Check how many keys we can store in the Account object.
const maxOneTimeKeys = crypto._olmDevice.maxNumberOfOneTimeKeys();
// Try to keep at most half that number on the server. This leaves the
// rest of the slots free to hold keys that have been claimed from the
// server but we haven't recevied a message for.
// If we run out of slots when generating new keys then olm will
// discard the oldest private keys first. This will eventually clean
// out stale private keys that won't receive a message.
const keyLimit = Math.floor(maxOneTimeKeys / 2);
function uploadLoop(keyCount) {
if (keyLimit <= keyCount) {
// If we don't need to generate any more keys then we are done.
return _bluebird2.default.resolve();
}
const keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle);
// Ask olm to generate new one time keys, then upload them to synapse.
return crypto._olmDevice.generateOneTimeKeys(keysThisLoop).then(() => {
return _uploadOneTimeKeys(crypto);
}).then(res => {
if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) {
// if the response contains a more up to date value use this
// for the next loop
return uploadLoop(res.one_time_key_counts.signed_curve25519);
} else {
throw new Error("response for uploading keys does not contain " + "one_time_key_counts.signed_curve25519");
}
});
}
crypto._oneTimeKeyCheckInProgress = true;
_bluebird2.default.resolve().then(() => {
if (crypto._oneTimeKeyCount !== undefined) {
// We already have the current one_time_key count from a /sync response.
// Use this value instead of asking the server for the current key count.
return _bluebird2.default.resolve(crypto._oneTimeKeyCount);
}
// ask the server how many keys we have
return crypto._baseApis.uploadKeysRequest({}, {
device_id: crypto._deviceId
}).then(res => {
return res.one_time_key_counts.signed_curve25519 || 0;
});
}).then(keyCount => {
// Start the uploadLoop with the current keyCount. The function checks if
// we need to upload new keys or not.
// If there are too many keys on the server then we don't need to
// create any more keys.
return uploadLoop(keyCount);
}).catch(e => {
_logger2.default.error("Error uploading one-time keys", e.stack || e);
}).finally(() => {
// reset _oneTimeKeyCount to prevent start uploading based on old data.
// it will be set again on the next /sync-response
crypto._oneTimeKeyCount = undefined;
crypto._oneTimeKeyCheckInProgress = false;
}).done();
}
// returns a promise which resolves to the response
async function _uploadOneTimeKeys(crypto) {
const oneTimeKeys = await crypto._olmDevice.getOneTimeKeys();
const oneTimeJson = {};
const promises = [];
for (const keyId in oneTimeKeys.curve25519) {
if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) {
const k = {
key: oneTimeKeys.curve25519[keyId]
};
oneTimeJson["signed_curve25519:" + keyId] = k;
promises.push(crypto._signObject(k));
}
}
await _bluebird2.default.all(promises);
const res = await crypto._baseApis.uploadKeysRequest({
one_time_keys: oneTimeJson
}, {
// for now, we set the device id explicitly, as we may not be using the
// same one as used in login.
device_id: crypto._deviceId
});
await crypto._olmDevice.markKeysAsPublished();
return res;
}
/**
* Download the keys for a list of users and stores the keys in the session
* store.
* @param {Array} userIds The users to fetch.
* @param {bool} forceDownload Always download the keys even if cached.
*
* @return {Promise} A promise which resolves to a map userId->deviceId->{@link
* module:crypto/deviceinfo|DeviceInfo}.
*/
Crypto.prototype.downloadKeys = function (userIds, forceDownload) {
return this._deviceList.downloadKeys(userIds, forceDownload);
};
/**
* Get the stored device keys for a user id
*
* @param {string} userId the user to list keys for.
*
* @return {module:crypto/deviceinfo[]|null} list of devices, or null if we haven't
* managed to get a list of devices for this user yet.
*/
Crypto.prototype.getStoredDevicesForUser = function (userId) {
return this._deviceList.getStoredDevicesForUser(userId);
};
/**
* Get the stored keys for a single device
*
* @param {string} userId
* @param {string} deviceId
*
* @return {module:crypto/deviceinfo?} device, or undefined
* if we don't know about this device
*/
Crypto.prototype.getStoredDevice = function (userId, deviceId) {
return this._deviceList.getStoredDevice(userId, deviceId);
};
/**
* Save the device list, if necessary
*
* @param {integer} delay Time in ms before which the save actually happens.
* By default, the save is delayed for a short period in order to batch
* multiple writes, but this behaviour can be disabled by passing 0.
*
* @return {Promise<bool>} true if the data was saved, false if
* it was not (eg. because no changes were pending). The promise
* will only resolve once the data is saved, so may take some time
* to resolve.
*/
Crypto.prototype.saveDeviceList = function (delay) {
return this._deviceList.saveIfDirty(delay);
};
/**
* Update the blocked/verified state of the given device
*
* @param {string} userId owner of the device
* @param {string} deviceId unique identifier for the device
*
* @param {?boolean} verified whether to mark the device as verified. Null to
* leave unchanged.
*
* @param {?boolean} blocked whether to mark the device as blocked. Null to
* leave unchanged.
*
* @param {?boolean} known whether to mark that the user has been made aware of
* the existence of this device. Null to leave unchanged
*
* @return {Promise<module:crypto/deviceinfo>} updated DeviceInfo
*/
Crypto.prototype.setDeviceVerification = async function (userId, deviceId, verified, blocked, known) {
const devices = this._deviceList.getRawStoredDevicesForUser(userId);
if (!devices || !devices[deviceId]) {
throw new Error("Unknown device " + userId + ":" + deviceId);
}
const dev = devices[deviceId];
let verificationStatus = dev.verified;
if (verified) {
verificationStatus = DeviceVerification.VERIFIED;
} else if (verified !== null && verificationStatus == DeviceVerification.VERIFIED) {
verificationStatus = DeviceVerification.UNVERIFIED;
}
if (blocked) {
verificationStatus = DeviceVerification.BLOCKED;
} else if (blocked !== null && verificationStatus == DeviceVerification.BLOCKED) {
verificationStatus = DeviceVerification.UNVERIFIED;
}
let knownStatus = dev.known;
if (known !== null && known !== undefined) {
knownStatus = known;
}
if (dev.verified !== verificationStatus || dev.known !== knownStatus) {
dev.verified = verificationStatus;
dev.known = knownStatus;
this._deviceList.storeDevicesForUser(userId, devices);
this._deviceList.saveIfDirty();
}
return DeviceInfo.fromStorage(dev, deviceId);
};
function verificationEventHandler(target, userId, roomId, eventId) {
return function (event) {
// listen for events related to this verification
if (event.getRoomId() !== roomId || event.getSender() !== userId) {
return;
}
const content = event.getContent();
if (!content["m.relates_to"]) {
return;
}
const relatesTo = content["m.relationship"] || content["m.relates_to"];
if (!relatesTo.rel_type || relatesTo.rel_type !== "m.reference" || !relatesTo.event_id || relatesTo.event_id !== eventId) {
return;
}
// the event seems to be related to this verification, so pass it on to
// the verification handler
target.handleEvent(event);
};
}
Crypto.prototype.requestVerificationDM = async function (userId, roomId, methods) {
let methodMap;
if (methods) {
methodMap = new Map();
for (const method of methods) {
if (typeof method === "string") {
methodMap.set(method, defaultVerificationMethods[method]);
} else if (method.NAME) {
methodMap.set(method.NAME, method);
}
}
} else {
methodMap = this._baseApis._crypto._verificationMethods;
}
let eventId = undefined;
const listenPromise = new _bluebird2.default((_resolve, _reject) => {
const listener = event => {
// listen for events related to this verification
if (event.getRoomId() !== roomId || event.getSender() !== userId) {
return;
}
const relatesTo = event.getRelation();
if (!relatesTo || !relatesTo.rel_type || relatesTo.rel_type !== "m.reference" || !relatesTo.event_id || relatesTo.event_id !== eventId) {
return;
}
const content = event.getContent();
// the event seems to be related to this verification
switch (event.getType()) {
case "m.key.verification.start":
{
const verifier = new (methodMap.get(content.method))(this._baseApis, userId, content.from_device, eventId, roomId, event);
verifier.handler = verificationEventHandler(verifier, userId, roomId, eventId);
// this handler gets removed when the verification finishes
// (see the verify method of crypto/verification/Base.js)
this._baseApis.on("event", verifier.handler);
resolve(verifier);
break;
}
case "m.key.verification.cancel":
{
reject(event);
break;
}
}
};
this._baseApis.on("event", listener);
const resolve = (...args) => {
this._baseApis.off("event", listener);
_resolve(...args);
};
const reject = (...args) => {
this._baseApis.off("event", listener);
_reject(...args);
};
});
const res = await this._baseApis.sendEvent(roomId, "m.room.message", {
body: this._baseApis.getUserId() + " is requesting to verify " + "your key, but your client does not support in-chat key " + "verification. You will need to use legacy key " + "verification to verify keys.",
msgtype: "m.key.verification.request",
to: userId,
from_device: this._baseApis.getDeviceId(),
methods: [...methodMap.keys()]
});
eventId = res.event_id;
return listenPromise;
};
Crypto.prototype.acceptVerificationDM = function (event, Method) {
if (typeof Method === "string") {
Method = defaultVerificationMethods[Method];
}
const content = event.getContent();
const verifier = new Method(this._baseApis, event.getSender(), content.from_device, event.getId(), event.getRoomId());
verifier.handler = verificationEventHandler(verifier, event.getSender(), event.getRoomId(), event.getId());
this._baseApis.on("event", verifier.handler);
return verifier;
};
Crypto.prototype.requestVerification = function (userId, methods, devices) {
if (!methods) {
// .keys() returns an iterator, so we need to explicitly turn it into an array
methods = [...this._verificationMethods.keys()];
}
if (!devices) {
devices = Object.keys(this._deviceList.getRawStoredDevicesForUser(userId));
}
if (!this._verificationTransactions.has(userId)) {
this._verificationTransactions.set(userId, new Map());
}
const transactionId = (0, _randomstring.randomString)(32);
const promise = new _bluebird2.default((resolve, reject) => {
this._verificationTransactions.get(userId).set(transactionId, {
request: {
methods: methods,
devices: devices,
resolve: resolve,
reject: reject
}
});
});
const message = {
transaction_id: transactionId,
from_device: this._baseApis.deviceId,
methods: methods,
timestamp: Date.now()
};
const msgMap = {};
for (const deviceId of devices) {
msgMap[deviceId] = message;
}
this._baseApis.sendToDevice("m.key.verification.request", { [userId]: msgMap });
return promise;
};
Crypto.prototype.beginKeyVerification = function (method, userId, deviceId, transactionId) {
if (!this._verificationTransactions.has(userId)) {
this._verificationTransactions.set(userId, new Map());
}
transactionId = transactionId || (0, _randomstring.randomString)(32);
if (this._verificationMethods.has(method)) {
const verifier = new (this._verificationMethods.get(method))(this._baseApis, userId, deviceId, transactionId);
if (!this._verificationTransactions.get(userId).has(transactionId)) {
this._verificationTransactions.get(userId).set(transactionId, {});
}
this._verificationTransactions.get(userId).get(transactionId).verifier = verifier;
return verifier;
} else {
throw (0, _Error.newUnknownMethodError)();
}
};
/**
* Get information on the active olm sessions with a user
* <p>
* Returns a map from device id to an object with keys 'deviceIdKey' (the
* device's curve25519 identity key) and 'sessions' (an array of objects in the
* same format as that returned by
* {@link module:crypto/OlmDevice#getSessionInfoForDevice}).
* <p>
* This method is provided for debugging purposes.
*
* @param {string} userId id of user to inspect
*
* @return {Promise<Object.<string, {deviceIdKey: string, sessions: object[]}>>}
*/
Crypto.prototype.getOlmSessionsForUser = async function (userId) {
const devices = this.getStoredDevicesForUser(userId) || [];
const result = {};
for (let j = 0; j < devices.length; ++j) {
const device = devices[j];
const deviceKey = device.getIdentityKey();
const sessions = await this._olmDevice.getSessionInfoForDevice(deviceKey);
result[device.deviceId] = {
deviceIdKey: deviceKey,
sessions: sessions
};
}
return result;
};
/**
* Get the device which sent an event
*
* @param {module:models/event.MatrixEvent} event event to be checked
*
* @return {module:crypto/deviceinfo?}
*/
Crypto.prototype.getEventSenderDeviceInfo = function (event) {
const senderKey = event.getSenderKey();
const algorithm = event.getWireContent().algorithm;
if (!senderKey || !algorithm) {
return null;
}
const forwardingChain = event.getForwardingCurve25519KeyChain();
if (forwardingChain.length > 0) {
// we got this event from somewhere else
// TODO: check if we can trust the forwarders.
return null;
}
// senderKey is the Curve25519 identity key of the device which the event
// was sent from. In the case of Megolm, it's actually the Curve25519
// identity key of the device which set up the Megolm session.
const device = this._deviceList.getDeviceByIdentityKey(algorithm, senderKey);
if (device === null) {
// we haven't downloaded the details of this device yet.
return null;
}
// so far so good, but now we need to check that the sender of this event
// hadn't advertised someone else's Curve25519 key as their own. We do that
// by checking the Ed25519 claimed by the event (or, in the case of megolm,
// the event which set up the megolm session), to check that it matches the
// fingerprint of the purported sending device.
//
// (see https://github.com/vector-im/vector-web/issues/2215)
const claimedKey = event.getClaimedEd25519Key();
if (!claimedKey) {
_logger2.default.warn("Event " + event.getId() + " claims no ed25519 key: " + "cannot verify sending device");
return null;
}
if (claimedKey !== device.getFingerprint()) {
_logger2.default.warn("Event " + event.getId() + " claims ed25519 key " + claimedKey + "but sender device has key " + device.getFingerprint());
return null;
}
return device;
};
/**
* Forces the current outbound group session to be discarded such
* that another one will be created next time an event is sent.
*
* @param {string} roomId The ID of the room to discard the session for
*
* This should not normally be necessary.
*/
Crypto.prototype.forceDiscardSession = function (roomId) {
const alg = this._roomEncryptors[roomId];
if (alg === undefined) throw new Error("Room not encrypted");
if (alg.forceDiscardSession === undefined) {
throw new Error("Room encryption algorithm doesn't support session discarding");
}
alg.forceDiscardSession();
};
/**
* Configure a room to use encryption (ie, save a flag in the cryptoStore).
*
* @param {string} roomId The room ID to enable encryption in.
*
* @param {object} config The encryption config for the room.
*
* @param {boolean=} inhibitDeviceQuery true to suppress device list query for
* users in the room (for now). In case lazy loading is enabled,