import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
/*
Copyright 2021 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.
*/

/**
 * Classes for dealing with key backup.
 */

import { MatrixClient } from "../client.js";
import { logger } from "../logger.js";
import { MEGOLM_ALGORITHM, verifySignature } from "./olmlib.js";
import { keyFromPassphrase } from "./key_passphrase.js";
import { encodeUri, safeSet, sleep } from "../utils.js";
import { IndexedDBCryptoStore } from "./store/indexeddb-crypto-store.js";
import { calculateKeyCheck, decryptAES, encryptAES } from "./aes.js";
import { UnstableValue } from "../NamespacedValue.js";
import { CryptoEvent } from "./index.js";
import { ClientPrefix, MatrixError, Method } from "../http-api/index.js";
import { encodeRecoveryKey } from "../crypto-api/index.js";
var KEY_BACKUP_KEYS_PER_REQUEST = 200;
var KEY_BACKUP_CHECK_RATE_LIMIT = 5000; // ms

/** @deprecated Prefer {@link BackupTrustInfo} */

/* eslint-disable camelcase */

/* eslint-enable camelcase */

/** A function used to get the secret key for a backup.
 */

/**
 * Manages the key backup.
 */
export class BackupManager {
  constructor(baseApis, getKey) {
    this.baseApis = baseApis;
    this.getKey = getKey;
    _defineProperty(this, "algorithm", void 0);
    _defineProperty(this, "backupInfo", void 0);
    // The info dict from /room_keys/version
    _defineProperty(this, "checkedForBackup", void 0);
    // Have we checked the server for a backup we can use?
    _defineProperty(this, "sendingBackups", void 0);
    // Are we currently sending backups?
    _defineProperty(this, "sessionLastCheckAttemptedTime", {});
    // When did we last try to check the server for a given session id?
    // The backup manager will schedule backup of keys when active (`scheduleKeyBackupSend`), this allows cancel when client is stopped
    _defineProperty(this, "clientRunning", true);
    this.checkedForBackup = false;
    this.sendingBackups = false;
  }

  /**
   * Stop the backup manager from backing up keys and allow a clean shutdown.
   */
  stop() {
    this.clientRunning = false;
  }
  get version() {
    return this.backupInfo && this.backupInfo.version;
  }

  /**
   * Performs a quick check to ensure that the backup info looks sane.
   *
   * Throws an error if a problem is detected.
   *
   * @param info - the key backup info
   */
  static checkBackupVersion(info) {
    var Algorithm = algorithmsByName[info.algorithm];
    if (!Algorithm) {
      throw new Error("Unknown backup algorithm: " + info.algorithm);
    }
    if (typeof info.auth_data !== "object") {
      throw new Error("Invalid backup data returned");
    }
    return Algorithm.checkBackupVersion(info);
  }
  static makeAlgorithm(info, getKey) {
    var Algorithm = algorithmsByName[info.algorithm];
    if (!Algorithm) {
      throw new Error("Unknown backup algorithm");
    }
    return Algorithm.init(info.auth_data, getKey);
  }
  enableKeyBackup(info) {
    var _this = this;
    return _asyncToGenerator(function* () {
      _this.backupInfo = info;
      if (_this.algorithm) {
        _this.algorithm.free();
      }
      _this.algorithm = yield BackupManager.makeAlgorithm(info, _this.getKey);
      _this.baseApis.emit(CryptoEvent.KeyBackupStatus, true);

      // There may be keys left over from a partially completed backup, so
      // schedule a send to check.
      _this.scheduleKeyBackupSend();
    })();
  }

