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 2015 - 2021, 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.
*/

/**
 * Defines m.olm encryption/decryption
 */

import { v4 as uuidv4 } from "uuid";
import { logger } from "../../logger.js";
import * as olmlib from "../olmlib.js";
import { DecryptionAlgorithm, EncryptionAlgorithm, registerAlgorithm, UnknownDeviceError } from "./base.js";
import { WITHHELD_MESSAGES } from "../OlmDevice.js";
import { EventType, MsgType, ToDeviceMessageId } from "../../@types/event.js";
import { RoomKeyRequestState } from "../OutgoingRoomKeyRequestManager.js";
import { immediate, MapWithDefault } from "../../utils.js";
import { KnownMembership } from "../../@types/membership.js";
import { DecryptionFailureCode } from "../../crypto-api/index.js";
import { DecryptionError } from "../../common-crypto/CryptoBackend.js";

// determine whether the key can be shared with invitees
export function isRoomSharedHistory(room) {
  var _room$currentState, _visibilityEvent$getC;
  var visibilityEvent = room === null || room === void 0 || (_room$currentState = room.currentState) === null || _room$currentState === void 0 ? void 0 : _room$currentState.getStateEvents("m.room.history_visibility", "");
  // NOTE: if the room visibility is unset, it would normally default to
  // "world_readable".
  // (https://spec.matrix.org/unstable/client-server-api/#server-behaviour-5)
  // But we will be paranoid here, and treat it as a situation where the room
  // is not shared-history
  var visibility = visibilityEvent === null || visibilityEvent === void 0 || (_visibilityEvent$getC = visibilityEvent.getContent()) === null || _visibilityEvent$getC === void 0 ? void 0 : _visibilityEvent$getC.history_visibility;
  return ["world_readable", "shared"].includes(visibility);
}

// map user Id → device Id → IBlockedDevice

/**
 * Tests whether an encrypted content has a ciphertext.
 * Ciphertext can be a string or object depending on the content type {@link IEncryptedContent}.
 *
 * @param content - Encrypted content
 * @returns true: has ciphertext, else false
 */
var hasCiphertext = content => {
  return typeof content.ciphertext === "string" ? !!content.ciphertext.length : !!Object.keys(content.ciphertext).length;
};

/** The result of parsing the an `m.room_key` or `m.forwarded_room_key` to-device event */

/**
 * @internal
 */
class OutboundSessionInfo {
  /**
   * @param sharedHistory - whether the session can be freely shared with
   *    other group members, according to the room history visibility settings
   */
  constructor(sessionId) {
    var sharedHistory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    this.sessionId = sessionId;
    this.sharedHistory = sharedHistory;
    /** number of times this session has been used */
    _defineProperty(this, "useCount", 0);
    /** when the session was created (ms since the epoch) */
    _defineProperty(this, "creationTime", void 0);
    /** devices with which we have shared the session key `userId -> {deviceId -> SharedWithData}` */
    _defineProperty(this, "sharedWithDevices", new MapWithDefault(() => new Map()));
    _defineProperty(this, "blockedDevicesNotified", new MapWithDefault(() => new Map()));
    this.creationTime = new Date().getTime();
  }

  /**
   * Check if it's time to rotate the session
   */
  needsRotation(rotationPeriodMsgs, rotationPeriodMs) {
    var sessionLifetime = new Date().getTime() - this.creationTime;
    if (this.useCount >= rotationPeriodMsgs || sessionLifetime >= rotationPeriodMs) {
      logger.log("Rotating megolm session after " + this.useCount + " messages, " + sessionLifetime + "ms");
      return true;
    }
    return false;
  }
  markSharedWithDevice(userId, deviceId, deviceKey, chainIndex) {
    this.sharedWithDevices.getOrCreate(userId).set(deviceId, {
      deviceKey,
      messageIndex: chainIndex
    });
  }
  markNotifiedBlockedDevice(userId, deviceId) {
    this.blockedDevicesNotified.getOrCreate(userId).set(deviceId, true);
  }

  /**
   * Determine if this session has been shared with devices which it shouldn't
   * have been.
   *
   * @param devicesInRoom - `userId -> {deviceId -> object}`
   *   devices we should shared the session with.
   *
   * @returns true if we have shared the session with devices which aren't
   * in devicesInRoom.
   */
  sharedWithTooManyDevices(devicesInRoom) {
    for (var [userId, devices] of this.sharedWithDevices) {
      if (!devicesInRoom.has(userId)) {
        logger.log("Starting new megolm session because we shared with " + userId);
        return true;
      }
      for (var [deviceId] of devices) {
        var _devicesInRoom$get;
        if (!((_devicesInRoom$get = devicesInRoom.get(userId)) !== null && _devicesInRoom$get !== void 0 && _devicesInRoom$get.get(deviceId))) {
          logger.log("Starting new megolm session because we shared with " + userId + ":" + deviceId);
          return true;
        }
      }
    }
    return false;
  }
}

/**
 * Megolm encryption implementation
 *
 * @param params - parameters, as per {@link EncryptionAlgorithm}
 */
export class MegolmEncryption extends EncryptionAlgorithm {
  constructor(params) {
    var _params$config$rotati, _params$config, _params$config$rotati2, _params$config2;
    super(params);
    // the most recent attempt to set up a session. This is used to serialise
    // the session setups, so that we have a race-free view of which session we
    // are using, and which devices we have shared the keys with. It resolves
    // with an OutboundSessionInfo (or undefined, for the first message in the
    // room).
    _defineProperty(this, "setupPromise", Promise.resolve(null));
    // Map of outbound sessions by sessions ID. Used if we need a particular
    // session (the session we're currently using to send is always obtained
    // using setupPromise).
    _defineProperty(this, "outboundSessions", {});
    _defineProperty(this, "sessionRotationPeriodMsgs", void 0);
    _defineProperty(this, "sessionRotationPeriodMs", void 0);
    _defineProperty(this, "encryptionPreparation", void 0);
    _defineProperty(this, "roomId", void 0);
    _defineProperty(this, "prefixedLogger", void 0);
    this.roomId = params.roomId;
    this.prefixedLogger = logger.getChild("[".concat(this.roomId, " encryption]"));
    this.sessionRotationPeriodMsgs = (_params$config$rotati = (_params$config = params.config) === null || _params$config === void 0 ? void 0 : _params$config.rotation_period_msgs) !== null && _params$config$rotati !== void 0 ? _params$config$rotati : 100;
    this.sessionRotationPeriodMs = (_params$config$rotati2 = (_params$config2 = params.config) === null || _params$config2 === void 0 ? void 0 : _params$config2.rotation_period_ms) !== null && _params$config$rotati2 !== void 0 ? _params$config$rotati2 : 7 * 24 * 3600 * 1000;
  }

