matrix-js-sdk
Version:
Matrix Client-Server SDK for Javascript
1,154 lines (1,083 loc) • 102 kB
JavaScript
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
/*
Copyright 2022-2023 The Matrix.org Foundation C.I.C.
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.
*/
import anotherjson from "another-json";
import * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-wasm";
import { KnownMembership } from "../@types/membership.js";
import { MatrixEventEvent } from "../models/event.js";
import { DecryptionError } from "../common-crypto/CryptoBackend.js";
import { LogSpan } from "../logger.js";
import { Method } from "../http-api/index.js";
import { RoomEncryptor } from "./RoomEncryptor.js";
import { OutgoingRequestProcessor } from "./OutgoingRequestProcessor.js";
import { KeyClaimManager } from "./KeyClaimManager.js";
import { MapWithDefault } from "../utils.js";
import { AllDevicesIsolationMode, CrossSigningKey, CryptoEvent, DecryptionFailureCode, DecryptionKeyDoesNotMatchError, deriveRecoveryKeyFromPassphrase, DeviceIsolationModeKind, DeviceVerificationStatus, encodeRecoveryKey, EventShieldColour, EventShieldReason, ImportRoomKeyStage, UserVerificationStatus } from "../crypto-api/index.js";
import { deviceKeysToDeviceMap, rustDeviceToJsDevice } from "./device-converter.js";
import { SECRET_STORAGE_ALGORITHM_V1_AES } from "../secret-storage.js";
import { CrossSigningIdentity } from "./CrossSigningIdentity.js";
import { secretStorageContainsCrossSigningKeys } from "./secret-storage.js";
import { isVerificationEvent, RustVerificationRequest, verificationMethodIdentifierToMethod } from "./verification.js";
import { EventType, MsgType } from "../@types/event.js";
import { TypedEventEmitter } from "../models/typed-event-emitter.js";
import { decryptionKeyMatchesKeyBackupInfo, RustBackupManager } from "./backup.js";
import { TypedReEmitter } from "../ReEmitter.js";
import { secureRandomString } from "../randomstring.js";
import { ClientStoppedError } from "../errors.js";
import { decodeBase64, encodeBase64 } from "../base64.js";
import { OutgoingRequestsManager } from "./OutgoingRequestsManager.js";
import { PerSessionKeyBackupDownloader } from "./PerSessionKeyBackupDownloader.js";
import { DehydratedDeviceManager } from "./DehydratedDeviceManager.js";
import { VerificationMethod } from "../types.js";
import { keyFromAuthData } from "../common-crypto/key-passphrase.js";
import { getHttpUriForMxc } from "../content-repo.js";
var ALL_VERIFICATION_METHODS = [VerificationMethod.Sas, VerificationMethod.ScanQrCode, VerificationMethod.ShowQrCode, VerificationMethod.Reciprocate];
/** The maximum time, in milliseconds, since we accepted an invite, that we should accept a key bundle. */
export var MAX_INVITE_ACCEPTANCE_MS_FOR_KEY_BUNDLE = 24 * 60 * 60 * 1000; // 24 hours
/**
* An implementation of {@link CryptoBackend} using the Rust matrix-sdk-crypto.
*
* @internal
*/
export class RustCrypto extends TypedEventEmitter {
constructor(logger, /** The `OlmMachine` from the underlying rust crypto sdk. */
olmMachine,
/**
* Low-level HTTP interface: used to make outgoing requests required by the rust SDK.
*
* We expect it to set the access token, etc.
*/
http, /** The local user's User ID. */
userId, /** The local user's Device ID. */
_deviceId, /** Interface to server-side secret storage */
secretStorage, /** Crypto callbacks provided by the application */
cryptoCallbacks) {
var enableEncryptedStateEvents = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : false;
super();
this.logger = logger;
this.olmMachine = olmMachine;
this.http = http;
this.userId = userId;
this.secretStorage = secretStorage;
this.cryptoCallbacks = cryptoCallbacks;
this.enableEncryptedStateEvents = enableEncryptedStateEvents;
/**
* The number of iterations to use when deriving a recovery key from a passphrase.
*/
_defineProperty(this, "RECOVERY_KEY_DERIVATION_ITERATIONS", 500000);
_defineProperty(this, "_trustCrossSignedDevices", true);
_defineProperty(this, "deviceIsolationMode", new AllDevicesIsolationMode(false));
/** whether {@link stop} has been called */
_defineProperty(this, "stopped", false);
/** mapping of roomId → encryptor class */
_defineProperty(this, "roomEncryptors", {});
_defineProperty(this, "eventDecryptor", void 0);
_defineProperty(this, "keyClaimManager", void 0);
_defineProperty(this, "outgoingRequestProcessor", void 0);
_defineProperty(this, "crossSigningIdentity", void 0);
_defineProperty(this, "backupManager", void 0);
_defineProperty(this, "outgoingRequestsManager", void 0);
_defineProperty(this, "perSessionBackupDownloader", void 0);
_defineProperty(this, "dehydratedDeviceManager", void 0);
_defineProperty(this, "reemitter", new TypedReEmitter(this));
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// CryptoApi implementation
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
_defineProperty(this, "globalBlacklistUnverifiedDevices", false);
/**
* The verification methods we offer to the other side during an interactive verification.
*/
_defineProperty(this, "_supportedVerificationMethods", ALL_VERIFICATION_METHODS);
this.outgoingRequestProcessor = new OutgoingRequestProcessor(logger, olmMachine, http);
this.outgoingRequestsManager = new OutgoingRequestsManager(this.logger, olmMachine, this.outgoingRequestProcessor);
this.keyClaimManager = new KeyClaimManager(olmMachine, this.outgoingRequestProcessor);
this.backupManager = new RustBackupManager(logger, olmMachine, http, this.outgoingRequestProcessor);
this.perSessionBackupDownloader = new PerSessionKeyBackupDownloader(this.logger, this.olmMachine, this.http, this.backupManager);
this.dehydratedDeviceManager = new DehydratedDeviceManager(this.logger, olmMachine, http, this.outgoingRequestProcessor, secretStorage);
this.eventDecryptor = new EventDecryptor(this.logger, olmMachine, this.perSessionBackupDownloader);
// re-emit the events emitted by managers
this.reemitter.reEmit(this.backupManager, [CryptoEvent.KeyBackupStatus, CryptoEvent.KeyBackupSessionsRemaining, CryptoEvent.KeyBackupFailed, CryptoEvent.KeyBackupDecryptionKeyCached]);
this.reemitter.reEmit(this.dehydratedDeviceManager, [CryptoEvent.DehydratedDeviceCreated, CryptoEvent.DehydratedDeviceUploaded, CryptoEvent.RehydrationStarted, CryptoEvent.RehydrationProgress, CryptoEvent.RehydrationCompleted, CryptoEvent.RehydrationError, CryptoEvent.DehydrationKeyCached, CryptoEvent.DehydratedDeviceRotationError]);
this.crossSigningIdentity = new CrossSigningIdentity(logger, olmMachine, this.outgoingRequestProcessor, secretStorage);
// Check and start in background the key backup connection
this.checkKeyBackupAndEnable();
}
/**
* Return the OlmMachine only if {@link RustCrypto#stop} has not been called.
*
* This allows us to better handle race conditions where the client is stopped before or during a crypto API call.
*
* @throws ClientStoppedError if {@link RustCrypto#stop} has been called.
*/
getOlmMachineOrThrow() {
if (this.stopped) {
throw new ClientStoppedError();
}
return this.olmMachine;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// CryptoBackend implementation
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
set globalErrorOnUnknownDevices(_v) {
// Not implemented for rust crypto.
}
get globalErrorOnUnknownDevices() {
// Not implemented for rust crypto.
return false;
}
stop() {
// stop() may be called multiple times, but attempting to close() the OlmMachine twice
// will cause an error.
if (this.stopped) {
return;
}
this.stopped = true;
this.keyClaimManager.stop();
this.backupManager.stop();
this.outgoingRequestsManager.stop();
this.perSessionBackupDownloader.stop();
this.dehydratedDeviceManager.stop();
// make sure we close() the OlmMachine; doing so means that all the Rust objects will be
// cleaned up; in particular, the indexeddb connections will be closed, which means they
// can then be deleted.
this.olmMachine.close();
}
encryptEvent(event, _room) {
var _this = this;
return _asyncToGenerator(function* () {
var roomId = event.getRoomId();
var encryptor = _this.roomEncryptors[roomId];
if (!encryptor) {
throw new Error("Cannot encrypt event in unconfigured room ".concat(roomId));
}
yield encryptor.encryptEvent(event, _this.globalBlacklistUnverifiedDevices, _this.deviceIsolationMode);
})();
}
decryptEvent(event) {
var _this2 = this;
return _asyncToGenerator(function* () {
var roomId = event.getRoomId();
if (!roomId) {
// presumably, a to-device message. These are normally decrypted in preprocessToDeviceMessages
// so the fact it has come back here suggests that decryption failed.
//
// once we drop support for the libolm crypto implementation, we can stop passing to-device messages
// through decryptEvent and hence get rid of this case.
throw new Error("to-device event was not decrypted in preprocessToDeviceMessages");
}
return yield _this2.eventDecryptor.attemptEventDecryption(event, _this2.deviceIsolationMode);
})();
}
/**
* Implementation of {@link CryptoBackend#getBackupDecryptor}.
*/
getBackupDecryptor(backupInfo, privKey) {
var _this3 = this;
return _asyncToGenerator(function* () {
if (!(privKey instanceof Uint8Array)) {
throw new Error("getBackupDecryptor: expects Uint8Array");
}
if (backupInfo.algorithm != "m.megolm_backup.v1.curve25519-aes-sha2") {
throw new Error("getBackupDecryptor: Unsupported algorithm ".concat(backupInfo.algorithm));
}
var backupDecryptionKey = RustSdkCryptoJs.BackupDecryptionKey.fromBase64(encodeBase64(privKey));
if (!decryptionKeyMatchesKeyBackupInfo(backupDecryptionKey, backupInfo)) {
throw new Error("getBackupDecryptor: key backup on server does not match the decryption key");
}
return _this3.backupManager.createBackupDecryptor(backupDecryptionKey);
})();
}
/**
* Implementation of {@link CryptoBackend#importBackedUpRoomKeys}.
*/
importBackedUpRoomKeys(keys, backupVersion, opts) {
var _this4 = this;
return _asyncToGenerator(function* () {
return yield _this4.backupManager.importBackedUpRoomKeys(keys, backupVersion, opts);
})();
}
/**
* Implementation of {@link CryptoBackend.maybeAcceptKeyBundle}.
*/
maybeAcceptKeyBundle(roomId, inviter) {
var _this5 = this;
return _asyncToGenerator(function* () {
// TODO: retry this if it gets interrupted or it fails. (https://github.com/matrix-org/matrix-rust-sdk/issues/5112)
// TODO: do this in the background.
var logger = new LogSpan(_this5.logger, "maybeAcceptKeyBundle(".concat(roomId, ", ").concat(inviter, ")"));
// Make sure we have an up-to-date idea of the inviter's cross-signing keys, so that we can check if the
// device that sent us the bundle data was correctly cross-signed.
//
// TODO: it would be nice to skip this step if we have an up-to-date copy of the inviter's cross-signing keys,
// but we don't have an easy way to check that. Possibly the rust side could trigger a key request and then
// block until it happens.
logger.info("Checking inviter cross-signing keys");
var request = _this5.olmMachine.queryKeysForUsers([new RustSdkCryptoJs.UserId(inviter)]);
yield _this5.outgoingRequestProcessor.makeOutgoingRequest(request);
var bundleData = yield _this5.olmMachine.getReceivedRoomKeyBundleData(new RustSdkCryptoJs.RoomId(roomId), new RustSdkCryptoJs.UserId(inviter));
if (!bundleData) {
logger.info("No key bundle found for user");
return false;
}
logger.info("Fetching key bundle ".concat(bundleData.url));
var url = getHttpUriForMxc(_this5.http.opts.baseUrl, bundleData.url, undefined, undefined, undefined, /* allowDirectLinks */false, /* allowRedirects */true, /* useAuthentication */true);
var encryptedBundle;
try {
var bundleUrl = new URL(url);
var encryptedBundleBlob = yield _this5.http.authedRequest(Method.Get, bundleUrl.pathname + bundleUrl.search, {}, undefined, {
rawResponseBody: true,
prefix: ""
});
logger.info("Received blob of length ".concat(encryptedBundleBlob.size));
encryptedBundle = new Uint8Array(yield encryptedBundleBlob.arrayBuffer());
} catch (err) {
logger.warn("Error downloading encrypted bundle from ".concat(url, ":"), err);
throw err;
}
try {
yield _this5.olmMachine.receiveRoomKeyBundle(bundleData, encryptedBundle);
} catch (err) {
logger.warn("Error receiving encrypted bundle:", err);
throw err;
} finally {
// Even if we were unable to import the bundle, we still clear the flag that indicates that we
// are waiting for the bundle to be received. The only reason this can happen is that the bundle was
// malformed somehow, so we don't want to keep retrying it.
yield _this5.olmMachine.clearRoomPendingKeyBundle(new RustSdkCryptoJs.RoomId(roomId));
}
return true;
})();
}
/**
* Implementation of {@link CryptoBackend.markRoomAsPendingKeyBundle}.
*/
markRoomAsPendingKeyBundle(roomId, inviter) {
var _this6 = this;
return _asyncToGenerator(function* () {
yield _this6.olmMachine.storeRoomPendingKeyBundle(new RustSdkCryptoJs.RoomId(roomId), new RustSdkCryptoJs.UserId(inviter));
})();
}
/**
* Implementation of {@link CryptoApi#getVersion}.
*/
getVersion() {
var versions = RustSdkCryptoJs.getVersions();
return "Rust SDK ".concat(versions.matrix_sdk_crypto, " (").concat(versions.git_sha, "), Vodozemac ").concat(versions.vodozemac);
}
/**
* Implementation of {@link CryptoApi#setDeviceIsolationMode}.
*/
setDeviceIsolationMode(isolationMode) {
this.deviceIsolationMode = isolationMode;
}
/**
* Implementation of {@link CryptoApi#isEncryptionEnabledInRoom}.
*/
isEncryptionEnabledInRoom(roomId) {
var _this7 = this;
return _asyncToGenerator(function* () {
var roomSettings = yield _this7.olmMachine.getRoomSettings(new RustSdkCryptoJs.RoomId(roomId));
return Boolean(roomSettings === null || roomSettings === void 0 ? void 0 : roomSettings.algorithm);
})();
}
/**
* Implementation of {@link CryptoApi#isStateEncryptionEnabledInRoom}.
*/
isStateEncryptionEnabledInRoom(roomId) {
var _this8 = this;
return _asyncToGenerator(function* () {
var roomSettings = yield _this8.olmMachine.getRoomSettings(new RustSdkCryptoJs.RoomId(roomId));
return Boolean(roomSettings === null || roomSettings === void 0 ? void 0 : roomSettings.encryptStateEvents);
})();
}
/**
* Implementation of {@link CryptoApi#getOwnDeviceKeys}.
*/
getOwnDeviceKeys() {
var _this9 = this;
return _asyncToGenerator(function* () {
var keys = _this9.olmMachine.identityKeys;
return {
ed25519: keys.ed25519.toBase64(),
curve25519: keys.curve25519.toBase64()
};
})();
}
prepareToEncrypt(room) {
var encryptor = this.roomEncryptors[room.roomId];
if (encryptor) {
encryptor.prepareForEncryption(this.globalBlacklistUnverifiedDevices, this.deviceIsolationMode);
}
}
forceDiscardSession(roomId) {
var _this$roomEncryptors$;
return (_this$roomEncryptors$ = this.roomEncryptors[roomId]) === null || _this$roomEncryptors$ === void 0 ? void 0 : _this$roomEncryptors$.forceDiscardSession();
}
exportRoomKeys() {
var _this0 = this;
return _asyncToGenerator(function* () {
var raw = yield _this0.olmMachine.exportRoomKeys(() => true);
return JSON.parse(raw);
})();
}
exportRoomKeysAsJson() {
var _this1 = this;
return _asyncToGenerator(function* () {
return yield _this1.olmMachine.exportRoomKeys(() => true);
})();
}
importRoomKeys(keys, opts) {
var _this10 = this;
return _asyncToGenerator(function* () {
return yield _this10.backupManager.importRoomKeys(keys, opts);
})();
}
importRoomKeysAsJson(keys, opts) {
var _this11 = this;
return _asyncToGenerator(function* () {
return yield _this11.backupManager.importRoomKeysAsJson(keys, opts);
})();
}
/**
* Implementation of {@link CryptoApi.userHasCrossSigningKeys}.
*/
userHasCrossSigningKeys() {
var _arguments = arguments,
_this12 = this;
return _asyncToGenerator(function* () {
var userId = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : _this12.userId;
var downloadUncached = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : false;
// TODO: could probably do with a more efficient way of doing this than returning the whole set and searching
var rustTrackedUsers = yield _this12.olmMachine.trackedUsers();
var rustTrackedUser;
for (var u of rustTrackedUsers) {
if (userId === u.toString()) {
rustTrackedUser = u;
break;
}
}
if (rustTrackedUser !== undefined) {
if (userId === _this12.userId) {
/* make sure we have an *up-to-date* idea of the user's cross-signing keys. This is important, because if we
* return "false" here, we will end up generating new cross-signing keys and replacing the existing ones.
*/
var request = _this12.olmMachine.queryKeysForUsers(
// clone as rust layer will take ownership and it's reused later
[rustTrackedUser.clone()]);
yield _this12.outgoingRequestProcessor.makeOutgoingRequest(request);
}
var userIdentity = yield _this12.olmMachine.getIdentity(rustTrackedUser);
userIdentity === null || userIdentity === void 0 || userIdentity.free();
return userIdentity !== undefined;
} else if (downloadUncached) {
var _keyResult$master_key;
// Download the cross signing keys and check if the master key is available
var keyResult = yield _this12.downloadDeviceList(new Set([userId]));
var keys = (_keyResult$master_key = keyResult.master_keys) === null || _keyResult$master_key === void 0 ? void 0 : _keyResult$master_key[userId];
// No master key
if (!keys) return false;
// `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }
// We assume only a single key, and we want the bare form without type
// prefix, so we select the values.
return Boolean(Object.values(keys.keys)[0]);
} else {
return false;
}
})();
}
/**
* Get the device information for the given list of users.
*
* @param userIds - The users to fetch.
* @param downloadUncached - If true, download the device list for users whose device list we are not
* currently tracking. Defaults to false, in which case such users will not appear at all in the result map.
*
* @returns A map `{@link DeviceMap}`.
*/
getUserDeviceInfo(userIds) {
var _arguments2 = arguments,
_this13 = this;
return _asyncToGenerator(function* () {
var downloadUncached = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : false;
var deviceMapByUserId = new Map();
var rustTrackedUsers = yield _this13.getOlmMachineOrThrow().trackedUsers();
// Convert RustSdkCryptoJs.UserId to a `Set<string>`
var trackedUsers = new Set();
rustTrackedUsers.forEach(rustUserId => trackedUsers.add(rustUserId.toString()));
// Keep untracked user to download their keys after
var untrackedUsers = new Set();
for (var _userId of userIds) {
// if this is a tracked user, we can just fetch the device list from the rust-sdk
// (NB: this is probably ok even if we race with a leave event such that we stop tracking the user's
// devices: the rust-sdk will return the last-known device list, which will be good enough.)
if (trackedUsers.has(_userId)) {
deviceMapByUserId.set(_userId, yield _this13.getUserDevices(_userId));
} else {
untrackedUsers.add(_userId);
}
}
// for any users whose device lists we are not tracking, fall back to downloading the device list
// over HTTP.
if (downloadUncached && untrackedUsers.size >= 1) {
var queryResult = yield _this13.downloadDeviceList(untrackedUsers);
Object.entries(queryResult.device_keys).forEach(_ref => {
var [userId, deviceKeys] = _ref;
return deviceMapByUserId.set(userId, deviceKeysToDeviceMap(deviceKeys));
});
}
return deviceMapByUserId;
})();
}
/**
* Get the device list for the given user from the olm machine
* @param userId - Rust SDK UserId
*/
getUserDevices(userId) {
var _this14 = this;
return _asyncToGenerator(function* () {
var rustUserId = new RustSdkCryptoJs.UserId(userId);
// For reasons I don't really understand, the Javascript FinalizationRegistry doesn't seem to run the
// registered callbacks when `userDevices` goes out of scope, nor when the individual devices in the array
// returned by `userDevices.devices` do so.
//
// This is particularly problematic, because each of those structures holds a reference to the
// VerificationMachine, which in turn holds a reference to the IndexeddbCryptoStore. Hence, we end up leaking
// open connections to the crypto store, which means the store can't be deleted on logout.
//
// To fix this, we explicitly call `.free` on each of the objects, which tells the rust code to drop the
// allocated memory and decrement the refcounts for the crypto store.
// Wait for up to a second for any in-flight device list requests to complete.
// The reason for this isn't so much to avoid races (some level of raciness is
// inevitable for this method) but to make testing easier.
var userDevices = yield _this14.olmMachine.getUserDevices(rustUserId, 1);
try {
var deviceArray = userDevices.devices();
try {
return new Map(deviceArray.map(device => [device.deviceId.toString(), rustDeviceToJsDevice(device, rustUserId)]));
} finally {
deviceArray.forEach(d => d.free());
}
} finally {
userDevices.free();
}
})();
}
/**
* Download the given user keys by calling `/keys/query` request
* @param untrackedUsers - download keys of these users
*/
downloadDeviceList(untrackedUsers) {
var _this15 = this;
return _asyncToGenerator(function* () {
var queryBody = {
device_keys: {}
};
untrackedUsers.forEach(user => queryBody.device_keys[user] = []);
return yield _this15.http.authedRequest(Method.Post, "/_matrix/client/v3/keys/query", undefined, queryBody, {
prefix: ""
});
})();
}
/**
* Implementation of {@link CryptoApi#getTrustCrossSignedDevices}.
*/
getTrustCrossSignedDevices() {
return this._trustCrossSignedDevices;
}
/**
* Implementation of {@link CryptoApi#setTrustCrossSignedDevices}.
*/
setTrustCrossSignedDevices(val) {
this._trustCrossSignedDevices = val;
// TODO: legacy crypto goes through the list of known devices and emits DeviceVerificationChanged
// events. Maybe we need to do the same?
}
/**
* Mark the given device as locally verified.
*
* Implementation of {@link CryptoApi#setDeviceVerified}.
*/
setDeviceVerified(userId, deviceId) {
var _arguments3 = arguments,
_this16 = this;
return _asyncToGenerator(function* () {
var verified = _arguments3.length > 2 && _arguments3[2] !== undefined ? _arguments3[2] : true;
var device = yield _this16.olmMachine.getDevice(new RustSdkCryptoJs.UserId(userId), new RustSdkCryptoJs.DeviceId(deviceId));
if (!device) {
throw new Error("Unknown device ".concat(userId, "|").concat(deviceId));
}
try {
yield device.setLocalTrust(verified ? RustSdkCryptoJs.LocalTrust.Verified : RustSdkCryptoJs.LocalTrust.Unset);
} finally {
device.free();
}
})();
}
/**
* Blindly cross-sign one of our other devices.
*
* Implementation of {@link CryptoApi#crossSignDevice}.
*/
crossSignDevice(deviceId) {
var _this17 = this;
return _asyncToGenerator(function* () {
var device = yield _this17.olmMachine.getDevice(new RustSdkCryptoJs.UserId(_this17.userId), new RustSdkCryptoJs.DeviceId(deviceId));
if (!device) {
throw new Error("Unknown device ".concat(deviceId));
}
try {
var outgoingRequest = yield device.verify();
yield _this17.outgoingRequestProcessor.makeOutgoingRequest(outgoingRequest);
} finally {
device.free();
}
})();
}
/**
* Implementation of {@link CryptoApi#getDeviceVerificationStatus}.
*/
getDeviceVerificationStatus(userId, deviceId) {
var _this18 = this;
return _asyncToGenerator(function* () {
var device = yield _this18.olmMachine.getDevice(new RustSdkCryptoJs.UserId(userId), new RustSdkCryptoJs.DeviceId(deviceId));
if (!device) return null;
try {
return new DeviceVerificationStatus({
signedByOwner: device.isCrossSignedByOwner(),
crossSigningVerified: device.isCrossSigningTrusted(),
localVerified: device.isLocallyTrusted(),
trustCrossSignedDevices: _this18._trustCrossSignedDevices
});
} finally {
device.free();
}
})();
}
/**
* Implementation of {@link CryptoApi#getUserVerificationStatus}.
*/
getUserVerificationStatus(userId) {
var _this19 = this;
return _asyncToGenerator(function* () {
var userIdentity = yield _this19.getOlmMachineOrThrow().getIdentity(new RustSdkCryptoJs.UserId(userId));
if (userIdentity === undefined) {
return new UserVerificationStatus(false, false, false);
}
var verified = userIdentity.isVerified();
var wasVerified = userIdentity.wasPreviouslyVerified();
var needsUserApproval = userIdentity instanceof RustSdkCryptoJs.OtherUserIdentity ? userIdentity.identityNeedsUserApproval() : false;
userIdentity.free();
return new UserVerificationStatus(verified, wasVerified, false, needsUserApproval);
})();
}
/**
* Implementation of {@link CryptoApi#pinCurrentUserIdentity}.
*/
pinCurrentUserIdentity(userId) {
var _this20 = this;
return _asyncToGenerator(function* () {
var userIdentity = yield _this20.getOlmMachineOrThrow().getIdentity(new RustSdkCryptoJs.UserId(userId));
if (userIdentity === undefined) {
throw new Error("Cannot pin identity of unknown user");
}
if (userIdentity instanceof RustSdkCryptoJs.OwnUserIdentity) {
throw new Error("Cannot pin identity of own user");
}
yield userIdentity.pinCurrentMasterKey();
})();
}
/**
* Implementation of {@link CryptoApi#withdrawVerificationRequirement}.
*/
withdrawVerificationRequirement(userId) {
var _this21 = this;
return _asyncToGenerator(function* () {
var userIdentity = yield _this21.getOlmMachineOrThrow().getIdentity(new RustSdkCryptoJs.UserId(userId));
if (userIdentity === undefined) {
throw new Error("Cannot withdraw verification of unknown user");
}
yield userIdentity.withdrawVerification();
})();
}
/**
* Implementation of {@link CryptoApi#isCrossSigningReady}
*/
isCrossSigningReady() {
var _this22 = this;
return _asyncToGenerator(function* () {
var {
privateKeysInSecretStorage,
privateKeysCachedLocally
} = yield _this22.getCrossSigningStatus();
var hasKeysInCache = Boolean(privateKeysCachedLocally.masterKey) && Boolean(privateKeysCachedLocally.selfSigningKey) && Boolean(privateKeysCachedLocally.userSigningKey);
var identity = yield _this22.getOwnIdentity();
// Cross-signing is ready if the public identity is trusted, and the private keys
// are either cached, or accessible via secret-storage.
return !!(identity !== null && identity !== void 0 && identity.isVerified()) && (hasKeysInCache || privateKeysInSecretStorage);
})();
}
/**
* Implementation of {@link CryptoApi#getCrossSigningKeyId}
*/
getCrossSigningKeyId() {
var _arguments4 = arguments,
_this23 = this;
return _asyncToGenerator(function* () {
var type = _arguments4.length > 0 && _arguments4[0] !== undefined ? _arguments4[0] : CrossSigningKey.Master;
var userIdentity = yield _this23.getOwnIdentity();
if (!userIdentity) {
// The public keys are not available on this device
return null;
}
try {
var crossSigningStatus = yield _this23.olmMachine.crossSigningStatus();
var privateKeysOnDevice = crossSigningStatus.hasMaster && crossSigningStatus.hasUserSigning && crossSigningStatus.hasSelfSigning;
if (!privateKeysOnDevice) {
// The private keys are not available on this device
return null;
}
if (!userIdentity.isVerified()) {
// We have both public and private keys, but they don't match!
return null;
}
var key;
switch (type) {
case CrossSigningKey.Master:
key = userIdentity.masterKey;
break;
case CrossSigningKey.SelfSigning:
key = userIdentity.selfSigningKey;
break;
case CrossSigningKey.UserSigning:
key = userIdentity.userSigningKey;
break;
default:
// Unknown type
return null;
}
var parsedKey = JSON.parse(key);
// `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }
// We assume only a single key, and we want the bare form without type
// prefix, so we select the values.
return Object.values(parsedKey.keys)[0];
} finally {
userIdentity.free();
}
})();
}
/**
* Implementation of {@link CryptoApi#bootstrapCrossSigning}
*/
bootstrapCrossSigning(opts) {
var _this24 = this;
return _asyncToGenerator(function* () {
yield _this24.crossSigningIdentity.bootstrapCrossSigning(opts);
})();
}
/**
* Implementation of {@link CryptoApi#isSecretStorageReady}
*/
isSecretStorageReady() {
var _this25 = this;
return _asyncToGenerator(function* () {
return (yield _this25.getSecretStorageStatus()).ready;
})();
}
/**
* Implementation of {@link CryptoApi#getSecretStorageStatus}
*/
getSecretStorageStatus() {
var _this26 = this;
return _asyncToGenerator(function* () {
// make sure that the cross-signing keys are stored
var secretsToCheck = ["m.cross_signing.master", "m.cross_signing.user_signing", "m.cross_signing.self_signing"];
// If key backup is active, we also need to check that the backup decryption key is stored
var keyBackupEnabled = (yield _this26.backupManager.getActiveBackupVersion()) != null;
if (keyBackupEnabled) {
secretsToCheck.push("m.megolm_backup.v1");
}
var defaultKeyId = yield _this26.secretStorage.getDefaultKeyId();
var result = {
// Assume we have all secrets until proven otherwise
ready: true,
defaultKeyId,
secretStorageKeyValidityMap: {}
};
for (var secretName of secretsToCheck) {
// Check which keys this particular secret is encrypted with
var record = (yield _this26.secretStorage.isStored(secretName)) || {};
// If it's encrypted with the right key, it is valid
var secretStored = !!defaultKeyId && defaultKeyId in record;
result.secretStorageKeyValidityMap[secretName] = secretStored;
result.ready = result.ready && secretStored;
}
return result;
})();
}
/**
* Implementation of {@link CryptoApi#bootstrapSecretStorage}
*/
bootstrapSecretStorage() {
var _arguments5 = arguments,
_this27 = this;
return _asyncToGenerator(function* () {
var {
createSecretStorageKey,
setupNewSecretStorage,
setupNewKeyBackup
} = _arguments5.length > 0 && _arguments5[0] !== undefined ? _arguments5[0] : {};
// If an AES Key is already stored in the secret storage and setupNewSecretStorage is not set
// we don't want to create a new key
var isNewSecretStorageKeyNeeded = setupNewSecretStorage || !(yield _this27.secretStorageHasAESKey());
if (isNewSecretStorageKeyNeeded) {
if (!createSecretStorageKey) {
throw new Error("unable to create a new secret storage key, createSecretStorageKey is not set");
}
// Create a new storage key and add it to secret storage
_this27.logger.info("bootstrapSecretStorage: creating new secret storage key");
var recoveryKey = yield createSecretStorageKey();
if (!recoveryKey) {
throw new Error("createSecretStorageKey() callback did not return a secret storage key");
}
yield _this27.addSecretStorageKeyToSecretStorage(recoveryKey);
}
var crossSigningPrivateKeys = yield _this27.olmMachine.exportCrossSigningKeys();
var hasPrivateKeys = crossSigningPrivateKeys && crossSigningPrivateKeys.masterKey !== undefined && crossSigningPrivateKeys.self_signing_key !== undefined && crossSigningPrivateKeys.userSigningKey !== undefined;
// If we have cross-signing private keys cached, store them in secret
// storage if they are not there already.
if (hasPrivateKeys && (isNewSecretStorageKeyNeeded || !(yield secretStorageContainsCrossSigningKeys(_this27.secretStorage)))) {
_this27.logger.info("bootstrapSecretStorage: cross-signing keys not yet exported; doing so now.");
yield _this27.secretStorage.store("m.cross_signing.master", crossSigningPrivateKeys.masterKey);
yield _this27.secretStorage.store("m.cross_signing.user_signing", crossSigningPrivateKeys.userSigningKey);
yield _this27.secretStorage.store("m.cross_signing.self_signing", crossSigningPrivateKeys.self_signing_key);
}
// likewise with the key backup key: if we have one, store it in secret storage (if it's not already there)
// also don't bother storing it if we're about to set up a new backup
if (!setupNewKeyBackup) {
yield _this27.saveBackupKeyToStorage();
} else {
yield _this27.resetKeyBackup();
}
})();
}
/**
* If we have a backup key for the current, trusted backup in cache,
* save it to secret storage.
*/
saveBackupKeyToStorage() {
var _this28 = this;
return _asyncToGenerator(function* () {
var keyBackupInfo = yield _this28.backupManager.getServerBackupInfo();
if (!keyBackupInfo || !keyBackupInfo.version) {
_this28.logger.info("Not saving backup key to secret storage: no backup info");
return;
}
var backupKeys = yield _this28.olmMachine.getBackupKeys();
if (!backupKeys.decryptionKey) {
_this28.logger.info("Not saving backup key to secret storage: no backup key");
return;
}
if (!decryptionKeyMatchesKeyBackupInfo(backupKeys.decryptionKey, keyBackupInfo)) {
_this28.logger.info("Not saving backup key to secret storage: decryption key does not match backup info");
return;
}
var backupKeyBase64 = backupKeys.decryptionKey.toBase64();
yield _this28.secretStorage.store("m.megolm_backup.v1", backupKeyBase64);
})();
}
/**
* Add the secretStorage key to the secret storage
* - The secret storage key must have the `keyInfo` field filled
* - The secret storage key is set as the default key of the secret storage
* - Call `cryptoCallbacks.cacheSecretStorageKey` when done
*
* @param secretStorageKey - The secret storage key to add in the secret storage.
*/
addSecretStorageKeyToSecretStorage(secretStorageKey) {
var _this29 = this;
return _asyncToGenerator(function* () {
var _secretStorageKey$key, _secretStorageKey$key2, _this29$cryptoCallbac, _this29$cryptoCallbac2;
var secretStorageKeyObject = yield _this29.secretStorage.addKey(SECRET_STORAGE_ALGORITHM_V1_AES, {
passphrase: (_secretStorageKey$key = secretStorageKey.keyInfo) === null || _secretStorageKey$key === void 0 ? void 0 : _secretStorageKey$key.passphrase,
name: (_secretStorageKey$key2 = secretStorageKey.keyInfo) === null || _secretStorageKey$key2 === void 0 ? void 0 : _secretStorageKey$key2.name,
key: secretStorageKey.privateKey
});
yield _this29.secretStorage.setDefaultKeyId(secretStorageKeyObject.keyId);
(_this29$cryptoCallbac = (_this29$cryptoCallbac2 = _this29.cryptoCallbacks).cacheSecretStorageKey) === null || _this29$cryptoCallbac === void 0 || _this29$cryptoCallbac.call(_this29$cryptoCallbac2, secretStorageKeyObject.keyId, secretStorageKeyObject.keyInfo, secretStorageKey.privateKey);
})();
}
/**
* Check if a secret storage AES Key is already added in secret storage
*
* @returns True if an AES key is in the secret storage
*/
secretStorageHasAESKey() {
var _this30 = this;
return _asyncToGenerator(function* () {
// See if we already have an AES secret-storage key.
var secretStorageKeyTuple = yield _this30.secretStorage.getKey();
if (!secretStorageKeyTuple) return false;
var [, keyInfo] = secretStorageKeyTuple;
// Check if the key is an AES key
return keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES;
})();
}
/**
* Implementation of {@link CryptoApi#getCrossSigningStatus}
*/
getCrossSigningStatus() {
var _this31 = this;
return _asyncToGenerator(function* () {
var userIdentity = yield _this31.getOwnIdentity();
var publicKeysOnDevice = Boolean(userIdentity === null || userIdentity === void 0 ? void 0 : userIdentity.masterKey) && Boolean(userIdentity === null || userIdentity === void 0 ? void 0 : userIdentity.selfSigningKey) && Boolean(userIdentity === null || userIdentity === void 0 ? void 0 : userIdentity.userSigningKey);
userIdentity === null || userIdentity === void 0 || userIdentity.free();
var privateKeysInSecretStorage = yield secretStorageContainsCrossSigningKeys(_this31.secretStorage);
var crossSigningStatus = yield _this31.getOlmMachineOrThrow().crossSigningStatus();
return {
publicKeysOnDevice,
privateKeysInSecretStorage,
privateKeysCachedLocally: {
masterKey: Boolean(crossSigningStatus === null || crossSigningStatus === void 0 ? void 0 : crossSigningStatus.hasMaster),
userSigningKey: Boolean(crossSigningStatus === null || crossSigningStatus === void 0 ? void 0 : crossSigningStatus.hasUserSigning),
selfSigningKey: Boolean(crossSigningStatus === null || crossSigningStatus === void 0 ? void 0 : crossSigningStatus.hasSelfSigning)
}
};
})();
}
/**
* Implementation of {@link CryptoApi#createRecoveryKeyFromPassphrase}
*/
createRecoveryKeyFromPassphrase(password) {
var _this32 = this;
return _asyncToGenerator(function* () {
if (password) {
// Generate the key from the passphrase
// first we generate a random salt
var salt = secureRandomString(32);
// then we derive the key from the passphrase
var recoveryKey = yield deriveRecoveryKeyFromPassphrase(password, salt, _this32.RECOVERY_KEY_DERIVATION_ITERATIONS);
return {
keyInfo: {
passphrase: {
algorithm: "m.pbkdf2",
iterations: _this32.RECOVERY_KEY_DERIVATION_ITERATIONS,
salt
}
},
privateKey: recoveryKey,
encodedPrivateKey: encodeRecoveryKey(recoveryKey)
};
} else {
// Using the navigator crypto API to generate the private key
var key = new Uint8Array(32);
globalThis.crypto.getRandomValues(key);
return {
privateKey: key,
encodedPrivateKey: encodeRecoveryKey(key)
};
}
})();
}
/**
* Implementation of {@link CryptoApi#getEncryptionInfoForEvent}.
*/
getEncryptionInfoForEvent(event) {
var _this33 = this;
return _asyncToGenerator(function* () {
return _this33.eventDecryptor.getEncryptionInfoForEvent(event);
})();
}
/**
* Returns to-device verification requests that are already in progress for the given user id.
*
* Implementation of {@link CryptoApi#getVerificationRequestsToDeviceInProgress}
*
* @param userId - the ID of the user to query
*
* @returns the VerificationRequests that are in progress
*/
getVerificationRequestsToDeviceInProgress(userId) {
var requests = this.olmMachine.getVerificationRequests(new RustSdkCryptoJs.UserId(userId));
return requests.filter(request => request.roomId === undefined && !request.isCancelled()).map(request => this.makeVerificationRequest(request));
}
/**
* Finds a DM verification request that is already in progress for the given room id
*
* Implementation of {@link CryptoApi#findVerificationRequestDMInProgress}
*
* @param roomId - the room to use for verification
* @param userId - search the verification request for the given user
*
* @returns the VerificationRequest that is in progress, if any
*
*/
findVerificationRequestDMInProgress(roomId, userId) {
if (!userId) throw new Error("missing userId");
var requests = this.olmMachine.getVerificationRequests(new RustSdkCryptoJs.UserId(userId));
// Search for the verification request for the given room id
var request = requests.find(request => {
var _request$roomId;
return ((_request$roomId = request.roomId) === null || _request$roomId === void 0 ? void 0 : _request$roomId.toString()) === roomId && !request.isCancelled();
});
if (request) {
return this.makeVerificationRequest(request);
}
}
/**
* Implementation of {@link CryptoApi#requestVerificationDM}
*/
requestVerificationDM(userId, roomId) {
var _this34 = this;
return _asyncToGenerator(function* () {
var userIdentity = yield _this34.olmMachine.getIdentity(new RustSdkCryptoJs.UserId(userId));
if (!userIdentity) throw new Error("unknown userId ".concat(userId));
try {
// Transform the verification methods into rust objects
var methods = _this34._supportedVerificationMethods.map(method => verificationMethodIdentifierToMethod(method));
// Get the request content to send to the DM room
var verCont = yield userIdentity.verificationRequestContent(methods);
// TODO: due to https://github.com/matrix-org/matrix-rust-sdk/issues/5643, we need to fix up the verification request content to include `msgtype`.
var verContObj = JSON.parse(verCont);
verContObj["msgtype"] = "m.key.verification.request";
var verificationEventContent = JSON.stringify(verContObj);
// Send the request content to send to the DM room
var eventId = yield _this34.sendVerificationRequestContent(roomId, verificationEventContent);
// Get a verification request
var request = yield userIdentity.requestVerification(new RustSdkCryptoJs.RoomId(roomId), new RustSdkCryptoJs.EventId(eventId), methods);
return _this34.makeVerificationRequest(request);
} finally {
userIdentity.free();
}
})();
}
/**
* Send the verification content to a room
* See https://spec.matrix.org/v1.7/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid
*
* Prefer to use {@link OutgoingRequestProcessor.makeOutgoingRequest} when dealing with {@link RustSdkCryptoJs.RoomMessageRequest}
*
* @param roomId - the targeted room
* @param verificationEventContent - the request body.
*
* @returns the event id
*/
sendVerificationRequestContent(roomId, verificationEventContent) {
var _this35 = this;
return _asyncToGenerator(function* () {
var txId = secureRandomString(32);
// Send the verification request content to the DM room
var {
event_id: eventId
} = yield _this35.http.authedRequest(Method.Put, "/_matrix/client/v3/rooms/".concat(encodeURIComponent(roomId), "/send/m.room.message/").concat(encodeURIComponent(txId)), undefined, verificationEventContent, {
prefix: ""
});
return eventId;
})();
}
/**
* Set the verification methods we offer to the other side during an interactive verification.
*
* If `undefined`, we will offer all the methods supported by the Rust SDK.
*/
setSupportedVerificationMethods(methods) {
// by default, the Rust SDK does not offer `m.qr_code.scan.v1`, but we do want to offer that.
this._supportedVerificationMethods = methods !== null && methods !== void 0 ? methods : ALL_VERIFICATION_METHODS;
}
/**
* Send a verification request to our other devices.
*
* If a verification is already in flight, returns it. Otherwise, initiates a new one.
*
* Implementation of {@link CryptoApi#requestOwnUserVerification}.
*
* @returns a VerificationRequest when the request has been sent to the other party.
*/
requestOwnUserVerification() {
var _this36 = this;
return _asyncToGenerator(function* () {
var userIdentity = yield _this36.getOwnIdentity();
if (userIdentity === undefined) {
throw new Error("cannot request verification for this device when there is no existing cross-signing key");
}
try {
var [request, outgoingRequest] = yield userIdentity.requestVerification(_this36._supportedVerificationMethods.map(verificationMethodIdentifierToMethod));
yield _this36.outgoingRequestProcessor.makeOutgoingRequest(outgoingRequest);
return _this36.makeVerificationRequest(request);
} finally {
userIdentity.free();
}
})();
}
/**
* Request an interactive verification with the given device.
*
* If a verification is already in flight, returns it. Otherwise, initiates a new one.
*
* Implementation of {@link CryptoApi#requestDeviceVerification}.
*
* @param userId - ID of the owner of the device to verify
* @param deviceId - ID of the device to verify
*
* @returns a VerificationRequest when the request has been sent to the other party.
*/
requestDeviceVerification(userId, deviceId) {
var _this37 = this;
return _asyncToGenerator(function* () {
var device = yield _this37.olmMachine.getDevice(new RustSdkCryptoJs.UserId(userId), new RustSdkCryptoJs.DeviceId(deviceId));
if (!device) {
throw new Error("Not a known device");
}
try {
var [request, outgoingRequest] = device.requestVerification(_this37._supportedVerificationMethods.map(verificationMethodIdentifierToMethod));
yield _this37.outgoingRequestProcessor.makeOutgoingRequest(outgoingRequest);
return _this37.makeVerificationRequest(request);
} finally {
device.free();
}
})();
}
/**
* Fetch the backup decryption key we have saved in our store.
*
* Implementation of {@link CryptoApi#getSessionBackupPrivateKey}.
*
* @returns the key, if any, or null
*/
getSessionBackupPrivateKey() {
var _this38 = this;
return _asyncToGenerator(function* () {
var backupKeys = yield _this38.olmMachine.getBackupKeys();
if (!backupKeys.decryptionKey) return null;
return decodeBase64(backupKeys.decryptionKey.toBase64());
})();
}
/**
* Store the backup decryption key.
*
* Implementation of {@link CryptoApi#storeSessionBackupPrivateKey}.
*
* @param key - the backup decryption key
* @param version - the backup version for this key.
*/
storeSessionBackupPrivateKey(key, version) {
var _this39 = this;
return _asyncToGenerator(function* () {
var base64Key = encodeBase64(key);
if (!vers