  /**
   * Disable backing up of keys.
   */
  disableKeyBackup() {
    if (this.algorithm) {
      this.algorithm.free();
    }
    this.algorithm = undefined;
    this.backupInfo = undefined;
    this.baseApis.emit(CryptoEvent.KeyBackupStatus, false);
  }
  getKeyBackupEnabled() {
    if (!this.checkedForBackup) {
      return null;
    }
    return Boolean(this.algorithm);
  }
  prepareKeyBackupVersion(key, algorithm) {
    return _asyncToGenerator(function* () {
      var Algorithm = algorithm ? algorithmsByName[algorithm] : DefaultAlgorithm;
      if (!Algorithm) {
        throw new Error("Unknown backup algorithm");
      }
      var [privateKey, authData] = yield Algorithm.prepare(key);
      var recoveryKey = encodeRecoveryKey(privateKey);
      return {
        algorithm: Algorithm.algorithmName,
        auth_data: authData,
        recovery_key: recoveryKey,
        privateKey
      };
    })();
  }
  createKeyBackupVersion(info) {
    var _this2 = this;
    return _asyncToGenerator(function* () {
      _this2.algorithm = yield BackupManager.makeAlgorithm(info, _this2.getKey);
    })();
  }

  /**
   * Deletes all key backups.
   *
   * Will call the API to delete active backup until there is no more present.
   */
  deleteAllKeyBackupVersions() {
    var _this3 = this;
    return _asyncToGenerator(function* () {
      var _yield$_this3$baseApi, _yield$_this3$baseApi2;
      // there could be several backup versions, delete all to be safe.
      var current = (_yield$_this3$baseApi = (_yield$_this3$baseApi2 = yield _this3.baseApis.getKeyBackupVersion()) === null || _yield$_this3$baseApi2 === void 0 ? void 0 : _yield$_this3$baseApi2.version) !== null && _yield$_this3$baseApi !== void 0 ? _yield$_this3$baseApi : null;
      while (current != null) {
        var _yield$_this3$baseApi3, _yield$_this3$baseApi4;
        yield _this3.deleteKeyBackupVersion(current);
        _this3.disableKeyBackup();
        current = (_yield$_this3$baseApi3 = (_yield$_this3$baseApi4 = yield _this3.baseApis.getKeyBackupVersion()) === null || _yield$_this3$baseApi4 === void 0 ? void 0 : _yield$_this3$baseApi4.version) !== null && _yield$_this3$baseApi3 !== void 0 ? _yield$_this3$baseApi3 : null;
      }
    })();
  }

  /**
   * Deletes the given key backup.
   *
   * @param version - The backup version to delete.
   */
  deleteKeyBackupVersion(version) {
    var _this4 = this;
    return _asyncToGenerator(function* () {
      var path = encodeUri("/room_keys/version/$version", {
        $version: version
      });
      yield _this4.baseApis.http.authedRequest(Method.Delete, path, undefined, undefined, {
        prefix: ClientPrefix.V3
      });
    })();
  }

  /**
   * 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.
   */
  checkAndStart() {
    var _this5 = this;
    return _asyncToGenerator(function* () {
      logger.log("Checking key backup status...");
      if (_this5.baseApis.isGuest()) {
        logger.log("Skipping key backup check since user is guest");
        _this5.checkedForBackup = true;
        return null;
      }
      var backupInfo;
      try {
        var _yield$_this5$baseApi;
        backupInfo = (_yield$_this5$baseApi = yield _this5.baseApis.getKeyBackupVersion()) !== null && _yield$_this5$baseApi !== void 0 ? _yield$_this5$baseApi : undefined;
      } catch (e) {
        logger.log("Error checking for active key backup", e);
        if (e.httpStatus === 404) {
          // 404 is returned when the key backup does not exist, so that
          // counts as successfully checking.
          _this5.checkedForBackup = true;
        }
        return null;
      }
      _this5.checkedForBackup = true;
      var trustInfo = yield _this5.isKeyBackupTrusted(backupInfo);
      if (trustInfo.usable && !_this5.backupInfo) {
        logger.log("Found usable key backup v".concat(backupInfo.version, ": enabling key backups"));
        yield _this5.enableKeyBackup(backupInfo);
      } else if (!trustInfo.usable && _this5.backupInfo) {
        logger.log("No usable key backup: disabling key backup");
        _this5.disableKeyBackup();
      } else if (!trustInfo.usable && !_this5.backupInfo) {
        logger.log("No usable key backup: not enabling key backup");
      } else if (trustInfo.usable && _this5.backupInfo) {
        // may not be the same version: if not, we should switch
        if (backupInfo.version !== _this5.backupInfo.version) {
          logger.log("On backup version ".concat(_this5.backupInfo.version, " but ") + "found version ".concat(backupInfo.version, ": switching."));
          _this5.disableKeyBackup();
          yield _this5.enableKeyBackup(backupInfo);
          // We're now using a new backup, so schedule all the keys we have to be
          // uploaded to the new backup. This is a bit of a workaround to upload
          // keys to a new backup in *most* cases, but it won't cover all cases
          // because we don't remember what backup version we uploaded keys to:
          // see https://github.com/vector-im/element-web/issues/14833
          yield _this5.scheduleAllGroupSessionsForBackup();
        } else {
          logger.log("Backup version ".concat(backupInfo.version, " still current"));
        }
      }
      return {
        backupInfo,
        trustInfo
      };
    })();
  }