  /**
   * @internal
   *
   * @param devicesInRoom - The devices in this room, indexed by user ID
   * @param blocked - The devices that are blocked, indexed by user ID
   * @param singleOlmCreationPhase - Only perform one round of olm
   *     session creation
   *
   * This method updates the setupPromise field of the class by chaining a new
   * call on top of the existing promise, and then catching and discarding any
   * errors that might happen while setting up the outbound group session. This
   * is done to ensure that `setupPromise` always resolves to `null` or the
   * `OutboundSessionInfo`.
   *
   * Using `>>=` to represent the promise chaining operation, it does the
   * following:
   *
   * ```
   * setupPromise = previousSetupPromise >>= setup >>= discardErrors
   * ```
   *
   * The initial value for the `setupPromise` is a promise that resolves to
   * `null`. The forceDiscardSession() resets setupPromise to this initial
   * promise.
   *
   * @returns Promise which resolves to the
   *    OutboundSessionInfo when setup is complete.
   */
  ensureOutboundSession(room, devicesInRoom, blocked) {
    var _arguments = arguments,
      _this = this;
    return _asyncToGenerator(function* () {
      var singleOlmCreationPhase = _arguments.length > 3 && _arguments[3] !== undefined ? _arguments[3] : false;
      // takes the previous OutboundSessionInfo, and considers whether to create
      // a new one. Also shares the key with any (new) devices in the room.
      //
      // returns a promise which resolves once the keyshare is successful.
      var setup = /*#__PURE__*/function () {
        var _ref = _asyncToGenerator(function* (oldSession) {
          var sharedHistory = isRoomSharedHistory(room);
          var session = yield _this.prepareSession(devicesInRoom, sharedHistory, oldSession);
          yield _this.shareSession(devicesInRoom, sharedHistory, singleOlmCreationPhase, blocked, session);
          return session;
        });
        return function setup(_x) {
          return _ref.apply(this, arguments);
        };
      }();

      // first wait for the previous share to complete
      var fallible = _this.setupPromise.then(setup);

      // Ensure any failures are logged for debugging and make sure that the
      // promise chain remains unbroken
      //
      // setupPromise resolves to `null` or the `OutboundSessionInfo` whether
      // or not the share succeeds
      _this.setupPromise = fallible.catch(e => {
        _this.prefixedLogger.error("Failed to setup outbound session", e);
        return null;
      });

      // but we return a promise which only resolves if the share was successful.
      return fallible;
    })();
  }
  prepareSession(devicesInRoom, sharedHistory, session) {
    var _this2 = this;
    return _asyncToGenerator(function* () {
      var _session, _session2;
      // history visibility changed
      if (session && sharedHistory !== session.sharedHistory) {
        session = null;
      }

      // need to make a brand new session?
      if ((_session = session) !== null && _session !== void 0 && _session.needsRotation(_this2.sessionRotationPeriodMsgs, _this2.sessionRotationPeriodMs)) {
        _this2.prefixedLogger.debug("Starting new megolm session because we need to rotate.");
        session = null;
      }

      // determine if we have shared with anyone we shouldn't have
      if ((_session2 = session) !== null && _session2 !== void 0 && _session2.sharedWithTooManyDevices(devicesInRoom)) {
        session = null;
      }
      if (!session) {
        _this2.prefixedLogger.debug("Starting new megolm session");
        session = yield _this2.prepareNewSession(sharedHistory);
        _this2.prefixedLogger.debug("Started new megolm session ".concat(session.sessionId));
        _this2.outboundSessions[session.sessionId] = session;
      }
      return session;
    })();
  }
  shareSession(devicesInRoom, sharedHistory, singleOlmCreationPhase, blocked, session) {
    var _this3 = this;
    return _asyncToGenerator(function* () {
      // now check if we need to share with any devices
      var shareMap = {};
      for (var [userId, userDevices] of devicesInRoom) {
        for (var [deviceId, deviceInfo] of userDevices) {
          var _session$sharedWithDe;
          var _key = deviceInfo.getIdentityKey();
          if (_key == _this3.olmDevice.deviceCurve25519Key) {
            // don't bother sending to ourself
            continue;
          }
          if (!((_session$sharedWithDe = session.sharedWithDevices.get(userId)) !== null && _session$sharedWithDe !== void 0 && _session$sharedWithDe.get(deviceId))) {
            shareMap[userId] = shareMap[userId] || [];
            shareMap[userId].push(deviceInfo);
          }
        }
      }
      var key = _this3.olmDevice.getOutboundGroupSessionKey(session.sessionId);
      var payload = {
        type: "m.room_key",
        content: {
          "algorithm": olmlib.MEGOLM_ALGORITHM,
          "room_id": _this3.roomId,
          "session_id": session.sessionId,
          "session_key": key.key,
          "chain_index": key.chain_index,
          "org.matrix.msc3061.shared_history": sharedHistory
        }
      };
      var [devicesWithoutSession, olmSessions] = yield olmlib.getExistingOlmSessions(_this3.olmDevice, _this3.baseApis, shareMap);
      yield Promise.all([_asyncToGenerator(function* () {
        // share keys with devices that we already have a session for
        var olmSessionList = Array.from(olmSessions.entries()).map(_ref3 => {
          var [userId, sessionsByUser] = _ref3;
          return Array.from(sessionsByUser.entries()).map(_ref4 => {
            var [deviceId, session] = _ref4;
            return "".concat(userId, "/").concat(deviceId, ": ").concat(session.sessionId);
          });
        }).flat(1);
        _this3.prefixedLogger.debug("Sharing keys with devices with existing Olm sessions:", olmSessionList);
        yield _this3.shareKeyWithOlmSessions(session, key, payload, olmSessions);
        _this3.prefixedLogger.debug("Shared keys with existing Olm sessions");
      })(), _asyncToGenerator(function* () {
        var deviceList = Array.from(devicesWithoutSession.entries()).map(_ref6 => {
          var [userId, devicesByUser] = _ref6;
          return devicesByUser.map(device => "".concat(userId, "/").concat(device.deviceId));
        }).flat(1);
        _this3.prefixedLogger.debug("Sharing keys (start phase 1) with devices without existing Olm sessions:", deviceList);
        var errorDevices = [];

        // meanwhile, establish olm sessions for devices that we don't
        // already have a session for, and share keys with them.  If
        // we're doing two phases of olm session creation, use a
        // shorter timeout when fetching one-time keys for the first
        // phase.
        var start = Date.now();
        var failedServers = [];
        yield _this3.shareKeyWithDevices(session, key, payload, devicesWithoutSession, errorDevices, singleOlmCreationPhase ? 10000 : 2000, failedServers);
        _this3.prefixedLogger.debug("Shared keys (end phase 1) with devices without existing Olm sessions");
        if (!singleOlmCreationPhase && Date.now() - start < 10000) {
          // perform the second phase of olm session creation if requested,
          // and if the first phase didn't take too long
          _asyncToGenerator(function* () {
            // Retry sending keys to devices that we were unable to establish
            // an olm session for.  This time, we use a longer timeout, but we
            // do this in the background and don't block anything else while we
            // do this.  We only need to retry users from servers that didn't
            // respond the first time.
            var retryDevices = new MapWithDefault(() => []);
            var failedServerMap = new Set();
            for (var server of failedServers) {
              failedServerMap.add(server);
            }
            var failedDevices = [];
            for (var {
              userId: _userId,
              deviceInfo: _deviceInfo2
            } of errorDevices) {
              var userHS = _userId.slice(_userId.indexOf(":") + 1);
              if (failedServerMap.has(userHS)) {
                retryDevices.getOrCreate(_userId).push(_deviceInfo2);
              } else {
                // if we aren't going to retry, then handle it
                // as a failed device
                failedDevices.push({
                  userId: _userId,
                  deviceInfo: _deviceInfo2
                });
              }
            }
            var retryDeviceList = Array.from(retryDevices.entries()).map(_ref8 => {
              var [userId, devicesByUser] = _ref8;
              return devicesByUser.map(device => "".concat(userId, "/").concat(device.deviceId));
            }).flat(1);
            if (retryDeviceList.length > 0) {
              _this3.prefixedLogger.debug("Sharing keys (start phase 2) with devices without existing Olm sessions:", retryDeviceList);
              yield _this3.shareKeyWithDevices(session, key, payload, retryDevices, failedDevices, 30000);
              _this3.prefixedLogger.debug("Shared keys (end phase 2) with devices without existing Olm sessions");
            }
            yield _this3.notifyFailedOlmDevices(session, key, failedDevices);
          })();
        } else {
          yield _this3.notifyFailedOlmDevices(session, key, errorDevices);
        }
      })(), _asyncToGenerator(function* () {
        _this3.prefixedLogger.debug("There are ".concat(blocked.size, " blocked devices:"), Array.from(blocked.entries()).map(_ref10 => {
          var [userId, blockedByUser] = _ref10;
          return Array.from(blockedByUser.entries()).map(_ref11 => {
            var [deviceId, _deviceInfo] = _ref11;
            return "".concat(userId, "/").concat(deviceId);
          });
        }).flat(1));

        // also, notify newly blocked devices that they're blocked
        var blockedMap = new MapWithDefault(() => new Map());
        var blockedCount = 0;
        for (var [_userId2, userBlockedDevices] of blocked) {
          for (var [_deviceId, device] of userBlockedDevices) {
            var _session$blockedDevic;
            if (((_session$blockedDevic = session.blockedDevicesNotified.get(_userId2)) === null || _session$blockedDevic === void 0 ? void 0 : _session$blockedDevic.get(_deviceId)) === undefined) {
              blockedMap.getOrCreate(_userId2).set(_deviceId, {
                device
              });
              blockedCount++;
            }
          }
        }
        if (blockedCount) {
          _this3.prefixedLogger.debug("Notifying ".concat(blockedCount, " newly blocked devices:"), Array.from(blockedMap.entries()).map(_ref12 => {
            var [userId, blockedByUser] = _ref12;
            return Object.entries(blockedByUser).map(_ref13 => {
              var [deviceId, _deviceInfo] = _ref13;
              return "".concat(userId, "/").concat(deviceId);
            });
          }).flat(1));
          yield _this3.notifyBlockedDevices(session, blockedMap);
          _this3.prefixedLogger.debug("Notified ".concat(blockedCount, " newly blocked devices"));
        }
      })()]);
    })();
  }

  /**
   * @internal
   *
   *
   * @returns session
   */
  prepareNewSession(sharedHistory) {
    var _this4 = this;
    return _asyncToGenerator(function* () {
      var sessionId = _this4.olmDevice.createOutboundGroupSession();
      var key = _this4.olmDevice.getOutboundGroupSessionKey(sessionId);
      yield _this4.olmDevice.addInboundGroupSession(_this4.roomId, _this4.olmDevice.deviceCurve25519Key, [], sessionId, key.key, {
        ed25519: _this4.olmDevice.deviceEd25519Key
      }, false, {
        sharedHistory
      });

      // don't wait for it to complete
      _this4.crypto.backupManager.backupGroupSession(_this4.olmDevice.deviceCurve25519Key, sessionId);
      return new OutboundSessionInfo(sessionId, sharedHistory);
    })();
  }

