diff --git a/bookmarklet.js b/bookmarklet.js index 2a8a1b1..d4c07b3 100644 --- a/bookmarklet.js +++ b/bookmarklet.js @@ -57,4 +57,4 @@ object-assign * content-type * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed - */var r=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,i=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,s=/\\([\u000b\u0020-\u00ff])/g,a=/([\\"])/g,c=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function f(e){var t=String(e);if(o.test(t))return t;if(t.length>0&&!i.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(a,"\\$1")+'"'}function u(e){this.parameters=Object.create(null),this.type=e}t.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,n=e.type;if(!n||!c.test(n))throw new TypeError("invalid type");var r=n;if(t&&"object"==typeof t)for(var i,s=Object.keys(t).sort(),a=0;an)break;t=s.shift(),t.key,i.push(t)}c();for(let n=0;n>1;t(e[i])>0?r=i:n=i+1}return n}}).call(this,n(5))},function(e,t,n){"use strict";function r(e){this.filter_json=e,this.types=e.types||null,this.not_types=e.not_types||[],this.rooms=e.rooms||null,this.not_rooms=e.not_rooms||[],this.senders=e.senders||null,this.not_senders=e.not_senders||[],this.contains_url=e.contains_url||null}Object.defineProperty(t,"__esModule",{value:!0}),t.FilterComponent=r,r.prototype.check=function(e){return this._checkFields(e.getRoomId(),e.getSender(),e.getType(),!!e.getContent()&&void 0!==e.getContent().url)},r.prototype._checkFields=function(e,t,n,r){const i={rooms:function(t){return e===t},senders:function(e){return t===e},types:function(e){return function(e,t){if(t.endsWith("*")){const n=t.slice(0,-1);return e.substr(0,n.length)===n}return e===t}(n,e)}},o=this;for(let e=0;e0)return!1;const r=o[t];if(r&&!r.map(n))return!1}const s=this.filter_json.contains_url;return void 0===s||s===r},r.prototype.filter=function(e){return e.filter(this.check,this)},r.prototype.limit=function(){return void 0!==this.filter_json.limit?this.filter_json.limit:10}},function(e,t,n){"use strict";(function(e){var r=n(6);Object.defineProperty(t,"__esModule",{value:!0}),t.SyncApi=m;var i=n(48),o=n(130),s=n(133),a=r(n(8)),c=n(76),f=n(25),u=n(75),l=n(4),d=n(79);function h(e,t){return"FILTER_SYNC_"+e+(t?"_"+t:"")}function p(...e){l.logger.log(...e)}function m(e,t){this.client=e,(t=t||{}).initialSyncLimit=void 0===t.initialSyncLimit?8:t.initialSyncLimit,t.resolveInvitesToProfiles=t.resolveInvitesToProfiles||!1,t.pollTimeout=t.pollTimeout||3e4,t.pendingEventOrdering=t.pendingEventOrdering||"chronological",t.canResetEntireTimeline||(t.canResetEntireTimeline=function(e){return!1}),this.opts=t,this._peekRoomId=null,this._currentSyncRequest=null,this._syncState=null,this._syncStateData=null,this._catchingUp=!1,this._running=!1,this._keepAliveTimer=null,this._connectionReturnedDefer=null,this._notifEvents=[],this._failedSyncCount=0,this._storeIsInvalid=!1,e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),["Room.timeline","Room.timelineReset"])}function g(e,t){const n=new i.User(t);return e.reEmitter.reEmit(n,["User.avatarUrl","User.displayName","User.presence","User.currentlyActive","User.lastPresenceTs"]),n}m.prototype.createRoom=function(e){const t=this.client,{timelineSupport:n,unstableClientRelationAggregation:r}=t,i=new o.Room(e,t,t.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:n,unstableClientRelationAggregation:r});return t.reEmitter.reEmit(i,["Room.name","Room.timeline","Room.redaction","Room.redactionCancelled","Room.receipt","Room.tags","Room.timelineReset","Room.localEchoUpdated","Room.accountData","Room.myMembership","Room.replaceEvent"]),this._registerStateListeners(i),i},m.prototype.createGroup=function(e){const t=this.client,n=new s.Group(e);return t.reEmitter.reEmit(n,["Group.profile","Group.myMembership"]),t.store.storeGroup(n),n},m.prototype._registerStateListeners=function(e){const t=this.client;t.reEmitter.reEmit(e.currentState,["RoomState.events","RoomState.members","RoomState.newMember"]),e.currentState.on("RoomState.newMember",(function(e,n,r){r.user=t.getUser(r.userId),t.reEmitter.reEmit(r,["RoomMember.name","RoomMember.typing","RoomMember.powerLevel","RoomMember.membership"])}))},m.prototype._deregisterStateListeners=function(e){e.currentState.removeAllListeners("RoomState.events"),e.currentState.removeAllListeners("RoomState.members"),e.currentState.removeAllListeners("RoomState.newMember")},m.prototype.syncLeftRooms=function(){const e=this.client,t=this,n=new c.Filter(this.client.credentials.userId);n.setTimelineLimit(1),n.setIncludeLeaveRooms(!0);const r=this.opts.pollTimeout+8e4,i={timeout:0};return e.getOrCreateFilter(h(e.credentials.userId,"LEFT_ROOMS"),n).then((function(t){return i.filter=t,e._http.authedRequest(void 0,"GET","/sync",i,void 0,r)})).then((function(n){let r=[];n.rooms&&n.rooms.leave&&(r=t._mapSyncResponseToRoomArray(n.rooms.leave));const i=[];return r.forEach((function(n){const r=n.room;if(i.push(r),!n.isBrandNewRoom)return;n.timeline=n.timeline||{};const o=t._mapSyncEventsFormat(n.timeline,r),s=t._mapSyncEventsFormat(n.state,r);r.getLiveTimeline().setPaginationToken(n.timeline.prev_batch,f.EventTimeline.BACKWARDS),t._processRoomEvents(r,s,o),r.recalculate(),e.store.storeRoom(r),e.emit("Room",r),t._processEventsForNotifs(r,o)})),i}))},m.prototype.peek=function(e){const t=this,n=this.client;return this._peekRoomId=e,this.client.roomInitialSync(e,20).then((function(r){r.messages=r.messages||{},r.messages.chunk=r.messages.chunk||[],r.state=r.state||[];const i=t.createRoom(e),o=a.map(a.deepCopy(r.state),n.getEventMapper()),s=a.map(r.state,n.getEventMapper()),c=a.map(r.messages.chunk,n.getEventMapper());return r.presence&&a.isArray(r.presence)&&r.presence.map(n.getEventMapper()).forEach((function(e){let t=n.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=g(n,e.getContent().user_id),t.setPresenceEvent(e),n.store.storeUser(t)),n.emit("event",e)})),r.messages.start&&(i.oldState.paginationToken=r.messages.start),i.oldState.setStateEvents(o),i.currentState.setStateEvents(s),t._resolveInvites(i),i.recalculate(),i.addEventsToTimeline(c.reverse(),!0,i.getLiveTimeline(),r.messages.start),n.store.storeRoom(i),n.emit("Room",i),t._peekPoll(i),i}))},m.prototype.stopPeeking=function(){this._peekRoomId=null},m.prototype._peekPoll=function(e,t){if(this._peekRoomId!==e.roomId)return void p("Stopped peeking in room %s",e.roomId);const n=this;this.client._http.authedRequest(void 0,"GET","/events",{room_id:e.roomId,timeout:3e4,from:t},void 0,5e4).then((function(t){if(n._peekRoomId!==e.roomId)return void p("Stopped peeking in room %s",e.roomId);t.chunk.filter((function(e){return"m.presence"===e.type})).map(n.client.getEventMapper()).forEach((function(e){let t=n.client.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=g(n.client,e.getContent().user_id),t.setPresenceEvent(e),n.client.store.storeUser(t)),n.client.emit("event",e)}));const r=t.chunk.filter((function(t){return t.room_id===e.roomId})).map(n.client.getEventMapper());e.addLiveEvents(r),n._peekPoll(e,t.end)}),(function(r){l.logger.error("[%s] Peek poll failed: %s",e.roomId,r),setTimeout((function(){n._peekPoll(e,t)}),3e4)}))},m.prototype.getSyncState=function(){return this._syncState},m.prototype.getSyncStateData=function(){return this._syncStateData},m.prototype.recoverFromSyncStartupError=async function(e,t){await e;const n=this._startKeepAlives();this._updateSyncState("ERROR",{error:t}),await n},m.prototype._wasLazyLoadingToggled=async function(e){e=!!e;let t=!1;if(!await this.client.store.isNewlyCreated()){const n=await this.client.store.getClientOptions();return n&&(t=!!n.lazyLoadMembers),t!==e}return!1},m.prototype._shouldAbortSync=function(e){return"M_UNKNOWN_TOKEN"===e.errcode&&(l.logger.warn("Token no longer valid - assuming logout"),this.stop(),!0)},m.prototype.sync=function(){const t=this.client,n=this;this._running=!0,e.document&&(this._onOnlineBound=this._onOnline.bind(this),e.document.addEventListener("online",this._onOnlineBound,!1));let r=Promise.resolve(),i=null;const o=async()=>{if(p("Checking lazy load status..."),this.opts.lazyLoadMembers&&t.isGuest()&&(this.opts.lazyLoadMembers=!1),this.opts.lazyLoadMembers){if(p("Checking server lazy load support..."),await t.doesServerSupportLazyLoading())try{p("Creating and storing lazy load sync filter..."),this.opts.filter=await t.createFilter(c.Filter.LAZY_LOADING_SYNC_FILTER),p("Created and stored lazy load sync filter")}catch(e){throw l.logger.error("Creating and storing lazy load sync filter failed",e),e}else p("LL: lazy loading requested but not supported by server, so disabling"),this.opts.lazyLoadMembers=!1}if(p("Checking whether lazy loading has changed in store..."),await this._wasLazyLoadingToggled(this.opts.lazyLoadMembers)){this._storeIsInvalid=!0;const e=d.InvalidStoreError.TOGGLED_LAZY_LOADING,t=new d.InvalidStoreError(e,!!this.opts.lazyLoadMembers);return this._updateSyncState("ERROR",{error:t}),void l.logger.warn("InvalidStoreError: store is not usable: stopping sync.")}this.opts.lazyLoadMembers&&this.opts.crypto&&this.opts.crypto.enableLazyLoading();try{p("Storing client options..."),await this.client._storeClientOptions(),p("Stored client options")}catch(e){throw l.logger.error("Storing client options failed",e),e}!async function e(){let o,s;p("Getting filter..."),n.opts.filter?o=n.opts.filter:(o=new c.Filter(t.credentials.userId),o.setTimelineLimit(n.opts.initialSyncLimit));try{s=await t.getOrCreateFilter(h(t.credentials.userId),o)}catch(t){if(l.logger.error("Getting filter failed",t),n._shouldAbortSync(t))return;return p("Waiting for saved sync before retrying filter..."),await n.recoverFromSyncStartupError(r,t),void e()}t.resetNotifTimelineSet(),null===n._currentSyncRequest&&(p("Sending first sync request..."),n._currentSyncRequest=n._doSyncRequest({filterId:s},i));p("Waiting for saved sync before starting sync processing..."),await r,n._sync({filterId:s})}()};t.isGuest()?n._sync({}):(p("Getting saved sync token..."),r=t.store.getSavedSyncToken().then(e=>(p("Got saved sync token"),i=e,p("Getting saved sync..."),t.store.getSavedSync())).then(e=>{if(p(`Got reply from saved sync, exists? ${!!e}`),e)return n._syncFromCache(e)}).catch(e=>{l.logger.error("Getting saved sync failed",e)}),async function e(){try{p("Getting push rules...");const e=await t.getPushRules();p("Got push rules"),t.pushRules=e}catch(t){if(l.logger.error("Getting push rules failed",t),n._shouldAbortSync(t))return;return p("Waiting for saved sync before retrying push rules..."),await n.recoverFromSyncStartupError(r,t),void e()}o()}())},m.prototype.stop=function(){p("SyncApi.stop"),e.document&&(e.document.removeEventListener("online",this._onOnlineBound,!1),this._onOnlineBound=void 0),this._running=!1,this._currentSyncRequest&&this._currentSyncRequest.abort(),this._keepAliveTimer&&(clearTimeout(this._keepAliveTimer),this._keepAliveTimer=null)},m.prototype.retryImmediately=function(){return!!this._connectionReturnedDefer&&(this._startKeepAlives(0),!0)},m.prototype._syncFromCache=async function(e){p("sync(): not doing HTTP hit, instead returning stored /sync data");const t=e.nextBatch;this.client.store.setSyncToken(t);const n={oldSyncToken:null,nextSyncToken:t,catchingUp:!1},r={next_batch:t,rooms:e.roomsData,groups:e.groupsData,account_data:{events:e.accountData}};try{await this._processSyncResponse(n,r)}catch(e){l.logger.error("Error processing cached sync",e.stack||e)}this._storeIsInvalid||this._updateSyncState("PREPARED",n)},m.prototype._sync=async function(e){const t=this.client;if(!this._running)return p("Sync no longer running: exiting."),this._connectionReturnedDefer&&(this._connectionReturnedDefer.reject(),this._connectionReturnedDefer=null),void this._updateSyncState("STOPPED");const n=t.store.getSyncToken();let r;try{null===this._currentSyncRequest&&(this._currentSyncRequest=this._doSyncRequest(e,n)),r=await this._currentSyncRequest}catch(t){return void this._onSyncError(t,e)}finally{this._currentSyncRequest=null}t.store.setSyncToken(r.next_batch),this._failedSyncCount=0,await t.store.setSyncData(r);const i={oldSyncToken:n,nextSyncToken:r.next_batch,catchingUp:this._catchingUp};this.opts.crypto&&await this.opts.crypto.onSyncWillProcess(i);try{await this._processSyncResponse(i,r)}catch(e){l.logger.error("Caught /sync error",e.stack||e),this.client.emit("sync.unexpectedError",e)}i.catchingUp=this._catchingUp,e.hasSyncedBefore||(this._updateSyncState("PREPARED",i),e.hasSyncedBefore=!0),this.opts.crypto&&await this.opts.crypto.onSyncCompleted(i),this._updateSyncState("SYNCING",i),t.store.wantsSave()&&(this.opts.crypto&&await this.opts.crypto.saveDeviceList(0),t.store.save()),this._sync(e)},m.prototype._doSyncRequest=function(e,t){const n=this._getSyncParams(e,t);return this.client._http.authedRequest(void 0,"GET","/sync",n,void 0,n.timeout+8e4)},m.prototype._getSyncParams=function(e,t){let n=this.opts.pollTimeout;("SYNCING"!==this.getSyncState()||this._catchingUp)&&(this._catchingUp=!0,n=0);let r=e.filterId;this.client.isGuest()&&!r&&(r=this._getGuestFilter());const i={filter:r,timeout:n};return this.opts.disablePresence&&(i.set_presence="offline"),t?i.since=t:i._cacheBuster=Date.now(),"ERROR"!=this.getSyncState()&&"RECONNECTING"!=this.getSyncState()||(i.timeout=0),i},m.prototype._onSyncError=function(e,t){if(!this._running)return p("Sync no longer running: exiting"),this._connectionReturnedDefer&&(this._connectionReturnedDefer.reject(),this._connectionReturnedDefer=null),void this._updateSyncState("STOPPED");l.logger.error("/sync error %s",e),l.logger.error(e),this._shouldAbortSync(e)||(this._failedSyncCount++,l.logger.log("Number of consecutive failed sync requests:",this._failedSyncCount),p("Starting keep-alive"),this._startKeepAlives().then(e=>{e&&"ERROR"===this.getSyncState()&&this._updateSyncState("CATCHUP",{oldSyncToken:null,nextSyncToken:null,catchingUp:!0}),this._sync(t)}),this._currentSyncRequest=null,this._updateSyncState(this._failedSyncCount>=3?"ERROR":"RECONNECTING",{error:e}))},m.prototype._processSyncResponse=async function(e,t){const n=this.client,r=this;if(t.presence&&a.isArray(t.presence.events)&&t.presence.events.map(n.getEventMapper()).forEach((function(e){let t=n.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=g(n,e.getSender()),t.setPresenceEvent(e),n.store.storeUser(t)),n.emit("event",e)})),t.account_data&&a.isArray(t.account_data.events)){const e=t.account_data.events.map(n.getEventMapper());n.store.storeAccountDataEvents(e),e.forEach((function(e){if("m.push_rules"===e.getType()){const t=e.getContent();n.pushRules=u.PushProcessor.rewriteDefaultRules(t)}return n.emit("accountData",e),e}))}if(t.to_device&&a.isArray(t.to_device.events)&&t.to_device.events.length>0){const e=[];t.to_device.events.map(n.getEventMapper()).map(t=>{if("m.key.verification.cancel"===t.getType()){const n=t.getContent().transaction_id;n&&e.push(n)}return t}).forEach((function(t){const r=t.getContent();if("m.room.message"!=t.getType()||"m.bad.encrypted"!=r.msgtype){if("m.key.verification.start"===t.getType()||"m.key.verification.request"===t.getType()){const n=r.transaction_id;e.includes(n)&&t.flagCancelled()}n.emit("toDeviceEvent",t)}else l.logger.log("Ignoring undecryptable to-device event from "+t.getSender())}))}else this._catchingUp=!1;t.groups&&(t.groups.invite&&this._processGroupSyncEntry(t.groups.invite,"invite"),t.groups.join&&this._processGroupSyncEntry(t.groups.join,"join"),t.groups.leave&&this._processGroupSyncEntry(t.groups.leave,"leave"));let i=[],o=[],s=[];if(t.rooms&&(t.rooms.invite&&(i=this._mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(o=this._mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(s=this._mapSyncResponseToRoomArray(t.rooms.leave))),this._notifEvents=[],i.forEach((function(e){const t=e.room,i=r._mapSyncEventsFormat(e.invite_state,t);r._processRoomEvents(t,i),e.isBrandNewRoom&&(t.recalculate(),n.store.storeRoom(t),n.emit("Room",t)),i.forEach((function(e){n.emit("event",e)})),t.updateMyMembership("invite")})),await a.promiseMapSeries(o,(async function(t){const i=t.room,o=r._mapSyncEventsFormat(t.state,i),s=r._mapSyncEventsFormat(t.timeline,i),c=r._mapSyncEventsFormat(t.ephemeral),u=r._mapSyncEventsFormat(t.account_data);if(t.unread_notifications){i.setUnreadNotificationCount("total",t.unread_notifications.notification_count);const e=n.isRoomEncrypted(i.roomId);(!e||e&&i.getUnreadNotificationCount("highlight")<=0)&&i.setUnreadNotificationCount("highlight",t.unread_notifications.highlight_count)}if(t.timeline=t.timeline||{},t.isBrandNewRoom)i.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,f.EventTimeline.BACKWARDS);else if(t.timeline.limited){let o=!0;for(let e=s.length-1;e>=0;e--){const t=s[e].getId();if(i.getTimelineForEvent(t)){p("Already have event "+t+" in limited sync - not resetting"),o=!1,s.splice(0,e);break}}o&&(r._deregisterStateListeners(i),i.resetLiveTimeline(t.timeline.prev_batch,r.opts.canResetEntireTimeline(i.roomId)?null:e.oldSyncToken),n.resetNotifTimelineSet(),r._registerStateListeners(i))}async function l(e){if(n.emit("event",e),e.isState()&&"m.room.encryption"==e.getType()&&r.opts.crypto&&await r.opts.crypto.onCryptoEvent(e),e.isState()&&"im.vector.user_status"===e.getType()){let t=n.store.getUser(e.getStateKey());t?t._unstable_updateStatusMessage(e):(t=g(n,e.getStateKey()),t._unstable_updateStatusMessage(e),n.store.storeUser(t))}}r._processRoomEvents(i,o,s),t.summary&&i.setSummary(t.summary),i.addEphemeralEvents(c),i.addAccountData(u),i.recalculate(),t.isBrandNewRoom&&(n.store.storeRoom(i),n.emit("Room",i)),r._processEventsForNotifs(i,s),await a.promiseMapSeries(o,l),await a.promiseMapSeries(s,l),c.forEach((function(e){n.emit("event",e)})),u.forEach((function(e){n.emit("event",e)})),i.updateMyMembership("join")})),s.forEach((function(e){const t=e.room,i=r._mapSyncEventsFormat(e.state,t),o=r._mapSyncEventsFormat(e.timeline,t),s=r._mapSyncEventsFormat(e.account_data);r._processRoomEvents(t,i,o),t.addAccountData(s),t.recalculate(),e.isBrandNewRoom&&(n.store.storeRoom(t),n.emit("Room",t)),r._processEventsForNotifs(t,o),i.forEach((function(e){n.emit("event",e)})),o.forEach((function(e){n.emit("event",e)})),s.forEach((function(e){n.emit("event",e)})),t.updateMyMembership("leave")})),e.oldSyncToken&&this._notifEvents.length&&(this._notifEvents.sort((function(e,t){return e.getTs()-t.getTs()})),this._notifEvents.forEach((function(e){n.getNotifTimelineSet().addLiveEvent(e)}))),t.device_lists&&this.opts.crypto&&await this.opts.crypto.handleDeviceListChanges(e,t.device_lists),this.opts.crypto&&t.device_one_time_keys_count){const e=t.device_one_time_keys_count.signed_curve25519||0;this.opts.crypto.updateOneTimeKeyCount(e)}},m.prototype._startKeepAlives=function(e){void 0===e&&(e=2e3+Math.floor(5e3*Math.random())),null!==this._keepAliveTimer&&clearTimeout(this._keepAliveTimer);const t=this;return e>0?t._keepAliveTimer=setTimeout(t._pokeKeepAlive.bind(t),e):t._pokeKeepAlive(),this._connectionReturnedDefer||(this._connectionReturnedDefer=a.defer()),this._connectionReturnedDefer.promise},m.prototype._pokeKeepAlive=function(e){void 0===e&&(e=!1);const t=this;function n(){clearTimeout(t._keepAliveTimer),t._connectionReturnedDefer&&(t._connectionReturnedDefer.resolve(e),t._connectionReturnedDefer=null)}this.client._http.request(void 0,"GET","/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15e3}).then((function(){n()}),(function(r){400==r.httpStatus||404==r.httpStatus?t._keepAliveTimer=setTimeout(n,2e3):(e=!0,t._keepAliveTimer=setTimeout(t._pokeKeepAlive.bind(t,e),5e3+Math.floor(5e3*Math.random())),t._updateSyncState("ERROR",{error:r}))}))},m.prototype._processGroupSyncEntry=function(e,t){for(const n of Object.keys(e)){const r=e[n];let i=this.client.store.getGroup(n);const o=null===i;null===i&&(i=this.createGroup(n)),r.profile&&i.setProfile(r.profile.name,r.profile.avatar_url),r.inviter&&i.setInviter({userId:r.inviter}),i.setMyMembership(t),o&&this.client.emit("Group",i)}},m.prototype._mapSyncResponseToRoomArray=function(e){const t=this.client,n=this;return a.keys(e).map((function(r){const i=e[r];let o=t.store.getRoom(r),s=!1;return o||(o=n.createRoom(r),s=!0),i.room=o,i.isBrandNewRoom=s,i}))},m.prototype._mapSyncEventsFormat=function(e,t){if(!e||!a.isArray(e.events))return[];const n=this.client.getEventMapper();return e.events.map((function(e){return t&&(e.room_id=t.roomId),n(e)}))},m.prototype._resolveInvites=function(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership("invite").forEach((function(n){if(n._requestedProfileInfo)return;n._requestedProfileInfo=!0;const r=t.getUser(n.userId);let i;i=r?Promise.resolve({avatar_url:r.avatarUrl,displayname:r.displayName}):t.getProfileInfo(n.userId),i.then((function(t){const r=n.events.member;"invite"===r.getContent().membership&&(r.getContent().avatar_url=t.avatar_url,r.getContent().displayname=t.displayname,n.setMembershipEvent(r,e.currentState))}),(function(e){}))}))},m.prototype._processRoomEvents=function(e,t,n){const r=e.getLiveTimeline(),i=0==r.getEvents().length;if(i){for(const e of t)this.client.getPushActionsForEvent(e);r.initialiseState(t)}this._resolveInvites(e),e.recalculate(),i||(e.oldState.setStateEvents(t||[]),e.currentState.setStateEvents(t||[])),e.addLiveEvents(n||[])},m.prototype._processEventsForNotifs=function(e,t){if(this.client.getNotifTimelineSet())for(let e=0;e{e.isSending()?t===s.EventStatus.CANCELLED&&(e.removeListener("Event.status",this._onEventStatus),this._removeEvent(e)):e.removeListener("Event.status",this._onEventStatus)}),(0,i.default)(this,"_onBeforeRedaction",e=>{this._relations.has(e)&&(this._relations.delete(e),"m.annotation"===this.relationType?this._removeAnnotationFromAggregation(e):"m.replace"===this.relationType&&this._targetEvent&&this._targetEvent.makeReplaced(this.getLastReplacement()),e.removeListener("Event.beforeRedaction",this._onBeforeRedaction),this.emit("Relations.redaction",e))}),this.relationType=e,this.eventType=t,this._relations=new Set,this._annotationsByKey={},this._annotationsBySender={},this._sortedAnnotationsByKey=[],this._targetEvent=null}addEvent(e){if(this._relations.has(e))return;const t=e.getRelation();if(!t)return void console.error("Event must have relation info");const n=t.rel_type,r=e.getType();this.relationType===n&&this.eventType===r?(e.isSending()&&e.on("Event.status",this._onEventStatus),this._relations.add(e),"m.annotation"===this.relationType?this._addAnnotationToAggregation(e):"m.replace"===this.relationType&&this._targetEvent&&this._targetEvent.makeReplaced(this.getLastReplacement()),e.on("Event.beforeRedaction",this._onBeforeRedaction),this.emit("Relations.add",e)):console.error("Event relation info doesn't match this container")}_removeEvent(e){if(!this._relations.has(e))return;const t=e.getRelation();if(!t)return void console.error("Event must have relation info");const n=t.rel_type,r=e.getType();this.relationType===n&&this.eventType===r?(this._relations.delete(e),"m.annotation"===this.relationType?this._removeAnnotationFromAggregation(e):"m.replace"===this.relationType&&this._targetEvent&&this._targetEvent.makeReplaced(this.getLastReplacement()),this.emit("Relations.remove",e)):console.error("Event relation info doesn't match this container")}getRelations(){return[...this._relations]}_addAnnotationToAggregation(e){const{key:t}=e.getRelation();if(!t)return;let n=this._annotationsByKey[t];n||(n=this._annotationsByKey[t]=new Set,this._sortedAnnotationsByKey.push([t,n])),n.add(e),this._sortedAnnotationsByKey.sort((e,t)=>{const n=e[1];return t[1].size-n.size});const r=e.getSender();let i=this._annotationsBySender[r];i||(i=this._annotationsBySender[r]=new Set),i.add(e)}_removeAnnotationFromAggregation(e){const{key:t}=e.getRelation();if(!t)return;const n=this._annotationsByKey[t];n&&(n.delete(e),this._sortedAnnotationsByKey.sort((e,t)=>{const n=e[1];return t[1].size-n.size}));const r=e.getSender(),i=this._annotationsBySender[r];i&&i.delete(e)}getSortedAnnotationsByKey(){return"m.annotation"!==this.relationType?null:this._sortedAnnotationsByKey}getAnnotationsBySender(){return"m.annotation"!==this.relationType?null:this._annotationsBySender}getLastReplacement(){if("m.replace"!==this.relationType)return null;if(!this._targetEvent)return null;const e=this._targetEvent.getServerAggregatedRelation("m.replace"),t=e&&e.origin_server_ts;return this.getRelations().reduce((e,n)=>n.getSender()!==this._targetEvent.getSender()?e:t&&t>n.getTs()?e:e&&e.getTs()>n.getTs()?e:n,null)}setTargetEvent(e){if(!this._targetEvent&&(this._targetEvent=e,"m.replace"===this.relationType)){const e=this.getLastReplacement();e&&this._targetEvent.makeReplaced(e)}}}t.Relations=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RoomSummary=function(e,t){this.roomId=e,this.info=t}},function(e,t,n){"use strict";var r=n(6);Object.defineProperty(t,"__esModule",{value:!0}),t.SearchResult=s;var i=r(n(8)),o=n(282);function s(e,t){this.rank=e,this.context=t}s.fromJson=function(e,t){const n=e.context||{},r=n.events_before||[],a=n.events_after||[],c=new o.EventContext(t(e.result));return c.setPaginateToken(n.start,!0),c.addEvents(i.map(r,t),!0),c.addEvents(i.map(a,t),!1),c.setPaginateToken(n.end,!1),new s(e.rank,c)}},function(e,t,n){"use strict";function r(e){this._timeline=[e],this._ourEventIndex=0,this._paginateTokens={b:null,f:null},this._paginateRequests={b:null,f:null}}Object.defineProperty(t,"__esModule",{value:!0}),t.EventContext=r,r.prototype.getEvent=function(){return this._timeline[this._ourEventIndex]},r.prototype.getTimeline=function(){return this._timeline},r.prototype.getOurEventIndex=function(){return this._ourEventIndex},r.prototype.getPaginateToken=function(e){return this._paginateTokens[e?"b":"f"]},r.prototype.setPaginateToken=function(e,t){this._paginateTokens[t?"b":"f"]=e},r.prototype.addEvents=function(e,t){t?(this._timeline=e.concat(this._timeline),this._ourEventIndex+=e.length):this._timeline=this._timeline.concat(e)}},function(e,t,n){"use strict";function r(){this.fromToken=null}Object.defineProperty(t,"__esModule",{value:!0}),t.StubStore=r,r.prototype={isNewlyCreated:function(){return Promise.resolve(!0)},getSyncToken:function(){return this.fromToken},setSyncToken:function(e){this.fromToken=e},storeGroup:function(e){},getGroup:function(e){return null},getGroups:function(){return[]},storeRoom:function(e){},getRoom:function(e){return null},getRooms:function(){return[]},removeRoom:function(e){},getRoomSummaries:function(){return[]},storeUser:function(e){},getUser:function(e){return null},getUsers:function(){return[]},scrollback:function(e,t){return[]},storeEvents:function(e,t,n,r){},storeFilter:function(e){},getFilter:function(e,t){return null},getFilterIdByName:function(e){return null},setFilterIdByName:function(e,t){},storeAccountDataEvents:function(e){},getAccountData:function(e){},setSyncData:function(e){return Promise.resolve()},wantsSave:function(){return!1},save:function(){},startup:function(){return Promise.resolve()},getSavedSync:function(){return Promise.resolve(null)},getSavedSyncToken:function(){return Promise.resolve(null)},deleteAllData:function(){return Promise.resolve()},getOutOfBandMembers:function(){return Promise.resolve(null)},setOutOfBandMembers:function(){return Promise.resolve()},clearOutOfBandMembers:function(){return Promise.resolve()},getClientOptions:function(){return Promise.resolve()},storeClientOptions:function(){return Promise.resolve()}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RoomList=void 0;var r=n(36);t.RoomList=class{constructor(e){this._cryptoStore=e,this._roomEncryption={}}async init(){await this._cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ROOMS],e=>{this._cryptoStore.getEndToEndRooms(e,e=>{this._roomEncryption=e})})}getRoomEncryption(e){return this._roomEncryption[e]||null}isRoomEncrypted(e){return Boolean(this.getRoomEncryption(e))}async setRoomEncryption(e,t){this._roomEncryption[e]=t,await this._cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ROOMS],n=>{this._cryptoStore.storeEndToEndRoom(e,t,n)})}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LocalStorageCryptoStore=void 0;var r=n(4),i=n(73);function o(e){return"crypto.sessions/"+e}function s(e){return"crypto.session.problems/"+e}function a(e,t){return"crypto.inboundgroupsessions/"+e+"/"+t}function c(e,t){return"crypto.inboundgroupsessions.withheld/"+e+"/"+t}function f(e){return"crypto.rooms/"+e}class u extends i.MemoryCryptoStore{constructor(e){super(),this.store=e}static exists(e){const t=e.length;for(let n=0;ne.time-t.time),d(this.store,r,i)}async getEndToEndSessionProblem(e,t){const n=s(e),r=l(this.store,n)||[];if(!r.length)return null;const i=r[r.length-1];for(const e of r)if(e.time>t)return Object.assign({},e,{fixed:i.fixed});return i.fixed?null:i}async filterOutNotifiedErrorDevices(e){const t=l(this.store,"crypto.notified_error_devices")||{},n=[];for(const r of e){const{userId:e,deviceInfo:i}=r;e in t?i.deviceId in t[e]||(n.push(r),t[e][i.deviceId]=!0):(n.push(r),t[e]={[i.deviceId]:!0})}return d(this.store,"crypto.notified_error_devices",t),n}getEndToEndInboundGroupSession(e,t,n,r){r(l(this.store,a(e,t)),l(this.store,c(e,t)))}getAllEndToEndInboundGroupSessions(e,t){for(let e=0;e{n.push({senderKey:t,sessionId:i,sessionData:e})}),e&&r.length>=e)break}return Promise.resolve(n)}countSessionsNeedingBackup(){const e=l(this.store,"crypto.sessionsneedingbackup")||{};return Promise.resolve(Object.keys(e).length)}unmarkSessionsNeedingBackup(e){const t=l(this.store,"crypto.sessionsneedingbackup")||{};for(const n of e)delete t[n.senderKey+"/"+n.sessionId];return d(this.store,"crypto.sessionsneedingbackup",t),Promise.resolve()}markSessionsNeedingBackup(e){const t=l(this.store,"crypto.sessionsneedingbackup")||{};for(const n of e)t[n.senderKey+"/"+n.sessionId]=!0;return d(this.store,"crypto.sessionsneedingbackup",t),Promise.resolve()}deleteAllData(){return this.store.removeItem("crypto.account"),Promise.resolve()}getAccount(e,t){t(l(this.store,"crypto.account"))}storeAccount(e,t){d(this.store,"crypto.account",t)}getCrossSigningKeys(e,t){t(l(this.store,"crypto.cross_signing_keys"))}storeCrossSigningKeys(e,t){d(this.store,"crypto.cross_signing_keys",t)}doTxn(e,t,n){return Promise.resolve(n(null))}}function l(e,t){try{return JSON.parse(e.getItem(t))}catch(e){r.logger.log("Error: Failed to get key %s: %s",t,e.stack||e),r.logger.log(e.stack)}return null}function d(e,t,n){e.setItem(t,JSON.stringify(n))}t.LocalStorageCryptoStore=u},function(e,t,n){"use strict";var r=n(6);Object.defineProperty(t,"__esModule",{value:!0}),t.upgradeDatabase=function(e,t){i.logger.log(`Upgrading IndexedDBCryptoStore from version ${t}`+" to 9"),t<1&&function(e){const t=e.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});t.createIndex("session",["requestBody.room_id","requestBody.session_id"]),t.createIndex("state","state")}(e);t<2&&e.createObjectStore("account");if(t<3){e.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]}).createIndex("deviceKey","deviceKey")}t<4&&e.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]});t<5&&e.createObjectStore("device_data");t<6&&e.createObjectStore("rooms");t<7&&e.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]});t<8&&e.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]});if(t<9){e.createObjectStore("session_problems",{keyPath:["deviceKey","time"]}).createIndex("deviceKey","deviceKey"),e.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})}},t.Backend=t.VERSION=void 0;var i=n(4),o=r(n(8));t.VERSION=9;function s(e,t){e._mx_abortexception=t;try{e.abort()}catch(t){}}function a(e){return new Promise((t,n)=>{e.oncomplete=()=>{void 0!==e._mx_abortexception&&n(e._mx_abortexception),t()},e.onerror=t=>{void 0!==e._mx_abortexception?n(e._mx_abortexception):(i.logger.log("Error performing indexeddb txn",t),n(t.target.error))},e.onabort=t=>{void 0!==e._mx_abortexception?n(e._mx_abortexception):(i.logger.log("Error performing indexeddb txn",t),n(t.target.error))}})}t.Backend=class{constructor(e){this._db=e,e.onversionchange=t=>{i.logger.log(`versionchange for indexeddb ${this._dbName}: closing`),e.close()}}getOrAddOutgoingRoomKeyRequest(e){const t=e.requestBody;return new Promise((n,r)=>{const o=this._db.transaction("outgoingRoomKeyRequests","readwrite");o.onerror=r,this._getOutgoingRoomKeyRequest(o,t,r=>{if(r)return i.logger.log("already have key request outstanding for "+`${t.room_id} / ${t.session_id}: `+"not sending another"),void n(r);i.logger.log(`enqueueing key request for ${t.room_id} / `+t.session_id),o.oncomplete=()=>{n(e)},o.objectStore("outgoingRoomKeyRequests").add(e)})})}getOutgoingRoomKeyRequest(e){return new Promise((t,n)=>{const r=this._db.transaction("outgoingRoomKeyRequests","readonly");r.onerror=n,this._getOutgoingRoomKeyRequest(r,e,e=>{t(e)})})}_getOutgoingRoomKeyRequest(e,t,n){e.objectStore("outgoingRoomKeyRequests").index("session").openCursor([t.room_id,t.session_id]).onsuccess=e=>{const r=e.target.result;if(!r)return void n(null);const i=r.value;o.deepCompare(i.requestBody,t)?n(i):r.continue()}}getOutgoingRoomKeyRequestByState(e){if(0===e.length)return Promise.resolve(null);let t,n=0;const r=this._db.transaction("outgoingRoomKeyRequests","readonly"),i=r.objectStore("outgoingRoomKeyRequests"),o=e[n];return i.index("state").openCursor(o).onsuccess=function r(i){const o=i.target.result;if(o)return void(t=o.value);if(n++,n>=e.length)return;const s=e[n];i.target.source.openCursor(s).onsuccess=r},a(r).then(()=>t)}getOutgoingRoomKeyRequestsByTarget(e,t,n){let r=0;const i=[];const o=this._db.transaction("outgoingRoomKeyRequests","readonly"),s=o.objectStore("outgoingRoomKeyRequests"),c=n[r];return s.index("state").openCursor(c).onsuccess=function o(s){const a=s.target.result;if(a){const n=a.value;n.recipients.includes({userId:e,deviceId:t})&&i.push(n),a.continue()}else{if(r++,r>=n.length)return;const e=n[r];s.target.source.openCursor(e).onsuccess=o}},a(o).then(()=>i)}updateOutgoingRoomKeyRequest(e,t,n){let r=null;const o=this._db.transaction("outgoingRoomKeyRequests","readwrite");return o.objectStore("outgoingRoomKeyRequests").openCursor(e).onsuccess=function(e){const o=e.target.result;if(!o)return;const s=o.value;s.state==t?(Object.assign(s,n),o.update(s),r=s):i.logger.warn(`Cannot update room key request from ${t} `+`as it was already updated to ${s.state}`)},a(o).then(()=>r)}deleteOutgoingRoomKeyRequest(e,t){const n=this._db.transaction("outgoingRoomKeyRequests","readwrite");return n.objectStore("outgoingRoomKeyRequests").openCursor(e).onsuccess=e=>{const n=e.target.result;if(!n)return;const r=n.value;r.state==t?n.delete():i.logger.warn(`Cannot delete room key request in state ${r.state} `+`(expected ${t})`)},a(n)}getAccount(e,t){const n=e.objectStore("account").get("-");n.onsuccess=function(){try{t(n.result||null)}catch(t){s(e,t)}}}storeAccount(e,t){e.objectStore("account").put(t,"-")}getCrossSigningKeys(e,t){const n=e.objectStore("account").get("crossSigningKeys");n.onsuccess=function(){try{t(n.result||null)}catch(t){s(e,t)}}}storeCrossSigningKeys(e,t){e.objectStore("account").put(t,"crossSigningKeys")}countEndToEndSessions(e,t){const n=e.objectStore("sessions").count();n.onsuccess=function(){t(n.result)}}getEndToEndSessions(e,t,n){const r=t.objectStore("sessions").index("deviceKey").openCursor(e),i={};r.onsuccess=function(){const e=r.result;if(e)i[e.value.sessionId]={session:e.value.session,lastReceivedMessageTs:e.value.lastReceivedMessageTs},e.continue();else try{n(i)}catch(e){s(t,e)}}}getEndToEndSession(e,t,n,r){const i=n.objectStore("sessions").get([e,t]);i.onsuccess=function(){try{i.result?r({session:i.result.session,lastReceivedMessageTs:i.result.lastReceivedMessageTs}):r(null)}catch(e){s(n,e)}}}getAllEndToEndSessions(e,t){const n=e.objectStore("sessions").openCursor();n.onsuccess=function(){const r=n.result;if(r)t(r.value),r.continue();else try{t(null)}catch(t){s(e,t)}}}storeEndToEndSession(e,t,n,r){r.objectStore("sessions").put({deviceKey:e,sessionId:t,session:n.session,lastReceivedMessageTs:n.lastReceivedMessageTs})}async storeEndToEndSessionProblem(e,t,n){const r=this._db.transaction("session_problems","readwrite");return r.objectStore("session_problems").put({deviceKey:e,type:t,fixed:n,time:Date.now()}),a(r)}async getEndToEndSessionProblem(e,t){let n;const r=this._db.transaction("session_problems","readwrite"),i=r.objectStore("session_problems").index("deviceKey").getAll(e);return i.onsuccess=e=>{const r=i.result;if(!r.length)return void(n=null);r.sort((e,t)=>e.time-t.time);const o=r[r.length-1];for(const e of r)if(e.time>t)return void(n=Object.assign({},e,{fixed:o.fixed}));n=o.fixed?null:o},await a(r),n}async filterOutNotifiedErrorDevices(e){const t=this._db.transaction("notified_error_devices","readwrite").objectStore("notified_error_devices"),n=[];return await Promise.all(e.map(e=>new Promise(r=>{const{userId:i,deviceInfo:o}=e,s=t.get([i,o.deviceId]);s.onsuccess=function(){s.result||(t.put({userId:i,deviceId:o.deviceId}),n.push(e)),r()}}))),n}getEndToEndInboundGroupSession(e,t,n,r){let i=!1,o=!1;const a=n.objectStore("inbound_group_sessions").get([e,t]);a.onsuccess=function(){try{i=a.result?a.result.session:null,!1!==o&&r(i,o)}catch(e){s(n,e)}};const c=n.objectStore("inbound_group_sessions_withheld").get([e,t]);c.onsuccess=function(){try{o=c.result?c.result.session:null,!1!==i&&r(i,o)}catch(e){s(n,e)}}}getAllEndToEndInboundGroupSessions(e,t){const n=e.objectStore("inbound_group_sessions").openCursor();n.onsuccess=function(){const r=n.result;if(r){try{t({senderKey:r.value.senderCurve25519Key,sessionId:r.value.sessionId,sessionData:r.value.session})}catch(t){s(e,t)}r.continue()}else try{t(null)}catch(t){s(e,t)}}}addEndToEndInboundGroupSession(e,t,n,r){const o=r.objectStore("inbound_group_sessions").add({senderCurve25519Key:e,sessionId:t,session:n});o.onerror=n=>{"ConstraintError"===o.error.name?(n.stopPropagation(),n.preventDefault(),i.logger.log("Ignoring duplicate inbound group session: "+e+" / "+t)):s(r,new Error("Failed to add inbound group session: "+o.error))}}storeEndToEndInboundGroupSession(e,t,n,r){r.objectStore("inbound_group_sessions").put({senderCurve25519Key:e,sessionId:t,session:n})}storeEndToEndInboundGroupSessionWithheld(e,t,n,r){r.objectStore("inbound_group_sessions_withheld").put({senderCurve25519Key:e,sessionId:t,session:n})}getEndToEndDeviceData(e,t){const n=e.objectStore("device_data").get("-");n.onsuccess=function(){try{t(n.result||null)}catch(t){s(e,t)}}}storeEndToEndDeviceData(e,t){t.objectStore("device_data").put(e,"-")}storeEndToEndRoom(e,t,n){n.objectStore("rooms").put(t,e)}getEndToEndRooms(e,t){const n={},r=e.objectStore("rooms").openCursor();r.onsuccess=function(){const i=r.result;if(i)n[i.key]=i.value,i.continue();else try{t(n)}catch(t){s(e,t)}}}getSessionsNeedingBackup(e){return new Promise((t,n)=>{const r=[],i=this._db.transaction(["sessions_needing_backup","inbound_group_sessions"],"readonly");i.onerror=n,i.oncomplete=function(){t(r)};const o=i.objectStore("sessions_needing_backup"),s=i.objectStore("inbound_group_sessions"),a=o.openCursor();a.onsuccess=function(){const t=a.result;if(t){const n=s.get(t.key);n.onsuccess=function(){r.push({senderKey:n.result.senderCurve25519Key,sessionId:n.result.sessionId,sessionData:n.result.session})},(!e||r.length{const r=t.count();r.onerror=n,r.onsuccess=()=>e(r.result)})}unmarkSessionsNeedingBackup(e,t){t||(t=this._db.transaction("sessions_needing_backup","readwrite"));const n=t.objectStore("sessions_needing_backup");return Promise.all(e.map(e=>new Promise((t,r)=>{const i=n.delete([e.senderKey,e.sessionId]);i.onsuccess=t,i.onerror=r})))}markSessionsNeedingBackup(e,t){t||(t=this._db.transaction("sessions_needing_backup","readwrite"));const n=t.objectStore("sessions_needing_backup");return Promise.all(e.map(e=>new Promise((t,r)=>{const i=n.put({senderCurve25519Key:e.senderKey,sessionId:e.sessionId});i.onsuccess=t,i.onerror=r})))}doTxn(e,t,n){const r=this._db.transaction(t,e),i=a(r),o=n(r);return i.then(()=>o)}}},function(e,t,n){"use strict";(function(e){var r=n(6),i=n(16);Object.defineProperty(t,"__esModule",{value:!0}),t.isCryptoAvailable=function(){return Boolean(e.Olm)},t.Crypto=O,t.verificationMethods=void 0;var o=i(n(80)),s=n(9),a=n(78),c=n(4),f=r(n(8)),u=n(137),l=r(n(21)),d=n(290),h=n(51),p=r(n(138)),m=n(139),g=n(291),y=n(292),b=n(36),_=n(293),v=n(294),A=n(141),w=n(142),E=n(82),k=n(298),S=n(299),I=r(n(49));const T=h.DeviceInfo.DeviceVerification,R={[_.ScanQRCode.NAME]:_.ScanQRCode,[_.ShowQRCode.NAME]:_.ShowQRCode,[v.SAS.NAME]:v.SAS},x={QR_CODE_SCAN:_.ScanQRCode.NAME,QR_CODE_SHOW:_.ShowQRCode.NAME,SAS:v.SAS.NAME};t.verificationMethods=x;function O(e,t,n,r,i,o,s,c){if(this._onDeviceListUserCrossSigningUpdated=this._onDeviceListUserCrossSigningUpdated.bind(this),this._reEmitter=new a.ReEmitter(this),this._baseApis=e,this._sessionStore=t,this._userId=n,this._deviceId=r,this._clientStore=i,this._cryptoStore=o,this._roomList=s,this._verificationMethods=new Map,c)for(const e of c)"string"==typeof e?R[e]&&this._verificationMethods.set(e,R[e]):e.NAME&&this._verificationMethods.set(e.NAME,e);this.backupInfo=null,this.backupKey=null,this._checkedForBackup=!1,this._sendingBackups=!1,this._olmDevice=new u.OlmDevice(o),this._deviceList=new d.DeviceList(e,o,this._olmDevice),this._deviceList.on("userCrossSigningUpdated",this._onDeviceListUserCrossSigningUpdated),this._reEmitter.reEmit(this._deviceList,["crypto.devicesUpdated"]),this._lastOneTimeKeyCheck=null,this._oneTimeKeyCheckInProgress=!1,this._roomEncryptors={},this._roomDecryptors={},this._supportedAlgorithms=f.keys(p.DECRYPTION_CLASSES),this._deviceKeys={},this._globalBlacklistUnverifiedDevices=!1,this._globalErrorOnUnknownDevices=!0,this._outgoingRoomKeyRequestManager=new y.OutgoingRoomKeyRequestManager(e,this._deviceId,this._cryptoStore),this._receivedRoomKeyRequests=[],this._receivedRoomKeyRequestCancellations=[],this._processingRoomKeyRequests=!1,this._lazyLoadMembers=!1,this._roomDeviceTrackingState={},this._lastNewSessionForced={},this._toDeviceVerificationRequests=new Map,this._inRoomVerificationRequests=new Map;const l=this._baseApis._cryptoCallbacks||{};this._crossSigningInfo=new m.CrossSigningInfo(n,l),this._secretStorage=new g.SecretStorage(e,l,this._crossSigningInfo),!l.getCrossSigningKey&&l.getSecretStorageKey&&(l.getCrossSigningKey=async e=>m.CrossSigningInfo.getFromSecretStorage(e,this._secretStorage))}function C(e){if(e._oneTimeKeyCheckInProgress)return;const t=Date.now();if(null!==e._lastOneTimeKeyCheck&&t-e._lastOneTimeKeyCheck<6e4)return;e._lastOneTimeKeyCheck=t;const n=e._olmDevice.maxNumberOfOneTimeKeys(),r=Math.floor(n/2);function i(t){if(r<=t)return Promise.resolve();const n=Math.min(r-t,5);return e._olmDevice.generateOneTimeKeys(n).then(()=>async function(e){const t=await e._olmDevice.getOneTimeKeys(),n={},r=[];for(const i in t.curve25519)if(t.curve25519.hasOwnProperty(i)){const o={key:t.curve25519[i]};n["signed_curve25519:"+i]=o,r.push(e._signObject(o))}await Promise.all(r);const i=await e._baseApis.uploadKeysRequest({one_time_keys:n},{device_id:e._deviceId});return await e._olmDevice.markKeysAsPublished(),i}(e)).then(e=>{if(e.one_time_key_counts&&e.one_time_key_counts.signed_curve25519)return i(e.one_time_key_counts.signed_curve25519);throw new Error("response for uploading keys does not contain one_time_key_counts.signed_curve25519")})}e._oneTimeKeyCheckInProgress=!0,Promise.resolve().then(()=>void 0!==e._oneTimeKeyCount?Promise.resolve(e._oneTimeKeyCount):e._baseApis.uploadKeysRequest({},{device_id:e._deviceId}).then(e=>e.one_time_key_counts.signed_curve25519||0)).then(e=>i(e)).catch(e=>{c.logger.error("Error uploading one-time keys",e.stack||e)}).finally(()=>{e._oneTimeKeyCount=void 0,e._oneTimeKeyCheckInProgress=!1})}f.inherits(O,s.EventEmitter),O.prototype.init=async function(){c.logger.log("Crypto: initialising Olm..."),await e.Olm.init(),c.logger.log("Crypto: initialising Olm device..."),await this._olmDevice.init(),c.logger.log("Crypto: loading device list..."),await this._deviceList.load(),this._deviceKeys["ed25519:"+this._deviceId]=this._olmDevice.deviceEd25519Key,this._deviceKeys["curve25519:"+this._deviceId]=this._olmDevice.deviceCurve25519Key,c.logger.log("Crypto: fetching own devices...");let t=this._deviceList.getRawStoredDevicesForUser(this._userId);if(t||(t={}),!t[this._deviceId]){c.logger.log("Crypto: adding this device to the store...");const e={keys:this._deviceKeys,algorithms:this._supportedAlgorithms,verified:T.VERIFIED,known:!0};t[this._deviceId]=e,this._deviceList.storeDevicesForUser(this._userId,t),this._deviceList.saveIfDirty()}await this._cryptoStore.doTxn("readonly",[b.IndexedDBCryptoStore.STORE_ACCOUNT],e=>{this._cryptoStore.getCrossSigningKeys(e,e=>{e&&(c.logger.log("Loaded cross-signing public keys from crypto store"),this._crossSigningInfo.setKeys(e))})}),this._deviceList.startTrackingDeviceList(this._userId),c.logger.log("Crypto: checking for key backup..."),this._checkAndStartKeyBackup()},O.prototype.createRecoveryKeyFromPassphrase=async function(t){const n=new e.Olm.PkDecryption;try{const e={};if(t){const r=await(0,A.keyFromPassphrase)(t);e.passphrase={algorithm:"m.pbkdf2",iterations:r.iterations,salt:r.salt},e.pubkey=n.init_with_private_key(r.key)}else e.pubkey=n.generate_key();const r=n.get_private_key();return[e,(0,w.encodeRecoveryKey)(r),r]}finally{n&&n.free()}},O.prototype.bootstrapSecretStorage=async function({authUploadDeviceSigningKeys:e,createSecretStorageKey:t=(async()=>{}),keyBackupInfo:n}={}){c.logger.log("Bootstrapping Secure Secret Storage");let r={};const i=Object.assign({},this._baseApis._cryptoCallbacks);try{const o=await this._crossSigningInfo.isStoredInSecretStorage(this._secretStorage);if(this._crossSigningInfo.getId()&&o?c.logger.log("Cross signing keys are present in secret storage"):(c.logger.log("Cross-signing public and/or private keys not found, checking secret storage for private keys"),o?(c.logger.log("Cross-signing private keys found in secret storage"),await this.checkOwnCrossSigningTrust()):(c.logger.log("Cross-signing private keys not found in secret storage, creating new keys"),this._baseApis._cryptoCallbacks.saveCrossSigningKeys=e=>r=e,this._baseApis._cryptoCallbacks.getCrossSigningKey=e=>r[e],await this.resetCrossSigningKeys(m.CrossSigningLevel.MASTER,{authUploadDeviceSigningKeys:e}))),await this.hasSecretStorageKey())c.logger.log("Have secret storage key");else{let e;if(n){c.logger.log("Secret storage default key not found, using key backup key");const t={pubkey:n.auth_data.public_key};n.auth_data.private_key_salt&&n.auth_data.private_key_iterations&&(t.passphrase={algorithm:"m.pbkdf2",iterations:n.auth_data.private_key_iterations,salt:n.auth_data.private_key_salt}),e=await this.addSecretStorageKey(g.SECRET_STORAGE_ALGORITHM_V1,t),this._secretStorage.storePassthrough("m.megolm_backup.v1",e),(await this.checkKeyBackup(n)).trustInfo.usable?(console.log("Adding cross signing signature to key backup"),await this._crossSigningInfo.signObject(n.auth_data,"master"),await this._baseApis._http.authedRequest(void 0,"PUT","/room_keys/version/"+n.version,void 0,n,{prefix:I.PREFIX_UNSTABLE})):console.log("Key backup is NOT TRUSTED: NOT adding cross signing signature")}else{c.logger.log("Secret storage default key not found, creating new key");const n=await t();e=await this.addSecretStorageKey(g.SECRET_STORAGE_ALGORITHM_V1,n)}await this.setDefaultSecretStorageKeyId(e)}Object.keys(r).length&&(c.logger.log("Storing cross-signing private keys in secret storage"),await this._secretStorage.signKey(),i.saveCrossSigningKeys||await m.CrossSigningInfo.storeInSecretStorage(r,this._secretStorage))}finally{this._baseApis._cryptoCallbacks=i}c.logger.log("Secure Secret Storage ready")},O.prototype.addSecretStorageKey=function(e,t,n){return this._secretStorage.addKey(e,t,n)},O.prototype.hasSecretStorageKey=function(e){return this._secretStorage.hasKey(e)},O.prototype.storeSecret=function(e,t,n){return this._secretStorage.store(e,t,n)},O.prototype.getSecret=function(e){return this._secretStorage.get(e)},O.prototype.isSecretStored=function(e,t){return this._secretStorage.isStored(e,t)},O.prototype.requestSecret=function(e,t){return t||(t=Object.keys(this._deviceList.getRawStoredDevicesForUser(this._userId))),this._secretStorage.request(e,t)},O.prototype.getDefaultSecretStorageKeyId=function(){return this._secretStorage.getDefaultKeyId()},O.prototype.setDefaultSecretStorageKeyId=function(e){return this._secretStorage.setDefaultKeyId(e)},O.prototype.checkSecretStoragePrivateKey=function(t,n){let r=null;try{return r=new e.Olm.PkDecryption,r.init_with_private_key(t)===n}finally{r&&r.free()}},O.prototype.checkCrossSigningPrivateKey=function(t,n){let r=null;try{return r=new e.Olm.PkSigning,r.init_with_seed(t)===n}finally{r&&r.free()}},O.prototype.resetCrossSigningKeys=async function(e,{authUploadDeviceSigningKeys:t=(async e=>await e())}={}){c.logger.info(`Resetting cross-signing keys at level ${e}`);const n=Object.assign({},this._crossSigningInfo.keys);try{await this._crossSigningInfo.resetKeys(e),await this._signObject(this._crossSigningInfo.keys.master);const n={};for(const[e,t]of Object.entries(this._crossSigningInfo.keys))n[e+"_key"]=t;await t(async e=>{await this._baseApis.uploadDeviceSigningKeys(e,n)}),await this._cryptoStore.doTxn("readwrite",[b.IndexedDBCryptoStore.STORE_ACCOUNT],e=>{this._cryptoStore.storeCrossSigningKeys(e,this._crossSigningInfo.keys)})}catch(e){throw c.logger.error("Resetting cross-signing keys failed, revert to previous keys",e),this._crossSigningInfo.keys=n,e}this._baseApis.emit("crossSigning.keysChanged",{}),await this._afterCrossSigningLocalKeyChange(),c.logger.info("Cross-signing key reset complete")},O.prototype._afterCrossSigningLocalKeyChange=async function(){const e=this._deviceList.getStoredDevice(this._userId,this._deviceId),t=await this._crossSigningInfo.signDevice(this._userId,e);await this._baseApis.uploadKeySignatures({[this._userId]:{[this._deviceId]:t}});const n={};for(const[e,t]of Object.entries(this._deviceList._crossSigningInfo)){const r=await this._checkForDeviceVerificationUpgrade(e,m.CrossSigningInfo.fromStorage(t,e));r&&(n[e]=r)}const r=this._baseApis._cryptoCallbacks.shouldUpgradeDeviceVerifications;if(Object.keys(n).length>0&&r)try{const e=await r({users:n});if(e)for(const t of e)t in n&&await this._baseApis.setDeviceVerified(t,n[t].crossSigningInfo.getId())}catch(e){c.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",e)}},O.prototype._checkForDeviceVerificationUpgrade=async function(e,t){const n=this._crossSigningInfo.checkUserTrust(t);if(t.firstUse&&!n.verified){const n=this._deviceList.getRawStoredDevicesForUser(e),r=await this._checkForValidDeviceSignature(e,t.keys.master,n);if(r.length)return{devices:r.map(e=>h.DeviceInfo.fromStorage(n[e],e)),crossSigningInfo:t}}},O.prototype._checkForValidDeviceSignature=async function(e,t,n){const r=[];if(n&&t.signatures&&t.signatures[e])for(const i of Object.keys(t.signatures[e])){const[,o]=i.split(":",2);if(o in n&&n[o].verified===T.VERIFIED)try{await l.verifySignature(this._olmDevice,t,e,o,n[o].keys[i]),r.push(o)}catch(e){}}return r},O.prototype.getCrossSigningId=function(e){return this._crossSigningInfo.getId(e)},O.prototype.getStoredCrossSigningForUser=function(e){return this._deviceList.getStoredCrossSigningForUser(e)},O.prototype.checkUserTrust=function(e){const t=this._deviceList.getStoredCrossSigningForUser(e);return t?this._crossSigningInfo.checkUserTrust(t):new m.UserTrustLevel(!1,!1)},O.prototype.checkDeviceTrust=function(e,t){const n=this._deviceList.getStoredDevice(e,t),r=n&&n.isVerified(),i=this._deviceList.getStoredCrossSigningForUser(e);return n&&i?this._crossSigningInfo.checkDeviceTrust(i,n,r):new m.DeviceTrustLevel(!1,!1,r)},O.prototype._onDeviceListUserCrossSigningUpdated=async function(e){if(e===this._userId){const t=this._deviceList.getStoredCrossSigningForUser(e),n=t?t.getId():null,r=this._crossSigningInfo.getId(),i=r!==n;r&&n&&!i?await this.checkOwnCrossSigningTrust():this.emit("crossSigning.keysChanged",{})}else await this._checkDeviceVerifications(e),this.emit("userTrustStatusChanged",e,this.checkUserTrust(e))},O.prototype.checkOwnCrossSigningTrust=async function(){const e=this._userId,t=this._deviceList.getStoredCrossSigningForUser(e);if(!t)return void c.logger.error("Got cross-signing update event for user "+e+" but no new cross-signing information found!");const n=t.getId(),r=this._crossSigningInfo.getId()!==n;if(r){c.logger.info("Got new master public key",n);let e=null;try{if(e=(await this._crossSigningInfo.getCrossSigningKey("master",n))[1],!e)throw new Error("Cross-signing master private key not available")}finally{e&&e.free()}c.logger.info("Got matching private key from callback for new public master key")}const i=this._crossSigningInfo.getId("self_signing"),o=this._crossSigningInfo.getId("user_signing");this._crossSigningInfo.setKeys(t.keys),await this._cryptoStore.doTxn("readwrite",[b.IndexedDBCryptoStore.STORE_ACCOUNT],e=>{this._cryptoStore.storeCrossSigningKeys(e,this._crossSigningInfo.keys)});const s={};if(i!==t.getId("self_signing")){c.logger.info("Got new self-signing key",t.getId("self_signing"));const e=this._deviceList.getStoredDevice(this._userId,this._deviceId),n=await this._crossSigningInfo.signDevice(this._userId,e);s[this._deviceId]=n}o!==t.getId("user_signing")&&c.logger.info("Got new user-signing key",t.getId("user_signing")),r&&(await this._signObject(this._crossSigningInfo.keys.master),s[this._crossSigningInfo.getId()]=this._crossSigningInfo.keys.master),Object.keys(s).length&&await this._baseApis.uploadKeySignatures({[this._userId]:s}),this.emit("userTrustStatusChanged",e,this.checkUserTrust(e)),r&&(this._baseApis.emit("crossSigning.keysChanged",{}),await this._afterCrossSigningLocalKeyChange()),await this.checkKeyBackup()},O.prototype._checkDeviceVerifications=async function(e){if(this._crossSigningInfo.keys.user_signing){const t=this._deviceList.getStoredCrossSigningForUser(e);if(t){const n=await this._checkForDeviceVerificationUpgrade(e,t),r=this._baseApis._cryptoCallbacks.shouldUpgradeDeviceVerifications;if(n&&r){(await r({users:{[e]:n}})).includes(e)&&await this._baseApis.setDeviceVerified(e,t.getId())}}}},O.prototype._checkAndStartKeyBackup=async function(){if(c.logger.log("Checking key backup status..."),this._baseApis.isGuest())return c.logger.log("Skipping key backup check since user is guest"),this._checkedForBackup=!0,null;let e;try{e=await this._baseApis.getKeyBackupVersion()}catch(e){return c.logger.log("Error checking for active key backup",e),e.httpStatus/100==4&&(this._checkedForBackup=!0),null}this._checkedForBackup=!0;const t=await this.isKeyBackupTrusted(e);return t.usable&&!this.backupInfo?(c.logger.log("Found usable key backup v"+e.version+": enabling key backups"),this._baseApis.enableKeyBackup(e)):!t.usable&&this.backupInfo?(c.logger.log("No usable key backup: disabling key backup"),this._baseApis.disableKeyBackup()):t.usable||this.backupInfo?t.usable&&this.backupInfo&&(e.version!==this.backupInfo.version?(c.logger.log("On backup version "+this.backupInfo.version+" but found version "+e.version+": switching."),this._baseApis.disableKeyBackup(),this._baseApis.enableKeyBackup(e)):c.logger.log("Backup version "+e.version+" still current")):c.logger.log("No usable key backup: not enabling key backup"),{backupInfo:e,trustInfo:t}},O.prototype.setTrustedBackupPubKey=async function(e){this._sessionStore.setLocalTrustedBackupPubKey(e),await this.checkKeyBackup()},O.prototype.checkKeyBackup=async function(){return this._checkedForBackup=!1,this._checkAndStartKeyBackup()},O.prototype.isKeyBackupTrusted=async function(e){const t={usable:!1,trusted_locally:!1,sigs:[]};if(!(e&&e.algorithm&&e.auth_data&&e.auth_data.public_key&&e.auth_data.signatures))return c.logger.info("Key backup is absent or missing required data"),t;const n=this._sessionStore.getLocalTrustedBackupPubKey();e.auth_data.public_key===n&&(c.logger.info("Backup public key "+n+" is trusted locally"),t.trusted_locally=!0);const r=e.auth_data.signatures[this._userId]||[];for(const n of Object.keys(r)){const r=n.split(":");if("ed25519"!==r[0]){c.logger.log("Ignoring unknown signature type: "+r[0]);continue}const i={deviceId:r[1]},o=this._crossSigningInfo.getId();if(o===i.deviceId){i.crossSigningId=!0;try{await l.verifySignature(this._olmDevice,e.auth_data,this._userId,i.deviceId,o),i.valid=!0}catch(e){c.logger.warning("Bad signature from cross signing key "+o,e),i.valid=!1}t.sigs.push(i);continue}const s=this._deviceList.getStoredDevice(this._userId,i.deviceId);if(s){i.device=s,i.deviceTrust=await this.checkDeviceTrust(this._userId,i.deviceId);try{await l.verifySignature(this._olmDevice,e.auth_data,this._userId,s.deviceId,s.getFingerprint()),i.valid=!0}catch(t){c.logger.info("Bad signature from key ID "+n+" userID "+this._userId+" device ID "+s.deviceId+" fingerprint: "+s.getFingerprint(),e.auth_data,t),i.valid=!1}}else i.valid=null,c.logger.info("Ignoring signature from unknown key "+n);t.sigs.push(i)}return t.usable=t.sigs.some(e=>e.valid&&(e.device&&e.deviceTrust.isVerified()||e.crossSigningId)),t.usable|=t.trusted_locally,t},O.prototype.enableLazyLoading=function(){this._lazyLoadMembers=!0},O.prototype.registerEventHandlers=function(e){const t=this;e.on("RoomMember.membership",(function(e,n,r){try{t._onRoomMembership(e,n,r)}catch(e){c.logger.error("Error handling membership change:",e)}})),e.on("toDeviceEvent",(function(e){t._onToDeviceEvent(e)})),e.on("Room.timeline",(function(e){t._onTimelineEvent(e)})),e.on("Event.decrypted",(function(e){t._onTimelineEvent(e)}))},O.prototype.start=function(){this._outgoingRoomKeyRequestManager.start()},O.prototype.stop=function(){this._outgoingRoomKeyRequestManager.stop(),this._deviceList.stop()},O.getOlmVersion=function(){return u.OlmDevice.getOlmVersion()},O.prototype.getDeviceEd25519Key=function(){return this._olmDevice.deviceEd25519Key},O.prototype.setGlobalBlacklistUnverifiedDevices=function(e){this._globalBlacklistUnverifiedDevices=e},O.prototype.getGlobalBlacklistUnverifiedDevices=function(){return this._globalBlacklistUnverifiedDevices},O.prototype.setGlobalErrorOnUnknownDevices=function(e){this._globalErrorOnUnknownDevices=e},O.prototype.getGlobalErrorOnUnknownDevices=function(){return this._globalErrorOnUnknownDevices},O.prototype.uploadDeviceKeys=function(){const e=this,t=e._userId,n=e._deviceId,r={algorithms:e._supportedAlgorithms,device_id:n,keys:e._deviceKeys,user_id:t};return e._signObject(r).then(()=>e._baseApis.uploadKeysRequest({device_keys:r},{device_id:n}))},O.prototype.updateOneTimeKeyCount=function(e){if(!isFinite(e))throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number");this._oneTimeKeyCount=e},O.prototype.downloadKeys=function(e,t){return this._deviceList.downloadKeys(e,t)},O.prototype.getStoredDevicesForUser=function(e){return this._deviceList.getStoredDevicesForUser(e)},O.prototype.getStoredDevice=function(e,t){return this._deviceList.getStoredDevice(e,t)},O.prototype.saveDeviceList=function(e){return this._deviceList.saveIfDirty(e)},O.prototype.setDeviceVerification=async function(e,t,n,r,i){void 0===n&&(n=null),void 0===r&&(r=null),void 0===i&&(i=null);const o=this._deviceList.getStoredCrossSigningForUser(e);if(o&&o.getId()===t){if(null!==r||null!==i)throw new Error("Cannot set blocked or known for a cross-signing key");if(!n)throw new Error("Cannot set a cross-signing key as unverified");const s=await this._crossSigningInfo.signUser(o);return s&&await this._baseApis.uploadKeySignatures({[e]:{[t]:s}}),s}const s=this._deviceList.getRawStoredDevicesForUser(e);if(!s||!s[t])throw new Error("Unknown device "+e+":"+t);const a=s[t];let c=a.verified;n?c=T.VERIFIED:null!==n&&c==T.VERIFIED&&(c=T.UNVERIFIED),r?c=T.BLOCKED:null!==r&&c==T.BLOCKED&&(c=T.UNVERIFIED);let f=a.known;if(null!==i&&(f=i),a.verified===c&&a.known===f||(a.verified=c,a.known=f,this._deviceList.storeDevicesForUser(e,s),this._deviceList.saveIfDirty()),n&&e===this._userId){const n=await this._crossSigningInfo.signDevice(e,h.DeviceInfo.fromStorage(a,t));n&&await this._baseApis.uploadKeySignatures({[e]:{[t]:n}})}const u=h.DeviceInfo.fromStorage(a,t);return this.emit("deviceVerificationChanged",e,t,u),u},O.prototype.requestVerificationDM=async function(e,t,n){const r=new k.InRoomChannel(this._baseApis,t,e),i=await this._requestVerificationWithChannel(e,n,r,this._inRoomVerificationRequests);return await i.waitForVerifier()},O.prototype.acceptVerificationDM=function(e,t){if(!k.InRoomChannel.validateEvent(e,this._baseApis))return;const n=e.getSender(),r=this._inRoomVerificationRequests.get(n);if(!r)return;const i=k.InRoomChannel.getTransactionId(e),o=r.get(i);return o?o.beginKeyVerification(t):void 0},O.prototype.requestVerification=async function(e,t,n){n||(n=Object.keys(this._deviceList.getRawStoredDevicesForUser(e)));const r=new S.ToDeviceChannel(this._baseApis,e,n),i=await this._requestVerificationWithChannel(e,t,r,this._toDeviceVerificationRequests);return await i.waitForVerifier()},O.prototype._requestVerificationWithChannel=async function(e,t,n,r){t||(t=[...this._verificationMethods.keys()]);const i=new E.VerificationRequest(n,this._verificationMethods,e,this._baseApis);await i.sendRequest();let o=r.get(e);return o||(o=new Map,r.set(e,o)),o.set(n.transactionId,i),i},O.prototype.beginKeyVerification=function(e,t,n,r=null){let i,o=this._toDeviceVerificationRequests.get(t);if(o||(o=new Map,this._toDeviceVerificationRequests.set(t,o)),r)i=o.get(r);else{r=S.ToDeviceChannel.makeTransactionId();const e=new S.ToDeviceChannel(this._baseApis,t,[n],r,n);i=new E.VerificationRequest(e,this._verificationMethods,t,this._baseApis),o.set(r,i)}if(!i)throw new Error(`No request found for user ${t} with transactionId ${r}`);return i.beginKeyVerification(e,{userId:t,deviceId:n})},O.prototype.getOlmSessionsForUser=async function(e){const t=this.getStoredDevicesForUser(e)||[],n={};for(let e=0;e0)return null;const r=this._deviceList.getDeviceByIdentityKey(n,t);if(null===r)return null;const i=e.getClaimedEd25519Key();return i?i!==r.getFingerprint()?(c.logger.warn("Event "+e.getId()+" claims ed25519 key "+i+"but sender device has key "+r.getFingerprint()),null):r:(c.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)},O.prototype.forceDiscardSession=function(e){const t=this._roomEncryptors[e];if(void 0===t)throw new Error("Room not encrypted");if(void 0===t.forceDiscardSession)throw new Error("Room encryption algorithm doesn't support session discarding");t.forceDiscardSession()},O.prototype.setRoomEncryption=async function(e,t,n){if(!t.algorithm)return void c.logger.log("Ignoring setRoomEncryption with no algorithm");const r=this._roomList.getRoomEncryption(e);if(r&&JSON.stringify(r)!=JSON.stringify(t))return void c.logger.error("Ignoring m.room.encryption event which requests a change of config in "+e);if(this._roomEncryptors[e])return;let i=null;r||(i=this._roomList.setRoomEncryption(e,t));const o=p.ENCRYPTION_CLASSES[t.algorithm];if(!o)throw new Error("Unable to encrypt with "+t.algorithm);const s=new o({userId:this._userId,deviceId:this._deviceId,crypto:this,olmDevice:this._olmDevice,baseApis:this._baseApis,roomId:e,config:t});this._roomEncryptors[e]=s,i&&await i,this._lazyLoadMembers?c.logger.log("Enabling encryption in "+e):(c.logger.log("Enabling encryption in "+e+"; starting to track device lists for all users therein"),await this.trackRoomDevices(e),this.inhibitDeviceQuery||this._deviceList.refreshOutdatedDeviceLists())},O.prototype.trackRoomDevices=function(e){const t=async()=>{if(!this._roomEncryptors[e])return;const t=this._clientStore.getRoom(e);if(!t)throw new Error(`Unable to start tracking devices in unknown room ${e}`);c.logger.log(`Starting to track devices for room ${e} ...`),(await t.getEncryptionTargetMembers()).forEach(e=>{this._deviceList.startTrackingDeviceList(e.userId)})};let n=this._roomDeviceTrackingState[e];return n||(n=t(),this._roomDeviceTrackingState[e]=n),n},O.prototype.ensureOlmSessionsForUsers=function(e){const t={};for(let n=0;n{this._cryptoStore.getAllEndToEndInboundGroupSessions(t,t=>{if(null===t)return;const n=this._olmDevice.exportInboundGroupSession(t.senderKey,t.sessionId,t.sessionData);delete n.first_known_index,n.algorithm=l.MEGOLM_ALGORITHM,e.push(n)})}),e},O.prototype.importRoomKeys=function(e){return Promise.all(e.map(e=>{if(!e.room_id||!e.algorithm)return c.logger.warn("ignoring room key entry with missing fields",e),null;return this._getRoomDecryptor(e.room_id,e.algorithm).importRoomKey(e)}))},O.prototype.scheduleKeyBackupSend=async function(e=1e4){if(!this._sendingBackups){this._sendingBackups=!0;try{const t=Math.random()*e;await(0,f.sleep)(t);let n=0;for(;;){if(!this.backupKey)return;try{if(0===await this._backupPendingKeys(200))return;n=0}catch(e){if(n++,c.logger.log("Key backup request failed",e),e.data&&("M_NOT_FOUND"==e.data.errcode||"M_WRONG_ROOM_KEYS_VERSION"==e.data.errcode))throw await this.checkKeyBackup(),this.emit("crypto.keyBackupFailed",e.data.errcode),e}n&&await(0,f.sleep)(1e3*Math.pow(2,Math.min(n-1,4)))}}finally{this._sendingBackups=!1}}},O.prototype._backupPendingKeys=async function(e){const t=await this._cryptoStore.getSessionsNeedingBackup(e);if(!t.length)return 0;let n=await this._cryptoStore.countSessionsNeedingBackup();this.emit("crypto.keyBackupSessionsRemaining",n);const r={};for(const e of t){const t=e.sessionData.room_id;void 0===r[t]&&(r[t]={sessions:{}});const n=await this._olmDevice.exportInboundGroupSession(e.senderKey,e.sessionId,e.sessionData);n.algorithm=l.MEGOLM_ALGORITHM,delete n.session_id,delete n.room_id;const i=n.first_known_index;delete n.first_known_index;const o=this.backupKey.encrypt(JSON.stringify(n)),s=(n.forwarding_curve25519_key_chain||[]).length,a=this._deviceList.getDeviceByIdentityKey(l.MEGOLM_ALGORITHM,e.senderKey);r[t].sessions[e.sessionId]={first_message_index:i,forwarded_count:s,is_verified:!(!a||!a.isVerified()),session_data:o}}return await this._baseApis.sendKeyBackup(void 0,void 0,this.backupInfo.version,{rooms:r}),await this._cryptoStore.unmarkSessionsNeedingBackup(t),n=await this._cryptoStore.countSessionsNeedingBackup(),this.emit("crypto.keyBackupSessionsRemaining",n),t.length},O.prototype.backupGroupSession=async function(e,t,n,r,i,o,s){if(!this.backupInfo)throw new Error("Key backups are not enabled");await this._cryptoStore.markSessionsNeedingBackup([{senderKey:t,sessionId:r}]),this.scheduleKeyBackupSend()},O.prototype.scheduleAllGroupSessionsForBackup=async function(){await this.flagAllGroupSessionsForBackup(),this.scheduleKeyBackupSend(0)},O.prototype.flagAllGroupSessionsForBackup=async function(){await this._cryptoStore.doTxn("readwrite",[b.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,b.IndexedDBCryptoStore.STORE_BACKUP],e=>{this._cryptoStore.getAllEndToEndInboundGroupSessions(e,t=>{null!==t&&this._cryptoStore.markSessionsNeedingBackup([t],e)})});const e=await this._cryptoStore.countSessionsNeedingBackup();return this.emit("crypto.keyBackupSessionsRemaining",e),e},O.prototype.encryptEvent=async function(e,t){if(!t)throw new Error("Cannot send encrypted messages in unknown rooms");const n=e.getRoomId(),r=this._roomEncryptors[n];if(!r)throw new Error("Room was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");this._roomDeviceTrackingState[n]||this.trackRoomDevices(n),await this._roomDeviceTrackingState[n];let i=e.getContent();const o=i["m.relates_to"];o&&(i=Object.assign({},i),delete i["m.relates_to"]);const s=await r.encryptMessage(t,e.getType(),i);o&&(s["m.relates_to"]=o),e.makeEncrypted("m.room.encrypted",s,this._olmDevice.deviceCurve25519Key,this._olmDevice.deviceEd25519Key)},O.prototype.decryptEvent=function(e){if(e.isRedacted())return Promise.resolve({clearEvent:{room_id:e.getRoomId(),type:"m.room.message",content:{}}});const t=e.getWireContent();return this._getRoomDecryptor(e.getRoomId(),t.algorithm).decryptEvent(e)},O.prototype.handleDeviceListChanges=async function(e,t){e.oldSyncToken&&await this._evalDeviceListChanges(t)},O.prototype.requestRoomKey=function(e,t,n=!1){return this._outgoingRoomKeyRequestManager.sendRoomKeyRequest(e,t,n).catch(e=>{c.logger.error("Error requesting key for event",e)})},O.prototype.cancelRoomKeyRequest=function(e){this._outgoingRoomKeyRequestManager.cancelRoomKeyRequest(e).catch(e=>{c.logger.warn("Error clearing pending room key requests",e)})},O.prototype.onCryptoEvent=async function(e){const t=e.getRoomId(),n=e.getContent();try{await this.setRoomEncryption(t,n,!0)}catch(e){c.logger.error("Error configuring encryption in room "+t+":",e)}},O.prototype.onSyncWillProcess=async function(e){e.oldSyncToken||(c.logger.log("Initial sync performed - resetting device tracking state"),this._deviceList.stopTrackingAllDeviceLists(),this._deviceList.startTrackingDeviceList(this._userId),this._roomDeviceTrackingState={})},O.prototype.onSyncCompleted=async function(e){const t=e.nextSyncToken;this._deviceList.setSyncToken(e.nextSyncToken),this._deviceList.saveIfDirty(),this._deviceList.lastKnownSyncToken=t,this._deviceList.startTrackingDeviceList(this._userId),this._deviceList.refreshOutdatedDeviceLists(),e.catchingUp||(C(this),this._processReceivedRoomKeyRequests())},O.prototype._evalDeviceListChanges=async function(e){if(e.changed&&Array.isArray(e.changed)&&e.changed.forEach(e=>{this._deviceList.invalidateUserDeviceList(e)}),e.left&&Array.isArray(e.left)&&e.left.length){const t=new Set(await this._getTrackedE2eUsers());e.left.forEach(e=>{t.has(e)||this._deviceList.stopTrackingDeviceList(e)})}},O.prototype._getTrackedE2eUsers=async function(){const e=[];for(const t of this._getTrackedE2eRooms()){const n=await t.getEncryptionTargetMembers();for(const t of n)e.push(t.userId)}return e},O.prototype._getTrackedE2eRooms=function(){return this._clientStore.getRooms().filter(e=>{if(!this._roomEncryptors[e.roomId])return!1;if(!this._roomDeviceTrackingState[e.roomId])return!1;const t=e.getMyMembership();return"join"===t||"invite"===t})},O.prototype._onToDeviceEvent=function(e){try{c.logger.log(`received to_device ${e.getType()} from: `+`${e.getSender()} id: ${e.getId()}`),"m.room_key"==e.getType()||"m.forwarded_room_key"==e.getType()?this._onRoomKeyEvent(e):"m.room_key_request"==e.getType()?this._onRoomKeyRequestEvent(e):"m.secret.request"===e.getType()?this._secretStorage._onRequestReceived(e):"m.secret.send"===e.getType()?this._secretStorage._onSecretReceived(e):"org.matrix.room_key.withheld"===e.getType()?this._onRoomKeyWithheldEvent(e):e.getContent().transaction_id?this._onKeyVerificationMessage(e):"m.bad.encrypted"===e.getContent().msgtype?this._onToDeviceBadEncrypted(e):e.isBeingDecrypted()&&e.once("Event.decrypted",e=>{this._onToDeviceEvent(e)})}catch(e){c.logger.error("Error handling toDeviceEvent:",e)}},O.prototype._onRoomKeyEvent=function(e){const t=e.getContent();t.room_id&&t.algorithm?(this._checkedForBackup||this._checkAndStartKeyBackup(),this._getRoomDecryptor(t.room_id,t.algorithm).onRoomKeyEvent(e)):c.logger.error("key event is missing fields")},O.prototype._onRoomKeyWithheldEvent=function(e){const t=e.getContent();if(!(("m.no_olm"===t.code||t.room_id&&t.session_id)&&t.algorithm&&t.sender_key))return void c.logger.error("key withheld event is missing fields");c.logger.info(`Got room key withheld event from ${e.getSender()} (${t.sender_key}) `+`for ${t.algorithm}/${t.room_id}/${t.session_id} `+`with reason ${t.code} (${t.reason})`);const n=this._getRoomDecryptor(t.room_id,t.algorithm);if(n.onRoomKeyWithheldEvent&&n.onRoomKeyWithheldEvent(e),!t.room_id){const e=this._getRoomDecryptors(t.algorithm);for(const n of e)n.retryDecryptionFromSender(t.sender_key)}},O.prototype._onKeyVerificationMessage=function(e){if(!S.ToDeviceChannel.validateEvent(e,this._baseApis))return;const t=S.ToDeviceChannel.getTransactionId(e);this._handleVerificationEvent(e,t,this._toDeviceVerificationRequests,e=>{if(!S.ToDeviceChannel.canCreateRequest(S.ToDeviceChannel.getEventType(e)))return;const t=e.getContent(),n=t&&t.from_device;if(!n)return;const r=e.getSender(),i=new S.ToDeviceChannel(this._baseApis,r,[n]);return new E.VerificationRequest(i,this._verificationMethods,r,this._baseApis)})},O.prototype._onTimelineEvent=function(e){if(!k.InRoomChannel.validateEvent(e,this._baseApis))return;const t=k.InRoomChannel.getTransactionId(e);this._handleVerificationEvent(e,t,this._inRoomVerificationRequests,e=>{if(!k.InRoomChannel.canCreateRequest(k.InRoomChannel.getEventType(e)))return;const t=e.getSender(),n=new k.InRoomChannel(this._baseApis,e.getRoomId(),t);return new E.VerificationRequest(n,this._verificationMethods,t,this._baseApis)})},O.prototype._handleVerificationEvent=async function(e,t,n,r){const i=e.getSender();let o=n.get(i),s=!1,a=o&&o.get(t);if(!a){if(a=r(e),!a)return;s=!0,o||(o=new Map,n.set(i,o)),o.set(t,a)}try{const t=!!a.verifier;await a.channel.handleEvent(e,a),!t&&a.verifier&&this._baseApis.emit("crypto.verification.start",a.verifier)}catch(t){console.error("error while handling verification event",e,t)}a.pending?s&&!a.initiatedByMe&&this._baseApis.emit("crypto.verification.request",a):(o.delete(t),0===o.size&&n.delete(i))},O.prototype._onToDeviceBadEncrypted=async function(e){const t=e.getWireContent(),n=e.getSender(),r=t.algorithm,i=t.sender_key,o=()=>{const e=this._getRoomDecryptors(l.MEGOLM_ALGORITHM);for(const t of e)t.retryDecryptionFromSender(i)};if(void 0===n||void 0===i||void 0===i)return;this._lastNewSessionForced[n]=this._lastNewSessionForced[n]||{};const s=this._lastNewSessionForced[n][i]||0;if(s+36e5>Date.now())return c.logger.debug("New session already forced with device "+n+":"+i+" at "+s+": not forcing another"),await this._olmDevice.recordSessionProblem(i,"wedged",!0),void o();const a=this._deviceList.getDeviceByIdentityKey(r,i);if(!a)return c.logger.info("Couldn't find device for identity key "+i+": not re-establishing session"),await this._olmDevice.recordSessionProblem(i,"wedged",!1),void o();const f={};f[n]=[a],await l.ensureOlmSessionsForDevices(this._olmDevice,this._baseApis,f,!0),this._lastNewSessionForced[n][i]=Date.now();const u={algorithm:l.OLM_ALGORITHM,sender_key:this._olmDevice.deviceCurve25519Key,ciphertext:{}};await l.encryptMessageForDevice(u.ciphertext,this._userId,this._deviceId,this._olmDevice,n,a,{type:"m.dummy"}),await this._olmDevice.recordSessionProblem(i,"wedged",!0),o(),await this._baseApis.sendToDevice("m.room.encrypted",{[n]:{[a.deviceId]:u}});const d=await this._outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(n,a.deviceId);for(const e of d)this.requestRoomKey(e.requestBody,e.recipients,!0)},O.prototype._onRoomMembership=function(e,t,n){const r=t.roomId,i=this._roomEncryptors[r];i&&(this._roomDeviceTrackingState[r]&&("join"==t.membership?(c.logger.log("Join event for "+t.userId+" in "+r),this._deviceList.startTrackingDeviceList(t.userId)):"invite"==t.membership&&this._clientStore.getRoom(r).shouldEncryptForInvitedMembers()&&(c.logger.log("Invite event for "+t.userId+" in "+r),this._deviceList.startTrackingDeviceList(t.userId))),i.onRoomMembership(e,t,n))},O.prototype._onRoomKeyRequestEvent=function(e){const t=e.getContent();if("request"===t.action){const t=new P(e);this._receivedRoomKeyRequests.push(t)}else if("request_cancellation"===t.action){const t=new M(e);this._receivedRoomKeyRequestCancellations.push(t)}},O.prototype._processReceivedRoomKeyRequests=async function(){if(!this._processingRoomKeyRequests){this._processingRoomKeyRequests=!0;try{const e=this._receivedRoomKeyRequests;this._receivedRoomKeyRequests=[];const t=this._receivedRoomKeyRequestCancellations;this._receivedRoomKeyRequestCancellations=[],await Promise.all(e.map(e=>this._processReceivedRoomKeyRequest(e))),await Promise.all(t.map(e=>this._processReceivedRoomKeyRequestCancellation(e)))}catch(e){c.logger.error(`Error processing room key requsts: ${e}`)}finally{this._processingRoomKeyRequests=!1}}},O.prototype._processReceivedRoomKeyRequest=async function(e){const t=e.userId,n=e.deviceId,r=e.requestBody,i=r.room_id,o=r.algorithm;if(c.logger.log(`m.room_key_request from ${t}:${n}`+` for ${i} / ${r.session_id} (id ${e.requestId})`),t!==this._userId){if(!this._roomEncryptors[i])return void c.logger.debug(`room key request for unencrypted room ${i}`);const e=this._roomEncryptors[i],o=this._deviceList.getStoredDevice(t,n);if(!o)return void c.logger.debug(`Ignoring keyshare for unknown device ${t}:${n}`);try{await e.reshareKeyWithDevice(r.sender_key,r.session_id,t,o)}catch(e){c.logger.warn("Failed to re-share keys for session "+r.session_id+" with device "+t+":"+o.deviceId,e)}return}if(!this._roomDecryptors[i])return void c.logger.log(`room key request for unencrypted room ${i}`);const s=this._roomDecryptors[i][o];if(!s)return void c.logger.log(`room key request for unknown alg ${o} in room ${i}`);if(!await s.hasKeysForKeyRequest(e))return void c.logger.log(`room key request for unknown session ${i} / `+r.session_id);e.share=()=>{s.shareKeysWithDevice(e)};const a=this._deviceList.getStoredDevice(t,n);if(a&&a.isVerified())return c.logger.log("device is already verified: sharing keys"),void e.share();this.emit("crypto.roomKeyRequest",e)},O.prototype._processReceivedRoomKeyRequestCancellation=async function(e){c.logger.log(`m.room_key_request cancellation for ${e.userId}:`+`${e.deviceId} (id ${e.requestId})`),this.emit("crypto.roomKeyRequestCancellation",e)},O.prototype._getRoomDecryptor=function(e,t){let n,r;if((e=e||null)&&(n=this._roomDecryptors[e],n||(this._roomDecryptors[e]=n={}),r=n[t],r))return r;const i=p.DECRYPTION_CLASSES[t];if(!i)throw new p.DecryptionError("UNKNOWN_ENCRYPTION_ALGORITHM",'Unknown encryption algorithm "'+t+'".');return r=new i({userId:this._userId,crypto:this,olmDevice:this._olmDevice,baseApis:this._baseApis,roomId:e}),n&&(n[t]=r),r},O.prototype._getRoomDecryptors=function(e){const t=[];for(const n of Object.values(this._roomDecryptors))e in n&&t.push(n[e]);return t},O.prototype._signObject=async function(e){const t=e.signatures||{},n=e.unsigned;delete e.signatures,delete e.unsigned,t[this._userId]=t[this._userId]||{},t[this._userId]["ed25519:"+this._deviceId]=await this._olmDevice.sign(o.default.stringify(e)),e.signatures=t,void 0!==n&&(e.unsigned=n)};class P{constructor(e){const t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id,this.requestBody=t.body||{},this.share=()=>{throw new Error("don't know how to share keys for this request yet")}}}class M{constructor(e){const t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id}}}).call(this,n(5))},function(e,t,n){"use strict";var r=n(6),i=n(4),o=r(n(8)),s=r(n(21)),a=n(51),c=n(81);const f=a.DeviceInfo.DeviceVerification;function u(e){(0,o.polyfillSuper)(this,c.EncryptionAlgorithm,e),this._sessionPrepared=!1,this._prepPromise=null}function l(e){(0,o.polyfillSuper)(this,c.DecryptionAlgorithm,e)}o.inherits(u,c.EncryptionAlgorithm),u.prototype._ensureSession=function(e){if(this._prepPromise)return this._prepPromise;if(this._sessionPrepared)return Promise.resolve();const t=this;return this._prepPromise=t._crypto.downloadKeys(e).then((function(n){return t._crypto.ensureOlmSessionsForUsers(e)})).then((function(){t._sessionPrepared=!0})).finally((function(){t._prepPromise=null})),this._prepPromise},u.prototype.encryptMessage=async function(e,t,n){const r=await e.getEncryptionTargetMembers(),i=o.map(r,(function(e){return e.userId})),a=this;await this._ensureSession(i);const c={room_id:e.roomId,type:t,content:n},u={algorithm:s.OLM_ALGORITHM,sender_key:a._olmDevice.deviceCurve25519Key,ciphertext:{}},l=[];for(let e=0;eu)},o.inherits(l,c.DecryptionAlgorithm),l.prototype.decryptEvent=async function(e){const t=e.getWireContent(),n=t.sender_key,r=t.ciphertext;if(!r)throw new c.DecryptionError("OLM_MISSING_CIPHERTEXT","Missing ciphertext");if(!(this._olmDevice.deviceCurve25519Key in r))throw new c.DecryptionError("OLM_NOT_INCLUDED_IN_RECIPIENTS","Not included in recipients");const i=r[this._olmDevice.deviceCurve25519Key];let o;try{o=await this._decryptMessage(n,i)}catch(e){throw new c.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE","Bad Encrypted Message",{sender:n,err:e})}const s=JSON.parse(o);if(s.recipient!=this._userId)throw new c.DecryptionError("OLM_BAD_RECIPIENT","Message was intented for "+s.recipient);if(s.recipient_keys.ed25519!=this._olmDevice.deviceEd25519Key)throw new c.DecryptionError("OLM_BAD_RECIPIENT_KEY","Message not intended for this device",{intended:s.recipient_keys.ed25519,our_key:this._olmDevice.deviceEd25519Key});if(s.sender!=e.getSender())throw new c.DecryptionError("OLM_FORWARDED_MESSAGE","Message forwarded from "+s.sender,{reported_sender:e.getSender()});if(s.room_id!==e.getRoomId())throw new c.DecryptionError("OLM_BAD_ROOM","Message intended for room "+s.room_id,{reported_room:e.room_id});return{clearEvent:s,senderCurve25519Key:n,claimedEd25519Key:(s.keys||{}).ed25519||null}},l.prototype._decryptMessage=async function(e,t){const n=await this._olmDevice.getSessionIdsForDevice(e),r={};for(let o=0;o=e||n>=t)&&(i.logger.log("Rotating megolm session after "+this.useCount+" messages, "+n+"ms"),!0)},f.prototype.markSharedWithDevice=function(e,t,n){this.sharedWithDevices[e]||(this.sharedWithDevices[e]={}),this.sharedWithDevices[e][t]=n},f.prototype.markNotifiedBlockedDevice=function(e,t){this.blockedDevicesNotified[e]||(this.blockedDevicesNotified[e]={}),this.blockedDevicesNotified[e][t]=!0},f.prototype.sharedWithTooManyDevices=function(e){for(const t in this.sharedWithDevices)if(this.sharedWithDevices.hasOwnProperty(t)){if(!e.hasOwnProperty(t))return i.logger.log("Starting new megolm session because we shared with "+t),!0;for(const n in this.sharedWithDevices[t])if(this.sharedWithDevices[t].hasOwnProperty(n)&&!e[t].hasOwnProperty(n))return i.logger.log("Starting new megolm session because we shared with "+t+":"+n),!0}},o.inherits(u,a.EncryptionAlgorithm),u.prototype._ensureOutboundSession=async function(e,t){const n=this;let r;function o(){return r}const s=this._setupPromise.then((async function(o){r=o,r&&r.needsRotation(n._sessionRotationPeriodMsgs,n._sessionRotationPeriodMs)&&(i.logger.log("Starting new megolm session because we need to rotate."),r=null),r&&r.sharedWithTooManyDevices(e)&&(r=null),r||(i.logger.log(`Starting new megolm session for room ${n._roomId}`),r=await n._prepareNewSession(),i.logger.log(`Started new megolm session ${r.sessionId} `+`for room ${n._roomId}`),n._outboundSessions[r.sessionId]=r);const s={};for(const t in e){if(!e.hasOwnProperty(t))continue;const i=e[t];for(const e in i){if(!i.hasOwnProperty(e))continue;const o=i[e];o.getIdentityKey()!=n._olmDevice.deviceCurve25519Key&&(r.sharedWithDevices[t]&&void 0!==r.sharedWithDevices[t][e]||(s[t]=s[t]||[],s[t].push(o)))}}const a=[];await n._shareKeyWithDevices(r,s,a);const f={};for(const e in t){if(!t.hasOwnProperty(e))continue;const n=t[e];for(const t in n)n.hasOwnProperty(t)&&(r.blockedDevicesNotified[e]&&void 0!==r.blockedDevicesNotified[e][t]||(f[e]=f[e]||[],f[e].push(n[t])))}const u=await n._olmDevice.filterOutNotifiedErrorDevices(a);for(const{userId:e,deviceInfo:t}of u)f[e]=f[e]||[],f[e].push({code:"m.no_olm",reason:c.WITHHELD_MESSAGES["m.no_olm"],deviceInfo:t});await n._notifyBlockedDevices(r,f)}));return this._setupPromise=s.then(o,o),s.then(o)},u.prototype._prepareNewSession=async function(){const e=this._olmDevice.createOutboundGroupSession(),t=this._olmDevice.getOutboundGroupSessionKey(e);return await this._olmDevice.addInboundGroupSession(this._roomId,this._olmDevice.deviceCurve25519Key,[],e,t.key,{ed25519:this._olmDevice.deviceEd25519Key}),this._crypto.backupInfo&&this._crypto.backupGroupSession(this._roomId,this._olmDevice.deviceCurve25519Key,[],e,t.key).catch(e=>{i.logger.log("Failed to back up megolm session",e)}),new f(e)},u.prototype._splitUserDeviceMap=function(e,t,n,r,o){const s=[];let a=0,c=0;for(const f of Object.keys(r)){const u=r[f],l=n[f];for(let n=0;n20&&(c=0,a++)}return s},u.prototype._splitBlockedDevices=function(e){let t=[];const n=[t];for(const r of Object.keys(e)){const i=e[r];for(const e of i)t.push({userId:r,blockedInfo:e});t.length>20&&(t=[],n.push(t))}return 0===t.length&&n.pop(),n},u.prototype._encryptAndSendKeysToDevices=function(e,t,n,r){const i={},o=[];for(let e=0;ethis._baseApis.sendToDevice("m.room.encrypted",i).then(()=>{for(const n of Object.keys(i))for(const r of Object.keys(i[n]))e.markSharedWithDevice(n,r,t)}))},u.prototype._sendBlockedNotificationsToDevices=async function(e,t,n){const r={};for(const e of t){const t=e.userId,i=e.blockedInfo,o=i.deviceInfo.deviceId,s=Object.assign({},n);s.code=i.code,s.reason=i.reason,"m.no_olm"===s.code&&(delete s.room_id,delete s.session_id),r[t]||(r[t]={}),r[t][o]=s}await this._baseApis.sendToDevice("org.matrix.room_key.withheld",r);for(const t of Object.keys(r))for(const n of Object.keys(r[t]))e.markNotifiedBlockedDevice(t,n)},u.prototype.reshareKeyWithDevice=async function(e,t,n,r){const o=this._outboundSessions[t];if(!o)return void i.logger.debug(`megolm session ${t} not found: not re-sharing keys`);if(void 0===o.sharedWithDevices[n])return void i.logger.debug(`megolm session ${t} never shared with user ${n}`);const a=o.sharedWithDevices[n][r.deviceId];if(void 0===a)return void i.logger.debug("megolm session ID "+t+" never shared with device "+n+":"+r.deviceId);const c=await this._olmDevice.getInboundGroupSessionKey(this._roomId,e,t,a);if(!c)return void i.logger.warn(`No inbound session key found for megolm ${t}: not re-sharing keys`);await s.ensureOlmSessionsForDevices(this._olmDevice,this._baseApis,{[n]:{[r.deviceId]:r}});const f={type:"m.forwarded_room_key",content:{algorithm:s.MEGOLM_ALGORITHM,room_id:this._roomId,session_id:t,session_key:c.key,chain_index:c.chain_index,sender_key:e,sender_claimed_ed25519_key:c.sender_claimed_ed25519_key,forwarding_curve25519_key_chain:c.forwarding_curve25519_key_chain}},u={algorithm:s.OLM_ALGORITHM,sender_key:this._olmDevice.deviceCurve25519Key,ciphertext:{}};await s.encryptMessageForDevice(u.ciphertext,this._userId,this._deviceId,this._olmDevice,n,r,f),await this._baseApis.sendToDevice("m.room.encrypted",{[n]:{[r.deviceId]:u}}),i.logger.debug(`Re-shared key for megolm session ${t} `+`with ${n}:${r.deviceId}`)},u.prototype._shareKeyWithDevices=async function(e,t,n){const r=this._olmDevice.getOutboundGroupSessionKey(e.sessionId),o={type:"m.room_key",content:{algorithm:s.MEGOLM_ALGORITHM,room_id:this._roomId,session_id:e.sessionId,session_key:r.key,chain_index:r.chain_index}},a=await s.ensureOlmSessionsForDevices(this._olmDevice,this._baseApis,t),c=this._splitUserDeviceMap(e,r.chain_index,a,t,n);for(let t=0;tnull)},u.prototype._checkForUnknownDevices=function(e){const t={};if(Object.keys(e).forEach(n=>{Object.keys(e[n]).forEach(r=>{const i=e[n][r];i.isUnverified()&&!i.isKnown()&&(t[n]||(t[n]={}),t[n][r]=i)})}),Object.keys(t).length)throw new a.UnknownDeviceError("This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.",t)},u.prototype._getDevicesInRoom=async function(e){const t=await e.getEncryptionTargetMembers(),n=o.map(t,(function(e){return e.userId}));let r=this._crypto.getGlobalBlacklistUnverifiedDevices();"boolean"==typeof e.getBlacklistUnverifiedDevices()&&(r=e.getBlacklistUnverifiedDevices());const i=await this._crypto.downloadKeys(n,!1),s={};for(const e in i){if(!i.hasOwnProperty(e))continue;const t=i[e];for(const n in t)if(t.hasOwnProperty(n)&&(t[n].isBlocked()||t[n].isUnverified()&&r)){s[e]||(s[e]={});const r=t[n].isBlocked()?{code:"m.blacklisted",reason:c.WITHHELD_MESSAGES["m.blacklisted"]}:{code:"m.unverified",reason:c.WITHHELD_MESSAGES["m.unverified"]};r.deviceInfo=t[n],s[e][n]=r,delete t[n]}}return[i,s]},o.inherits(l,a.DecryptionAlgorithm);const d={no_olm:"The sender was unable to establish a secure channel.",unknown:"The secure channel with the sender was corrupted."};l.prototype.decryptEvent=async function(e){const t=e.getWireContent();if(!t.sender_key||!t.session_id||!t.ciphertext)throw new a.DecryptionError("MEGOLM_MISSING_FIELDS","Missing fields in input");let n;this._addEventToPendingList(e);try{n=await this._olmDevice.decryptGroupMessage(e.getRoomId(),t.sender_key,t.session_id,t.ciphertext,e.getId(),e.getTs())}catch(n){if("DecryptionError"===n.name)throw n;let r="OLM_DECRYPT_GROUP_MESSAGE_ERROR";throw n&&"OLM.UNKNOWN_MESSAGE_INDEX"===n.message&&(this._requestKeysForEvent(e),r="OLM_UNKNOWN_MESSAGE_INDEX"),new a.DecryptionError(r,n?n.toString():"Unknown Error: Error is undefined",{session:t.sender_key+"|"+t.session_id})}if(null===n){this._requestKeysForEvent(e);const n=await this._olmDevice.sessionMayHaveProblems(t.sender_key,e.getTs()-12e4);if(n){let e=d[n.type]||d.unknown;throw n.fixed&&(e+=" Trying to create a new secure channel and re-requesting the keys."),new a.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",e,{session:t.sender_key+"|"+t.session_id})}throw new a.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID","The sender's device has not sent us the keys for this message.",{session:t.sender_key+"|"+t.session_id})}this._removeEventFromPendingList(e);const r=JSON.parse(n.result);if(r.room_id!==e.getRoomId())throw new a.DecryptionError("MEGOLM_BAD_ROOM","Message intended for room "+r.room_id);return{clearEvent:r,senderCurve25519Key:n.senderKey,claimedEd25519Key:n.keysClaimed.ed25519,forwardingCurve25519KeyChain:n.forwardingCurve25519KeyChain}},l.prototype._requestKeysForEvent=function(e){const t=e.getWireContent(),n=e.getKeyRequestRecipients(this._userId);this._crypto.requestRoomKey({room_id:e.getRoomId(),algorithm:t.algorithm,sender_key:t.sender_key,session_id:t.session_id},n)},l.prototype._addEventToPendingList=function(e){const t=e.getWireContent(),n=t.sender_key,r=t.session_id;this._pendingEvents[n]||(this._pendingEvents[n]=new Map);const i=this._pendingEvents[n];i.has(r)||i.set(r,new Set),i.get(r).add(e)},l.prototype._removeEventFromPendingList=function(e){const t=e.getWireContent(),n=t.sender_key,r=t.session_id,i=this._pendingEvents[n],o=i&&i.get(r);o&&(o.delete(e),0===o.size&&i.delete(n),0===i.size&&delete this._pendingEvents[n])},l.prototype.onRoomKeyEvent=function(e){const t=e.getContent(),n=t.session_id;let r,s=e.getSenderKey(),a=[],c=!1;if(t.room_id&&n&&t.session_key){if(s){if("m.forwarded_room_key"==e.getType()){if(c=!0,a=t.forwarding_curve25519_key_chain,o.isArray(a)||(a=[]),a=a.slice(),a.push(s),s=t.sender_key,!s)return void i.logger.error("forwarded_room_key event is missing sender_key field");const e=t.sender_claimed_ed25519_key;if(!e)return void i.logger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field");r={ed25519:e}}else r=e.getKeysClaimed();return i.logger.log(`Received and adding key for megolm session ${s}|${n}`),this._olmDevice.addInboundGroupSession(t.room_id,s,a,n,t.session_key,r,c).then(()=>{this._retryDecryption(s,n).then(e=>{e&&this._crypto.cancelRoomKeyRequest({algorithm:t.algorithm,room_id:t.room_id,session_id:t.session_id,sender_key:s})})}).then(()=>{this._crypto.backupInfo&&this._crypto.backupGroupSession(t.room_id,s,a,t.session_id,t.session_key,r,c).catch(e=>{i.logger.log("Failed to back up megolm session",e)})}).catch(e=>{i.logger.error(`Error handling m.room_key_event: ${e}`)})}i.logger.error("key event has no sender key (not encrypted?)")}else i.logger.error("key event is missing fields")},l.prototype.onRoomKeyWithheldEvent=async function(e){const t=e.getContent(),n=t.sender_key;if("m.no_olm"===t.code){const r=e.getSender();if(await this._olmDevice.getSessionIdForDevice(n))return await this._olmDevice.recordSessionProblem(n,"no_olm",!0),void this.retryDecryptionFromSender(n);const o=this._crypto._deviceList.getDeviceByIdentityKey(t.algorithm,n);if(!o)return i.logger.info("Couldn't find device for identity key "+n+": not establishing session"),await this._olmDevice.recordSessionProblem(n,"no_olm",!1),void this.retryDecryptionFromSender(n);await s.ensureOlmSessionsForDevices(this._olmDevice,this._baseApis,{[r]:[o]},!1);const a={algorithm:s.OLM_ALGORITHM,sender_key:this._olmDevice.deviceCurve25519Key,ciphertext:{}};await s.encryptMessageForDevice(a.ciphertext,this._userId,this._deviceId,this._olmDevice,r,o,{type:"m.dummy"}),await this._olmDevice.recordSessionProblem(n,"no_olm",!0),this.retryDecryptionFromSender(n),await this._baseApis.sendToDevice("m.room.encrypted",{[r]:{[o.deviceId]:a}})}else await this._olmDevice.addInboundGroupSessionWithheld(t.room_id,n,t.session_id,t.code,t.reason)},l.prototype.hasKeysForKeyRequest=function(e){const t=e.requestBody;return this._olmDevice.hasInboundSessionKeys(t.room_id,t.sender_key,t.session_id)},l.prototype.shareKeysWithDevice=function(e){const t=e.userId,n=e.deviceId,r=this._crypto.getStoredDevice(t,n),o=e.requestBody;this.olmlib.ensureOlmSessionsForDevices(this._olmDevice,this._baseApis,{[t]:[r]}).then(e=>e[t][n].sessionId?(i.logger.log("sharing keys for session "+o.sender_key+"|"+o.session_id+" with device "+t+":"+n),this._buildKeyForwardingMessage(o.room_id,o.sender_key,o.session_id)):null).then(e=>{const i={algorithm:s.OLM_ALGORITHM,sender_key:this._olmDevice.deviceCurve25519Key,ciphertext:{}};return this.olmlib.encryptMessageForDevice(i.ciphertext,this._userId,this._deviceId,this._olmDevice,t,r,e).then(()=>{const e={[t]:{[n]:i}};return this._baseApis.sendToDevice("m.room.encrypted",e)})})},l.prototype._buildKeyForwardingMessage=async function(e,t,n){const r=await this._olmDevice.getInboundGroupSessionKey(e,t,n);return{type:"m.forwarded_room_key",content:{algorithm:s.MEGOLM_ALGORITHM,room_id:e,sender_key:t,sender_claimed_ed25519_key:r.sender_claimed_ed25519_key,session_id:n,session_key:r.key,chain_index:r.chain_index,forwarding_curve25519_key_chain:r.forwarding_curve25519_key_chain}}},l.prototype.importRoomKey=function(e){return this._olmDevice.addInboundGroupSession(e.room_id,e.sender_key,e.forwarding_curve25519_key_chain,e.session_id,e.session_key,e.sender_claimed_keys,!0).then(()=>{this._crypto.backupInfo&&this._crypto.backupGroupSession(e.room_id,e.sender_key,e.forwarding_curve25519_key_chain,e.session_id,e.session_key,e.sender_claimed_keys,!0).catch(e=>{i.logger.log("Failed to back up megolm session",e)}),this._retryDecryption(e.sender_key,e.session_id)})},l.prototype._retryDecryption=async function(e,t){const n=this._pendingEvents[e];if(!n)return!0;const r=n.get(t);return!r||(r.delete(t),0===r.size&&this._pendingEvents[e],await Promise.all([...r].map(async e=>{try{await e.attemptDecryption(this._crypto)}catch(e){}})),!(this._pendingEvents[e]||{})[t])},l.prototype.retryDecryptionFromSender=async function(e){const t=this._pendingEvents[e];return i.logger.warn(t),!t||(delete this._pendingEvents[e],await Promise.all([...t].map(async([e,t])=>{await Promise.all([...t].map(async e=>{try{i.logger.warn(e.getId()),await e.attemptDecryption(this._crypto)}catch(e){}}))})),!this._pendingEvents[e])},(0,a.registerAlgorithm)(s.MEGOLM_ALGORITHM,u,l)},function(e,t,n){"use strict";var r=n(6);Object.defineProperty(t,"__esModule",{value:!0}),t.DeviceList=void 0;var i=n(9),o=n(4),s=n(51),a=n(139),c=r(n(21)),f=n(36),u=n(8);class l extends i.EventEmitter{constructor(e,t,n){super(),this._cryptoStore=t,this._devices={},this._crossSigningInfo={},this._userByIdentityKey={},this._deviceTrackingStatus={},this._syncToken=null,this._serialiser=new d(e,n,this),this._keyDownloadsInProgressByUser={},this._dirty=!1,this._savePromise=null,this._resolveSavePromise=null,this._savePromiseTime=null,this._saveTimer=null}async load(){await this._cryptoStore.doTxn("readonly",[f.IndexedDBCryptoStore.STORE_DEVICE_DATA],e=>{this._cryptoStore.getEndToEndDeviceData(e,e=>{this._devices=e?e.devices:{},this._crossSigningInfo=e&&e.crossSigningInfo||{},this._deviceTrackingStatus=e?e.trackingStatus:{},this._syncToken=e?e.syncToken:null,this._userByIdentityKey={};for(const e of Object.keys(this._devices)){const t=this._devices[e];for(const n of Object.keys(t)){const r=t[n].keys["curve25519:"+n];void 0!==r&&(this._userByIdentityKey[r]=e)}}})});for(const e of Object.keys(this._deviceTrackingStatus))2==this._deviceTrackingStatus[e]&&(this._deviceTrackingStatus[e]=1)}stop(){null!==this._saveTimer&&clearTimeout(this._saveTimer)}async saveIfDirty(e){if(!this._dirty)return Promise.resolve(!1);void 0===e&&(e=500);const t=Date.now+e;this._savePromiseTime&&t{this._resolveSavePromise=e}),this._savePromise=n),null===this._saveTimer){const n=this._resolveSavePromise;this._savePromiseTime=t,this._saveTimer=setTimeout(()=>{o.logger.log("Saving device tracking data at token "+this._syncToken),this._savePromiseTime=null,this._saveTimer=null,this._savePromise=null,this._resolveSavePromise=null,this._dirty=!1,this._cryptoStore.doTxn("readwrite",[f.IndexedDBCryptoStore.STORE_DEVICE_DATA],e=>{this._cryptoStore.storeEndToEndDeviceData({devices:this._devices,crossSigningInfo:this._crossSigningInfo,trackingStatus:this._deviceTrackingStatus,syncToken:this._syncToken},e)}).then(()=>{n()})},e)}return n}getSyncToken(){return this._syncToken}setSyncToken(e){this._syncToken=e}downloadKeys(e,t){const n=[],r=[];if(e.forEach(e=>{const i=this._deviceTrackingStatus[e];this._keyDownloadsInProgressByUser[e]?(o.logger.log("downloadKeys: already have a download in progress for "+`${e}: awaiting its result`),r.push(this._keyDownloadsInProgressByUser[e])):(t||3!=i)&&n.push(e)}),0!=n.length){o.logger.log("downloadKeys: downloading for",n);const e=this._doKeyDownload(n);r.push(e)}return 0===r.length&&o.logger.log("downloadKeys: already have all necessary keys"),Promise.all(r).then(()=>this._getDevicesFromStore(e))}_getDevicesFromStore(e){const t={},n=this;return e.map((function(e){t[e]={},(n.getStoredDevicesForUser(e)||[]).map((function(n){t[e][n.deviceId]=n}))})),t}getStoredDevicesForUser(e){const t=this._devices[e];if(!t)return null;const n=[];for(const e in t)t.hasOwnProperty(e)&&n.push(s.DeviceInfo.fromStorage(t[e],e));return n}getRawStoredDevicesForUser(e){return this._devices[e]}getStoredCrossSigningForUser(e){return this._crossSigningInfo[e]?a.CrossSigningInfo.fromStorage(this._crossSigningInfo[e],e):null}storeCrossSigningForUser(e,t){this._crossSigningInfo[e]=t,this._dirty=!0}getStoredDevice(e,t){const n=this._devices[e];if(n&&n[t])return s.DeviceInfo.fromStorage(n[t],t)}getDeviceByIdentityKey(e,t){const n=this._userByIdentityKey[t];if(!n)return null;if(e!==c.OLM_ALGORITHM&&e!==c.MEGOLM_ALGORITHM)return null;const r=this._devices[n];if(!r)return null;for(const e in r){if(!r.hasOwnProperty(e))continue;const n=r[e];for(const r in n.keys){if(!n.keys.hasOwnProperty(r))continue;if(0!==r.indexOf("curve25519:"))continue;if(n.keys[r]==t)return s.DeviceInfo.fromStorage(n,e)}}return null}storeDevicesForUser(e,t){if(void 0!==this._devices[e])for(const[t,n]of Object.entries(this._devices[e])){const e=n.keys["curve25519:"+t];delete this._userByIdentityKey[e]}this._devices[e]=t;for(const[n,r]of Object.entries(t)){const t=r.keys["curve25519:"+n];this._userByIdentityKey[t]=e}this._dirty=!0}startTrackingDeviceList(e){if("string"!=typeof e)throw new Error("userId must be a string; was "+e);this._deviceTrackingStatus[e]||(o.logger.log("Now tracking device list for "+e),this._deviceTrackingStatus[e]=1,this._dirty=!0)}stopTrackingDeviceList(e){this._deviceTrackingStatus[e]&&(o.logger.log("No longer tracking device list for "+e),this._deviceTrackingStatus[e]=0,this._dirty=!0)}stopTrackingAllDeviceLists(){for(const e of Object.keys(this._deviceTrackingStatus))this._deviceTrackingStatus[e]=0;this._dirty=!0}invalidateUserDeviceList(e){this._deviceTrackingStatus[e]&&(o.logger.log("Marking device list outdated for",e),this._deviceTrackingStatus[e]=1,this._dirty=!0)}refreshOutdatedDeviceLists(){this.saveIfDirty();const e=[];for(const t of Object.keys(this._deviceTrackingStatus)){1==this._deviceTrackingStatus[t]&&e.push(t)}return this._doKeyDownload(e)}_setRawStoredDevicesForUser(e,t){if(void 0!==this._devices[e])for(const[t,n]of Object.entries(this._devices[e])){const e=n.keys["curve25519:"+t];delete this._userByIdentityKey[e]}this._devices[e]=t;for(const[n,r]of Object.entries(t)){const t=r.keys["curve25519:"+n];this._userByIdentityKey[t]=e}}setRawStoredCrossSigningForUser(e,t){this._crossSigningInfo[e]=t}_doKeyDownload(e){if(0===e.length)return Promise.resolve();const t=this._serialiser.updateDevicesForUsers(e,this._syncToken).then(()=>{n(!0)},t=>{throw o.logger.error("Error downloading keys for "+e+":",t),n(!1),t});e.forEach(e=>{this._keyDownloadsInProgressByUser[e]=t,1==this._deviceTrackingStatus[e]&&(this._deviceTrackingStatus[e]=2)});const n=n=>{e.forEach(e=>{if(this._dirty=!0,this._keyDownloadsInProgressByUser[e]!==t)return void o.logger.log("Another update in the queue for",e,"- not marking up-to-date");delete this._keyDownloadsInProgressByUser[e],2==this._deviceTrackingStatus[e]&&(n?(this._deviceTrackingStatus[e]=3,o.logger.log("Device list for",e,"now up to date")):this._deviceTrackingStatus[e]=1)}),this.saveIfDirty(),this.emit("crypto.devicesUpdated",e)};return t}}t.DeviceList=l;class d{constructor(e,t,n){this._baseApis=e,this._olmDevice=t,this._deviceList=n,this._downloadInProgress=!1,this._keyDownloadsQueuedByUser={},this._queuedQueryDeferred=null,this._syncToken=null}updateDevicesForUsers(e,t){return e.forEach(e=>{this._keyDownloadsQueuedByUser[e]=!0}),this._queuedQueryDeferred||(this._queuedQueryDeferred=(0,u.defer)()),this._syncToken=t,this._downloadInProgress?(o.logger.log("Queued key download for",e),this._queuedQueryDeferred.promise):this._doQueuedQueries()}_doQueuedQueries(){if(this._downloadInProgress)throw new Error("DeviceListUpdateSerialiser._doQueuedQueries called with request active");const e=Object.keys(this._keyDownloadsQueuedByUser);this._keyDownloadsQueuedByUser={};const t=this._queuedQueryDeferred;this._queuedQueryDeferred=null,o.logger.log("Starting key download for",e),this._downloadInProgress=!0;const n={};return this._syncToken&&(n.token=this._syncToken),this._baseApis.downloadKeysForUsers(e,n).then(t=>{const n=t.device_keys||{},r=t.master_keys||{},i=t.self_signing_keys||{},o=t.user_signing_keys||{};let s=Promise.resolve();for(const t of e)s=s.then((0,u.sleep)(5)).then(()=>this._processQueryResponseForUser(t,n[t],{master:r[t],self_signing:i[t],user_signing:o[t]}));return s}).then(()=>{o.logger.log("Completed key download for "+e),this._downloadInProgress=!1,t.resolve(),this._queuedQueryDeferred&&this._doQueuedQueries()},n=>{o.logger.warn("Error downloading keys for "+e+":",n),this._downloadInProgress=!1,t.reject(n)}),t.promise}async _processQueryResponseForUser(e,t,n,r){o.logger.log("got device keys for "+e+":",t),o.logger.log("got cross-signing keys for "+e+":",n);{const n={},r=this._deviceList.getRawStoredDevicesForUser(e);r&&Object.keys(r).forEach(e=>{const t=s.DeviceInfo.fromStorage(r[e],e);n[e]=t}),await async function(e,t,n,r){let i=!1;for(const e in n)n.hasOwnProperty(e)&&(e in r||(o.logger.log("Device "+t+":"+e+" has been removed"),delete n[e],i=!0));for(const s in r){if(!r.hasOwnProperty(s))continue;const a=r[s];a.user_id===t?a.device_id===s?await h(e,n,a)&&(i=!0):o.logger.warn("Mismatched device_id "+a.device_id+" in keys from "+t+":"+s):o.logger.warn("Mismatched user_id "+a.user_id+" in keys from "+t+":"+s)}return i}(this._olmDevice,e,n,t||{});const i={};Object.keys(n).forEach(e=>{i[e]=n[e].toStorage()}),this._deviceList._setRawStoredDevicesForUser(e,i)}if(n&&(n.master||n.self_signing||n.user_signing)){const t=this._deviceList.getStoredCrossSigningForUser(e)||new a.CrossSigningInfo(e);t.setKeys(n),this._deviceList.setRawStoredCrossSigningForUser(e,t.toStorage()),this._deviceList.emit("userCrossSigningUpdated",e)}}}async function h(e,t,n){if(!n.keys)return!1;const r=n.device_id,i=n.user_id,a="ed25519:"+r,f=n.keys[a];if(!f)return o.logger.warn("Device "+i+":"+r+" has no ed25519 key"),!1;const u=n.unsigned||{},l=n.signatures||{};try{await c.verifySignature(e,n,i,r,f)}catch(e){return o.logger.warn("Unable to verify signature on device "+i+":"+r+":"+e),!1}let d;if(r in t){if(d=t[r],d.getFingerprint()!=f)return o.logger.warn("Ed25519 key for device "+i+":"+r+" has changed"),!1}else t[r]=d=new s.DeviceInfo(r);return d.keys=n.keys||{},d.algorithms=n.algorithms||[],d.unsigned=u,d.signatures=l,!0}},function(e,t,n){"use strict";(function(e){var r=n(6);Object.defineProperty(t,"__esModule",{value:!0}),t.SecretStorage=t.SECRET_STORAGE_ALGORITHM_V1=void 0;var i=n(9),o=n(4),s=r(n(21)),a=n(52);const c="m.secret_storage.v1.curve25519-aes-sha2";t.SECRET_STORAGE_ALGORITHM_V1=c;class f extends i.EventEmitter{constructor(e,t,n){super(),this._baseApis=e,this._cryptoCallbacks=t,this._crossSigningInfo=n,this._requests={},this._incomingRequests={}}async getDefaultKeyId(){const e=await this._baseApis.getAccountDataFromServer("m.secret_storage.default_key");return e?e.key:null}setDefaultKeyId(e){return new Promise(t=>{const n=r=>{"m.secret_storage.default_key"===r.getType()&&r.getContent().key===e&&(this._baseApis.removeListener("accountData",n),t())};this._baseApis.on("accountData",n),this._baseApis.setAccountData("m.secret_storage.default_key",{key:e})})}async addKey(t,n,r){const i={algorithm:t};switch(n||(n={}),n.name&&(i.name=n.name),t){case c:{const t=new e.Olm.PkDecryption;try{const{passphrase:e,pubkey:r}=n;e&&r?(i.passphrase=e,i.pubkey=r):i.pubkey=r||t.generate_key()}finally{t.free()}break}default:throw new Error(`Unknown key algorithm ${n.algorithm}`)}if(!r)do{r=(0,a.randomString)(32)}while(await this._baseApis.getAccountDataFromServer(`m.secret_storage.key.${r}`));return await this._crossSigningInfo.signObject(i,"master"),await this._baseApis.setAccountData(`m.secret_storage.key.${r}`,i),r}async signKey(e){if(e||(e=await this.getDefaultKeyId()),!e)throw new Error("signKey requires a key ID");const t=await this._baseApis.getAccountDataFromServer(`m.secret_storage.key.${e}`);if(!t)throw new Error(`Key ${e} does not exist in account data`);await this._crossSigningInfo.signObject(t,"master"),await this._baseApis.setAccountData(`m.secret_storage.key.${e}`,t)}async hasKey(e){return e||(e=await this.getDefaultKeyId()),!!e&&!!this._baseApis.getAccountDataFromServer("m.secret_storage.key."+e)}async store(t,n,r){const i={};if(!r){const e=await this.getDefaultKeyId();if(!e)throw new Error("No keys specified and no default key present");r=[e]}if(0===r.length)throw new Error("Zero keys given to encrypt with!");for(const t of r){const r=await this._baseApis.getAccountDataFromServer("m.secret_storage.key."+t);if(!r)throw new Error("Unknown key: "+t);switch((0,s.pkVerify)(r,this._crossSigningInfo.getId("master"),this._crossSigningInfo.userId),r.algorithm){case c:{const o=new e.Olm.PkEncryption;try{o.set_recipient_key(r.pubkey),i[t]=o.encrypt(n)}finally{o.free()}break}default:o.logger.warn("unknown algorithm for secret storage key "+t+": "+r.algorithm)}}await this._baseApis.setAccountData(t,{encrypted:i})}storePassthrough(e,t){return this._baseApis.setAccountData(e,{[t]:{passthrough:!0}})}async get(e){const t=await this._baseApis.getAccountDataFromServer(e);if(!t)return;if(!t.encrypted)throw new Error("Content is not encrypted!");const n={};for(const e of Object.keys(t.encrypted)){const r=await this._baseApis.getAccountDataFromServer("m.secret_storage.key."+e),i=t.encrypted[e];switch(r.algorithm){case c:r.pubkey&&i.ciphertext&&i.mac&&i.ephemeral&&(n[e]=r)}}let r,i;try{[r,i]=await this._getSecretStorageKey(n);const e=t.encrypted[r];if(e.passthrough)return i.get_private_key();switch(n[r].algorithm){case c:return i.decrypt(e.ephemeral,e.mac,e.ciphertext)}}finally{i&&i.free()}}async isStored(e,t){const n=await this._baseApis.getAccountDataFromServer(e);if(!n||!n.encrypted)return!1;void 0===t&&(t=!0);for(const e of Object.keys(n.encrypted)){const r=await this._baseApis.getAccountDataFromServer("m.secret_storage.key."+e);if(!r)return!1;const i=n.encrypted[e];switch(t&&(0,s.pkVerify)(r,this._crossSigningInfo.getId("master"),this._crossSigningInfo.userId),r.algorithm){case c:if(r.pubkey&&i.ciphertext&&i.mac&&i.ephemeral)return!0}}return!1}request(e,t){const n=this._baseApis.makeTxnId(),r=this._requests[n]={devices:t},i=new Promise((e,t)=>{r.resolve=e,r.reject=t}),o={name:e,action:"request",requesting_device_id:this._baseApis.deviceId,request_id:n},s={};for(const e of t)s[e]=o;return this._baseApis.sendToDevice("m.secret.request",{[this._baseApis.getUserId()]:s}),{request_id:n,promise:i,cancel:e=>{const i={action:"request_cancellation",requesting_device_id:this._baseApis.deviceId,request_id:n},o={};for(const e of t)o[e]=i;this._baseApis.sendToDevice("m.secret.request",{[this._baseApis.getUserId()]:o}),r.reject(new Error(e||"Cancelled"))}}}async _onRequestReceived(e){const t=e.getSender(),n=e.getContent();if(t!==this._baseApis.getUserId()||!(n.name&&n.action&&n.requesting_device_id&&n.request_id))return;const r=n.requesting_device_id;if("request_cancellation"===n.action)this._incomingRequests[r]&&this._incomingRequests[r][n.request_id]&&(o.logger.info("received request cancellation for secret ("+t+", "+r+", "+n.request_id+")"),this.baseApis.emit("crypto.secrets.requestCancelled",{user_id:t,device_id:r,request_id:n.request_id}));else if("request"===n.action){if(r===this._baseApis.deviceId)return;if(o.logger.info("received request for secret ("+t+", "+r+", "+n.request_id+")"),!this._cryptoCallbacks.onSecretRequested)return;const e=await this._cryptoCallbacks.onSecretRequested({user_id:t,device_id:r,request_id:n.request_id,name:n.name,device_trust:this._baseApis.checkDeviceTrust(t,r)});if(e){const i={type:"m.secret.send",content:{request_id:n.request_id,secret:e}},o={algorithm:s.OLM_ALGORITHM,sender_key:this._baseApis._crypto._olmDevice.deviceCurve25519Key,ciphertext:{}};await s.ensureOlmSessionsForDevices(this._baseApis._crypto._olmDevice,this._baseApis,{[t]:[await this._baseApis.getStoredDevice(t,r)]}),await s.encryptMessageForDevice(o.ciphertext,this._baseApis.getUserId(),this._baseApis.deviceId,this._baseApis._crypto._olmDevice,t,this._baseApis._crypto.getStoredDevice(t,r),i);const a={[t]:{[r]:o}};this._baseApis.sendToDevice("m.room.encrypted",a)}}}_onSecretReceived(e){if(e.getSender()!==this._baseApis.getUserId())return;const t=e.getContent();o.logger.log("got secret share for request ",t.request_id);const n=this._requests[t.request_id];if(n){const r=this._baseApis._crypto._deviceList.getDeviceByIdentityKey(s.OLM_ALGORITHM,e.getSenderKey());if(!r)return void o.logger.log("secret share from unknown device with key",e.getSenderKey());if(!n.devices.includes(r.deviceId))return void o.logger.log("unsolicited secret share from device",r.deviceId);n.resolve(t.secret)}}async _getSecretStorageKey(t){if(!this._cryptoCallbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");const n=await this._cryptoCallbacks.getSecretStorageKey({keys:t});if(!n)throw new Error("getSecretStorageKey callback returned falsey");if(n.length<2)throw new Error("getSecretStorageKey callback returned invalid data");const[r,i]=n;if(!t[r])throw new Error("App returned unknown key from getSecretStorageKey!");switch(t[r].algorithm){case c:{const n=new e.Olm.PkDecryption;let o;try{o=n.init_with_private_key(i)}catch(e){throw n.free(),new Error("getSecretStorageKey callback returned invalid key")}if(o!==t[r].pubkey)throw n.free(),new Error("getSecretStorageKey callback returned incorrect key");return[r,n]}default:throw new Error("Unknown key type: "+t[r].algorithm)}}}t.SecretStorage=f}).call(this,n(5))},function(e,t,n){"use strict";(function(e){var r=n(6);Object.defineProperty(t,"__esModule",{value:!0}),t.OutgoingRoomKeyRequestManager=void 0;var i=n(4),o=r(n(8));const s=0,a=1,c=2,f=3;function u(e){return e.room_id+" / "+e.session_id}function l(e){return"["+o.map(e,e=>`${e.userId}:${e.deviceId}`).join(",")+"]"}t.OutgoingRoomKeyRequestManager=class{constructor(e,t,n){this._baseApis=e,this._deviceId=t,this._cryptoStore=n,this._sendOutgoingRoomKeyRequestsTimer=null,this._sendOutgoingRoomKeyRequestsRunning=!1,this._clientRunning=!1}start(){this._clientRunning=!0,this._startTimer()}stop(){i.logger.log("stopping OutgoingRoomKeyRequestManager"),this._clientRunning=!1}async sendRoomKeyRequest(e,t,n=!1){const r=await this._cryptoStore.getOutgoingRoomKeyRequest(e);if(r)switch(r.state){case f:case s:return;case c:{const e=n?f:a;await this._cryptoStore.updateOutgoingRoomKeyRequest(r.requestId,c,{state:e,cancellationTxnId:this._baseApis.makeTxnId()});break}case a:if(n){const o=f,s=await this._cryptoStore.updateOutgoingRoomKeyRequest(r.requestId,a,{state:o,cancellationTxnId:this._baseApis.makeTxnId(),requestTxnId:this._baseApis.makeTxnId()});if(!s)return await this.sendRoomKeyRequest(e,t,n);try{await this._sendOutgoingRoomKeyRequestCancellation(s,!0)}catch(e){i.logger.error("Error sending room key request cancellation; will retry later.",e)}}break;default:throw new Error("unhandled state: "+r.state)}else await this._cryptoStore.getOrAddOutgoingRoomKeyRequest({requestBody:e,recipients:t,requestId:this._baseApis.makeTxnId(),state:s});this._startTimer()}cancelRoomKeyRequest(e){return this._cryptoStore.getOutgoingRoomKeyRequest(e).then(t=>{if(t)switch(t.state){case c:case f:return;case s:return i.logger.log("deleting unnecessary room key request for "+u(e)),this._cryptoStore.deleteOutgoingRoomKeyRequest(t.requestId,s);case a:return this._cryptoStore.updateOutgoingRoomKeyRequest(t.requestId,a,{state:c,cancellationTxnId:this._baseApis.makeTxnId()}).then(t=>{t?this._sendOutgoingRoomKeyRequestCancellation(t).catch(e=>{i.logger.error("Error sending room key request cancellation; will retry later.",e),this._startTimer()}):i.logger.log("Tried to cancel room key request for "+u(e)+" but it was already cancelled in another tab")});default:throw new Error("unhandled state: "+t.state)}})}getOutgoingSentRoomKeyRequest(e,t){return this._cryptoStore.getOutgoingRoomKeyRequestsByTarget(e,t,[a])}_startTimer(){if(this._sendOutgoingRoomKeyRequestsTimer)return;this._sendOutgoingRoomKeyRequestsTimer=e.setTimeout(()=>{if(this._sendOutgoingRoomKeyRequestsRunning)throw new Error("RoomKeyRequestSend already in progress!");this._sendOutgoingRoomKeyRequestsRunning=!0,this._sendOutgoingRoomKeyRequests().finally(()=>{this._sendOutgoingRoomKeyRequestsRunning=!1}).catch(e=>{i.logger.warn(`error in OutgoingRoomKeyRequestManager: ${e}`)})},500)}_sendOutgoingRoomKeyRequests(){return this._clientRunning?(i.logger.log("Looking for queued outgoing room key requests"),this._cryptoStore.getOutgoingRoomKeyRequestByState([c,f,s]).then(e=>{if(!e)return i.logger.log("No more outgoing room key requests"),void(this._sendOutgoingRoomKeyRequestsTimer=null);let t;switch(e.state){case s:t=this._sendOutgoingRoomKeyRequest(e);break;case c:t=this._sendOutgoingRoomKeyRequestCancellation(e);break;case f:t=this._sendOutgoingRoomKeyRequestCancellation(e,!0)}return t.then(()=>this._sendOutgoingRoomKeyRequests()).catch(e=>{i.logger.error("Error sending room key request; will retry later.",e),this._sendOutgoingRoomKeyRequestsTimer=null,this._startTimer()})})):(this._sendOutgoingRoomKeyRequestsTimer=null,Promise.resolve())}_sendOutgoingRoomKeyRequest(e){i.logger.log(`Requesting keys for ${u(e.requestBody)}`+` from ${l(e.recipients)}`+`(id ${e.requestId})`);const t={action:"request",requesting_device_id:this._deviceId,request_id:e.requestId,body:e.requestBody};return this._sendMessageToDevices(t,e.recipients,e.requestTxnId||e.requestId).then(()=>this._cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,s,{state:a}))}_sendOutgoingRoomKeyRequestCancellation(e,t){i.logger.log("Sending cancellation for key request for "+`${u(e.requestBody)} to `+`${l(e.recipients)} `+`(cancellation id ${e.cancellationTxnId})`);const n={action:"request_cancellation",requesting_device_id:this._deviceId,request_id:e.requestId};return this._sendMessageToDevices(n,e.recipients,e.cancellationTxnId).then(()=>t?this._cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,f,{state:s}):this._cryptoStore.deleteOutgoingRoomKeyRequest(e.requestId,c))}_sendMessageToDevices(e,t,n){const r={};for(const n of t)r[n.userId]||(r[n.userId]={}),r[n.userId][n.deviceId]=e;return this._baseApis.sendToDevice("m.room_key_request",r,n)}}}).call(this,n(5))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ScanQRCode=t.ShowQRCode=void 0;var r=n(140),i=n(37);const o=/^(?:https?:\/\/)?(?:www\.)?matrix\.to\/#\/([#@!+][^?]+)\?(.+)$/,s=/^key_([^:]+:.+)$/,a=(0,i.errorFactory)("m.qr_code.invalid","Invalid QR code");class c extends r.VerificationBase{_doVerification(){if(!this._done){const e="https://matrix.to/#/"+this._baseApis.getUserId()+"?device="+encodeURIComponent(this._baseApis.deviceId)+"&action=verify&key_ed25519%3A"+encodeURIComponent(this._baseApis.deviceId)+"="+encodeURIComponent(this._baseApis.getDeviceEd25519Key());this.emit("show_qr_code",{url:e})}}}t.ShowQRCode=c,c.NAME="m.qr_code.show.v1";class f extends r.VerificationBase{static factory(...e){return new f(...e)}async _doVerification(){const e=(await new Promise((e,t)=>{this.emit("scan",{done:e,cancel:()=>t((0,i.newUserCancelledError)())})})).match(o);let t;const n={};if(!e)throw a();const r=e[1],c=e[2].split("&").map(e=>e.split("=",2).map(decodeURIComponent));let f;for(const[e,r]of c)if("device"===e)t=r;else if("action"===e)f=r;else{const t=e.match(s);t&&(n[t[1]]=r)}if(!t||"verify"!==f||0===Object.keys(n).length)throw a();if(this.userId){if(this.userId!==r)throw(0,i.newUserMismatchError)({expected:this.userId,actual:r})}else await new Promise((e,t)=>{this.emit("confirm_user_id",{userId:r,confirm:e,cancel:()=>t((0,i.newUserMismatchError)())})});await this._verifyKeys(r,n,(e,t,n)=>{if(t.keys[e]!==n)throw(0,i.newKeyMismatchError)()})}}t.ScanQRCode=f,f.NAME="m.qr_code.scan.v1"},function(e,t,n){"use strict";(function(e){var r=n(16);Object.defineProperty(t,"__esModule",{value:!0}),t.SAS=void 0;var i=n(140),o=r(n(80)),s=n(37);const a=["m.key.verification.accept","m.key.verification.key","m.key.verification.mac"];let c;const f=(0,s.errorFactory)("m.mismatched_sas","Mismatched short authentication string"),u=(0,s.errorFactory)("m.mismatched_commitment","Mismatched commitment");const l=[["🐶","dog"],["🐱","cat"],["🦁","lion"],["🐎","horse"],["🦄","unicorn"],["🐷","pig"],["🐘","elephant"],["🐰","rabbit"],["🐼","panda"],["🐓","rooster"],["🐧","penguin"],["🐢","turtle"],["🐟","fish"],["🐙","octopus"],["🦋","butterfly"],["🌷","flower"],["🌳","tree"],["🌵","cactus"],["🍄","mushroom"],["🌏","globe"],["🌙","moon"],["☁️","cloud"],["🔥","fire"],["🍌","banana"],["🍎","apple"],["🍓","strawberry"],["🌽","corn"],["🍕","pizza"],["🎂","cake"],["❤️","heart"],["🙂","smiley"],["🤖","robot"],["🎩","hat"],["👓","glasses"],["🔧","spanner"],["🎅","santa"],["👍","thumbs up"],["☂️","umbrella"],["⌛","hourglass"],["⏰","clock"],["🎁","gift"],["💡","light bulb"],["📕","book"],["✏️","pencil"],["📎","paperclip"],["✂️","scissors"],["🔒","lock"],["🔑","key"],["🔨","hammer"],["☎️","telephone"],["🏁","flag"],["🚂","train"],["🚲","bicycle"],["✈️","aeroplane"],["🚀","rocket"],["🏆","trophy"],["⚽","ball"],["🎸","guitar"],["🎺","trumpet"],["🔔","bell"],["⚓️","anchor"],["🎧","headphones"],["📁","folder"],["📌","pin"]];const d={decimal:function(e){return[1e3+(e[0]<<5|e[1]>>3),1e3+((7&e[1])<<10|e[2]<<2|e[3]>>6),1e3+((63&e[3])<<7|e[4]>>1)]},emoji:function(e){return[e[0]>>2,(3&e[0])<<4|e[1]>>4,(15&e[1])<<2|e[2]>>6,63&e[2],e[3]>>2,(3&e[3])<<4|e[4]>>4,(15&e[4])<<2|e[5]>>6].map(e=>l[e])}};function h(e,t){const n={};for(const r of t)r in d&&(n[r]=d[r](e));return n}const p={"hkdf-hmac-sha256":"calculate_mac","hmac-sha256":"calculate_mac_long_kdf"},m=["curve25519"],g=["sha256"],y=["hkdf-hmac-sha256","hmac-sha256"],b=Object.keys(d),_=new Set(m),v=new Set(g),A=new Set(y),w=new Set(b);function E(e,t){return e instanceof Array?e.filter(e=>t.has(e)):[]}class k extends i.VerificationBase{static get NAME(){return"m.sas.v1"}get events(){return a}async _doVerification(){return await e.Olm.init(),c=c||new e.Olm.Utility,await this._baseApis.downloadKeys([this.userId]),this.startEvent?await this._doRespondVerification():await this._doSendVerification()}async _doSendVerification(){const t="m.key.verification.start",n=this._channel.completeContent(t,{method:k.NAME,from_device:this._baseApis.deviceId,key_agreement_protocols:m,hashes:g,message_authentication_codes:y,short_authentication_string:b});this._channel.sendCompleted(t,n);let r=await this._waitForEvent("m.key.verification.accept"),i=r.getContent();const a=E(i.short_authentication_string,w);if(!(_.has(i.key_agreement_protocol)&&v.has(i.hash)&&A.has(i.message_authentication_code)&&a.length))throw(0,s.newUnknownMethodError)();if("string"!=typeof i.commitment)throw(0,s.newInvalidMessageError)();const l=i.message_authentication_code,d=i.commitment,p=new e.Olm.SAS;try{this._send("m.key.verification.key",{key:p.get_pubkey()}),r=await this._waitForEvent("m.key.verification.key"),i=r.getContent();const e=i.key+o.default.stringify(n);if(c.sha256(e)!==d)throw u();p.set_their_key(i.key);const t="MATRIX_KEY_VERIFICATION_SAS"+this._baseApis.getUserId()+this._baseApis.deviceId+this.userId+this.deviceId+this._channel.transactionId,m=p.generate_bytes(t,6),g=new Promise((e,t)=>{this.emit("show_sas",{sas:h(m,a),confirm:()=>{this._sendMAC(p,l),e()},cancel:()=>t((0,s.newUserCancelledError)()),mismatch:()=>t(f())})});[r]=await Promise.all([this._waitForEvent("m.key.verification.mac").then(e=>(this._expectedEvent="m.key.verification.done",e)),g]),i=r.getContent(),await this._checkMAC(p,i,l)}finally{p.free()}}async _doRespondVerification(){let t=this._channel.completedContentFromEvent(this.startEvent);const n=E(m,new Set(t.key_agreement_protocols))[0],r=E(g,new Set(t.hashes))[0],i=E(y,new Set(t.message_authentication_codes))[0],a=E(t.short_authentication_string,w);if(void 0===n||void 0===r||void 0===i||!a.length)throw(0,s.newUnknownMethodError)();const u=new e.Olm.SAS;try{const e=u.get_pubkey()+o.default.stringify(t);this._send("m.key.verification.accept",{key_agreement_protocol:n,hash:r,message_authentication_code:i,short_authentication_string:a,commitment:c.sha256(e)});let l=await this._waitForEvent("m.key.verification.key");t=l.getContent(),u.set_their_key(t.key),this._send("m.key.verification.key",{key:u.get_pubkey()});const d="MATRIX_KEY_VERIFICATION_SAS"+this.userId+this.deviceId+this._baseApis.getUserId()+this._baseApis.deviceId+this._channel.transactionId,p=u.generate_bytes(d,6),m=new Promise((e,t)=>{this.emit("show_sas",{sas:h(p,a),confirm:()=>{this._sendMAC(u,i),e()},cancel:()=>t((0,s.newUserCancelledError)()),mismatch:()=>t(f())})});[l]=await Promise.all([this._waitForEvent("m.key.verification.mac").then(e=>(this._expectedEvent="m.key.verification.done",e)),m]),t=l.getContent(),await this._checkMAC(u,t,i)}finally{u.free()}}_sendMAC(e,t){const n={},r=[],i="MATRIX_KEY_VERIFICATION_MAC"+this._baseApis.getUserId()+this._baseApis.deviceId+this.userId+this.deviceId+this._channel.transactionId,o=`ed25519:${this._baseApis.deviceId}`;n[o]=e[p[t]](this._baseApis.getDeviceEd25519Key(),i+o),r.push(o);const s=this._baseApis.getCrossSigningId();if(s){const o=`ed25519:${s}`;n[o]=e[p[t]](s,i+o),r.push(o)}const a=e[p[t]](r.sort().join(","),i+"KEY_IDS");this._send("m.key.verification.mac",{mac:n,keys:a})}async _checkMAC(e,t,n){const r="MATRIX_KEY_VERIFICATION_MAC"+this.userId+this.deviceId+this._baseApis.getUserId()+this._baseApis.deviceId+this._channel.transactionId;if(t.keys!==e[p[n]](Object.keys(t.mac).sort().join(","),r+"KEY_IDS"))throw(0,s.newKeyMismatchError)();await this._verifyKeys(this.userId,t.mac,(t,i,o)=>{if(o!==e[p[n]](i.keys[t],r+t))throw(0,s.newKeyMismatchError)()})}}t.SAS=k}).call(this,n(5))},function(e,t,n){var r=n(296);e.exports=r("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},function(e,t,n){"use strict";var r=n(3).Buffer;e.exports=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");var t=new Uint8Array(256);t.fill(255);for(var n=0;n>>0,u=new Uint8Array(f);e[n];){var l=t[e.charCodeAt(n)];if(255===l)return;for(var d=0,h=f-1;(0!==l||d>>0,u[h]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");o=d,n++}if(" "!==e[n]){for(var p=f-o;p!==f&&0===u[p];)p++;var m=r.allocUnsafe(i+(f-p));m.fill(0,0,i);for(var g=i;p!==f;)m[g++]=u[p++];return m}}}return{encode:function(t){if(!r.isBuffer(t))throw new TypeError("Expected Buffer");if(0===t.length)return"";for(var n=0,i=0,o=0,c=t.length;o!==c&&0===t[o];)o++,n++;for(var u=(c-o)*f+1>>>0,l=new Uint8Array(u);o!==c;){for(var d=t[o],h=0,p=u-1;(0!==d||h>>0,l[p]=d%s>>>0,d=d/s>>>0;if(0!==d)throw new Error("Non-zero carry");i=h,o++}for(var m=u-i;m!==u&&0===l[m];)m++;for(var g=a.repeat(n);me!==this._deviceId);if(e.length){const t=this.completeContent({code:"m.accepted",reason:"Verification request accepted by another device"});await this._sendToDevices(o.CANCEL_TYPE,t,e)}}}completedContentFromEvent(e){return e.getContent()}completeContent(e,t){return t=Object.assign({},t),this.transactionId&&(t.transaction_id=this.transactionId),e!==o.REQUEST_TYPE&&e!==o.START_TYPE||(t.from_device=this._client.getDeviceId()),e===o.REQUEST_TYPE&&(t.timestamp=Date.now()),t}send(e,t={}){e!==o.REQUEST_TYPE&&e!==o.START_TYPE||this.transactionId||(this.transactionId=a.makeTransactionId());const n=this.completeContent(e,t);return this.sendCompleted(e,n)}sendCompleted(e,t){return e===o.REQUEST_TYPE?this._sendToDevices(e,t,this._devices):this._sendToDevices(e,t,[this._deviceId])}_sendToDevices(e,t,n){if(n.length){const r={};for(const e of n)r[e]=t;return this._client.sendToDevice(e,{[this._userId]:r})}return Promise.resolve()}static makeTransactionId(){return(0,r.randomString)(32)}}t.ToDeviceChannel=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AutoDiscovery=void 0;var r=n(4),i=n(74);class o{static get ERROR_INVALID(){return"Invalid homeserver discovery response"}static get ERROR_GENERIC_FAILURE(){return"Failed to get autodiscovery configuration from server"}static get ERROR_INVALID_HS_BASE_URL(){return"Invalid base_url for m.homeserver"}static get ERROR_INVALID_HOMESERVER(){return"Homeserver URL does not appear to be a valid Matrix homeserver"}static get ERROR_INVALID_IS_BASE_URL(){return"Invalid base_url for m.identity_server"}static get ERROR_INVALID_IDENTITY_SERVER(){return"Identity server URL does not appear to be a valid identity server"}static get ERROR_INVALID_IS(){return"Invalid identity server discovery response"}static get ERROR_MISSING_WELLKNOWN(){return"No .well-known JSON file found"}static get ERROR_INVALID_JSON(){return"Invalid JSON"}static get ALL_ERRORS(){return[o.ERROR_INVALID,o.ERROR_GENERIC_FAILURE,o.ERROR_INVALID_HS_BASE_URL,o.ERROR_INVALID_HOMESERVER,o.ERROR_INVALID_IS_BASE_URL,o.ERROR_INVALID_IDENTITY_SERVER,o.ERROR_INVALID_IS,o.ERROR_MISSING_WELLKNOWN,o.ERROR_INVALID_JSON]}static get FAIL_ERROR(){return"FAIL_ERROR"}static get FAIL_PROMPT(){return"FAIL_PROMPT"}static get PROMPT(){return"PROMPT"}static get SUCCESS(){return"SUCCESS"}static async fromDiscoveryConfig(e){const t={"m.homeserver":{state:o.FAIL_ERROR,error:o.ERROR_INVALID,base_url:null},"m.identity_server":{state:o.PROMPT,error:null,base_url:null}};if(!e||!e["m.homeserver"])return r.logger.error("No m.homeserver key in config"),t["m.homeserver"].state=o.FAIL_PROMPT,t["m.homeserver"].error=o.ERROR_INVALID,Promise.resolve(t);if(!e["m.homeserver"].base_url)return r.logger.error("No m.homeserver base_url in config"),t["m.homeserver"].state=o.FAIL_PROMPT,t["m.homeserver"].error=o.ERROR_INVALID_HS_BASE_URL,Promise.resolve(t);const n=this._sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!n)return r.logger.error("Invalid base_url for m.homeserver"),t["m.homeserver"].error=o.ERROR_INVALID_HS_BASE_URL,Promise.resolve(t);const i=await this._fetchWellKnownObject(`${n}/_matrix/client/versions`);if(!i||!i.raw.versions)return r.logger.error("Invalid /versions response"),t["m.homeserver"].error=o.ERROR_INVALID_HOMESERVER,t["m.homeserver"].base_url=n,Promise.resolve(t);t["m.homeserver"]={state:o.SUCCESS,error:null,base_url:n};let s="";if(e["m.identity_server"]){const n={"m.homeserver":t["m.homeserver"],"m.identity_server":{state:o.FAIL_PROMPT,error:o.ERROR_INVALID_IS,base_url:null}};if(s=this._sanitizeWellKnownUrl(e["m.identity_server"].base_url),!s)return r.logger.error("Invalid base_url for m.identity_server"),n["m.identity_server"].error=o.ERROR_INVALID_IS_BASE_URL,Promise.resolve(n);const i=await this._fetchWellKnownObject(`${s}/_matrix/identity/api/v1`);if(!i||!i.raw||"SUCCESS"!==i.action)return r.logger.error("Invalid /api/v1 response"),n["m.identity_server"].error=o.ERROR_INVALID_IDENTITY_SERVER,n["m.identity_server"].base_url=s,Promise.resolve(n)}return s&&s.length>0&&(t["m.identity_server"]={state:o.SUCCESS,error:null,base_url:s}),Object.keys(e).map(n=>{if("m.homeserver"===n||"m.identity_server"===n){const r=["error","state","base_url"];for(const i of Object.keys(e[n]))r.includes(i)||(t[n][i]=e[n][i])}else t[n]=e[n]}),Promise.resolve(t)}static async findClientConfig(e){if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const t={"m.homeserver":{state:o.FAIL_ERROR,error:o.ERROR_INVALID,base_url:null},"m.identity_server":{state:o.PROMPT,error:null,base_url:null}},n=await this._fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return n&&"SUCCESS"===n.action?o.fromDiscoveryConfig(n.raw):(r.logger.error("No response or error when parsing .well-known"),n.reason&&r.logger.error(n.reason),"IGNORE"===n.action?t["m.homeserver"]={state:o.PROMPT,error:null,base_url:null}:(t["m.homeserver"].state=o.FAIL_PROMPT,t["m.homeserver"].error=o.ERROR_INVALID),Promise.resolve(t))}static async getRawClientConfig(e){if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const t=await this._fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return t&&t.raw||{}}static _sanitizeWellKnownUrl(e){if(!e)return!1;try{let t=null;try{t=i.URL?new i.URL(e):new URL(e)}catch(n){t=new URL(e)}if(!t||!t.hostname)return!1;if("http:"!==t.protocol&&"https:"!==t.protocol)return!1;const n=t.port?`:${t.port}`:"",r=t.pathname?t.pathname:"";let o=`${t.protocol}//${t.hostname}${n}${r}`;return o.endsWith("/")&&(o=o.substring(0,o.length-1)),o}catch(e){return r.logger.error(e),!1}}static async _fetchWellKnownObject(e){return new Promise((function(t,r){const i=n(127).getRequest();if(!i)throw new Error("No request library available");i({method:"GET",uri:e,timeout:5e3},(e,n,r)=>{if(e||n.statusCode<200||n.statusCode>=300){let r="FAIL_PROMPT",i=(e?e.message:null)||"General failure";return 404===n.statusCode&&(r="IGNORE",i=o.ERROR_MISSING_WELLKNOWN),void t({raw:{},action:r,reason:i,error:e})}try{t({raw:JSON.parse(r),action:"SUCCESS"})}catch(e){let n=o.ERROR_INVALID;"SyntaxError"===e.name&&(n=o.ERROR_INVALID_JSON),t({raw:{},action:"FAIL_PROMPT",reason:n,error:e})}})}))}}t.AutoDiscovery=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TimelineWindow=o,t.TimelineIndex=s;var r=n(25);n(4);const i=function(){};function o(e,t,n){n=n||{},this._client=e,this._timelineSet=t,this._start=null,this._end=null,this._eventCount=0,this._windowLimit=n.windowLimit||1e3}function s(e,t){this.timeline=e,this.index=t}o.prototype.load=function(e,t){const n=this;t=t||20;const r=function(r){let i;const o=r.getEvents();if(e){for(let t=0;tt.minIndex())return!0}else if(t.index0&&this.unpaginate(t,e!=r.EventTimeline.BACKWARDS),Promise.resolve(!0)}if(!n||0===o)return Promise.resolve(!1);if(!s.timeline.getPaginationToken(e))return i("TimelineWindow: no token"),Promise.resolve(!1);i("TimelineWindow: starting request");const c=this,f=this._client.paginateEventTimeline(s.timeline,{backwards:e==r.EventTimeline.BACKWARDS,limit:t}).finally((function(){s.pendingPaginate=null})).then((function(n){return i("TimelineWindow: request completed with result "+n),!!n&&c.paginate(e,t,!0,o-1)}));return s.pendingPaginate=f,f},o.prototype.unpaginate=function(e,t){const n=t?this._start:this._end;if(e>this._eventCount||e<0)throw new Error("Attemting to unpaginate "+e+" events, but only have "+this._eventCount+" in the timeline");for(;e>0;){const r=t?n.advance(e):n.retreat(e);if(r<=0)throw new Error("Unable to unpaginate any further, but still have "+this._eventCount+" events");e-=r,this._eventCount-=r,i("TimelineWindow.unpaginate: dropped "+r+" (now "+this._eventCount+")")}},o.prototype.getEvents=function(){if(!this._start)return[];const e=[];let t=this._start.timeline;for(;;){const n=t.getEvents();let i=0,o=n.length;t===this._start.timeline&&(i=this._start.index+t.getBaseIndex()),t===this._end.timeline&&(o=this._end.index+t.getBaseIndex());for(let t=i;t0)return this.index+=t,t;const n=this.timeline.getNeighbouringTimeline(e<0?r.EventTimeline.BACKWARDS:r.EventTimeline.FORWARDS);return n?(this.timeline=n,this.index=e<0?this.maxIndex():this.minIndex(),i("paginate: switched to new neighbour"),this.advance(e)):0},s.prototype.retreat=function(e){return-1*this.advance(-1*e)}},function(e,t,n){"use strict";var r=n(6),i=n(16);Object.defineProperty(t,"__esModule",{value:!0}),t.InteractiveAuth=c;var o=i(n(74)),s=r(n(8)),a=n(4);function c(e){this._matrixClient=e.matrixClient,this._data=e.authData||{},this._requestCallback=e.doRequest,this._busyChangedCallback=e.busyChanged,this._stateUpdatedCallback=e.stateUpdated||e.startAuthStage,this._resolveFunc=null,this._rejectFunc=null,this._inputs=e.inputs||{},this._requestEmailTokenCallback=e.requestEmailToken,e.sessionId&&(this._data.session=e.sessionId),this._clientSecret=e.clientSecret||this._matrixClient.generateClientSecret(),this._emailSid=e.emailSid,void 0===this._emailSid&&(this._emailSid=null),this._requestingEmailToken=!1,this._chosenFlow=null,this._currentStage=null,this._submitPromise=null}c.prototype={attemptAuth:function(){return new Promise((e,t)=>{this._resolveFunc=e,this._rejectFunc=t,this._data.flows?this._startNextAuthStage():(this._busyChangedCallback&&this._busyChangedCallback(!0),this._doRequest(this._data).finally(()=>{this._busyChangedCallback&&this._busyChangedCallback(!1)}))})},poll:async function(){if(!this._data.session)return;if(this._submitPromise)return;let e={};if("m.login.email.identity"==this._currentStage&&this._emailSid){const t={sid:this._emailSid,client_secret:this._clientSecret};if(await this._matrixClient.doesServerRequireIdServerParam()){const e=o.default.parse(this._matrixClient.getIdentityServerUrl());t.id_server=e.host}e={type:"m.login.email.identity",threepid_creds:t}}this.submitAuthDict(e,!0)},getSessionId:function(){return this._data?this._data.session:void 0},getClientSecret:function(){return this._clientSecret},getStageParams:function(e){let t={};return this._data&&this._data.params&&(t=this._data.params),t[e]},getChosenFlow(){return this._chosenFlow},submitAuthDict:async function(e,t){if(!this._resolveFunc)throw new Error("submitAuthDict() called before attemptAuth()");for(!t&&this._busyChangedCallback&&this._busyChangedCallback(!0);this._submitPromise;)try{await this._submitPromise}catch(e){}const n={session:this._data.session};s.extend(n,e);try{this._submitPromise=this._doRequest(n,t),await this._submitPromise}finally{this._submitPromise=null,!t&&this._busyChangedCallback&&this._busyChangedCallback(!1)}},getEmailSid:function(){return this._emailSid},setEmailSid:function(e){this._emailSid=e},_doRequest:async function(e,t){try{const n=await this._requestCallback(e,t);this._resolveFunc(n)}catch(e){const n=e.data?e.data.flows:null,r=Boolean(this._data.flows)||Boolean(n);if(401===e.httpStatus&&e.data&&r||(t?a.logger.log("Background poll request failed doing UI auth: ignoring",e):this._rejectFunc(e)),e.data.flows||e.data.completed||e.data.session||(e.data.flows=this._data.flows,e.data.completed=this._data.completed,e.data.session=this._data.session),this._data=e.data,this._startNextAuthStage(),!this._emailSid&&!this._requestingEmailToken&&this._chosenFlow.stages.includes("m.login.email.identity")){this._requestingEmailToken=!0;try{const e=await this._requestEmailTokenCallback(this._inputs.emailAddress,this._clientSecret,1,this._data.session);this._emailSid=e.sid}catch(e){this._rejectFunc(e)}finally{this._requestingEmailToken=!1}}}},_startNextAuthStage:function(){const e=this._chooseStage();if(!e)throw new Error("No incomplete flows from the server");if(this._currentStage=e,"m.login.dummy"===e)return void this.submitAuthDict({type:"m.login.dummy"});if(this._data.errcode||this._data.error)return void this._stateUpdatedCallback(e,{errcode:this._data.errcode||"",error:this._data.error||""});const t={};"m.login.email.identity"==e&&(t.emailSid=this._emailSid),this._stateUpdatedCallback(e,t)},_chooseStage:function(){null===this._chosenFlow&&(this._chosenFlow=this._chooseFlow()),a.logger.log("Active flow => %s",JSON.stringify(this._chosenFlow));const e=this._firstUncompletedStage(this._chosenFlow);return a.logger.log("Next stage: %s",e),e},_chooseFlow:function(){const e=this._data.flows||[],t=Boolean(this._inputs.emailAddress)||Boolean(this._emailSid),n=Boolean(this._inputs.phoneCountry)&&Boolean(this._inputs.phoneNumber);for(const r of e){let e=!1,i=!1;for(const t of r.stages)"m.login.email.identity"===t?e=!0:"m.login.msisdn"==t&&(i=!0);if(e==t&&i==n)return r}const r=new Error("No appropriate authentication flow found");throw r.name="NoAuthFlowFoundError",r.required_stages=[],t&&r.required_stages.push("m.login.email.identity"),n&&r.required_stages.push("m.login.msisdn"),r.available_flows=e,r},_firstUncompletedStage:function(e){const t=(this._data||{}).completed||[];for(let n=0;n(l.logger.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents())).then(e=>{l.logger.log("IndexedDBStore.startup: processing presence events"),e.forEach(([e,t])=>{const n=new f.User(e);t&&n.setPresenceEvent(new u.MatrixEvent(t)),this._userModifiedMap[n.userId]=n.getLastModifiedTime(),this.storeUser(n)})}))},d.prototype.getSavedSync=h((function(){return this.backend.getSavedSync()}),"getSavedSync"),d.prototype.isNewlyCreated=h((function(){return this.backend.isNewlyCreated()}),"isNewlyCreated"),d.prototype.getSavedSyncToken=h((function(){return this.backend.getNextBatchToken()}),"getSavedSyncToken"),d.prototype.deleteAllData=h((function(){return i.MemoryStore.prototype.deleteAllData.call(this),this.backend.clearDatabase().then(()=>{l.logger.log("Deleted indexeddb data.")},e=>{throw l.logger.error(`Failed to delete indexeddb data: ${e}`),e})})),d.prototype.wantsSave=function(){return Date.now()-this._syncTs>3e5},d.prototype.save=function(e){return e||this.wantsSave()?this._reallySave():Promise.resolve()},d.prototype._reallySave=h((function(){this._syncTs=Date.now();const e=[];for(const t of this.getUsers())this._userModifiedMap[t.userId]!==t.getLastModifiedTime()&&t.events.presence&&(e.push([t.userId,t.events.presence.event]),this._userModifiedMap[t.userId]=t.getLastModifiedTime());return this.backend.syncToDatabase(e)})),d.prototype.setSyncData=h((function(e){return this.backend.setSyncData(e)}),"setSyncData"),d.prototype.getOutOfBandMembers=h((function(e){return this.backend.getOutOfBandMembers(e)}),"getOutOfBandMembers"),d.prototype.setOutOfBandMembers=h((function(e,t){return i.MemoryStore.prototype.setOutOfBandMembers.call(this,e,t),this.backend.setOutOfBandMembers(e,t)}),"setOutOfBandMembers"),d.prototype.clearOutOfBandMembers=h((function(e){return i.MemoryStore.prototype.clearOutOfBandMembers.call(this),this.backend.clearOutOfBandMembers(e)}),"clearOutOfBandMembers"),d.prototype.getClientOptions=h((function(){return this.backend.getClientOptions()}),"getClientOptions"),d.prototype.storeClientOptions=h((function(e){return i.MemoryStore.prototype.storeClientOptions.call(this,e),this.backend.storeClientOptions(e)}),"storeClientOptions")}).call(this,n(5))},function(e,t,n){"use strict";var r=n(6);Object.defineProperty(t,"__esModule",{value:!0}),t.LocalIndexedDBStoreBackend=d;var i=n(143),o=r(n(8)),s=r(n(136)),a=n(4);function c(e,t,n){const r=e.openCursor(t);return new Promise((e,t)=>{const i=[];r.onerror=e=>{t(new Error("Query failed: "+e.target.errorCode))},r.onsuccess=t=>{const r=t.target.result;r?(i.push(n(r)),r.continue()):e(i)}})}function f(e){return new Promise((t,n)=>{e.oncomplete=function(e){t(e)},e.onerror=function(e){n(e.target.error)}})}function u(e){return new Promise((t,n)=>{e.onsuccess=function(e){t(e)},e.onerror=function(e){n(e.target.error)}})}function l(e){return u(e).then(e=>e.target.result)}function d(e,t){this.indexedDB=e,this._dbName="matrix-js-sdk:"+(t||"default"),this.db=null,this._disconnected=!0,this._syncAccumulator=new i.SyncAccumulator,this._isNewlyCreated=!1}d.exists=function(e,t){return t="matrix-js-sdk:"+(t||"default"),s.exists(e,t)},d.prototype={connect:function(){if(!this._disconnected)return a.logger.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this._disconnected=!1,a.logger.log("LocalIndexedDBStoreBackend.connect: connecting...");const e=this.indexedDB.open(this._dbName,3);return e.onupgradeneeded=e=>{const t=e.target.result,n=e.oldVersion;a.logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${n}`),n<1&&(this._isNewlyCreated=!0,function(e){e.createObjectStore("users",{keyPath:["userId"]}),e.createObjectStore("accountData",{keyPath:["type"]}),e.createObjectStore("sync",{keyPath:["clobber"]})}(t)),n<2&&function(e){e.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]}).createIndex("room","room_id")}(t),n<3&&function(e){e.createObjectStore("client_options",{keyPath:["clobber"]})}(t)},e.onblocked=()=>{a.logger.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},a.logger.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),u(e).then(e=>(a.logger.log("LocalIndexedDBStoreBackend.connect: connected"),this.db=e.target.result,this.db.onversionchange=()=>{this.db.close()},this._init()))},isNewlyCreated:function(){return Promise.resolve(this._isNewlyCreated)},_init:function(){return Promise.all([this._loadAccountData(),this._loadSyncData()]).then(([e,t])=>{a.logger.log("LocalIndexedDBStoreBackend: loaded initial data"),this._syncAccumulator.accumulate({next_batch:t.nextBatch,rooms:t.roomsData,groups:t.groupsData,account_data:{events:e}})})},getOutOfBandMembers:function(e){return new Promise((t,n)=>{const r=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),i=IDBKeyRange.only(e),o=r.openCursor(i),s=[];let a=!1;o.onsuccess=e=>{const n=e.target.result;if(!n)return s.length||a?t(s):t(null);const r=n.value;r.oob_written?a=!0:s.push(r),n.continue()},o.onerror=e=>{n(e)}}).then(t=>(a.logger.log(`LL: got ${t&&t.length}`+` membershipEvents from storage for room ${e} ...`),t))},setOutOfBandMembers:async function(e,t){a.logger.log(`LL: backend about to store ${t.length}`+` members for ${e}`);const n=this.db.transaction(["oob_membership_events"],"readwrite"),r=n.objectStore("oob_membership_events");t.forEach(e=>{r.put(e)});const i={room_id:e,oob_written:!0,state_key:0};r.put(i),await f(n),a.logger.log(`LL: backend done storing for ${e}!`)},clearOutOfBandMembers:async function(e){const t=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),n=IDBKeyRange.only(e),r=l(t.openKeyCursor(n,"next")).then(e=>e&&e.primaryKey[1]),i=l(t.openKeyCursor(n,"prev")).then(e=>e&&e.primaryKey[1]),[o,s]=await Promise.all([r,i]),c=this.db.transaction(["oob_membership_events"],"readwrite").objectStore("oob_membership_events"),f=IDBKeyRange.bound([e,o],[e,s]);var u;a.logger.log("LL: Deleting all users + marker in storage for "+`room ${e}, with key range:`,[e,o],[e,s]),await(u=c.delete(f),new Promise((e,t)=>{u.onsuccess=()=>e(u),u.onerror=e=>t(e)}))},clearDatabase:function(){return new Promise((e,t)=>{a.logger.log(`Removing indexeddb instance: ${this._dbName}`);const n=this.indexedDB.deleteDatabase(this._dbName);n.onblocked=()=>{a.logger.log(`can't yet delete indexeddb ${this._dbName}`+" because it is open elsewhere")},n.onerror=t=>{a.logger.warn(`unable to delete js-sdk store indexeddb: ${t.target.error}`),e()},n.onsuccess=()=>{a.logger.log(`Removed indexeddb instance: ${this._dbName}`),e()}})},getSavedSync:function(e){void 0===e&&(e=!0);const t=this._syncAccumulator.getJSON();return t.nextBatch?e?Promise.resolve(o.deepCopy(t)):Promise.resolve(t):Promise.resolve(null)},getNextBatchToken:function(){return Promise.resolve(this._syncAccumulator.getNextBatchToken())},setSyncData:function(e){return Promise.resolve().then(()=>{this._syncAccumulator.accumulate(e)})},syncToDatabase:function(e){const t=this._syncAccumulator.getJSON();return Promise.all([this._persistUserPresenceEvents(e),this._persistAccountData(t.accountData),this._persistSyncData(t.nextBatch,t.roomsData,t.groupsData)])},_persistSyncData:function(e,t,n){return a.logger.log("Persisting sync data up to ",e),o.promiseTry(()=>{const r=this.db.transaction(["sync"],"readwrite");return r.objectStore("sync").put({clobber:"-",nextBatch:e,roomsData:t,groupsData:n}),f(r)})},_persistAccountData:function(e){return o.promiseTry(()=>{const t=this.db.transaction(["accountData"],"readwrite"),n=t.objectStore("accountData");for(let t=0;t{const t=this.db.transaction(["users"],"readwrite"),n=t.objectStore("users");for(const t of e)n.put({userId:t[0],event:t[1]});return f(t)})},getUserPresenceEvents:function(){return o.promiseTry(()=>c(this.db.transaction(["users"],"readonly").objectStore("users"),void 0,e=>[e.value.userId,e.value.event]))},_loadAccountData:function(){return a.logger.log("LocalIndexedDBStoreBackend: loading account data..."),o.promiseTry(()=>c(this.db.transaction(["accountData"],"readonly").objectStore("accountData"),void 0,e=>e.value).then(e=>(a.logger.log("LocalIndexedDBStoreBackend: loaded account data"),e)))},_loadSyncData:function(){return a.logger.log("LocalIndexedDBStoreBackend: loading sync data..."),o.promiseTry(()=>c(this.db.transaction(["sync"],"readonly").objectStore("sync"),void 0,e=>e.value).then(e=>(a.logger.log("LocalIndexedDBStoreBackend: loaded sync data"),e.length>1&&a.logger.warn("loadSyncData: More than 1 sync row found."),e.length>0?e[0]:{})))},getClientOptions:function(){return Promise.resolve().then(()=>c(this.db.transaction(["client_options"],"readonly").objectStore("client_options"),void 0,e=>{if(e.value&&e.value&&e.value.options)return e.value.options}).then(e=>e[0]))},storeClientOptions:async function(e){const t=this.db.transaction(["client_options"],"readwrite");t.objectStore("client_options").put({clobber:"-",options:e}),await f(t)}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteIndexedDBStoreBackend=o;var r=n(4),i=n(8);function o(e,t,n){this._workerScript=e,this._dbName=t,this._workerApi=n,this._worker=null,this._nextSeq=0,this._inFlight={},this._startPromise=null}o.prototype={connect:function(){return this._ensureStarted().then(()=>this._doCmd("connect"))},clearDatabase:function(){return this._ensureStarted().then(()=>this._doCmd("clearDatabase"))},isNewlyCreated:function(){return this._doCmd("isNewlyCreated")},getSavedSync:function(){return this._doCmd("getSavedSync")},getNextBatchToken:function(){return this._doCmd("getNextBatchToken")},setSyncData:function(e){return this._doCmd("setSyncData",[e])},syncToDatabase:function(e){return this._doCmd("syncToDatabase",[e])},getOutOfBandMembers:function(e){return this._doCmd("getOutOfBandMembers",[e])},setOutOfBandMembers:function(e,t){return this._doCmd("setOutOfBandMembers",[e,t])},clearOutOfBandMembers:function(e){return this._doCmd("clearOutOfBandMembers",[e])},getClientOptions:function(){return this._doCmd("getClientOptions")},storeClientOptions:function(e){return this._doCmd("storeClientOptions",[e])},getUserPresenceEvents:function(){return this._doCmd("getUserPresenceEvents")},_ensureStarted:function(){return null===this._startPromise&&(this._worker=new this._workerApi(this._workerScript),this._worker.onmessage=this._onWorkerMessage.bind(this),this._startPromise=this._doCmd("_setupWorker",[this._dbName]).then(()=>{r.logger.log("IndexedDB worker is ready")})),this._startPromise},_doCmd:function(e,t){return Promise.resolve().then(()=>{const n=this._nextSeq++,r=(0,i.defer)();return this._inFlight[n]=r,this._worker.postMessage({command:e,seq:n,args:t}),r.promise})},_onWorkerMessage:function(e){const t=e.data;if("cmd_success"==t.command||"cmd_fail"==t.command){if(void 0===t.seq)return void r.logger.error("Got reply from worker with no seq");const e=this._inFlight[t.seq];if(void 0===e)return void r.logger.error("Got reply for unknown seq "+t.seq);if(delete this._inFlight[t.seq],"cmd_success"==t.command)e.resolve(t.result);else{const n=new Error(t.error.message);n.name=t.error.name,e.reject(n)}}else r.logger.warn("Unrecognised message from worker: "+t)}}},function(e,t,n){"use strict";var r=n(6);Object.defineProperty(t,"__esModule",{value:!0}),t.WebStorageSessionStore=s;var i=r(n(8));n(4);const o="session.e2e.";function s(e){if(this.store=e,!(i.isFunction(e.getItem)&&i.isFunction(e.setItem)&&i.isFunction(e.removeItem)&&i.isFunction(e.key)&&"number"==typeof e.length))throw new Error("Supplied webStore does not meet the WebStorage API interface")}s.prototype={removeEndToEndAccount:function(){this.store.removeItem(a)},getEndToEndAccount:function(){return this.store.getItem(a)},getAllEndToEndDevices:function(){const e=l(""),t={};for(let n=0;n>18&63,o=c>>12&63,s=c>>6&63,a=63&c,h[l++]=f.charAt(i)+f.charAt(o)+f.charAt(s)+f.charAt(a)}while(u299)&&r.error){for(var i in e=new Error("CouchDB error: "+(r.error.reason||r.error.error)),r)e[i]=r[i];return n(e,t,r)}return n(e,t,r)}))},t})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){"use strict";var r=n(309),i=n(310),o=n(144);e.exports={formats:o,parse:i,stringify:r}},function(e,t,n){"use strict";var r=n(83),i=n(144),o=Object.prototype.hasOwnProperty,s={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},a=Array.isArray,c=Array.prototype.push,f=function(e,t){c.apply(e,a(t)?t:[t])},u=Date.prototype.toISOString,l=i.default,d={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:r.encode,encodeValuesOnly:!1,format:l,formatter:i.formatters[l],indices:!1,serializeDate:function(e){return u.call(e)},skipNulls:!1,strictNullHandling:!1},h=function e(t,n,i,o,s,c,u,l,h,p,m,g,y){var b,_=t;if("function"==typeof u?_=u(n,_):_ instanceof Date?_=p(_):"comma"===i&&a(_)&&(_=_.join(",")),null===_){if(o)return c&&!g?c(n,d.encoder,y,"key"):n;_=""}if("string"==typeof(b=_)||"number"==typeof b||"boolean"==typeof b||"symbol"==typeof b||"bigint"==typeof b||r.isBuffer(_))return c?[m(g?n:c(n,d.encoder,y,"key"))+"="+m(c(_,d.encoder,y,"value"))]:[m(n)+"="+m(String(_))];var v,A=[];if(void 0===_)return A;if(a(u))v=u;else{var w=Object.keys(_);v=l?w.sort(l):w}for(var E=0;E0?b+y:""}},function(e,t,n){"use strict";var r=n(83),i=Object.prototype.hasOwnProperty,o=Array.isArray,s={allowDots:!1,allowPrototypes:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:r.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},a=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},c=function(e,t,n){if(e){var r=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/g,s=n.depth>0&&/(\[[^[\]]*])/.exec(r),a=s?r.slice(0,s.index):r,c=[];if(a){if(!n.plainObjects&&i.call(Object.prototype,a)&&!n.allowPrototypes)return;c.push(a)}for(var f=0;n.depth>0&&null!==(s=o.exec(r))&&f=0;--i){var o,s=e[i];if("[]"===s&&n.parseArrays)o=[].concat(r);else{o=n.plainObjects?Object.create(null):{};var a="["===s.charAt(0)&&"]"===s.charAt(s.length-1)?s.slice(1,-1):s,c=parseInt(a,10);n.parseArrays||""!==a?!isNaN(c)&&s!==a&&String(c)===a&&c>=0&&n.parseArrays&&c<=n.arrayLimit?(o=[])[c]=r:o[a]=r:o={0:r}}r=o}return r}(c,t,n)}};e.exports=function(e,t){var n=function(e){if(!e)return s;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new Error("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?s.charset:e.charset;return{allowDots:void 0===e.allowDots?s.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:s.allowPrototypes,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:s.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:s.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:s.comma,decoder:"function"==typeof e.decoder?e.decoder:s.decoder,delimiter:"string"==typeof e.delimiter||r.isRegExp(e.delimiter)?e.delimiter:s.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:s.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:s.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:s.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:s.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:s.strictNullHandling}}(t);if(""===e||null==e)return n.plainObjects?Object.create(null):{};for(var f="string"==typeof e?function(e,t){var n,c={},f=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,u=t.parameterLimit===1/0?void 0:t.parameterLimit,l=f.split(t.delimiter,u),d=-1,h=t.charset;if(t.charsetSentinel)for(n=0;n-1&&(m=m.split(",")),g.indexOf("[]=")>-1&&(m=o(m)?[m]:m),i.call(c,p)?c[p]=r.combine(c[p],m):c[p]=m}return c}(e,n):e,u=n.plainObjects?Object.create(null):{},l=Object.keys(f),d=0;d>>((3&t)<<3)&255;return i}}},function(e,t,n){var r=n(314),i=n(315);e.exports=r("v5",80,i)},function(e,t,n){var r=n(145);e.exports=function(e,t,n){var i=function(e,i,o,s){var a=o&&s||0;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=new Array(e.length),n=0;n>>32-t}e.exports=function(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var o=unescape(encodeURIComponent(e));e=new Array(o.length);for(var s=0;s>>0;y=g,g=m,m=i(p,30)>>>0,p=h,h=_}n[0]=n[0]+h>>>0,n[1]=n[1]+p>>>0,n[2]=n[2]+m>>>0,n[3]=n[3]+g>>>0,n[4]=n[4]+y>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]}},function(e,t,n){"use strict";t.__esModule=!0;var r,i=n(0),o=(r=i)&&r.__esModule?r:{default:r},s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(n(317));function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}var f=s.options,u=f.Options;function l(e,t){for(var n=s.tokenize(e),r=[],i=0,a=0;a2&&void 0!==arguments[2]?arguments[2]:0;if(0===o.default.Children.count(t.props.children))return t;var i=[];o.default.Children.forEach(t.props.children,(function(t){"string"==typeof t?(r+=1,i.push.apply(i,l(t,n))):o.default.isValidElement(t)?"string"==typeof t.type&&f.contains(n.ignoreTags,t.type.toUpperCase())?i.push(t):i.push(e(t,n,++r)):i.push(t)}));var s={key:"linkified-element-"+r};for(var a in t.props)s[a]=t.props[a];return o.default.cloneElement(t,s,i)}(o.default.createElement(r,e),n,0)},t}(o.default.Component);t.default=d},function(e,t,n){"use strict";t.__esModule=!0,t.tokenize=t.test=t.scanner=t.parser=t.options=t.inherits=t.find=void 0;var r=n(53),i=a(n(318)),o=a(n(319)),s=a(n(320));function a(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)});var c=function(e){return s.run(o.run(e))};t.find=function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=c(e),r=[],i=0;i1&&void 0!==arguments[1]?arguments[1]:null,n=c(e);return 1===n.length&&n[0].isLink&&(!t||n[0].type===t)},t.tokenize=c},function(e,t,n){"use strict";t.__esModule=!0;var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i={defaultProtocol:"http",events:null,format:s,formatHref:s,nl2br:!1,tagName:"a",target:function(e,t){return"url"===t?"_blank":null},validate:!0,ignoreTags:[],attributes:null,className:"linkified"};function o(e){e=e||{},this.defaultProtocol=e.hasOwnProperty("defaultProtocol")?e.defaultProtocol:i.defaultProtocol,this.events=e.hasOwnProperty("events")?e.events:i.events,this.format=e.hasOwnProperty("format")?e.format:i.format,this.formatHref=e.hasOwnProperty("formatHref")?e.formatHref:i.formatHref,this.nl2br=e.hasOwnProperty("nl2br")?e.nl2br:i.nl2br,this.tagName=e.hasOwnProperty("tagName")?e.tagName:i.tagName,this.target=e.hasOwnProperty("target")?e.target:i.target,this.validate=e.hasOwnProperty("validate")?e.validate:i.validate,this.ignoreTags=[],this.attributes=e.attributes||e.linkAttributes||i.attributes,this.className=e.hasOwnProperty("className")?e.className:e.linkClass||i.className;for(var t=e.hasOwnProperty("ignoreTags")?e.ignoreTags:i.ignoreTags,n=0;n",l(i.CLOSEANGLEBRACKET)).on(")",l(i.CLOSEPAREN)).on("&",l(i.AMPERSAND)).on([",",";","!",'"',"'"],l(i.PUNCTUATION)),d.on("\n",l(i.NL)).on(f,g),g.on(f,g);for(var y=0;y=0&&f++,a++,i++;if(!(f<0)){i-=f,a-=f;var u=c.emit();r.push(new u(e.substr(i-a,a)))}}return r},t.start=P},function(e,t,n){"use strict";t.__esModule=!0,t.start=t.run=t.TOKENS=t.State=void 0;var r=n(146),i=n(321),o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(i),s=n(84);var a=function(e){return new r.TokenState(e)},c=a(),f=a(),u=a(),l=a(),d=a(),h=a(),p=a(),m=a(i.URL),g=a(),y=a(i.URL),b=a(i.URL),_=a(),v=a(),A=a(),w=a(),E=a(),k=a(i.URL),S=a(i.URL),I=a(i.URL),T=a(i.URL),R=a(),x=a(),O=a(),C=a(),P=a(),M=a(),D=a(i.EMAIL),B=a(),N=a(i.EMAIL),j=a(i.MAILTOEMAIL),U=a(),L=a(),F=a(),q=a(),K=a(i.NL);c.on(s.NL,K).on(s.PROTOCOL,f).on(s.MAILTO,u).on(s.SLASH,l),f.on(s.SLASH,l),l.on(s.SLASH,d),c.on(s.TLD,h).on(s.DOMAIN,h).on(s.LOCALHOST,m).on(s.NUM,h),d.on(s.TLD,b).on(s.DOMAIN,b).on(s.NUM,b).on(s.LOCALHOST,b),h.on(s.DOT,p),P.on(s.DOT,M),p.on(s.TLD,m).on(s.DOMAIN,h).on(s.NUM,h).on(s.LOCALHOST,h),M.on(s.TLD,D).on(s.DOMAIN,P).on(s.NUM,P).on(s.LOCALHOST,P),m.on(s.DOT,p),D.on(s.DOT,M),m.on(s.COLON,g).on(s.SLASH,b),g.on(s.NUM,y),y.on(s.SLASH,b),D.on(s.COLON,B),B.on(s.NUM,N);var z=[s.DOMAIN,s.AT,s.LOCALHOST,s.NUM,s.PLUS,s.POUND,s.PROTOCOL,s.SLASH,s.TLD,s.UNDERSCORE,s.SYM,s.AMPERSAND],G=[s.COLON,s.DOT,s.QUERY,s.PUNCTUATION,s.CLOSEBRACE,s.CLOSEBRACKET,s.CLOSEANGLEBRACKET,s.CLOSEPAREN,s.OPENBRACE,s.OPENBRACKET,s.OPENANGLEBRACKET,s.OPENPAREN];b.on(s.OPENBRACE,v).on(s.OPENBRACKET,A).on(s.OPENANGLEBRACKET,w).on(s.OPENPAREN,E),_.on(s.OPENBRACE,v).on(s.OPENBRACKET,A).on(s.OPENANGLEBRACKET,w).on(s.OPENPAREN,E),v.on(s.CLOSEBRACE,b),A.on(s.CLOSEBRACKET,b),w.on(s.CLOSEANGLEBRACKET,b),E.on(s.CLOSEPAREN,b),k.on(s.CLOSEBRACE,b),S.on(s.CLOSEBRACKET,b),I.on(s.CLOSEANGLEBRACKET,b),T.on(s.CLOSEPAREN,b),R.on(s.CLOSEBRACE,b),x.on(s.CLOSEBRACKET,b),O.on(s.CLOSEANGLEBRACKET,b),C.on(s.CLOSEPAREN,b),v.on(z,k),A.on(z,S),w.on(z,I),E.on(z,T),v.on(G,R),A.on(G,x),w.on(G,O),E.on(G,C),k.on(z,k),S.on(z,S),I.on(z,I),T.on(z,T),k.on(G,k),S.on(G,S),I.on(G,I),T.on(G,T),R.on(z,k),x.on(z,S),O.on(z,I),C.on(z,T),R.on(G,R),x.on(G,x),O.on(G,O),C.on(G,C),b.on(z,b),_.on(z,b),b.on(G,_),_.on(G,_),u.on(s.TLD,j).on(s.DOMAIN,j).on(s.NUM,j).on(s.LOCALHOST,j),j.on(z,j).on(G,U),U.on(z,j).on(G,U);var H=[s.DOMAIN,s.NUM,s.PLUS,s.POUND,s.QUERY,s.UNDERSCORE,s.SYM,s.AMPERSAND,s.TLD];h.on(H,L).on(s.AT,F),m.on(H,L).on(s.AT,F),p.on(H,L),L.on(H,L).on(s.AT,F).on(s.DOT,q),q.on(H,L),F.on(s.TLD,P).on(s.DOMAIN,P).on(s.LOCALHOST,D);t.State=r.TokenState,t.TOKENS=o,t.run=function(e){for(var t=e.length,n=0,r=[],o=[];n=0&&d++,n++,u++;if(d<0)for(var h=n-u;h0&&(r.push(new i.TEXT(o)),o=[]),n-=d,u-=d;var p=l.emit();r.push(new p(e.slice(n-u,n)))}}return o.length>0&&r.push(new i.TEXT(o)),r},t.start=c},function(e,t,n){"use strict";t.__esModule=!0,t.URL=t.TEXT=t.NL=t.EMAIL=t.MAILTOEMAIL=t.Base=void 0;var r=n(147),i=n(53),o=n(84);function s(e){return e instanceof o.DOMAIN||e instanceof o.TLD}var a=(0,r.createTokenClass)();a.prototype={type:"token",isLink:!1,toString:function(){for(var e=[],t=0;t0&&void 0!==arguments[0]?arguments[0]:"http";return{type:this.type,value:this.toString(),href:this.toHref(e)}}};var c=(0,i.inherits)(a,(0,r.createTokenClass)(),{type:"email",isLink:!0}),f=(0,i.inherits)(a,(0,r.createTokenClass)(),{type:"email",isLink:!0,toHref:function(){return"mailto:"+this.toString()}}),u=(0,i.inherits)(a,(0,r.createTokenClass)(),{type:"text"}),l=(0,i.inherits)(a,(0,r.createTokenClass)(),{type:"nl"}),d=(0,i.inherits)(a,(0,r.createTokenClass)(),{type:"url",isLink:!0,toHref:function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"http",t=!1,n=!1,r=this.v,i=[],a=0;r[a]instanceof o.PROTOCOL;)t=!0,i.push(r[a].toString().toLowerCase()),a++;for(;r[a]instanceof o.SLASH;)n=!0,i.push(r[a].toString()),a++;for(;s(r[a]);)i.push(r[a].toString().toLowerCase()),a++;for(;a