  /**
   * Forces a re-check of the key backup and enables/disables it
   * as appropriate.
   *
   * @returns Object with backup info (as returned by
   *     getKeyBackupVersion) in backupInfo and
   *     trust information (as returned by isKeyBackupTrusted)
   *     in trustInfo.
   */
  checkKeyBackup() {
    var _this6 = this;
    return _asyncToGenerator(function* () {
      _this6.checkedForBackup = false;
      return _this6.checkAndStart();
    })();
  }

  /**
   * Attempts to retrieve a session from a key backup, if enough time
   * has elapsed since the last check for this session id.
   */
  queryKeyBackupRateLimited(targetRoomId, targetSessionId) {
    var _this7 = this;
    return _asyncToGenerator(function* () {
      if (!_this7.backupInfo) {
        return;
      }
      var now = new Date().getTime();
      if (!_this7.sessionLastCheckAttemptedTime[targetSessionId] || now - _this7.sessionLastCheckAttemptedTime[targetSessionId] > KEY_BACKUP_CHECK_RATE_LIMIT) {
        _this7.sessionLastCheckAttemptedTime[targetSessionId] = now;
        yield _this7.baseApis.restoreKeyBackupWithCache(targetRoomId, targetSessionId, _this7.backupInfo, {});
      }
    })();
  }