  /**
   * Determines what devices in devicesByUser don't have an olm session as given
   * in devicemap.
   *
   * @internal
   *
   * @param deviceMap - the devices that have olm sessions, as returned by
   *     olmlib.ensureOlmSessionsForDevices.
   * @param devicesByUser - a map of user IDs to array of deviceInfo
   * @param noOlmDevices - an array to fill with devices that don't have
   *     olm sessions
   *
   * @returns an array of devices that don't have olm sessions.  If
   *     noOlmDevices is specified, then noOlmDevices will be returned.
   */
  getDevicesWithoutSessions(deviceMap, devicesByUser) {
    var noOlmDevices = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
    for (var [userId, devicesToShareWith] of devicesByUser) {
      var sessionResults = deviceMap.get(userId);
      for (var deviceInfo of devicesToShareWith) {
        var deviceId = deviceInfo.deviceId;
        var sessionResult = sessionResults === null || sessionResults === void 0 ? void 0 : sessionResults.get(deviceId);
        if (!(sessionResult !== null && sessionResult !== void 0 && sessionResult.sessionId)) {
          // no session with this device, probably because there
          // were no one-time keys.

          noOlmDevices.push({
            userId,
            deviceInfo
          });
          sessionResults === null || sessionResults === void 0 || sessionResults.delete(deviceId);

          // ensureOlmSessionsForUsers has already done the logging,
          // so just skip it.
          continue;
        }
      }
    }
    return noOlmDevices;
  }

  /**
   * Splits the user device map into multiple chunks to reduce the number of
   * devices we encrypt to per API call.
   *
   * @internal
   *
   * @param devicesByUser - map from userid to list of devices
   *
   * @returns the blocked devices, split into chunks
   */
  splitDevices(devicesByUser) {
    var maxDevicesPerRequest = 20;

    // use an array where the slices of a content map gets stored
    var currentSlice = [];
    var mapSlices = [currentSlice];
    for (var [userId, userDevices] of devicesByUser) {
      for (var deviceInfo of userDevices.values()) {
        currentSlice.push({
          userId: userId,
          deviceInfo: deviceInfo.device
        });
      }

      // We do this in the per-user loop as we prefer that all messages to the
      // same user end up in the same API call to make it easier for the
      // server (e.g. only have to send one EDU if a remote user, etc). This
      // does mean that if a user has many devices we may go over the desired
      // limit, but its not a hard limit so that is fine.
      if (currentSlice.length > maxDevicesPerRequest) {
        // the current slice is filled up. Start inserting into the next slice
        currentSlice = [];
        mapSlices.push(currentSlice);
      }
    }
    if (currentSlice.length === 0) {
      mapSlices.pop();
    }
    return mapSlices;
  }

  /**
   * @internal
   *
   *
   * @param chainIndex - current chain index
   *
   * @param userDeviceMap - mapping from userId to deviceInfo
   *
   * @param payload - fields to include in the encrypted payload
   *
   * @returns Promise which resolves once the key sharing
   *     for the given userDeviceMap is generated and has been sent.
   */
  encryptAndSendKeysToDevices(session, chainIndex, devices, payload) {
    return this.crypto.encryptAndSendToDevices(devices, payload).then(() => {
      // store that we successfully uploaded the keys of the current slice
      for (var device of devices) {
        session.markSharedWithDevice(device.userId, device.deviceInfo.deviceId, device.deviceInfo.getIdentityKey(), chainIndex);
      }
    }).catch(error => {
      this.prefixedLogger.error("failed to encryptAndSendToDevices", error);
      throw error;
    });
  }

  /**
   * @internal
   *
   *
   * @param userDeviceMap - list of blocked devices to notify
   *
   * @param payload - fields to include in the notification payload
   *
   * @returns Promise which resolves once the notifications
   *     for the given userDeviceMap is generated and has been sent.
   */
  sendBlockedNotificationsToDevices(session, userDeviceMap, payload) {
    var _this5 = this;
    return _asyncToGenerator(function* () {
      var contentMap = new MapWithDefault(() => new Map());
      for (var val of userDeviceMap) {
        var userId = val.userId;
        var blockedInfo = val.deviceInfo;
        var deviceInfo = blockedInfo.deviceInfo;
        var deviceId = deviceInfo.deviceId;
        var message = _objectSpread(_objectSpread({}, payload), {}, {
          code: blockedInfo.code,
          reason: blockedInfo.reason,
          [ToDeviceMessageId]: uuidv4()
        });
        if (message.code === "m.no_olm") {
          delete message.room_id;
          delete message.session_id;
        }
        contentMap.getOrCreate(userId).set(deviceId, message);
      }
      yield _this5.baseApis.sendToDevice("m.room_key.withheld", contentMap);

      // record the fact that we notified these blocked devices
      for (var [_userId3, _userDeviceMap] of contentMap) {
        for (var _deviceId2 of _userDeviceMap.keys()) {
          session.markNotifiedBlockedDevice(_userId3, _deviceId2);
        }
      }
    })();
  }

  /**
   * Re-shares a megolm session key with devices if the key has already been
   * sent to them.
   *
   * @param senderKey - The key of the originating device for the session
   * @param sessionId - ID of the outbound session to share
   * @param userId - ID of the user who owns the target device
   * @param device - The target device
   */
  reshareKeyWithDevice(senderKey, sessionId, userId, device) {
    var _this6 = this;
    return _asyncToGenerator(function* () {
      var _obSessionInfo$shared;
      var obSessionInfo = _this6.outboundSessions[sessionId];
      if (!obSessionInfo) {
        _this6.prefixedLogger.debug("megolm session ".concat(senderKey, "|").concat(sessionId, " not found: not re-sharing keys"));
        return;
      }

      // The chain index of the key we previously sent this device
      if (!obSessionInfo.sharedWithDevices.has(userId)) {
        _this6.prefixedLogger.debug("megolm session ".concat(senderKey, "|").concat(sessionId, " never shared with user ").concat(userId));
        return;
      }
      var sessionSharedData = (_obSessionInfo$shared = obSessionInfo.sharedWithDevices.get(userId)) === null || _obSessionInfo$shared === void 0 ? void 0 : _obSessionInfo$shared.get(device.deviceId);
      if (sessionSharedData === undefined) {
        _this6.prefixedLogger.debug("megolm session ".concat(senderKey, "|").concat(sessionId, " never shared with device ").concat(userId, ":").concat(device.deviceId));
        return;
      }
      if (sessionSharedData.deviceKey !== device.getIdentityKey()) {
        _this6.prefixedLogger.warn("Megolm session ".concat(senderKey, "|").concat(sessionId, " has been shared with device ").concat(device.deviceId, " but ") + "with identity key ".concat(sessionSharedData.deviceKey, ". Key is now ").concat(device.getIdentityKey(), "!"));
        return;
      }

      // get the key from the inbound session: the outbound one will already
      // have been ratcheted to the next chain index.
      var key = yield _this6.olmDevice.getInboundGroupSessionKey(_this6.roomId, senderKey, sessionId, sessionSharedData.messageIndex);
      if (!key) {
        _this6.prefixedLogger.warn("No inbound session key found for megolm session ".concat(senderKey, "|").concat(sessionId, ": not re-sharing keys"));
        return;
      }
      yield olmlib.ensureOlmSessionsForDevices(_this6.olmDevice, _this6.baseApis, new Map([[userId, [device]]]));
      var payload = {
        type: "m.forwarded_room_key",
        content: {
          "algorithm": olmlib.MEGOLM_ALGORITHM,
          "room_id": _this6.roomId,
          "session_id": sessionId,
          "session_key": key.key,
          "chain_index": key.chain_index,
          "sender_key": senderKey,
          "sender_claimed_ed25519_key": key.sender_claimed_ed25519_key,
          "forwarding_curve25519_key_chain": key.forwarding_curve25519_key_chain,
          "org.matrix.msc3061.shared_history": key.shared_history || false
        }
      };
      var encryptedContent = {
        algorithm: olmlib.OLM_ALGORITHM,
        sender_key: _this6.olmDevice.deviceCurve25519Key,
        ciphertext: {},
        [ToDeviceMessageId]: uuidv4()
      };
      yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, _this6.userId, _this6.deviceId, _this6.olmDevice, userId, device, payload);
      yield _this6.baseApis.sendToDevice("m.room.encrypted", new Map([[userId, new Map([[device.deviceId, encryptedContent]])]]));
      _this6.prefixedLogger.debug("Re-shared key for megolm session ".concat(senderKey, "|").concat(sessionId, " with ").concat(userId, ":").concat(device.deviceId));
    })();
  }

  /**
   * @internal
   *
   *
   * @param key - the session key as returned by
   *    OlmDevice.getOutboundGroupSessionKey
   *
   * @param payload - the base to-device message payload for sharing keys
   *
   * @param devicesByUser - map from userid to list of devices
   *
   * @param errorDevices - array that will be populated with the devices that we can't get an
   *    olm session for
   *
   * @param otkTimeout - The timeout in milliseconds when requesting
   *     one-time keys for establishing new olm sessions.
   *
   * @param failedServers - An array to fill with remote servers that
   *     failed to respond to one-time-key requests.
   */
  shareKeyWithDevices(session, key, payload, devicesByUser, errorDevices, otkTimeout, failedServers) {
    var _this7 = this;
    return _asyncToGenerator(function* () {
      var devicemap = yield olmlib.ensureOlmSessionsForDevices(_this7.olmDevice, _this7.baseApis, devicesByUser, false, otkTimeout, failedServers, _this7.prefixedLogger);
      _this7.getDevicesWithoutSessions(devicemap, devicesByUser, errorDevices);
      yield _this7.shareKeyWithOlmSessions(session, key, payload, devicemap);
    })();
  }
  shareKeyWithOlmSessions(session, key, payload, deviceMap) {
    var _this8 = this;
    return _asyncToGenerator(function* () {
      var userDeviceMaps = _this8.splitDevices(deviceMap);
      for (var i = 0; i < userDeviceMaps.length; i++) {
        var taskDetail = "megolm keys for ".concat(session.sessionId, " (slice ").concat(i + 1, "/").concat(userDeviceMaps.length, ")");
        try {
          _this8.prefixedLogger.debug("Sharing ".concat(taskDetail), userDeviceMaps[i].map(d => "".concat(d.userId, "/").concat(d.deviceInfo.deviceId)));
          yield _this8.encryptAndSendKeysToDevices(session, key.chain_index, userDeviceMaps[i], payload);
          _this8.prefixedLogger.debug("Shared ".concat(taskDetail));
        } catch (e) {
          _this8.prefixedLogger.error("Failed to share ".concat(taskDetail));
          throw e;
        }
      }
    })();
  }

  /**
   * Notify devices that we weren't able to create olm sessions.
   *
   *
   *
   * @param failedDevices - the devices that we were unable to
   *     create olm sessions for, as returned by shareKeyWithDevices
   */
  notifyFailedOlmDevices(session, key, failedDevices) {
    var _this9 = this;
    return _asyncToGenerator(function* () {
      _this9.prefixedLogger.debug("Notifying ".concat(failedDevices.length, " devices we failed to create Olm sessions"));

      // mark the devices that failed as "handled" because we don't want to try
      // to claim a one-time-key for dead devices on every message.
      for (var {
        userId,
        deviceInfo
      } of failedDevices) {
        var deviceId = deviceInfo.deviceId;
        session.markSharedWithDevice(userId, deviceId, deviceInfo.getIdentityKey(), key.chain_index);
      }
      var unnotifiedFailedDevices = yield _this9.olmDevice.filterOutNotifiedErrorDevices(failedDevices);
      _this9.prefixedLogger.debug("Need to notify ".concat(unnotifiedFailedDevices.length, " failed devices which haven't been notified before"));
      var blockedMap = new MapWithDefault(() => new Map());
      for (var {
        userId: _userId4,
        deviceInfo: _deviceInfo3
      } of unnotifiedFailedDevices) {
        // we use a similar format to what
        // olmlib.ensureOlmSessionsForDevices returns, so that
        // we can use the same function to split
        blockedMap.getOrCreate(_userId4).set(_deviceInfo3.deviceId, {
          device: {
            code: "m.no_olm",
            reason: WITHHELD_MESSAGES["m.no_olm"],
            deviceInfo: _deviceInfo3
          }
        });
      }

      // send the notifications
      yield _this9.notifyBlockedDevices(session, blockedMap);
      _this9.prefixedLogger.debug("Notified ".concat(unnotifiedFailedDevices.length, " devices we failed to create Olm sessions"));
    })();
  }

  /**
   * Notify blocked devices that they have been blocked.
   *
   *
   * @param devicesByUser - map from userid to device ID to blocked data
   */
  notifyBlockedDevices(session, devicesByUser) {
    var _this10 = this;
    return _asyncToGenerator(function* () {
      var payload = {
        room_id: _this10.roomId,
        session_id: session.sessionId,
        algorithm: olmlib.MEGOLM_ALGORITHM,
        sender_key: _this10.olmDevice.deviceCurve25519Key
      };
      var userDeviceMaps = _this10.splitDevices(devicesByUser);
      for (var i = 0; i < userDeviceMaps.length; i++) {
        try {
          yield _this10.sendBlockedNotificationsToDevices(session, userDeviceMaps[i], payload);
          _this10.prefixedLogger.debug("Completed blacklist notification for ".concat(session.sessionId, " ") + "(slice ".concat(i + 1, "/").concat(userDeviceMaps.length, ")"));
        } catch (e) {
          _this10.prefixedLogger.debug("blacklist notification for ".concat(session.sessionId, " ") + "(slice ".concat(i + 1, "/").concat(userDeviceMaps.length, ") failed"));
          throw e;
        }
      }
    })();
  }

  /**
   * Perform any background tasks that can be done before a message is ready to
   * send, in order to speed up sending of the message.
   *
   * @param room - the room the event is in
   * @returns A function that, when called, will stop the preparation
   */
  prepareToEncrypt(room) {
    var _this11 = this;
    if (room.roomId !== this.roomId) {
      throw new Error("MegolmEncryption.prepareToEncrypt called on unexpected room");
    }
    if (this.encryptionPreparation != null) {
      // We're already preparing something, so don't do anything else.
      var elapsedTime = Date.now() - this.encryptionPreparation.startTime;
      this.prefixedLogger.debug("Already started preparing to encrypt for this room ".concat(elapsedTime, "ms ago, skipping"));
      return this.encryptionPreparation.cancel;
    }
    this.prefixedLogger.debug("Preparing to encrypt events");
    var cancelled = false;
    var isCancelled = () => cancelled;
    this.encryptionPreparation = {
      startTime: Date.now(),
      promise: _asyncToGenerator(function* () {
        try {
          // Attempt to enumerate the devices in room, and gracefully
          // handle cancellation if it occurs.
          var getDevicesResult = yield _this11.getDevicesInRoom(room, false, isCancelled);
          if (getDevicesResult === null) return;
          var [devicesInRoom, blocked] = getDevicesResult;
          if (_this11.crypto.globalErrorOnUnknownDevices) {
            // Drop unknown devices for now.  When the message gets sent, we'll
            // throw an error, but we'll still be prepared to send to the known
            // devices.
            _this11.removeUnknownDevices(devicesInRoom);
          }
          _this11.prefixedLogger.debug("Ensuring outbound megolm session");
          yield _this11.ensureOutboundSession(room, devicesInRoom, blocked, true);
          _this11.prefixedLogger.debug("Ready to encrypt events");
        } catch (e) {
          _this11.prefixedLogger.error("Failed to prepare to encrypt events", e);
        } finally {
          delete _this11.encryptionPreparation;
        }
      })(),
      cancel: () => {
        // The caller has indicated that the process should be cancelled,
        // so tell the promise that we'd like to halt, and reset the preparation state.
        cancelled = true;
        delete this.encryptionPreparation;
      }
    };
    return this.encryptionPreparation.cancel;
  }

  /**
   * @param content - plaintext event content
   *
   * @returns Promise which resolves to the new event body
   */
  encryptMessage(room, eventType, content) {
    var _this12 = this;
    return _asyncToGenerator(function* () {
      _this12.prefixedLogger.debug("Starting to encrypt event");
      if (_this12.encryptionPreparation != null) {
        // If we started sending keys, wait for it to be done.
        // FIXME: check if we need to cancel
        // (https://github.com/matrix-org/matrix-js-sdk/issues/1255)
        try {
          yield _this12.encryptionPreparation.promise;
        } catch (e) {
          // ignore any errors -- if the preparation failed, we'll just
          // restart everything here
        }
      }

      /**
       * When using in-room messages and the room has encryption enabled,
       * clients should ensure that encryption does not hinder the verification.
       */
      var forceDistributeToUnverified = _this12.isVerificationEvent(eventType, content);
      var [devicesInRoom, blocked] = yield _this12.getDevicesInRoom(room, forceDistributeToUnverified);

      // check if any of these devices are not yet known to the user.
      // if so, warn the user so they can verify or ignore.
      if (_this12.crypto.globalErrorOnUnknownDevices) {
        _this12.checkForUnknownDevices(devicesInRoom);
      }
      var session = yield _this12.ensureOutboundSession(room, devicesInRoom, blocked);
      var payloadJson = {
        room_id: _this12.roomId,
        type: eventType,
        content: content
      };
      var ciphertext = _this12.olmDevice.encryptGroupMessage(session.sessionId, JSON.stringify(payloadJson));
      var encryptedContent = {
        algorithm: olmlib.MEGOLM_ALGORITHM,
        sender_key: _this12.olmDevice.deviceCurve25519Key,
        ciphertext: ciphertext,
        session_id: session.sessionId,
        // Include our device ID so that recipients can send us a
        // m.new_device message if they don't have our session key.
        // XXX: Do we still need this now that m.new_device messages
        // no longer exist since #483?
        device_id: _this12.deviceId
      };
      session.useCount++;
      return encryptedContent;
    })();
  }
  isVerificationEvent(eventType, content) {
    switch (eventType) {
      case EventType.KeyVerificationCancel:
      case EventType.KeyVerificationDone:
      case EventType.KeyVerificationMac:
      case EventType.KeyVerificationStart:
      case EventType.KeyVerificationKey:
      case EventType.KeyVerificationReady:
      case EventType.KeyVerificationAccept:
        {
          return true;
        }
      case EventType.RoomMessage:
        {
          return content["msgtype"] === MsgType.KeyVerificationRequest;
        }
      default:
        {
          return false;
        }
    }
  }

  /**
   * Forces the current outbound group session to be discarded such
   * that another one will be created next time an event is sent.
   *
   * This should not normally be necessary.
   */
  forceDiscardSession() {
    this.setupPromise = this.setupPromise.then(() => null);
  }

  /**
   * Checks the devices we're about to send to and see if any are entirely
   * unknown to the user.  If so, warn the user, and mark them as known to
   * give the user a chance to go verify them before re-sending this message.
   *
   * @param devicesInRoom - `userId -> {deviceId -> object}`
   *   devices we should shared the session with.
   */
  checkForUnknownDevices(devicesInRoom) {
    var unknownDevices = new MapWithDefault(() => new Map());
    for (var [userId, userDevices] of devicesInRoom) {
      for (var [deviceId, device] of userDevices) {
        if (device.isUnverified() && !device.isKnown()) {
          unknownDevices.getOrCreate(userId).set(deviceId, device);
        }
      }
    }
    if (unknownDevices.size) {
      // it'd be kind to pass unknownDevices up to the user in this error
      throw new UnknownDeviceError("This room contains unknown devices which have not been verified. " + "We strongly recommend you verify them before continuing.", unknownDevices);
    }
  }

  /**
   * Remove unknown devices from a set of devices.  The devicesInRoom parameter
   * will be modified.
   *
   * @param devicesInRoom - `userId -> {deviceId -> object}`
   *   devices we should shared the session with.
   */
  removeUnknownDevices(devicesInRoom) {
    for (var [userId, userDevices] of devicesInRoom) {
      for (var [deviceId, device] of userDevices) {
        if (device.isUnverified() && !device.isKnown()) {
          userDevices.delete(deviceId);
        }
      }
      if (userDevices.size === 0) {
        devicesInRoom.delete(userId);
      }
    }
  }

  /**
   * Get the list of unblocked devices for all users in the room
   *
   * @param forceDistributeToUnverified - if set to true will include the unverified devices
   * even if setting is set to block them (useful for verification)
   * @param isCancelled - will cause the procedure to abort early if and when it starts
   * returning `true`. If omitted, cancellation won't happen.
   *
   * @returns Promise which resolves to `null`, or an array whose
   *     first element is a {@link DeviceInfoMap} indicating
   *     the devices that messages should be encrypted to, and whose second
   *     element is a map from userId to deviceId to data indicating the devices
   *     that are in the room but that have been blocked.
   *     If `isCancelled` is provided and returns `true` while processing, `null`
   *     will be returned.
   *     If `isCancelled` is not provided, the Promise will never resolve to `null`.
   */

  getDevicesInRoom(room) {
    var _arguments2 = arguments,
      _this13 = this;
    return _asyncToGenerator(function* () {
      var forceDistributeToUnverified = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : false;
      var isCancelled = _arguments2.length > 2 ? _arguments2[2] : undefined;
      var members = yield room.getEncryptionTargetMembers();
      _this13.prefixedLogger.debug("Encrypting for users (shouldEncryptForInvitedMembers: ".concat(room.shouldEncryptForInvitedMembers(), "):"), members.map(u => "".concat(u.userId, " (").concat(u.membership, ")")));
      var roomMembers = members.map(function (u) {
        return u.userId;
      });

      // The global value is treated as a default for when rooms don't specify a value.
      var isBlacklisting = _this13.crypto.globalBlacklistUnverifiedDevices;
      var isRoomBlacklisting = room.getBlacklistUnverifiedDevices();
      if (typeof isRoomBlacklisting === "boolean") {
        isBlacklisting = isRoomBlacklisting;
      }

      // We are happy to use a cached version here: we assume that if we already
      // have a list of the user's devices, then we already share an e2e room
      // with them, which means that they will have announced any new devices via
      // device_lists in their /sync response.  This cache should then be maintained
      // using all the device_lists changes and left fields.
      // See https://github.com/vector-im/element-web/issues/2305 for details.
      var devices = yield _this13.crypto.downloadKeys(roomMembers, false);
      if ((isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) === true) {
        return null;
      }
      var blocked = new MapWithDefault(() => new Map());
      // remove any blocked devices
      for (var [userId, userDevices] of devices) {
        for (var [deviceId, userDevice] of userDevices) {
          // Yield prior to checking each device so that we don't block
          // updating/rendering for too long.
          // See https://github.com/vector-im/element-web/issues/21612
          if (isCancelled !== undefined) yield immediate();
          if ((isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) === true) return null;
          var deviceTrust = _this13.crypto.checkDeviceTrust(userId, deviceId);
          if (userDevice.isBlocked() || !deviceTrust.isVerified() && isBlacklisting && !forceDistributeToUnverified) {
            var blockedDevices = blocked.getOrCreate(userId);
            var isBlocked = userDevice.isBlocked();
            blockedDevices.set(deviceId, {
              code: isBlocked ? "m.blacklisted" : "m.unverified",
              reason: WITHHELD_MESSAGES[isBlocked ? "m.blacklisted" : "m.unverified"],
              deviceInfo: userDevice
            });
            userDevices.delete(deviceId);
          }
        }
      }
      return [devices, blocked];
    })();
  }
}