  /**
   * Check if the given backup info is trusted.
   *
   * @param backupInfo - key backup info dict from /room_keys/version
   */
  isKeyBackupTrusted(backupInfo) {
    var _this8 = this;
    return _asyncToGenerator(function* () {
      var ret = {
        usable: false,
        trusted_locally: false,
        sigs: []
      };
      if (!backupInfo || !backupInfo.algorithm || !backupInfo.auth_data || !backupInfo.auth_data.signatures) {
        logger.info("Key backup is absent or missing required data: ".concat(JSON.stringify(backupInfo)));
        return ret;
      }
      var userId = _this8.baseApis.getUserId();
      var privKey = yield _this8.baseApis.crypto.getSessionBackupPrivateKey();
      if (privKey) {
        var algorithm = null;
        try {
          algorithm = yield BackupManager.makeAlgorithm(backupInfo, /*#__PURE__*/_asyncToGenerator(function* () {
            return privKey;
          }));
          if (yield algorithm.keyMatches(privKey)) {
            logger.info("Backup is trusted locally");
            ret.trusted_locally = true;
          }
        } catch (_unused) {
          // do nothing -- if we have an error, then we don't mark it as
          // locally trusted
        } finally {
          var _algorithm;
          (_algorithm = algorithm) === null || _algorithm === void 0 || _algorithm.free();
        }
      }
      var mySigs = backupInfo.auth_data.signatures[userId] || {};
      for (var keyId of Object.keys(mySigs)) {
        var keyIdParts = keyId.split(":");
        if (keyIdParts[0] !== "ed25519") {
          logger.log("Ignoring unknown signature type: " + keyIdParts[0]);
          continue;
        }
        // Could be a cross-signing master key, but just say this is the device
        // ID for backwards compat
        var sigInfo = {
          deviceId: keyIdParts[1]
        };

        // first check to see if it's from our cross-signing key
        var crossSigningId = _this8.baseApis.crypto.crossSigningInfo.getId();
        if (crossSigningId === sigInfo.deviceId) {
          sigInfo.crossSigningId = true;
          try {
            yield verifySignature(_this8.baseApis.crypto.olmDevice, backupInfo.auth_data, userId, sigInfo.deviceId, crossSigningId);
            sigInfo.valid = true;
          } catch (e) {
            logger.warn("Bad signature from cross signing key " + crossSigningId, e);
            sigInfo.valid = false;
          }
          ret.sigs.push(sigInfo);
          continue;
        }

        // Now look for a sig from a device
        // At some point this can probably go away and we'll just support
        // it being signed by the cross-signing master key
        var device = _this8.baseApis.crypto.deviceList.getStoredDevice(userId, sigInfo.deviceId);
        if (device) {
          sigInfo.device = device;
          sigInfo.deviceTrust = _this8.baseApis.checkDeviceTrust(userId, sigInfo.deviceId);
          try {
            yield verifySignature(_this8.baseApis.crypto.olmDevice, backupInfo.auth_data, userId, device.deviceId, device.getFingerprint());
            sigInfo.valid = true;
          } catch (e) {
            logger.info("Bad signature from key ID " + keyId + " userID " + _this8.baseApis.getUserId() + " 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
          logger.info("Ignoring signature from unknown key " + keyId);
        }
        ret.sigs.push(sigInfo);
      }
      ret.usable = ret.sigs.some(s => {
        var _s$deviceTrust;
        return s.valid && (s.device && ((_s$deviceTrust = s.deviceTrust) === null || _s$deviceTrust === void 0 ? void 0 : _s$deviceTrust.isVerified()) || s.crossSigningId);
      });
      return ret;
    })();
  }

  /**
   * Schedules sending all keys waiting to be sent to the backup, if not already
   * scheduled. Retries if necessary.
   *
   * @param maxDelay - Maximum delay to wait in ms. 0 means no delay.
   */
  scheduleKeyBackupSend() {
    var _arguments = arguments,
      _this9 = this;
    return _asyncToGenerator(function* () {
      var maxDelay = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : 10000;
      logger.debug("Key backup: scheduleKeyBackupSend currentSending:".concat(_this9.sendingBackups, " delay:").concat(maxDelay));
      if (_this9.sendingBackups) return;
      _this9.sendingBackups = true;
      try {
        // wait between 0 and `maxDelay` seconds, to avoid backup
        // requests from different clients hitting the server all at
        // the same time when a new key is sent
        var delay = Math.random() * maxDelay;
        yield sleep(delay);
        if (!_this9.clientRunning) {
          _this9.sendingBackups = false;
          return;
        }
        var numFailures = 0; // number of consecutive failures
        for (;;) {
          if (!_this9.algorithm) {
            return;
          }
          try {
            var numBackedUp = yield _this9.backupPendingKeys(KEY_BACKUP_KEYS_PER_REQUEST);
            if (numBackedUp === 0) {
              // no sessions left needing backup: we're done
              _this9.sendingBackups = false;
              return;
            }
            numFailures = 0;
          } catch (err) {
            numFailures++;
            logger.log("Key backup request failed", err);
            if (err instanceof MatrixError) {
              var errCode = err.data.errcode;
              if (errCode == "M_NOT_FOUND" || errCode == "M_WRONG_ROOM_KEYS_VERSION") {
                // Set to false now as `checkKeyBackup` might schedule a backupsend before this one ends.
                _this9.sendingBackups = false;
                // Backup version has changed or this backup version
                // has been deleted
                _this9.baseApis.crypto.emit(CryptoEvent.KeyBackupFailed, errCode);
                // Re-check key backup status on error, so we can be
                // sure to present the current situation when asked.
                // This call might restart the backup loop if new backup version is trusted
                yield _this9.checkKeyBackup();
                return;
              }
            }
          }
          if (numFailures) {
            // exponential backoff if we have failures
            yield sleep(1000 * Math.pow(2, Math.min(numFailures - 1, 4)));
          }
          if (!_this9.clientRunning) {
            logger.debug("Key backup send loop aborted, client stopped");
            _this9.sendingBackups = false;
            return;
          }
        }
      } catch (err) {
        // No one actually checks errors on this promise, it's spawned internally.
        // Just log, apps/client should use events to check status
        logger.log("Backup loop failed ".concat(err));
        _this9.sendingBackups = false;
      }
    })();
  }

  /**
   * Take some e2e keys waiting to be backed up and send them
   * to the backup.
   *
   * @param limit - Maximum number of keys to back up
   * @returns Number of sessions backed up
   */
  backupPendingKeys(limit) {
    var _this10 = this;
    return _asyncToGenerator(function* () {
      var sessions = yield _this10.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(limit);
      if (!sessions.length) {
        return 0;
      }
      var remaining = yield _this10.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();
      _this10.baseApis.crypto.emit(CryptoEvent.KeyBackupSessionsRemaining, remaining);
      var rooms = {};
      for (var session of sessions) {
        var _deviceList$getDevice;
        var roomId = session.sessionData.room_id;
        safeSet(rooms, roomId, rooms[roomId] || {
          sessions: {}
        });
        var sessionData = _this10.baseApis.crypto.olmDevice.exportInboundGroupSession(session.senderKey, session.sessionId, session.sessionData);
        sessionData.algorithm = MEGOLM_ALGORITHM;
        var forwardedCount = (sessionData.forwarding_curve25519_key_chain || []).length;
        var userId = _this10.baseApis.crypto.deviceList.getUserByIdentityKey(MEGOLM_ALGORITHM, session.senderKey);
        var device = (_deviceList$getDevice = _this10.baseApis.crypto.deviceList.getDeviceByIdentityKey(MEGOLM_ALGORITHM, session.senderKey)) !== null && _deviceList$getDevice !== void 0 ? _deviceList$getDevice : undefined;
        var verified = _this10.baseApis.crypto.checkDeviceInfoTrust(userId, device).isVerified();
        safeSet(rooms[roomId]["sessions"], session.sessionId, {
          first_message_index: sessionData.first_known_index,
          forwarded_count: forwardedCount,
          is_verified: verified,
          session_data: yield _this10.algorithm.encryptSession(sessionData)
        });
      }
      yield _this10.baseApis.sendKeyBackup(undefined, undefined, _this10.backupInfo.version, {
        rooms
      });
      yield _this10.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(sessions);
      remaining = yield _this10.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();
      _this10.baseApis.crypto.emit(CryptoEvent.KeyBackupSessionsRemaining, remaining);
      return sessions.length;
    })();
  }
  backupGroupSession(senderKey, sessionId) {
    var _this11 = this;
    return _asyncToGenerator(function* () {
      yield _this11.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{
        senderKey: senderKey,
        sessionId: sessionId
      }]);
      if (_this11.backupInfo) {
        // don't wait for this to complete: it will delay so
        // happens in the background
        _this11.scheduleKeyBackupSend();
      }
      // if this.backupInfo is not set, then the keys will be backed up when
      // this.enableKeyBackup is called
    })();
  }