/**
 * Megolm decryption implementation
 *
 * @param params - parameters, as per {@link DecryptionAlgorithm}
 */
export class MegolmDecryption extends DecryptionAlgorithm {
  constructor(params) {
    super(params);
    // events which we couldn't decrypt due to unknown sessions /
    // indexes, or which we could only decrypt with untrusted keys:
    // map from senderKey|sessionId to Set of MatrixEvents
    _defineProperty(this, "pendingEvents", new Map());
    // this gets stubbed out by the unit tests.
    _defineProperty(this, "olmlib", olmlib);
    _defineProperty(this, "roomId", void 0);
    _defineProperty(this, "prefixedLogger", void 0);
    this.roomId = params.roomId;
    this.prefixedLogger = logger.getChild("[".concat(this.roomId, " decryption]"));
  }

  /**
   * returns a promise which resolves to a
   * {@link EventDecryptionResult} once we have finished
   * decrypting, or rejects with an `algorithms.DecryptionError` if there is a
   * problem decrypting the event.
   */
  decryptEvent(event) {
    var _this14 = this;
    return _asyncToGenerator(function* () {
      var content = event.getWireContent();
      if (!content.sender_key || !content.session_id || !content.ciphertext) {
        throw new DecryptionError(DecryptionFailureCode.MEGOLM_MISSING_FIELDS, "Missing fields in input");
      }

      // we add the event to the pending list *before* we start decryption.
      //
      // then, if the key turns up while decryption is in progress (and
      // decryption fails), we will schedule a retry.
      // (fixes https://github.com/vector-im/element-web/issues/5001)
      _this14.addEventToPendingList(event);
      var res;
      try {
        res = yield _this14.olmDevice.decryptGroupMessage(event.getRoomId(), content.sender_key, content.session_id, content.ciphertext, event.getId(), event.getTs());
      } catch (e) {
        if (e.name === "DecryptionError") {
          // re-throw decryption errors as-is
          throw e;
        }
        var errorCode = DecryptionFailureCode.OLM_DECRYPT_GROUP_MESSAGE_ERROR;
        if ((e === null || e === void 0 ? void 0 : e.message) === "OLM.UNKNOWN_MESSAGE_INDEX") {
          _this14.requestKeysForEvent(event);
          errorCode = DecryptionFailureCode.OLM_UNKNOWN_MESSAGE_INDEX;
        }
        throw new DecryptionError(errorCode, e instanceof Error ? e.message : "Unknown Error: Error is undefined", {
          session: content.sender_key + "|" + content.session_id
        });
      }
      if (res === null) {
        // We've got a message for a session we don't have.
        // try and get the missing key from the backup first
        _this14.crypto.backupManager.queryKeyBackupRateLimited(event.getRoomId(), content.session_id).catch(() => {});

        // (XXX: We might actually have received this key since we started
        // decrypting, in which case we'll have scheduled a retry, and this
        // request will be redundant. We could probably check to see if the
        // event is still in the pending list; if not, a retry will have been
        // scheduled, so we needn't send out the request here.)
        _this14.requestKeysForEvent(event);

        // See if there was a problem with the olm session at the time the
        // event was sent.  Use a fuzz factor of 2 minutes.
        var problem = yield _this14.olmDevice.sessionMayHaveProblems(content.sender_key, event.getTs() - 120000);
        if (problem) {
          _this14.prefixedLogger.info("When handling UISI from ".concat(event.getSender(), " (sender key ").concat(content.sender_key, "): ") + "recent session problem with that sender:", problem);
          var problemDescription = PROBLEM_DESCRIPTIONS[problem.type] || PROBLEM_DESCRIPTIONS.unknown;
          if (problem.fixed) {
            problemDescription += " Trying to create a new secure channel and re-requesting the keys.";
          }
          throw new DecryptionError(DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID, problemDescription, {
            session: content.sender_key + "|" + content.session_id
          });
        }
        throw new DecryptionError(DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID, "The sender's device has not sent us the keys for this message.", {
          session: content.sender_key + "|" + content.session_id
        });
      }

      // Success. We can remove the event from the pending list, if
      // that hasn't already happened. However, if the event was
      // decrypted with an untrusted key, leave it on the pending
      // list so it will be retried if we find a trusted key later.
      if (!res.untrusted) {
        _this14.removeEventFromPendingList(event);
      }
      var payload = JSON.parse(res.result);

      // belt-and-braces check that the room id matches that indicated by the HS
      // (this is somewhat redundant, since the megolm session is scoped to the
      // room, so neither the sender nor a MITM can lie about the room_id).
      if (payload.room_id !== event.getRoomId()) {
        throw new DecryptionError(DecryptionFailureCode.MEGOLM_BAD_ROOM, "Message intended for room " + payload.room_id);
      }
      return {
        clearEvent: payload,
        senderCurve25519Key: res.senderKey,
        claimedEd25519Key: res.keysClaimed.ed25519,
        forwardingCurve25519KeyChain: res.forwardingCurve25519KeyChain,
        untrusted: res.untrusted
      };
    })();
  }
  requestKeysForEvent(event) {
    var wireContent = event.getWireContent();
    var recipients = event.getKeyRequestRecipients(this.userId);
    this.crypto.requestRoomKey({
      room_id: event.getRoomId(),
      algorithm: wireContent.algorithm,
      sender_key: wireContent.sender_key,
      session_id: wireContent.session_id
    }, recipients);
  }

  /**
   * Add an event to the list of those awaiting their session keys.
   *
   * @internal
   *
   */
  addEventToPendingList(event) {
    var _senderPendingEvents$;
    var content = event.getWireContent();
    var senderKey = content.sender_key;
    var sessionId = content.session_id;
    if (!this.pendingEvents.has(senderKey)) {
      this.pendingEvents.set(senderKey, new Map());
    }
    var senderPendingEvents = this.pendingEvents.get(senderKey);
    if (!senderPendingEvents.has(sessionId)) {
      senderPendingEvents.set(sessionId, new Set());
    }
    (_senderPendingEvents$ = senderPendingEvents.get(sessionId)) === null || _senderPendingEvents$ === void 0 || _senderPendingEvents$.add(event);
  }

  /**
   * Remove an event from the list of those awaiting their session keys.
   *
   * @internal
   *
   */
  removeEventFromPendingList(event) {
    var content = event.getWireContent();
    var senderKey = content.sender_key;
    var sessionId = content.session_id;
    var senderPendingEvents = this.pendingEvents.get(senderKey);
    var pendingEvents = senderPendingEvents === null || senderPendingEvents === void 0 ? void 0 : senderPendingEvents.get(sessionId);
    if (!pendingEvents) {
      return;
    }
    pendingEvents.delete(event);
    if (pendingEvents.size === 0) {
      senderPendingEvents.delete(sessionId);
    }
    if (senderPendingEvents.size === 0) {
      this.pendingEvents.delete(senderKey);
    }
  }

  /**
   * Parse a RoomKey out of an `m.room_key` event.
   *
   * @param event - the event containing the room key.
   *
   * @returns The `RoomKey` if it could be successfully parsed out of the
   * event.
   *
   * @internal
   *
   */
  roomKeyFromEvent(event) {
    var senderKey = event.getSenderKey();
    var content = event.getContent();
    var extraSessionData = {};
    if (!content.room_id || !content.session_key || !content.session_id || !content.algorithm) {
      this.prefixedLogger.error("key event is missing fields");
      return;
    }
    if (!olmlib.isOlmEncrypted(event)) {
      this.prefixedLogger.error("key event not properly encrypted");
      return;
    }
    if (content["org.matrix.msc3061.shared_history"]) {
      extraSessionData.sharedHistory = true;
    }
    var roomKey = {
      senderKey: senderKey,
      sessionId: content.session_id,
      sessionKey: content.session_key,
      extraSessionData,
      exportFormat: false,
      roomId: content.room_id,
      algorithm: content.algorithm,
      forwardingKeyChain: [],
      keysClaimed: event.getKeysClaimed()
    };
    return roomKey;
  }

  /**
   * Parse a RoomKey out of an `m.forwarded_room_key` event.
   *
   * @param event - the event containing the forwarded room key.
   *
   * @returns The `RoomKey` if it could be successfully parsed out of the
   * event.
   *
   * @internal
   *
   */
  forwardedRoomKeyFromEvent(event) {
    // the properties in m.forwarded_room_key are a superset of those in m.room_key, so
    // start by parsing the m.room_key fields.
    var roomKey = this.roomKeyFromEvent(event);
    if (!roomKey) {
      return;
    }
    var senderKey = event.getSenderKey();
    var content = event.getContent();
    var senderKeyUser = this.baseApis.crypto.deviceList.getUserByIdentityKey(olmlib.OLM_ALGORITHM, senderKey);

    // We received this to-device event from event.getSenderKey(), but the original
    // creator of the room key is claimed in the content.
    var claimedCurve25519Key = content.sender_key;
    var claimedEd25519Key = content.sender_claimed_ed25519_key;
    var forwardingKeyChain = Array.isArray(content.forwarding_curve25519_key_chain) ? content.forwarding_curve25519_key_chain : [];

    // copy content before we modify it
    forwardingKeyChain = forwardingKeyChain.slice();
    forwardingKeyChain.push(senderKey);

    // Check if we have all the fields we need.
    if (senderKeyUser !== event.getSender()) {
      this.prefixedLogger.error("sending device does not belong to the user it claims to be from");
      return;
    }
    if (!claimedCurve25519Key) {
      this.prefixedLogger.error("forwarded_room_key event is missing sender_key field");
      return;
    }
    if (!claimedEd25519Key) {
      this.prefixedLogger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field");
      return;
    }
    var keysClaimed = {
      ed25519: claimedEd25519Key
    };

    // FIXME: We're reusing the same field to track both:
    //
    // 1. The Olm identity we've received this room key from.
    // 2. The Olm identity deduced (in the trusted case) or claiming (in the
    // untrusted case) to be the original creator of this room key.
    //
    // We now overwrite the value tracking usage 1 with the value tracking usage 2.
    roomKey.senderKey = claimedCurve25519Key;
    // Replace our keysClaimed as well.
    roomKey.keysClaimed = keysClaimed;
    roomKey.exportFormat = true;
    roomKey.forwardingKeyChain = forwardingKeyChain;
    // forwarded keys are always untrusted
    roomKey.extraSessionData.untrusted = true;
    return roomKey;
  }

  /**
   * Determine if we should accept the forwarded room key that was found in the given
   * event.
   *
   * @param event - An `m.forwarded_room_key` event.
   * @param roomKey - The room key that was found in the event.
   *
   * @returns promise that will resolve to a boolean telling us if it's ok to
   * accept the given forwarded room key.
   *
   * @internal
   *
   */
  shouldAcceptForwardedKey(event, roomKey) {
    var _this15 = this;
    return _asyncToGenerator(function* () {
      var _this15$crypto$device;
      var senderKey = event.getSenderKey();
      var sendingDevice = (_this15$crypto$device = _this15.crypto.deviceList.getDeviceByIdentityKey(olmlib.OLM_ALGORITHM, senderKey)) !== null && _this15$crypto$device !== void 0 ? _this15$crypto$device : undefined;
      var deviceTrust = _this15.crypto.checkDeviceInfoTrust(event.getSender(), sendingDevice);

      // Using the plaintext sender here is fine since we checked that the
      // sender matches to the user id in the device keys when this event was
      // originally decrypted. This can obviously only happen if the device
      // keys have been downloaded, but if they haven't the
      // `deviceTrust.isVerified()` flag would be false as well.
      //
      // It would still be far nicer if the `sendingDevice` had a user ID
      // attached to it that went through signature checks.
      var fromUs = event.getSender() === _this15.baseApis.getUserId();
      var keyFromOurVerifiedDevice = deviceTrust.isVerified() && fromUs;
      var weRequested = yield _this15.wasRoomKeyRequested(event, roomKey);
      var fromInviter = _this15.wasRoomKeyForwardedByInviter(event, roomKey);
      var sharedAsHistory = _this15.wasRoomKeyForwardedAsHistory(roomKey);
      return weRequested && keyFromOurVerifiedDevice || fromInviter && sharedAsHistory;
    })();
  }