  /**
   * Marks all group sessions as needing to be backed up and schedules them to
   * upload in the background as soon as possible.
   */
  scheduleAllGroupSessionsForBackup() {
    var _this12 = this;
    return _asyncToGenerator(function* () {
      yield _this12.flagAllGroupSessionsForBackup();

      // Schedule keys to upload in the background as soon as possible.
      _this12.scheduleKeyBackupSend(0 /* maxDelay */);
    })();
  }

  /**
   * Marks all group sessions as needing to be backed up without scheduling
   * them to upload in the background.
   * @returns Promise which resolves to the number of sessions now requiring a backup
   *     (which will be equal to the number of sessions in the store).
   */
  flagAllGroupSessionsForBackup() {
    var _this13 = this;
    return _asyncToGenerator(function* () {
      yield _this13.baseApis.crypto.cryptoStore.doTxn("readwrite", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, IndexedDBCryptoStore.STORE_BACKUP], txn => {
        _this13.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(txn, session => {
          if (session !== null) {
            _this13.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([session], txn);
          }
        });
      });
      var remaining = yield _this13.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();
      _this13.baseApis.emit(CryptoEvent.KeyBackupSessionsRemaining, remaining);
      return remaining;
    })();
  }

  /**
   * Counts the number of end to end session keys that are waiting to be backed up
   * @returns Promise which resolves to the number of sessions requiring backup
   */
  countSessionsNeedingBackup() {
    return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();
  }
}
export class Curve25519 {
  constructor(authData, publicKey,
  // FIXME: PkEncryption
  getKey) {
    this.authData = authData;
    this.publicKey = publicKey;
    this.getKey = getKey;
  }
  static init(authData, getKey) {
    return _asyncToGenerator(function* () {
      if (!authData || !("public_key" in authData)) {
        throw new Error("auth_data missing required information");
      }
      var publicKey = new global.Olm.PkEncryption();
      publicKey.set_recipient_key(authData.public_key);
      return new Curve25519(authData, publicKey, getKey);
    })();
  }
  static prepare(key) {
    return _asyncToGenerator(function* () {
      var decryption = new global.Olm.PkDecryption();
      try {
        var _authData = {};
        if (!key) {
          _authData.public_key = decryption.generate_key();
        } else if (key instanceof Uint8Array) {
          _authData.public_key = decryption.init_with_private_key(key);
        } else {
          var derivation = yield keyFromPassphrase(key);
          _authData.private_key_salt = derivation.salt;
          _authData.private_key_iterations = derivation.iterations;
          _authData.public_key = decryption.init_with_private_key(derivation.key);
        }
        var _publicKey = new global.Olm.PkEncryption();
        _publicKey.set_recipient_key(_authData.public_key);
        return [decryption.get_private_key(), _authData];
      } finally {
        decryption.free();
      }
    })();
  }
  static checkBackupVersion(info) {
    if (!("public_key" in info.auth_data)) {
      throw new Error("Invalid backup data returned");
    }
  }
  get untrusted() {
    return true;
  }
  encryptSession(data) {
    var _this14 = this;
    return _asyncToGenerator(function* () {
      var plainText = Object.assign({}, data);
      delete plainText.session_id;
      delete plainText.room_id;
      delete plainText.first_known_index;
      return _this14.publicKey.encrypt(JSON.stringify(plainText));
    })();
  }
  decryptSessions(sessions) {
    var _this15 = this;
    return _asyncToGenerator(function* () {
      var privKey = yield _this15.getKey();
      var decryption = new global.Olm.PkDecryption();
      try {
        var backupPubKey = decryption.init_with_private_key(privKey);
        if (backupPubKey !== _this15.authData.public_key) {
          throw new MatrixError({
            errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY
          });
        }
        var keys = [];
        for (var [sessionId, sessionData] of Object.entries(sessions)) {
          try {
            var decrypted = JSON.parse(decryption.decrypt(sessionData.session_data.ephemeral, sessionData.session_data.mac, sessionData.session_data.ciphertext));
            decrypted.session_id = sessionId;
            keys.push(decrypted);
          } catch (e) {
            logger.log("Failed to decrypt megolm session from backup", e, sessionData);
          }
        }
        return keys;
      } finally {
        decryption.free();
      }
    })();
  }
  keyMatches(key) {
    var _this16 = this;
    return _asyncToGenerator(function* () {
      var decryption = new global.Olm.PkDecryption();
      var pubKey;
      try {
        pubKey = decryption.init_with_private_key(key);
      } finally {
        decryption.free();
      }
      return pubKey === _this16.authData.public_key;
    })();
  }
  free() {
    this.publicKey.free();
  }
}
_defineProperty(Curve25519, "algorithmName", "m.megolm_backup.v1.curve25519-aes-sha2");
function randomBytes(size) {
  var buf = new Uint8Array(size);
  globalThis.crypto.getRandomValues(buf);
  return buf;
}
var UNSTABLE_MSC3270_NAME = new UnstableValue("m.megolm_backup.v1.aes-hmac-sha2", "org.matrix.msc3270.v1.aes-hmac-sha2");
export class Aes256 {
  constructor(authData, key) {
    this.authData = authData;
    this.key = key;
  }
  static init(authData, getKey) {
    return _asyncToGenerator(function* () {
      if (!authData) {
        throw new Error("auth_data missing");
      }
      var key = yield getKey();
      if (authData.mac) {
        var {
          mac
        } = yield calculateKeyCheck(key, authData.iv);
        if (authData.mac.replace(/=+$/g, "") !== mac.replace(/=+/g, "")) {
          throw new Error("Key does not match");
        }
      }
      return new Aes256(authData, key);
    })();
  }
  static prepare(key) {
    return _asyncToGenerator(function* () {
      var outKey;
      var authData = {};
      if (!key) {
        outKey = randomBytes(32);
      } else if (key instanceof Uint8Array) {
        outKey = new Uint8Array(key);
      } else {
        var derivation = yield keyFromPassphrase(key);
        authData.private_key_salt = derivation.salt;
        authData.private_key_iterations = derivation.iterations;
        outKey = derivation.key;
      }
      var {
        iv,
        mac
      } = yield calculateKeyCheck(outKey);
      authData.iv = iv;
      authData.mac = mac;
      return [outKey, authData];
    })();
  }
  static checkBackupVersion(info) {
    if (!("iv" in info.auth_data && "mac" in info.auth_data)) {
      throw new Error("Invalid backup data returned");
    }
  }
  get untrusted() {
    return false;
  }
  encryptSession(data) {
    var plainText = Object.assign({}, data);
    delete plainText.session_id;
    delete plainText.room_id;
    delete plainText.first_known_index;
    return encryptAES(JSON.stringify(plainText), this.key, data.session_id);
  }
  decryptSessions(sessions) {
    var _this17 = this;
    return _asyncToGenerator(function* () {
      var keys = [];
      for (var [sessionId, sessionData] of Object.entries(sessions)) {
        try {
          var decrypted = JSON.parse(yield decryptAES(sessionData.session_data, _this17.key, sessionId));
          decrypted.session_id = sessionId;
          keys.push(decrypted);
        } catch (e) {
          logger.log("Failed to decrypt megolm session from backup", e, sessionData);
        }
      }
      return keys;
    })();
  }
  keyMatches(key) {
    var _this18 = this;
    return _asyncToGenerator(function* () {
      if (_this18.authData.mac) {
        var {
          mac
        } = yield calculateKeyCheck(key, _this18.authData.iv);
        return _this18.authData.mac.replace(/=+$/g, "") === mac.replace(/=+/g, "");
      } else {
        // if we have no information, we have to assume the key is right
        return true;
      }
    })();
  }
  free() {
    this.key.fill(0);
  }
}
_defineProperty(Aes256, "algorithmName", UNSTABLE_MSC3270_NAME.name);
export var algorithmsByName = {
  [Curve25519.algorithmName]: Curve25519,
  [Aes256.algorithmName]: Aes256
};