  /**
   * Did we ever request the given room key from the event sender and its
   * accompanying device.
   *
   * @param event - An `m.forwarded_room_key` event.
   * @param roomKey - The room key that was found in the event.
   *
   * @internal
   *
   */
  wasRoomKeyRequested(event, roomKey) {
    var _this16 = this;
    return _asyncToGenerator(function* () {
      // We send the `m.room_key_request` out as a wildcard to-device request,
      // otherwise we would have to duplicate the same content for each
      // device. This is why we need to pass in "*" as the device id here.
      var outgoingRequests = yield _this16.crypto.cryptoStore.getOutgoingRoomKeyRequestsByTarget(event.getSender(), "*", [RoomKeyRequestState.Sent]);
      return outgoingRequests.some(req => req.requestBody.room_id === roomKey.roomId && req.requestBody.session_id === roomKey.sessionId);
    })();
  }
  wasRoomKeyForwardedByInviter(event, roomKey) {
    var _room$getMember, _memberEvent$getUnsig, _memberEvent$getPrevC;
    // TODO: This is supposed to have a time limit. We should only accept
    // such keys if we happen to receive them for a recently joined room.
    var room = this.baseApis.getRoom(roomKey.roomId);
    var senderKey = event.getSenderKey();
    if (!senderKey) {
      return false;
    }
    var senderKeyUser = this.crypto.deviceList.getUserByIdentityKey(olmlib.OLM_ALGORITHM, senderKey);
    if (!senderKeyUser) {
      return false;
    }
    var memberEvent = room === null || room === void 0 || (_room$getMember = room.getMember(this.userId)) === null || _room$getMember === void 0 ? void 0 : _room$getMember.events.member;
    var fromInviter = (memberEvent === null || memberEvent === void 0 ? void 0 : memberEvent.getSender()) === senderKeyUser || (memberEvent === null || memberEvent === void 0 || (_memberEvent$getUnsig = memberEvent.getUnsigned()) === null || _memberEvent$getUnsig === void 0 ? void 0 : _memberEvent$getUnsig.prev_sender) === senderKeyUser && (memberEvent === null || memberEvent === void 0 || (_memberEvent$getPrevC = memberEvent.getPrevContent()) === null || _memberEvent$getPrevC === void 0 ? void 0 : _memberEvent$getPrevC.membership) === KnownMembership.Invite;
    if (room && fromInviter) {
      return true;
    } else {
      return false;
    }
  }
  wasRoomKeyForwardedAsHistory(roomKey) {
    var room = this.baseApis.getRoom(roomKey.roomId);

    // If the key is not for a known room, then something fishy is going on,
    // so we reject the key out of caution. In practice, this is a bit moot
    // because we'll only accept shared_history forwarded by the inviter, and
    // we won't know who was the inviter for an unknown room, so we'll reject
    // it anyway.
    if (room && roomKey.extraSessionData.sharedHistory) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * Check if a forwarded room key should be parked.
   *
   * A forwarded room key should be parked if it's a key for a room we're not
   * in. We park the forwarded room key in case *this sender* invites us to
   * that room later.
   */
  shouldParkForwardedKey(roomKey) {
    var room = this.baseApis.getRoom(roomKey.roomId);
    if (!room && roomKey.extraSessionData.sharedHistory) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * Park the given room key to our store.
   *
   * @param event - An `m.forwarded_room_key` event.
   * @param roomKey - The room key that was found in the event.
   *
   * @internal
   *
   */
  parkForwardedKey(event, roomKey) {
    var _this17 = this;
    return _asyncToGenerator(function* () {
      var parkedData = {
        senderId: event.getSender(),
        senderKey: roomKey.senderKey,
        sessionId: roomKey.sessionId,
        sessionKey: roomKey.sessionKey,
        keysClaimed: roomKey.keysClaimed,
        forwardingCurve25519KeyChain: roomKey.forwardingKeyChain
      };
      yield _this17.crypto.cryptoStore.doTxn("readwrite", ["parked_shared_history"], txn => _this17.crypto.cryptoStore.addParkedSharedHistory(roomKey.roomId, parkedData, txn), logger.getChild("[addParkedSharedHistory]"));
    })();
  }

  /**
   * Add the given room key to our store.
   *
   * @param roomKey - The room key that should be added to the store.
   *
   * @internal
   *
   */
  addRoomKey(roomKey) {
    var _this18 = this;
    return _asyncToGenerator(function* () {
      try {
        yield _this18.olmDevice.addInboundGroupSession(roomKey.roomId, roomKey.senderKey, roomKey.forwardingKeyChain, roomKey.sessionId, roomKey.sessionKey, roomKey.keysClaimed, roomKey.exportFormat, roomKey.extraSessionData);

        // have another go at decrypting events sent with this session.
        if (yield _this18.retryDecryption(roomKey.senderKey, roomKey.sessionId, !roomKey.extraSessionData.untrusted)) {
          // cancel any outstanding room key requests for this session.
          // Only do this if we managed to decrypt every message in the
          // session, because if we didn't, we leave the other key
          // requests in the hopes that someone sends us a key that
          // includes an earlier index.
          _this18.crypto.cancelRoomKeyRequest({
            algorithm: roomKey.algorithm,
            room_id: roomKey.roomId,
            session_id: roomKey.sessionId,
            sender_key: roomKey.senderKey
          });
        }

        // don't wait for the keys to be backed up for the server
        yield _this18.crypto.backupManager.backupGroupSession(roomKey.senderKey, roomKey.sessionId);
      } catch (e) {
        _this18.prefixedLogger.error("Error handling m.room_key_event: ".concat(e));
      }
    })();
  }

  /**
   * Handle room keys that have been forwarded to us as an
   * `m.forwarded_room_key` event.
   *
   * Forwarded room keys need special handling since we have no way of knowing
   * who the original creator of the room key was. This naturally means that
   * forwarded room keys are always untrusted and should only be accepted in
   * some cases.
   *
   * @param event - An `m.forwarded_room_key` event.
   *
   * @internal
   *
   */
  onForwardedRoomKey(event) {
    var _this19 = this;
    return _asyncToGenerator(function* () {
      var roomKey = _this19.forwardedRoomKeyFromEvent(event);
      if (!roomKey) {
        return;
      }
      if (yield _this19.shouldAcceptForwardedKey(event, roomKey)) {
        yield _this19.addRoomKey(roomKey);
      } else if (_this19.shouldParkForwardedKey(roomKey)) {
        yield _this19.parkForwardedKey(event, roomKey);
      }
    })();
  }
  onRoomKeyEvent(event) {
    var _this20 = this;
    return _asyncToGenerator(function* () {
      if (event.getType() == "m.forwarded_room_key") {
        yield _this20.onForwardedRoomKey(event);
      } else {
        var roomKey = _this20.roomKeyFromEvent(event);
        if (!roomKey) {
          return;
        }
        yield _this20.addRoomKey(roomKey);
      }
    })();
  }

  /**
   * @param event - key event
   */
  onRoomKeyWithheldEvent(event) {
    var _this21 = this;
    return _asyncToGenerator(function* () {
      var content = event.getContent();
      var senderKey = content.sender_key;
      if (content.code === "m.no_olm") {
        yield _this21.onNoOlmWithheldEvent(event);
      } else if (content.code === "m.unavailable") {
        // this simply means that the other device didn't have the key, which isn't very useful information. Don't
        // record it in the storage
      } else {
        yield _this21.olmDevice.addInboundGroupSessionWithheld(content.room_id, senderKey, content.session_id, content.code, content.reason);
      }

      // Having recorded the problem, retry decryption on any affected messages.
      // It's unlikely we'll be able to decrypt sucessfully now, but this will
      // update the error message.
      //
      if (content.session_id) {
        yield _this21.retryDecryption(senderKey, content.session_id);
      } else {
        // no_olm messages aren't specific to a given megolm session, so
        // we trigger retrying decryption for all the messages from the sender's
        // key, so that we can update the error message to indicate the olm
        // session problem.
        yield _this21.retryDecryptionFromSender(senderKey);
      }
    })();
  }
  onNoOlmWithheldEvent(event) {
    var _this22 = this;
    return _asyncToGenerator(function* () {
      var content = event.getContent();
      var senderKey = content.sender_key;
      var sender = event.getSender();
      _this22.prefixedLogger.warn("".concat(sender, ":").concat(senderKey, " was unable to establish an olm session with us"));
      // if the sender says that they haven't been able to establish an olm
      // session, let's proactively establish one

      if (yield _this22.olmDevice.getSessionIdForDevice(senderKey)) {
        // a session has already been established, so we don't need to
        // create a new one.
        _this22.prefixedLogger.debug("New session already created.  Not creating a new one.");
        yield _this22.olmDevice.recordSessionProblem(senderKey, "no_olm", true);
        return;
      }
      var device = _this22.crypto.deviceList.getDeviceByIdentityKey(content.algorithm, senderKey);
      if (!device) {
        // if we don't know about the device, fetch the user's devices again
        // and retry before giving up
        yield _this22.crypto.downloadKeys([sender], false);
        device = _this22.crypto.deviceList.getDeviceByIdentityKey(content.algorithm, senderKey);
        if (!device) {
          _this22.prefixedLogger.info("Couldn't find device for identity key " + senderKey + ": not establishing session");
          yield _this22.olmDevice.recordSessionProblem(senderKey, "no_olm", false);
          return;
        }
      }

      // XXX: switch this to use encryptAndSendToDevices() rather than duplicating it?

      yield olmlib.ensureOlmSessionsForDevices(_this22.olmDevice, _this22.baseApis, new Map([[sender, [device]]]), false);
      var encryptedContent = {
        algorithm: olmlib.OLM_ALGORITHM,
        sender_key: _this22.olmDevice.deviceCurve25519Key,
        ciphertext: {},
        [ToDeviceMessageId]: uuidv4()
      };
      yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, _this22.userId, undefined, _this22.olmDevice, sender, device, {
        type: "m.dummy"
      });
      yield _this22.olmDevice.recordSessionProblem(senderKey, "no_olm", true);
      yield _this22.baseApis.sendToDevice("m.room.encrypted", new Map([[sender, new Map([[device.deviceId, encryptedContent]])]]));
    })();
  }
  hasKeysForKeyRequest(keyRequest) {
    var body = keyRequest.requestBody;
    return this.olmDevice.hasInboundSessionKeys(body.room_id, body.sender_key, body.session_id
    // TODO: ratchet index
    );
  }
  shareKeysWithDevice(keyRequest) {
    var userId = keyRequest.userId;
    var deviceId = keyRequest.deviceId;
    var deviceInfo = this.crypto.getStoredDevice(userId, deviceId);
    var body = keyRequest.requestBody;

    // XXX: switch this to use encryptAndSendToDevices()?

    this.olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, new Map([[userId, [deviceInfo]]])).then(devicemap => {
      var _devicemap$get;
      var olmSessionResult = (_devicemap$get = devicemap.get(userId)) === null || _devicemap$get === void 0 ? void 0 : _devicemap$get.get(deviceId);
      if (!(olmSessionResult !== null && olmSessionResult !== void 0 && olmSessionResult.sessionId)) {
        // no session with this device, probably because there
        // were no one-time keys.
        //
        // ensureOlmSessionsForUsers has already done the logging,
        // so just skip it.
        return null;
      }
      this.prefixedLogger.debug("sharing keys for session " + body.sender_key + "|" + body.session_id + " with device " + userId + ":" + deviceId);
      return this.buildKeyForwardingMessage(body.room_id, body.sender_key, body.session_id);
    }).then(payload => {
      var encryptedContent = {
        algorithm: olmlib.OLM_ALGORITHM,
        sender_key: this.olmDevice.deviceCurve25519Key,
        ciphertext: {},
        [ToDeviceMessageId]: uuidv4()
      };
      return this.olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, undefined, this.olmDevice, userId, deviceInfo, payload).then(() => {
        // TODO: retries
        return this.baseApis.sendToDevice("m.room.encrypted", new Map([[userId, new Map([[deviceId, encryptedContent]])]]));
      });
    });
  }
  buildKeyForwardingMessage(roomId, senderKey, sessionId) {
    var _this23 = this;
    return _asyncToGenerator(function* () {
      var key = yield _this23.olmDevice.getInboundGroupSessionKey(roomId, senderKey, sessionId);
      return {
        type: "m.forwarded_room_key",
        content: {
          "algorithm": olmlib.MEGOLM_ALGORITHM,
          "room_id": roomId,
          "sender_key": senderKey,
          "sender_claimed_ed25519_key": key.sender_claimed_ed25519_key,
          "session_id": sessionId,
          "session_key": key.key,
          "chain_index": key.chain_index,
          "forwarding_curve25519_key_chain": key.forwarding_curve25519_key_chain,
          "org.matrix.msc3061.shared_history": key.shared_history || false
        }
      };
    })();
  }

  /**
   * @param untrusted - whether the key should be considered as untrusted
   * @param source - where the key came from
   */
  importRoomKey(session) {
    var {
      untrusted,
      source
    } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var extraSessionData = {};
    if (untrusted || session.untrusted) {
      extraSessionData.untrusted = true;
    }
    if (session["org.matrix.msc3061.shared_history"]) {
      extraSessionData.sharedHistory = true;
    }
    return this.olmDevice.addInboundGroupSession(session.room_id, session.sender_key, session.forwarding_curve25519_key_chain, session.session_id, session.session_key, session.sender_claimed_keys, true, extraSessionData).then(() => {
      if (source !== "backup") {
        // don't wait for it to complete
        this.crypto.backupManager.backupGroupSession(session.sender_key, session.session_id).catch(e => {
          // This throws if the upload failed, but this is fine
          // since it will have written it to the db and will retry.
          this.prefixedLogger.debug("Failed to back up megolm session", e);
        });
      }
      // have another go at decrypting events sent with this session.
      this.retryDecryption(session.sender_key, session.session_id, !extraSessionData.untrusted);
    });
  }

  /**
   * Have another go at decrypting events after we receive a key. Resolves once
   * decryption has been re-attempted on all events.
   *
   * @internal
   * @param forceRedecryptIfUntrusted - whether messages that were already
   *     successfully decrypted using untrusted keys should be re-decrypted
   *
   * @returns whether all messages were successfully
   *     decrypted with trusted keys
   */
  retryDecryption(senderKey, sessionId, forceRedecryptIfUntrusted) {
    var _this24 = this;
    return _asyncToGenerator(function* () {
      var _this24$pendingEvents;
      var senderPendingEvents = _this24.pendingEvents.get(senderKey);
      if (!senderPendingEvents) {
        return true;
      }
      var pending = senderPendingEvents.get(sessionId);
      if (!pending) {
        return true;
      }
      var pendingList = [...pending];
      _this24.prefixedLogger.debug("Retrying decryption on events:", pendingList.map(e => "".concat(e.getId())));
      yield Promise.all(pendingList.map(/*#__PURE__*/function () {
        var _ref15 = _asyncToGenerator(function* (ev) {
          try {
            yield ev.attemptDecryption(_this24.crypto, {
              isRetry: true,
              forceRedecryptIfUntrusted
            });
          } catch (e) {
            // don't die if something goes wrong
          }
        });
        return function (_x2) {
          return _ref15.apply(this, arguments);
        };
      }()));

      // If decrypted successfully with trusted keys, they'll have
      // been removed from pendingEvents
      return !((_this24$pendingEvents = _this24.pendingEvents.get(senderKey)) !== null && _this24$pendingEvents !== void 0 && _this24$pendingEvents.has(sessionId));
    })();
  }
  retryDecryptionFromSender(senderKey) {
    var _this25 = this;
    return _asyncToGenerator(function* () {
      var senderPendingEvents = _this25.pendingEvents.get(senderKey);
      if (!senderPendingEvents) {
        return true;
      }
      _this25.pendingEvents.delete(senderKey);
      yield Promise.all([...senderPendingEvents].map(/*#__PURE__*/function () {
        var _ref17 = _asyncToGenerator(function* (_ref16) {
          var [_sessionId, pending] = _ref16;
          yield Promise.all([...pending].map(/*#__PURE__*/function () {
            var _ref18 = _asyncToGenerator(function* (ev) {
              try {
                yield ev.attemptDecryption(_this25.crypto);
              } catch (e) {
                // don't die if something goes wrong
              }
            });
            return function (_x4) {
              return _ref18.apply(this, arguments);
            };
          }()));
        });
        return function (_x3) {
          return _ref17.apply(this, arguments);
        };
      }()));
      return !_this25.pendingEvents.has(senderKey);
    })();
  }
  sendSharedHistoryInboundSessions(devicesByUser) {
    var _this26 = this;
    return _asyncToGenerator(function* () {
      yield olmlib.ensureOlmSessionsForDevices(_this26.olmDevice, _this26.baseApis, devicesByUser);
      var sharedHistorySessions = yield _this26.olmDevice.getSharedHistoryInboundGroupSessions(_this26.roomId);
      _this26.prefixedLogger.debug("Sharing history in with users ".concat(Array.from(devicesByUser.keys())), sharedHistorySessions.map(_ref19 => {
        var [senderKey, sessionId] = _ref19;
        return "".concat(senderKey, "|").concat(sessionId);
      }));
      for (var [senderKey, _sessionId2] of sharedHistorySessions) {
        var payload = yield _this26.buildKeyForwardingMessage(_this26.roomId, senderKey, _sessionId2);

        // FIXME: use encryptAndSendToDevices() rather than duplicating it here.
        var promises = [];
        var contentMap = new Map();
        for (var [userId, devices] of devicesByUser) {
          var deviceMessages = new Map();
          contentMap.set(userId, deviceMessages);
          for (var deviceInfo of devices) {
            var encryptedContent = {
              algorithm: olmlib.OLM_ALGORITHM,
              sender_key: _this26.olmDevice.deviceCurve25519Key,
              ciphertext: {},
              [ToDeviceMessageId]: uuidv4()
            };
            deviceMessages.set(deviceInfo.deviceId, encryptedContent);
            promises.push(olmlib.encryptMessageForDevice(encryptedContent.ciphertext, _this26.userId, undefined, _this26.olmDevice, userId, deviceInfo, payload));
          }
        }
        yield Promise.all(promises);

        // prune out any devices that encryptMessageForDevice could not encrypt for,
        // in which case it will have just not added anything to the ciphertext object.
        // There's no point sending messages to devices if we couldn't encrypt to them,
        // since that's effectively a blank message.
        for (var [_userId5, _deviceMessages] of contentMap) {
          for (var [deviceId, content] of _deviceMessages) {
            if (!hasCiphertext(content)) {
              _this26.prefixedLogger.debug("No ciphertext for device " + _userId5 + ":" + deviceId + ": pruning");
              _deviceMessages.delete(deviceId);
            }
          }
          // No devices left for that user? Strip that too.
          if (_deviceMessages.size === 0) {
            _this26.prefixedLogger.debug("Pruned all devices for user " + _userId5);
            contentMap.delete(_userId5);
          }
        }

        // Is there anything left?
        if (contentMap.size === 0) {
          _this26.prefixedLogger.debug("No users left to send to: aborting");
          return;
        }
        yield _this26.baseApis.sendToDevice("m.room.encrypted", contentMap);
      }
    })();
  }
}
var PROBLEM_DESCRIPTIONS = {
  no_olm: "The sender was unable to establish a secure channel.",
  unknown: "The secure channel with the sender was corrupted."
};
registerAlgorithm(olmlib.MEGOLM_ALGORITHM, MegolmEncryption, MegolmDecryption);
//# sourceMappingURL=megolm.js.map