// the linter doesn't like this but knip does
// eslint-disable-next-line tsdoc/syntax
/** @alias */
export var DefaultAlgorithm = Curve25519;

/**
 * Map a legacy {@link TrustInfo} into a new-style {@link BackupTrustInfo}.
 *
 * @param trustInfo - trustInfo to convert
 */
export function backupTrustInfoFromLegacyTrustInfo(trustInfo) {
  var _trustInfo$trusted_lo;
  return {
    trusted: trustInfo.usable,
    matchesDecryptionKey: (_trustInfo$trusted_lo = trustInfo.trusted_locally) !== null && _trustInfo$trusted_lo !== void 0 ? _trustInfo$trusted_lo : false
  };
}

/**
 * Implementation of {@link BackupDecryptor} for the libolm crypto backend.
 */
export class LibOlmBackupDecryptor {
  constructor(algorithm) {
    _defineProperty(this, "algorithm", void 0);
    _defineProperty(this, "sourceTrusted", void 0);
    this.algorithm = algorithm;
    this.sourceTrusted = !algorithm.untrusted;
  }

  /**
   * Implements {@link BackupDecryptor#free}
   */
  free() {
    this.algorithm.free();
  }

  /**
   * Implements {@link BackupDecryptor#decryptSessions}
   */
  decryptSessions(sessions) {
    var _this19 = this;
    return _asyncToGenerator(function* () {
      return yield _this19.algorithm.decryptSessions(sessions);
    })();
  }
}
//# sourceMappingURL=backup.js.map