mowetentertainment1 730de334a7 initial
2025-12-05 11:05:33 -05:00

2 lines
84 KiB
JavaScript

"use strict";(self.webpackChunkelement_web=self.webpackChunkelement_web||[]).push([[1787],{"./node_modules/another-json/another-json.js":e=>{for(var t=/[\\\"\x00-\x1F]/g,i={},s=0;s<32;++s)i[String.fromCharCode(s)]="\\U"+("0000"+s.toString(16)).slice(-4).toUpperCase();function r(e){return t.lastIndex=0,e.replace(t,function(e){return i[e]})}function n(e){switch(typeof e){case"string":return'"'+r(e)+'"';case"number":return isFinite(e)?e:"null";case"boolean":return e;case"object":return null===e?"null":Array.isArray(e)?function(e){for(var t="[",i="",s=0;s<e.length;++s)i+=t,t=",",i+=n(e[s]);return","!=t?"[]":i+"]"}(e):function(e){var t="{",i="",s=Object.keys(e);s.sort();for(var o=0;o<s.length;++o){var a=s[o];i+=t+'"'+r(a)+'":',t=",",i+=n(e[a])}return","!=t?"{}":i+"}"}(e);default:throw new Error("Cannot stringify: "+typeof e)}}i["\b"]="\\b",i["\t"]="\\t",i["\n"]="\\n",i["\f"]="\\f",i["\r"]="\\r",i['"']='\\"',i["\\"]="\\\\",e.exports={stringify:n}},"./node_modules/matrix-js-sdk/src/rust-crypto/index.ts":(e,t,i)=>{i.r(t),i.d(t,{initRustCrypto:()=>ye});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),r=i("./node_modules/@matrix-org/matrix-sdk-crypto-wasm/index-wasm-esm.mjs"),n=i("./node_modules/another-json/another-json.js"),o=i.n(n),a=i("./node_modules/matrix-js-sdk/src/@types/membership.ts"),c=i("./node_modules/matrix-js-sdk/src/models/event.ts"),g=i("./node_modules/matrix-js-sdk/src/common-crypto/CryptoBackend.ts"),u=i("./node_modules/matrix-js-sdk/src/logger.ts"),h=i("./node_modules/matrix-js-sdk/src/http-api/index.ts"),d=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),l=i("./node_modules/matrix-js-sdk/src/@types/partials.ts"),y=i("./node_modules/matrix-js-sdk/src/utils.ts"),p=i("./node_modules/matrix-js-sdk/src/crypto-api/index.ts");class m{constructor(e,t,i,n,o,a){(0,s.A)(this,"lazyLoadedMembersResolved",!1),(0,s.A)(this,"currentEncryptionPromise",Promise.resolve()),this.prefixedLogger=e,this.olmMachine=t,this.keyClaimManager=i,this.outgoingRequestManager=n,this.room=o,this.encryptionSettings=a;const c=o.getJoinedMembers();this.olmMachine.updateTrackedUsers(c.map(e=>new r.VvS(e.userId))).catch(e=>this.prefixedLogger.error("Error initializing tracked users",e))}onCryptoEvent(e){if(JSON.stringify(this.encryptionSettings)!=JSON.stringify(e))throw new Error("Cannot reconfigure an active RoomEncryptor")}onRoomMembership(e){(e.membership==a.O.Join||e.membership==a.O.Invite&&this.room.shouldEncryptForInvitedMembers())&&this.olmMachine.updateTrackedUsers([new r.VvS(e.userId)]).catch(e=>{this.prefixedLogger.error("Unable to update tracked users",e)})}async prepareForEncryption(e,t){await this.encryptEvent(null,e,t)}encryptEvent(e,t,i){var s;const r=new u.Tl(this.prefixedLogger,e?null!==(s=e.getTxnId())&&void 0!==s?s:"":"prepareForEncryption"),n=this.currentEncryptionPromise.catch(()=>{}).then(async()=>{await(0,y.NQ)(r,"ensureEncryptionSession",async()=>{await this.ensureEncryptionSession(r,t,i)}),e&&await(0,y.NQ)(r,"encryptEventInner",async()=>{await this.encryptEventInner(r,e)})});return this.currentEncryptionPromise=n,n}async ensureEncryptionSession(e,t,i){if("m.megolm.v1.aes-sha2"!==this.encryptionSettings.algorithm)throw new Error(`Cannot encrypt in ${this.room.roomId} for unsupported algorithm '${this.encryptionSettings.algorithm}'`);e.debug("Starting encryption");const s=await this.room.getEncryptionTargetMembers();this.lazyLoadedMembersResolved?(e.debug("Processing outgoing requests in background"),this.outgoingRequestManager.doProcessOutgoingRequests()):(await(0,y.NQ)(e,"loadMembersIfNeeded: updateTrackedUsers",async()=>{await this.olmMachine.updateTrackedUsers(s.map(e=>new r.VvS(e.userId)))}),e.debug("Updated tracked users"),this.lazyLoadedMembersResolved=!0,e.debug("Processing outgoing requests"),await(0,y.NQ)(e,"doProcessOutgoingRequests",async()=>{await this.outgoingRequestManager.doProcessOutgoingRequests()})),e.debug(`Encrypting for users (shouldEncryptForInvitedMembers: ${this.room.shouldEncryptForInvitedMembers()}):`,s.map(e=>`${e.userId} (${e.membership})`));const n=s.map(e=>new r.VvS(e.userId));await(0,y.NQ)(e,"ensureSessionsForUsers",async()=>{await this.keyClaimManager.ensureSessionsForUsers(e,n)});const o=new r.XlD;switch(o.historyVisibility=function(e){switch(e){case l.Jv.Invited:return r.JvM.Invited;case l.Jv.Joined:return r.JvM.Joined;case l.Jv.Shared:return r.JvM.Shared;case l.Jv.WorldReadable:return r.JvM.WorldReadable}}(this.room.getHistoryVisibility()),o.algorithm=r.liC.MegolmV1AesSha2,"number"==typeof this.encryptionSettings.rotation_period_ms&&(o.rotationPeriod=BigInt(1e3*this.encryptionSettings.rotation_period_ms)),"number"==typeof this.encryptionSettings.rotation_period_msgs&&(o.rotationPeriodMessages=BigInt(this.encryptionSettings.rotation_period_msgs)),i.kind){case p.YH.AllDevicesIsolationMode:{var a;const e=null!==(a=this.room.getBlacklistUnverifiedDevices())&&void 0!==a?a:t;o.sharingStrategy=r.EZX.deviceBasedStrategy(e,i.errorOnVerifiedUserProblems)}break;case p.YH.OnlySignedDevicesIsolationMode:o.sharingStrategy=r.EZX.identityBasedStrategy()}await(0,y.NQ)(e,"shareRoomKey",async()=>{const e=await this.olmMachine.shareRoomKey(new r.BVS(this.room.roomId),n,o);if(e)for(const t of e)await this.outgoingRequestManager.outgoingRequestProcessor.makeOutgoingRequest(t)})}async forceDiscardSession(){await this.olmMachine.invalidateGroupSession(new r.BVS(this.room.roomId))&&this.prefixedLogger.info("Discarded existing group session")}async encryptEventInner(e,t){e.debug("Encrypting actual message content");const i=new r.BVS(this.room.roomId),s=t.getType(),n=JSON.stringify(t.getContent());let o;o=t.isState()?await this.olmMachine.encryptStateEvent(i,s,t.getStateKey(),n):await this.olmMachine.encryptRoomEvent(i,s,n),t.makeEncrypted(d.Bx.RoomMessageEncrypted,JSON.parse(o),this.olmMachine.identityKeys.curve25519.toBase64(),this.olmMachine.identityKeys.ed25519.toBase64()),e.debug("Encrypted event successfully")}}var f=i("./node_modules/matrix-js-sdk/src/base64.ts"),v=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts");const w="/_matrix/client/unstable/org.matrix.msc3814.v1",k="org.matrix.msc3814";class S extends v.X{constructor(e,t,i,r,n){super(),(0,s.A)(this,"intervalId",void 0),this.logger=e,this.olmMachine=t,this.http=i,this.outgoingRequestProcessor=r,this.secretStorage=n}async cacheKey(e){await this.olmMachine.dehydratedDevices().saveDehydratedDeviceKey(e),this.emit(p.cr.DehydrationKeyCached)}async isSupported(){try{await this.http.authedRequest(h.IT.Get,"/dehydrated_device",void 0,void 0,{prefix:w})}catch(e){const t=e;if("M_UNRECOGNIZED"===t.errcode)return!1;if("M_NOT_FOUND"===t.errcode)return!0;throw e}return!0}async start(e={}){if("boolean"==typeof e&&(e={createNewKey:e}),!e.onlyIfKeyCached||await this.olmMachine.dehydratedDevices().getDehydratedDeviceKey()){if(this.stop(),!1!==e.rehydrate)try{await this.rehydrateDeviceIfAvailable()}catch(e){this.logger.info("dehydration: Error rehydrating device:",e),this.emit(p.cr.RehydrationError,e.message)}e.createNewKey&&await this.resetKey(),await this.scheduleDeviceDehydration()}}async isKeyStored(){return Boolean(await this.secretStorage.isStored(k))}async resetKey(){const e=r.YFH.createRandomKey();return await this.secretStorage.store(k,e.toBase64()),await this.cacheKey(e),e}async getKey(e){const t=await this.olmMachine.dehydratedDevices().getDehydratedDeviceKey();if(t)return t;const i=await this.secretStorage.get(k);if(void 0===i)return e?await this.resetKey():null;const s=(0,f.y4)(i);try{const e=r.YFH.createKeyFromArray(s);return await this.cacheKey(e),e}finally{s.fill(0)}}async rehydrateDeviceIfAvailable(){const e=await this.getKey(!1);if(!e)return!1;let t;try{t=await this.http.authedRequest(h.IT.Get,"/dehydrated_device",void 0,void 0,{prefix:w})}catch(e){const t=e;if("M_NOT_FOUND"===t.errcode||"M_UNRECOGNIZED"===t.errcode)return this.logger.info("dehydration: No dehydrated device"),!1;throw t}this.logger.info("dehydration: dehydrated device found"),this.emit(p.cr.RehydrationStarted);const i=await this.olmMachine.dehydratedDevices().rehydrate(e,new r._rJ(t.device_id),JSON.stringify(t.device_data));let s;this.logger.info("dehydration: device rehydrated");let n=0,o=0;const a=(0,y.RR)("/dehydrated_device/$device_id/events",{$device_id:t.device_id});for(;;){const e=await this.http.authedRequest(h.IT.Post,a,void 0,s?{next_batch:s}:{},{prefix:w});if(0===e.events.length)break;n+=e.events.length,s=e.next_batch;o+=(await i.receiveEvents(JSON.stringify(e.events))).length,this.emit(p.cr.RehydrationProgress,o,n)}return this.logger.info(`dehydration: received ${o} room keys from ${n} to-device events`),this.emit(p.cr.RehydrationCompleted),!0}async createAndUploadDehydratedDevice(){const e=await this.getKey(!0),t=await this.olmMachine.dehydratedDevices().create();this.emit(p.cr.DehydratedDeviceCreated);const i=await t.keysForUpload("Dehydrated device",e);await this.outgoingRequestProcessor.makeOutgoingRequest(i),this.emit(p.cr.DehydratedDeviceUploaded),this.logger.info("dehydration: uploaded device")}async scheduleDeviceDehydration(){this.stop(),await this.createAndUploadDehydratedDevice(),this.intervalId=setInterval(()=>{this.createAndUploadDehydratedDevice().catch(e=>{this.emit(p.cr.DehydratedDeviceRotationError,e.message),this.logger.error("Error creating dehydrated device:",e)})},6048e5)}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}async delete(){this.stop();try{await this.http.authedRequest(h.IT.Delete,"/dehydrated_device",void 0,{},{prefix:w})}catch(e){const t=e;if("M_UNRECOGNIZED"===t.errcode)return;if("M_NOT_FOUND"===t.errcode)return;throw e}}}function b(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}class R{constructor(e,t,i){this.logger=e,this.olmMachine=t,this.http=i}async makeOutgoingRequest(e,t){let i;if(e instanceof r.LRK)i=await this.requestWithRetry(h.IT.Post,"/_matrix/client/v3/keys/upload",{},e.body);else if(e instanceof r.OMe)i=await this.requestWithRetry(h.IT.Post,"/_matrix/client/v3/keys/query",{},e.body);else if(e instanceof r.u_L)i=await this.requestWithRetry(h.IT.Post,"/_matrix/client/v3/keys/claim",{},e.body);else if(e instanceof r.rzz)i=await this.requestWithRetry(h.IT.Post,"/_matrix/client/v3/keys/signatures/upload",{},e.body);else if(e instanceof r.c55)i=await this.requestWithRetry(h.IT.Put,"/_matrix/client/v3/room_keys/keys",{version:e.version},e.body);else if(e instanceof r.bCf)i=await this.sendToDeviceRequest(e);else if(e instanceof r.UMe){const t=`/_matrix/client/v3/rooms/${encodeURIComponent(e.room_id)}/send/${encodeURIComponent(e.event_type)}/${encodeURIComponent(e.txn_id)}`;i=await this.requestWithRetry(h.IT.Put,t,{},e.body)}else{if(e instanceof r.kZZ)return void await this.makeRequestWithUIA(h.IT.Post,"/_matrix/client/v3/keys/device_signing/upload",{},e.body,t);if(e instanceof r.JJE){const t=w+"/dehydrated_device";return void await this.rawJsonRequest(h.IT.Put,t,{},e.body)}this.logger.warn("Unsupported outgoing message",Object.getPrototypeOf(e)),i=""}if(e.id)try{await(0,y.NQ)(this.logger,`Mark Request as sent ${e.type}`,async()=>{await this.olmMachine.markRequestAsSent(e.id,e.type,i)})}catch(e){if(!(e instanceof Error)||"Attempt to use a moved value"!==e.message&&"null pointer passed to rust"!==e.message)throw e;this.logger.debug(`Ignoring error '${e.message}': client is likely shutting down`)}else this.logger.trace(`Outgoing request type:${e.type} does not have an ID`)}async sendToDeviceRequest(e){const t=JSON.parse(e.body),i=[];for(const[e,s]of Object.entries(t.messages))for(const[t,r]of Object.entries(s))i.push(`${e}/${t} (msgid ${r[d.wt]})`);this.logger.info(`Sending batch of to-device messages. type=${e.event_type} txnid=${e.txn_id}`,i);const s=`/_matrix/client/v3/sendToDevice/${encodeURIComponent(e.event_type)}/`+encodeURIComponent(e.txn_id);return await this.requestWithRetry(h.IT.Put,s,{},e.body)}async makeRequestWithUIA(e,t,i,r,n){if(!n)return await this.requestWithRetry(e,t,i,r);const o=JSON.parse(r),a=await n(async r=>{const n=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?b(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):b(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},o);null!==r&&(n.auth=r);const a=await this.requestWithRetry(e,t,i,JSON.stringify(n));return JSON.parse(a)});return JSON.stringify(a)}async requestWithRetry(e,t,i,s){let r=0;for(;;)try{return await this.rawJsonRequest(e,t,i,s)}catch(e){r++;const t=(0,h.fZ)(e,r,!0);if(t<0)throw e;await(0,y.yy)(t)}}async rawJsonRequest(e,t,i,s){return await this.http.authedRequest(e,t,i,s,{json:!1,headers:{"Content-Type":"application/json",Accept:"application/json"},prefix:"",localTimeoutMs:6e4})}}class K{constructor(e,t){(0,s.A)(this,"currentClaimPromise",void 0),(0,s.A)(this,"stopped",!1),this.olmMachine=e,this.outgoingRequestProcessor=t,this.currentClaimPromise=Promise.resolve()}stop(){this.stopped=!0}ensureSessionsForUsers(e,t){const i=this.currentClaimPromise.catch(()=>{}).then(()=>this.ensureSessionsForUsersInner(e,t));return this.currentClaimPromise=i,i}async ensureSessionsForUsersInner(e,t){if(this.stopped)throw new Error("Cannot ensure Olm sessions: shutting down");e.info("Checking for missing Olm sessions");const i=await this.olmMachine.getMissingSessions(t.map(e=>e.clone()));i&&(e.info("Making /keys/claim request"),await this.outgoingRequestProcessor.makeOutgoingRequest(i)),e.info("Olm sessions prepared")}}var I=i("./node_modules/matrix-js-sdk/src/models/device.ts");function _(e,t){const i=new Map;for(const[t,s]of e.keys.entries())i.set(t.toString(),s.toBase64());let s=I.u.Unverified;e.isBlacklisted()?s=I.u.Blocked:e.isVerified()&&(s=I.u.Verified);const n=new Map,o=e.signatures.get(t);if(o){const e=new Map;for(const[t,i]of o.entries())i.isValid()&&i.signature&&e.set(t,i.signature.toBase64());n.set(t.toString(),e)}const a=e.algorithms,c=new Set;return a.forEach(e=>{switch(e){case r.liC.MegolmV1AesSha2:c.add("m.megolm.v1.aes-sha2");break;case r.liC.OlmV1Curve25519AesSha2:default:c.add("m.olm.v1.curve25519-aes-sha2")}}),new I.p({deviceId:e.deviceId.toString(),userId:t.toString(),keys:i,algorithms:Array.from(c),verified:s,signatures:n,displayName:e.displayName,dehydrated:e.isDehydrated})}function M(e){var t;const i=new Map(Object.entries(e.keys)),s=null===(t=e.unsigned)||void 0===t?void 0:t.device_display_name,r=new Map;if(e.signatures)for(const t in e.signatures)r.set(t,new Map(Object.entries(e.signatures[t])));return new I.p({deviceId:e.device_id,userId:e.user_id,keys:i,algorithms:e.algorithms,verified:I.u.Unverified,signatures:r,displayName:s})}var E=i("./node_modules/matrix-js-sdk/src/secret-storage.ts");class C{constructor(e,t,i,s){this.logger=e,this.olmMachine=t,this.outgoingRequestProcessor=i,this.secretStorage=s}async bootstrapCrossSigning(e){if(e.setupNewCrossSigning)return void await this.resetCrossSigning(e.authUploadDeviceSigningKeys);const t=await this.olmMachine.crossSigningStatus(),i=await this.secretStorage.get("m.cross_signing.master"),s=await this.secretStorage.get("m.cross_signing.self_signing"),r=await this.secretStorage.get("m.cross_signing.user_signing"),n=Boolean(i&&s&&r),o=t.hasMaster&&t.hasUserSigning&&t.hasSelfSigning;if(this.logger.debug("bootstrapCrossSigning: starting",{setupNewCrossSigning:e.setupNewCrossSigning,olmDeviceHasMaster:t.hasMaster,olmDeviceHasUserSigning:t.hasUserSigning,olmDeviceHasSelfSigning:t.hasSelfSigning,privateKeysInSecretStorage:n}),o)await this.secretStorage.hasKey()?n?this.logger.debug("bootstrapCrossSigning: Olm device has private keys and they are saved in secret storage; doing nothing"):(this.logger.debug("bootstrapCrossSigning: Olm device has private keys: exporting to secret storage"),await this.exportCrossSigningKeysToStorage()):this.logger.warn("bootstrapCrossSigning: Olm device has private keys, but secret storage is not yet set up; doing nothing for now.");else if(n){this.logger.debug("bootstrapCrossSigning: Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally");const e=await this.olmMachine.importCrossSigningKeys(i,s,r);if(!e.hasMaster||!e.hasSelfSigning||!e.hasUserSigning)throw new Error("importCrossSigningKeys failed to import the keys");const t=await this.olmMachine.getDevice(this.olmMachine.userId,this.olmMachine.deviceId);try{const e=await t.verify();await this.outgoingRequestProcessor.makeOutgoingRequest(e)}finally{t.free()}}else this.logger.debug("bootstrapCrossSigning: Cross-signing private keys not found locally or in secret storage, creating new keys"),await this.resetCrossSigning(e.authUploadDeviceSigningKeys);this.logger.debug("bootstrapCrossSigning: complete")}async resetCrossSigning(e){const t=await this.olmMachine.bootstrapCrossSigning(!0);await this.secretStorage.hasKey()?(this.logger.debug("resetCrossSigning: exporting private keys to secret storage"),await this.exportCrossSigningKeysToStorage()):this.logger.warn("resetCrossSigning: Secret storage is not yet set up; not exporting keys to secret storage yet."),this.logger.debug("resetCrossSigning: publishing public keys to server");for(const i of[t.uploadKeysRequest,t.uploadSigningKeysRequest,t.uploadSignaturesRequest])i&&await this.outgoingRequestProcessor.makeOutgoingRequest(i,e)}async exportCrossSigningKeysToStorage(){const e=await this.olmMachine.exportCrossSigningKeys();null!=e&&e.masterKey?await this.secretStorage.store("m.cross_signing.master",e.masterKey):this.logger.error("Cannot export MSK to secret storage, private key unknown"),null!=e&&e.self_signing_key?await this.secretStorage.store("m.cross_signing.self_signing",e.self_signing_key):this.logger.error("Cannot export SSK to secret storage, private key unknown"),null!=e&&e.userSigningKey?await this.secretStorage.store("m.cross_signing.user_signing",e.userSigningKey):this.logger.error("Cannot export USK to secret storage, private key unknown")}}async function O(e){return B(e,["m.cross_signing.master","m.cross_signing.user_signing","m.cross_signing.self_signing"])}async function B(e,t){const i=await e.getDefaultKeyId();if(!i)return!1;for(const s of t){if(!(i in(await e.isStored(s)||{})))return!1}return!0}var D=i("./node_modules/matrix-js-sdk/src/crypto-api/verification.ts"),V=i("./node_modules/matrix-js-sdk/src/ReEmitter.ts"),T=i("./node_modules/matrix-js-sdk/src/types.ts");class q extends v.X{constructor(e,t,i,r,n){super(),(0,s.A)(this,"reEmitter",void 0),(0,s.A)(this,"_accepting",!1),(0,s.A)(this,"_cancelling",!1),(0,s.A)(this,"_verifier",void 0),this.logger=e,this.olmMachine=t,this.inner=i,this.outgoingRequestProcessor=r,this.supportedVerificationMethods=n,this.reEmitter=new V.Q(this);const o=new WeakRef(this);i.registerChangesCallback(async()=>{var e;return null===(e=o.deref())||void 0===e?void 0:e.onChange()})}onChange(){const e=this.inner.getVerification();e instanceof r.Kj7?void 0===this._verifier||this._verifier instanceof N?this.setVerifier(new A(e,this,this.outgoingRequestProcessor)):this._verifier instanceof A&&this._verifier.replaceInner(e):e instanceof r.Qr&&void 0===this._verifier&&this.setVerifier(new N(e,this.outgoingRequestProcessor)),this.emit(D.FM.Change)}setVerifier(e){this._verifier&&this.reEmitter.stopReEmitting(this._verifier,[D.FM.Change]),this._verifier=e,this.reEmitter.reEmit(this._verifier,[D.FM.Change])}get transactionId(){return this.inner.flowId}get roomId(){var e;return null===(e=this.inner.roomId)||void 0===e?void 0:e.toString()}get initiatedByMe(){return this.inner.weStarted()}get otherUserId(){return this.inner.otherUserId.toString()}get otherDeviceId(){var e;return null===(e=this.inner.otherDeviceId)||void 0===e?void 0:e.toString()}async getOtherDevice(){const e=this.inner.otherDeviceId;if(e)return await this.olmMachine.getDevice(this.inner.otherUserId,e,5)}get isSelfVerification(){return this.inner.isSelfVerification()}get phase(){const e=this.inner.phase();switch(e){case r.ggh.Created:case r.ggh.Requested:return D.X9.Requested;case r.ggh.Ready:return this._accepting?D.X9.Requested:D.X9.Ready;case r.ggh.Transitioned:if(!this._verifier)throw new Error("VerificationRequest: inner phase == Transitioned but no verifier!");return this._verifier.verificationPhase;case r.ggh.Done:return D.X9.Done;case r.ggh.Cancelled:return D.X9.Cancelled}throw new Error(`Unknown verification phase ${e}`)}get pending(){if(this.inner.isPassive())return!1;const e=this.phase;return e!==D.X9.Done&&e!==D.X9.Cancelled}get accepting(){return this._accepting}get declining(){return this._cancelling}get timeout(){return this.inner.timeRemainingMillis()}get methods(){throw new Error("not implemented")}get chosenMethod(){if(this.phase!==D.X9.Started)return null;const e=this.inner.getVerification();return e instanceof r.Kj7?T.V.Sas:e instanceof r.Qr?T.V.Reciprocate:null}otherPartySupportsMethod(e){const t=this.inner.theirSupportedMethods;if(void 0===t)return!1;const i=U[e];return t.some(e=>e===i)}async accept(){if(this.inner.phase()!==r.ggh.Requested||this._accepting)throw new Error(`Cannot accept a verification request in phase ${this.phase}`);this._accepting=!0;try{const e=this.inner.acceptWithMethods(this.supportedVerificationMethods.map(x));e&&await this.outgoingRequestProcessor.makeOutgoingRequest(e)}finally{this._accepting=!1}this.emit(D.FM.Change)}async cancel(e){if(!this._cancelling){this.logger.info("Cancelling verification request with params:",e),this._cancelling=!0;try{const e=this.inner.cancel();e&&await this.outgoingRequestProcessor.makeOutgoingRequest(e)}finally{this._cancelling=!1}}}beginKeyVerification(e,t){throw new Error("not implemented")}async startVerification(e){if(e!==T.V.Sas)throw new Error(`Unsupported verification method ${e}`);if(!await this.getOtherDevice())throw new Error("startVerification(): other device is unknown");const t=await this.inner.startSas();if(t){const[,e]=t;await this.outgoingRequestProcessor.makeOutgoingRequest(e)}if(!this._verifier)throw new Error("Still no verifier after startSas() call");return this._verifier}async scanQRCode(e){const t=r.CvR.fromBytes(e),i=await this.inner.scanQrCode(t);if(!this._verifier)throw new Error("Still no verifier after scanQrCode() call");const s=i.reciprocate();return s&&await this.outgoingRequestProcessor.makeOutgoingRequest(s),this._verifier}get verifier(){return this.phase===D.X9.Started?this._verifier:void 0}getQRCodeBytes(){throw new Error("getQRCodeBytes() unsupported in Rust Crypto; use generateQRCode() instead.")}async generateQRCode(){if(!await this.getOtherDevice())throw new Error("generateQRCode(): other device is unknown");const e=await this.inner.generateQrCode();if(e)return e.toBytes()}get cancellationCode(){var e,t;return null!==(e=null===(t=this.inner.cancelInfo)||void 0===t?void 0:t.cancelCode())&&void 0!==e?e:null}get cancellingUserId(){const e=this.inner.cancelInfo;return e?e.cancelledbyUs()?this.olmMachine.userId.toString():this.inner.otherUserId.toString():void 0}}class P extends v.X{constructor(e,t){super(),(0,s.A)(this,"completionDeferred",void 0),this.inner=e,this.outgoingRequestProcessor=t,this.completionDeferred=Promise.withResolvers();const i=new WeakRef(this);e.registerChangesCallback(async()=>{var e;return null===(e=i.deref())||void 0===e?void 0:e.onChange()}),this.completionDeferred.promise.catch(()=>null)}onChange(){if(this.inner.isDone())this.completionDeferred.resolve(void 0);else if(this.inner.isCancelled()){const e=this.inner.cancelInfo();this.completionDeferred.reject(new Error(`Verification cancelled by ${e.cancelledbyUs()?"us":"them"} with code ${e.cancelCode()}: ${e.reason()}`))}this.emit(D.FM.Change)}get hasBeenCancelled(){return this.inner.isCancelled()}get userId(){return this.inner.otherUserId.toString()}cancel(e){const t=this.inner.cancel();t&&this.outgoingRequestProcessor.makeOutgoingRequest(t)}getShowSasCallbacks(){return null}getReciprocateQrCodeCallbacks(){return null}}class N extends P{constructor(e,t){super(e,t),(0,s.A)(this,"callbacks",null)}onChange(){null===this.callbacks&&this.inner.hasBeenScanned()&&(this.callbacks={confirm:()=>{this.confirmScanning()},cancel:()=>this.cancel()}),super.onChange()}async verify(){null!==this.callbacks&&this.emit(D.Ji.ShowReciprocateQr,this.callbacks),await this.completionDeferred.promise}get verificationPhase(){switch(this.inner.state()){case r.dNT.Created:return D.X9.Ready;case r.dNT.Scanned:case r.dNT.Confirmed:case r.dNT.Reciprocated:return D.X9.Started;case r.dNT.Done:return D.X9.Done;case r.dNT.Cancelled:return D.X9.Cancelled;default:throw new Error(`Unknown qr code state ${this.inner.state()}`)}}getReciprocateQrCodeCallbacks(){return this.callbacks}async confirmScanning(){const e=this.inner.confirmScanning();e&&await this.outgoingRequestProcessor.makeOutgoingRequest(e)}}class A extends P{constructor(e,t,i){super(e,i),(0,s.A)(this,"callbacks",null)}async verify(){await this.sendAccept(),await this.completionDeferred.promise}async sendAccept(){const e=this.inner.accept();e&&await this.outgoingRequestProcessor.makeOutgoingRequest(e)}onChange(){if(super.onChange(),null===this.callbacks){const e=this.inner.emoji(),t=this.inner.decimals();if(void 0===e&&void 0===t)return;const i={};e&&(i.emoji=e.map(e=>[e.symbol,e.description])),t&&(i.decimal=[t[0],t[1],t[2]]),this.callbacks={sas:i,confirm:async()=>{const e=await this.inner.confirm();for(const t of e)await this.outgoingRequestProcessor.makeOutgoingRequest(t)},mismatch:()=>{const e=this.inner.cancelWithCode("m.mismatched_sas");e&&this.outgoingRequestProcessor.makeOutgoingRequest(e)},cancel:()=>{const e=this.inner.cancelWithCode("m.user");e&&this.outgoingRequestProcessor.makeOutgoingRequest(e)}},this.emit(D.Ji.ShowSas,this.callbacks)}}get verificationPhase(){return D.X9.Started}getShowSasCallbacks(){return this.callbacks}replaceInner(e){if(this.inner!=e){this.inner=e;const t=new WeakRef(this);e.registerChangesCallback(async()=>{var e;return null===(e=t.deref())||void 0===e?void 0:e.onChange()}),this.sendAccept(),this.onChange()}}}const U={[T.V.Sas]:r.VFM.SasV1,[T.V.ScanQrCode]:r.VFM.QrCodeScanV1,[T.V.ShowQrCode]:r.VFM.QrCodeShowV1,[T.V.Reciprocate]:r.VFM.ReciprocateV1};function x(e){const t=U[e];if(void 0===t)throw new Error(`Unknown verification method ${e}`);return t}class $ extends v.X{constructor(e,t,i,r){super(),(0,s.A)(this,"checkedForBackup",!1),(0,s.A)(this,"serverBackupInfo",void 0),(0,s.A)(this,"activeBackupVersion",null),(0,s.A)(this,"stopped",!1),(0,s.A)(this,"backupKeysLoopRunning",!1),(0,s.A)(this,"keyBackupCheckInProgress",null),this.logger=e,this.olmMachine=t,this.http=i,this.outgoingRequestProcessor=r}stop(){this.stopped=!0}async getActiveBackupVersion(){return await this.olmMachine.isBackupEnabled()?this.activeBackupVersion:null}async getServerBackupInfo(){return await this.checkKeyBackupAndEnable(!1),this.serverBackupInfo}async isKeyBackupTrusted(e){const t=await this.olmMachine.verifyBackup(e),i=await this.olmMachine.getBackupKeys(),s=null==i?void 0:i.decryptionKey;return{matchesDecryptionKey:!!s&&this.backupInfoMatchesBackupDecryptionKey(e,s),trusted:t.trusted()}}checkKeyBackupAndEnable(e){return!e&&this.checkedForBackup?Promise.resolve(null):(this.keyBackupCheckInProgress||(this.keyBackupCheckInProgress=this.doCheckKeyBackup().finally(()=>{this.keyBackupCheckInProgress=null})),this.keyBackupCheckInProgress)}async handleBackupSecretReceived(e){var t;let i;try{i=await this.requestKeyBackupVersion()}catch(e){return this.logger.warn("handleBackupSecretReceived: Error checking for latest key backup",e),!1}if(null===(t=i)||void 0===t||!t.version)return this.logger.warn("handleBackupSecretReceived: Received a backup decryption key, but there is no trusted server-side key backup"),!1;try{const t=r.xqv.fromBase64(e);return this.backupInfoMatchesBackupDecryptionKey(i,t)?(this.logger.info("handleBackupSecretReceived: A valid backup decryption key has been received and stored in cache."),await this.saveBackupDecryptionKey(t,i.version),!0):(this.logger.warn("handleBackupSecretReceived: Private decryption key does not match the public key of the current remote backup."),!1)}catch(e){this.logger.warn("handleBackupSecretReceived: Invalid backup decryption key",e)}return!1}async saveBackupDecryptionKey(e,t){await this.olmMachine.saveBackupDecryptionKey(e,t),this.emit(p.cr.KeyBackupDecryptionKeyCached,t)}async importRoomKeys(e,t){await this.importRoomKeysAsJson(JSON.stringify(e),t)}async importRoomKeysAsJson(e,t){await this.olmMachine.importExportedRoomKeys(e,(e,i)=>{var s;const r={total:Number(i),successes:Number(e),stage:p.wF.LoadKeys,failures:0};null==t||null===(s=t.progressCallback)||void 0===s||s.call(t,r)})}async importBackedUpRoomKeys(e,t,i){const s=new Map;for(const t of e){const e=new r.BVS(t.room_id);s.has(e)||s.set(e,new Map),s.get(e).set(t.session_id,t)}await this.olmMachine.importBackedUpRoomKeys(s,(e,t,s)=>{var r;const n={total:Number(t),successes:Number(e),stage:p.wF.LoadKeys,failures:Number(s)};null==i||null===(r=i.progressCallback)||void 0===r||r.call(i,n)},t)}async doCheckKeyBackup(){let e;this.logger.debug("Checking key backup status...");try{e=await this.requestKeyBackupVersion()}catch(e){return this.logger.warn("Error checking for active key backup",e),this.serverBackupInfo=void 0,null}this.checkedForBackup=!0,e&&!e.version&&(this.logger.warn("active backup lacks a useful 'version'; ignoring it"),e=void 0),this.serverBackupInfo=e;const t=await this.getActiveBackupVersion();if(!e)return null!==t?(this.logger.debug("No key backup present on server: disabling key backup"),await this.disableKeyBackup()):this.logger.debug("No key backup present on server: not enabling key backup"),null;const i=await this.isKeyBackupTrusted(e);return i.matchesDecryptionKey||i.trusted?null===t?(this.logger.debug(`Found usable key backup v${e.version}: enabling key backups`),await this.enableKeyBackup(e)):t!==e.version?(this.logger.debug(`On backup version ${t} but found version ${e.version}: switching.`),await this.disableKeyBackup(),await this.enableKeyBackup(e)):this.logger.debug(`Backup version ${e.version} still current`):null!==t?(this.logger.debug("Key backup present on server but not trusted: disabling key backup"),await this.disableKeyBackup()):this.logger.debug("Key backup present on server but not trusted: not enabling key backup"),{backupInfo:e,trustInfo:i}}async enableKeyBackup(e){await this.olmMachine.enableBackupV1(e.auth_data.public_key,e.version),this.activeBackupVersion=e.version,this.emit(p.cr.KeyBackupStatus,!0),this.backupKeysLoop()}async maybeUploadKey(){null!=this.activeBackupVersion&&this.backupKeysLoop()}async disableKeyBackup(){await this.olmMachine.disableBackup(),this.activeBackupVersion=null,this.emit(p.cr.KeyBackupStatus,!1)}async backupKeysLoop(e=1e4){if(this.backupKeysLoopRunning)return void this.logger.debug("Backup loop already running");this.backupKeysLoopRunning=!0,this.logger.debug(`Backup: Starting keys upload loop for backup version:${this.activeBackupVersion}.`);const t=Math.random()*e;await(0,y.yy)(t);try{let e=0,t=null,i=!0;for(;!this.stopped;){let s;try{s=await(0,y.NQ)(this.logger,"BackupRoomKeys: Get keys to backup from rust crypto-sdk",async()=>await this.olmMachine.backupRoomKeys())}catch(e){this.logger.error("Backup: Failed to get keys to backup from rust crypto-sdk",e)}if(!s||this.stopped||!this.activeBackupVersion)return this.logger.debug(`Backup: Ending loop for version ${this.activeBackupVersion}.`),void(s||this.emit(p.cr.KeyBackupSessionsRemaining,0));try{if(await this.outgoingRequestProcessor.makeOutgoingRequest(s),e=0,this.stopped)break;if(!i&&null===t)try{const e=await this.olmMachine.roomKeyCounts();t=e.total-e.backedUp}catch(e){this.logger.error("Backup: Failed to get key counts from rust crypto-sdk",e)}if(null!==t){this.emit(p.cr.KeyBackupSessionsRemaining,t);const e=this.keysCountInBatch(s);t=Math.max(t-e,0)}}catch(t){if(e++,this.logger.error("Backup: Error processing backup request for rust crypto-sdk",t),t instanceof h.up){const e=t.data.errcode;if("M_NOT_FOUND"==e||"M_WRONG_ROOM_KEYS_VERSION"==e){this.logger.debug(`Backup: Failed to upload keys to current vesion: ${e}.`);try{await this.disableKeyBackup()}catch(e){this.logger.error("Backup: An error occurred while disabling key backup:",e)}return this.emit(p.cr.KeyBackupFailed,t.data.errcode),this.backupKeysLoopRunning=!1,void this.checkKeyBackupAndEnable(!0)}if(t.isRateLimitError())try{const e=t.getRetryAfterMs();if(e&&e>0){await(0,y.yy)(e);continue}}catch(e){this.logger.warn("Backup: An error occurred while retrieving a rate-limit retry delay",e)}}await(0,y.yy)(1e3*Math.pow(2,Math.min(e-1,4)))}i=!1}}finally{this.backupKeysLoopRunning=!1}}keysCountInBatch(e){return J(JSON.parse(e.body))}async requestKeyBackupVersion(e){return await F(this.http,e)}async setupKeyBackup(e){await this.deleteAllKeyBackupVersions();const t=r.xqv.createRandomKey(),i=t.megolmV1PublicKey,s={public_key:i.publicKeyBase64};await e(s);const n=await this.http.authedRequest(h.IT.Post,"/room_keys/version",void 0,{algorithm:i.algorithm,auth_data:s},{prefix:h.iD.V3});return await this.saveBackupDecryptionKey(t,n.version),{version:n.version,algorithm:i.algorithm,authData:s,decryptionKey:t}}async deleteAllKeyBackupVersions(){var e,t;let i=null!==(e=null===(t=await this.requestKeyBackupVersion())||void 0===t?void 0:t.version)&&void 0!==e?e:null;for(;null!=i;){var s,r;await this.deleteKeyBackupVersion(i),i=null!==(s=null===(r=await this.requestKeyBackupVersion())||void 0===r?void 0:r.version)&&void 0!==s?s:null}}async deleteKeyBackupVersion(e){this.logger.debug(`deleteKeyBackupVersion v:${e}`);const t=(0,y.RR)("/room_keys/version/$version",{$version:e});await this.http.authedRequest(h.IT.Delete,t,void 0,void 0,{prefix:h.iD.V3}),this.activeBackupVersion===e&&(this.serverBackupInfo=null,await this.disableKeyBackup())}createBackupDecryptor(e){return new j(this.logger,e)}async restoreKeyBackup(e,t,i){const s=await this.downloadKeyBackup(e);return this.importKeyBackup(s,e,t,i)}downloadKeyBackup(e){return this.http.authedRequest(h.IT.Get,"/room_keys/keys",{version:e},void 0,{prefix:h.iD.V3})}async importKeyBackup(e,t,i,s){var r;const n=J(e);let o=0,a=0;null==s||null===(r=s.progressCallback)||void 0===r||r.call(s,{total:n,successes:o,stage:p.wF.LoadKeys,failures:a});const c=async e=>{var r;const c=[];for(const t of e.keys()){(await i.decryptSessions(e.get(t))).forEach(e=>{e.room_id=t,c.push(e)})}try{await this.importBackedUpRoomKeys(c,t),o+=c.length}catch(e){a+=c.length,this.logger.error("Error importing keys from backup",e)}null==s||null===(r=s.progressCallback)||void 0===r||r.call(s,{total:n,successes:o,stage:p.wF.LoadKeys,failures:a})};let g=0,u=new Map;for(const[t,i]of Object.entries(e.rooms))if(i.sessions){u.set(t,{});for(const[e,s]of Object.entries(i.sessions)){u.get(t)[e]=s,g+=1,g>=200&&(await c(u),u=new Map,u.set(t,{}),g=0)}}return g>0&&await c(u),{total:n,imported:o}}backupInfoMatchesBackupDecryptionKey(e,t){var i;return"m.megolm_backup.v1.curve25519-aes-sha2"!==e.algorithm?(this.logger.warn("backupMatchesPrivateKey: Unsupported backup algorithm",e.algorithm),!1):(null===(i=e.auth_data)||void 0===i?void 0:i.public_key)===t.megolmV1PublicKey.publicKeyBase64}}class j{constructor(e,t){(0,s.A)(this,"decryptionKey",void 0),(0,s.A)(this,"sourceTrusted",void 0),this.logger=e,this.decryptionKey=t,this.sourceTrusted=!1}async decryptSessions(e){const t=[];for(const[i,s]of Object.entries(e))try{const e=JSON.parse(this.decryptionKey.decryptV1(s.session_data.ephemeral,s.session_data.mac,s.session_data.ciphertext));e.session_id=i,t.push(e)}catch(e){this.logger.debug("Failed to decrypt megolm session from backup",e,s)}return t}free(){this.decryptionKey.free()}}async function F(e,t){try{const i=t?(0,y.RR)("/room_keys/version/$version",{$version:t}):"/room_keys/version";return await e.authedRequest(h.IT.Get,i,void 0,void 0,{prefix:h.iD.V3})}catch(e){if("M_NOT_FOUND"===e.errcode)return null;throw e}}function L(e,t){return t.auth_data.public_key===e.megolmV1PublicKey.publicKeyBase64}function J(e){let t=0;for(const{sessions:i}of Object.values(e.rooms))t+=Object.keys(i).length;return t}var G=i("./node_modules/matrix-js-sdk/src/randomstring.ts"),W=i("./node_modules/matrix-js-sdk/src/errors.ts");class Q{constructor(e,t,i){(0,s.A)(this,"stopped",!1),(0,s.A)(this,"outgoingRequestLoopRunning",!1),(0,s.A)(this,"nextLoopDeferred",void 0),this.logger=e,this.olmMachine=t,this.outgoingRequestProcessor=i}stop(){this.stopped=!0}doProcessOutgoingRequests(){this.nextLoopDeferred||(this.nextLoopDeferred=Promise.withResolvers());const e=this.nextLoopDeferred.promise;return this.outgoingRequestLoopRunning||this.outgoingRequestLoop().catch(e=>{this.logger.error("Uncaught error in outgoing request loop",e)}),e}async outgoingRequestLoop(){if(this.outgoingRequestLoopRunning)throw new Error("Cannot run two outgoing request loops");this.outgoingRequestLoopRunning=!0;try{for(;!this.stopped&&this.nextLoopDeferred;){const e=this.nextLoopDeferred;this.nextLoopDeferred=void 0,await this.processOutgoingRequests().then(e.resolve,e.reject)}}finally{this.outgoingRequestLoopRunning=!1}this.nextLoopDeferred&&this.nextLoopDeferred.reject(new Error("OutgoingRequestsManager was stopped"))}async processOutgoingRequests(){if(this.stopped)return;const e=await this.olmMachine.outgoingRequests();for(const t of e){if(this.stopped)return;try{await(0,y.NQ)(this.logger,`Make outgoing request ${t.type}`,async()=>{await this.outgoingRequestProcessor.makeOutgoingRequest(t)})}catch(e){this.logger.error(`Failed to process outgoing request ${t.type}: ${e}`)}}}}const Y=5e3;var H=function(e){return e.MISSING_DECRYPTION_KEY="MISSING_DECRYPTION_KEY",e.NETWORK_ERROR="NETWORK_ERROR",e.STOPPED="STOPPED",e}(H||{});class X extends Error{constructor(e){super(`Failed to get key from backup: ${e}`),this.code=e,this.name="KeyDownloadError"}}class z extends Error{constructor(e){super("Failed to get key from backup: rate limited"),this.retryMillis=e,this.name="KeyDownloadRateLimitError"}}class Z{constructor(e,t,i,r){(0,s.A)(this,"stopped",!1),(0,s.A)(this,"configuration",null),(0,s.A)(this,"sessionLastCheckAttemptedTime",new Map),(0,s.A)(this,"logger",void 0),(0,s.A)(this,"downloadLoopRunning",!1),(0,s.A)(this,"queuedRequests",[]),(0,s.A)(this,"hasConfigurationProblem",!1),(0,s.A)(this,"currentBackupVersionCheck",null),(0,s.A)(this,"onBackupStatusChanged",()=>{this.hasConfigurationProblem=!1,this.configuration=null,this.getOrCreateBackupConfiguration().then(e=>{e&&this.downloadKeysLoop()})}),this.olmMachine=t,this.http=i,this.backupManager=r,this.logger=e.getChild("[PerSessionKeyBackupDownloader]"),r.on(p.cr.KeyBackupStatus,this.onBackupStatusChanged),r.on(p.cr.KeyBackupFailed,this.onBackupStatusChanged),r.on(p.cr.KeyBackupDecryptionKeyCached,this.onBackupStatusChanged)}isKeyBackupDownloadConfigured(){return null!==this.configuration}async getServerBackupInfo(){return await this.backupManager.getServerBackupInfo()}onDecryptionKeyMissingError(e,t){this.isAlreadyInQueue(e,t)?this.logger.trace(`Not checking key backup for session ${t} as it is already queued`):this.wasRequestedRecently(t)?this.logger.trace(`Not checking key backup for session ${t} as it was already requested recently`):(this.queuedRequests.push({roomId:e,megolmSessionId:t}),this.downloadKeysLoop())}stop(){this.stopped=!0,this.backupManager.off(p.cr.KeyBackupStatus,this.onBackupStatusChanged),this.backupManager.off(p.cr.KeyBackupFailed,this.onBackupStatusChanged),this.backupManager.off(p.cr.KeyBackupDecryptionKeyCached,this.onBackupStatusChanged)}isAlreadyInQueue(e,t){return this.queuedRequests.some(i=>i.roomId==e&&i.megolmSessionId==t)}markAsNotFoundInBackup(e){const t=Date.now();this.sessionLastCheckAttemptedTime.set(e,t),this.sessionLastCheckAttemptedTime.size>100&&(this.sessionLastCheckAttemptedTime=new Map(Array.from(this.sessionLastCheckAttemptedTime).filter((e,i)=>Math.max(t-i,0)<Y)))}wasRequestedRecently(e){const t=this.sessionLastCheckAttemptedTime.get(e);return!!t&&Math.max(Date.now()-t,0)<Y}async getBackupDecryptionKey(){try{return await this.olmMachine.getBackupKeys()}catch{return null}}async requestRoomKeyFromBackup(e,t,i){const s=(0,y.RR)("/room_keys/keys/$roomId/$sessionId",{$roomId:t,$sessionId:i});return await this.http.authedRequest(h.IT.Get,s,{version:e},void 0,{prefix:h.iD.V3})}async downloadKeysLoop(){if(!this.downloadLoopRunning&&!this.hasConfigurationProblem){this.downloadLoopRunning=!0;try{for(;this.queuedRequests.length>0;){const e=this.queuedRequests[0];try{const t=await this.getOrCreateBackupConfiguration();if(!t)return void(this.downloadLoopRunning=!1);const i=await this.queryKeyBackup(e.roomId,e.megolmSessionId,t);if(this.stopped)return;try{await this.decryptAndImport(e,i,t)}catch(t){this.logger.error(`Error while decrypting and importing key backup for session ${e.megolmSessionId}`,t)}this.queuedRequests.shift()}catch(t){if(t instanceof X)switch(t.code){case H.MISSING_DECRYPTION_KEY:this.markAsNotFoundInBackup(e.megolmSessionId),this.queuedRequests.shift();break;case H.NETWORK_ERROR:await(0,y.yy)(Y);break;case H.STOPPED:return void(this.downloadLoopRunning=!1)}else t instanceof z&&await(0,y.yy)(t.retryMillis)}}}finally{this.downloadLoopRunning=!1}}}async queryKeyBackup(e,t,i){if(this.logger.debug(`Checking key backup for session ${t}`),this.stopped)throw new X(H.STOPPED);try{const s=await this.requestRoomKeyFromBackup(i.backupVersion,e,t);return this.logger.debug(`Got key from backup for sessionId:${t}`),s}catch(e){if(this.stopped)throw new X(H.STOPPED);if(this.logger.info(`No luck requesting key backup for session ${t}: ${e}`),e instanceof h.up){if("M_NOT_FOUND"==e.data.errcode)throw new X(H.MISSING_DECRYPTION_KEY);if(e.isRateLimitError()){let t;try{var s;t=null!==(s=e.getRetryAfterMs())&&void 0!==s?s:void 0}catch(e){this.logger.warn("Error while retrieving a rate-limit retry delay",e)}throw t&&t>0&&this.logger.info(`Rate limited by server, waiting ${t}ms`),new z(null!=t?t:Y)}}throw new X(H.NETWORK_ERROR)}}async decryptAndImport(e,t,i){const s={[e.megolmSessionId]:t},r=await i.decryptor.decryptSessions(s);for(const t of r)t.room_id=e.roomId;await this.backupManager.importBackedUpRoomKeys(r,i.backupVersion)}async getOrCreateBackupConfiguration(){if(this.configuration)return this.configuration;if(this.hasConfigurationProblem)return null;if(null!=this.currentBackupVersionCheck)return this.logger.debug("Already checking server version, use current promise"),await this.currentBackupVersionCheck;this.currentBackupVersionCheck=this.internalCheckFromServer();try{return await this.currentBackupVersionCheck}finally{this.currentBackupVersionCheck=null}}async internalCheckFromServer(){var e,t,i;let s=null;try{s=await this.backupManager.getServerBackupInfo()}catch(e){return this.logger.debug(`Backup: error while checking server version: ${e}`),this.hasConfigurationProblem=!0,null}var r;if(this.logger.debug(`Got current backup version from server: ${null===(e=s)||void 0===e?void 0:e.version}`),"m.megolm_backup.v1.curve25519-aes-sha2"!=(null===(t=s)||void 0===t?void 0:t.algorithm))return this.logger.info(`Unsupported algorithm ${null===(r=s)||void 0===r?void 0:r.algorithm}`),this.hasConfigurationProblem=!0,null;if(null===(i=s)||void 0===i||!i.version)return this.logger.info("No current key backup"),this.hasConfigurationProblem=!0,null;const n=await this.backupManager.getActiveBackupVersion();if(null==n||s.version!=n)return this.logger.info(`The current backup version on the server (${s.version}) is not trusted. Version we are currently backing up to: ${n}`),this.hasConfigurationProblem=!0,null;const o=await this.getBackupDecryptionKey();if(null==o||!o.decryptionKey)return this.logger.debug("Not checking key backup for session (no decryption key)"),this.hasConfigurationProblem=!0,null;if(n!=o.backupVersion)return this.logger.debug(`Version for which we have a decryption key (${o.backupVersion}) doesn't match the version we are backing up to (${n})`),this.hasConfigurationProblem=!0,null;if(s.auth_data.public_key!=o.decryptionKey.megolmV1PublicKey.publicKeyBase64)return this.logger.debug("Key backup on server does not match our decryption key"),this.hasConfigurationProblem=!0,null;const a=this.backupManager.createBackupDecryptor(o.decryptionKey);return this.hasConfigurationProblem=!1,this.configuration={decryptor:a,backupVersion:n},this.configuration}}var ee=i("./node_modules/matrix-js-sdk/src/content-repo.ts");function te(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function ie(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?te(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):te(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}const se=[T.V.Sas,T.V.ScanQrCode,T.V.ShowQrCode,T.V.Reciprocate];class re extends v.X{constructor(e,t,i,r,n,o,a,c=!1){super(),(0,s.A)(this,"RECOVERY_KEY_DERIVATION_ITERATIONS",5e5),(0,s.A)(this,"_trustCrossSignedDevices",!0),(0,s.A)(this,"deviceIsolationMode",new p.ux(!1)),(0,s.A)(this,"stopped",!1),(0,s.A)(this,"roomEncryptors",{}),(0,s.A)(this,"eventDecryptor",void 0),(0,s.A)(this,"keyClaimManager",void 0),(0,s.A)(this,"outgoingRequestProcessor",void 0),(0,s.A)(this,"crossSigningIdentity",void 0),(0,s.A)(this,"backupManager",void 0),(0,s.A)(this,"outgoingRequestsManager",void 0),(0,s.A)(this,"perSessionBackupDownloader",void 0),(0,s.A)(this,"dehydratedDeviceManager",void 0),(0,s.A)(this,"reemitter",new V.Q(this)),(0,s.A)(this,"globalBlacklistUnverifiedDevices",!1),(0,s.A)(this,"_supportedVerificationMethods",se),this.logger=e,this.olmMachine=t,this.http=i,this.userId=r,this.secretStorage=o,this.cryptoCallbacks=a,this.enableEncryptedStateEvents=c,this.outgoingRequestProcessor=new R(e,t,i),this.outgoingRequestsManager=new Q(this.logger,t,this.outgoingRequestProcessor),this.keyClaimManager=new K(t,this.outgoingRequestProcessor),this.backupManager=new $(e,t,i,this.outgoingRequestProcessor),this.perSessionBackupDownloader=new Z(this.logger,this.olmMachine,this.http,this.backupManager),this.dehydratedDeviceManager=new S(this.logger,t,i,this.outgoingRequestProcessor,o),this.eventDecryptor=new ne(this.logger,t,this.perSessionBackupDownloader),this.reemitter.reEmit(this.backupManager,[p.cr.KeyBackupStatus,p.cr.KeyBackupSessionsRemaining,p.cr.KeyBackupFailed,p.cr.KeyBackupDecryptionKeyCached]),this.reemitter.reEmit(this.dehydratedDeviceManager,[p.cr.DehydratedDeviceCreated,p.cr.DehydratedDeviceUploaded,p.cr.RehydrationStarted,p.cr.RehydrationProgress,p.cr.RehydrationCompleted,p.cr.RehydrationError,p.cr.DehydrationKeyCached,p.cr.DehydratedDeviceRotationError]),this.crossSigningIdentity=new C(e,t,this.outgoingRequestProcessor,o),this.checkKeyBackupAndEnable()}getOlmMachineOrThrow(){if(this.stopped)throw new W.LA;return this.olmMachine}set globalErrorOnUnknownDevices(e){}get globalErrorOnUnknownDevices(){return!1}stop(){this.stopped||(this.stopped=!0,this.keyClaimManager.stop(),this.backupManager.stop(),this.outgoingRequestsManager.stop(),this.perSessionBackupDownloader.stop(),this.dehydratedDeviceManager.stop(),this.olmMachine.close())}async encryptEvent(e,t){const i=e.getRoomId(),s=this.roomEncryptors[i];if(!s)throw new Error(`Cannot encrypt event in unconfigured room ${i}`);await s.encryptEvent(e,this.globalBlacklistUnverifiedDevices,this.deviceIsolationMode)}async decryptEvent(e){if(!e.getRoomId())throw new Error("to-device event was not decrypted in preprocessToDeviceMessages");return await this.eventDecryptor.attemptEventDecryption(e,this.deviceIsolationMode)}async getBackupDecryptor(e,t){if(!(t instanceof Uint8Array))throw new Error("getBackupDecryptor: expects Uint8Array");if("m.megolm_backup.v1.curve25519-aes-sha2"!=e.algorithm)throw new Error(`getBackupDecryptor: Unsupported algorithm ${e.algorithm}`);const i=r.xqv.fromBase64((0,f.WG)(t));if(!L(i,e))throw new Error("getBackupDecryptor: key backup on server does not match the decryption key");return this.backupManager.createBackupDecryptor(i)}async importBackedUpRoomKeys(e,t,i){return await this.backupManager.importBackedUpRoomKeys(e,t,i)}async maybeAcceptKeyBundle(e,t){const i=new u.Tl(this.logger,`maybeAcceptKeyBundle(${e}, ${t})`);i.info("Checking inviter cross-signing keys");const s=this.olmMachine.queryKeysForUsers([new r.VvS(t)]);await this.outgoingRequestProcessor.makeOutgoingRequest(s);const n=await this.olmMachine.getReceivedRoomKeyBundleData(new r.BVS(e),new r.VvS(t));if(!n)return void i.info("No key bundle found for user");i.info(`Fetching key bundle ${n.url}`);const o=(0,ee.y)(this.http.opts.baseUrl,n.url,void 0,void 0,void 0,!1,!0,!0);let a;try{const e=new URL(o);a=await this.http.authedRequest(h.IT.Get,e.pathname+e.search,{},void 0,{rawResponseBody:!0,prefix:""})}catch(e){throw i.warn(`Error downloading encrypted bundle from ${o}:`,e),e}i.info(`Received blob of length ${a.size}`);try{await this.olmMachine.receiveRoomKeyBundle(n,new Uint8Array(await a.arrayBuffer()))}catch(e){throw i.warn("Error receiving encrypted bundle:",e),e}}getVersion(){const e=r.cSE();return`Rust SDK ${e.matrix_sdk_crypto} (${e.git_sha}), Vodozemac ${e.vodozemac}`}setDeviceIsolationMode(e){this.deviceIsolationMode=e}async isEncryptionEnabledInRoom(e){const t=await this.olmMachine.getRoomSettings(new r.BVS(e));return Boolean(null==t?void 0:t.algorithm)}async isStateEncryptionEnabledInRoom(e){const t=await this.olmMachine.getRoomSettings(new r.BVS(e));return Boolean(null==t?void 0:t.encryptStateEvents)}async getOwnDeviceKeys(){const e=this.olmMachine.identityKeys;return{ed25519:e.ed25519.toBase64(),curve25519:e.curve25519.toBase64()}}prepareToEncrypt(e){const t=this.roomEncryptors[e.roomId];t&&t.prepareForEncryption(this.globalBlacklistUnverifiedDevices,this.deviceIsolationMode)}forceDiscardSession(e){var t;return null===(t=this.roomEncryptors[e])||void 0===t?void 0:t.forceDiscardSession()}async exportRoomKeys(){const e=await this.olmMachine.exportRoomKeys(()=>!0);return JSON.parse(e)}async exportRoomKeysAsJson(){return await this.olmMachine.exportRoomKeys(()=>!0)}async importRoomKeys(e,t){return await this.backupManager.importRoomKeys(e,t)}async importRoomKeysAsJson(e,t){return await this.backupManager.importRoomKeysAsJson(e,t)}async userHasCrossSigningKeys(e=this.userId,t=!1){const i=await this.olmMachine.trackedUsers();let s;for(const t of i)if(e===t.toString()){s=t;break}if(void 0!==s){if(e===this.userId){const e=this.olmMachine.queryKeysForUsers([s.clone()]);await this.outgoingRequestProcessor.makeOutgoingRequest(e)}const t=await this.olmMachine.getIdentity(s);return null==t||t.free(),void 0!==t}if(t){var r;const t=null===(r=(await this.downloadDeviceList(new Set([e]))).master_keys)||void 0===r?void 0:r[e];return!!t&&Boolean(Object.values(t.keys)[0])}return!1}async getUserDeviceInfo(e,t=!1){const i=new Map,s=await this.getOlmMachineOrThrow().trackedUsers(),r=new Set;s.forEach(e=>r.add(e.toString()));const n=new Set;for(const t of e)r.has(t)?i.set(t,await this.getUserDevices(t)):n.add(t);if(t&&n.size>=1){const e=await this.downloadDeviceList(n);Object.entries(e.device_keys).forEach(([e,t])=>i.set(e,function(e){return new Map(Object.entries(e).map(([e,t])=>[e,M(t)]))}(t)))}return i}async getUserDevices(e){const t=new r.VvS(e),i=await this.olmMachine.getUserDevices(t,1);try{const e=i.devices();try{return new Map(e.map(e=>[e.deviceId.toString(),_(e,t)]))}finally{e.forEach(e=>e.free())}}finally{i.free()}}async downloadDeviceList(e){const t={device_keys:{}};return e.forEach(e=>t.device_keys[e]=[]),await this.http.authedRequest(h.IT.Post,"/_matrix/client/v3/keys/query",void 0,t,{prefix:""})}getTrustCrossSignedDevices(){return this._trustCrossSignedDevices}setTrustCrossSignedDevices(e){this._trustCrossSignedDevices=e}async setDeviceVerified(e,t,i=!0){const s=await this.olmMachine.getDevice(new r.VvS(e),new r._rJ(t));if(!s)throw new Error(`Unknown device ${e}|${t}`);try{await s.setLocalTrust(i?r.Yg7.Verified:r.Yg7.Unset)}finally{s.free()}}async crossSignDevice(e){const t=await this.olmMachine.getDevice(new r.VvS(this.userId),new r._rJ(e));if(!t)throw new Error(`Unknown device ${e}`);try{const e=await t.verify();await this.outgoingRequestProcessor.makeOutgoingRequest(e)}finally{t.free()}}async getDeviceVerificationStatus(e,t){const i=await this.olmMachine.getDevice(new r.VvS(e),new r._rJ(t));if(!i)return null;try{return new p.wc({signedByOwner:i.isCrossSignedByOwner(),crossSigningVerified:i.isCrossSigningTrusted(),localVerified:i.isLocallyTrusted(),trustCrossSignedDevices:this._trustCrossSignedDevices})}finally{i.free()}}async getUserVerificationStatus(e){const t=await this.getOlmMachineOrThrow().getIdentity(new r.VvS(e));if(void 0===t)return new p.L0(!1,!1,!1);const i=t.isVerified(),s=t.wasPreviouslyVerified(),n=t instanceof r.ENy&&t.identityNeedsUserApproval();return t.free(),new p.L0(i,s,!1,n)}async pinCurrentUserIdentity(e){const t=await this.getOlmMachineOrThrow().getIdentity(new r.VvS(e));if(void 0===t)throw new Error("Cannot pin identity of unknown user");if(t instanceof r.cGL)throw new Error("Cannot pin identity of own user");await t.pinCurrentMasterKey()}async withdrawVerificationRequirement(e){const t=await this.getOlmMachineOrThrow().getIdentity(new r.VvS(e));if(void 0===t)throw new Error("Cannot withdraw verification of unknown user");await t.withdrawVerification()}async isCrossSigningReady(){const{privateKeysInSecretStorage:e,privateKeysCachedLocally:t}=await this.getCrossSigningStatus(),i=Boolean(t.masterKey)&&Boolean(t.selfSigningKey)&&Boolean(t.userSigningKey),s=await this.getOwnIdentity();return!(null==s||!s.isVerified())&&(i||e)}async getCrossSigningKeyId(e=p.nX.Master){const t=await this.olmMachine.getIdentity(new r.VvS(this.userId));if(!t)return null;try{const i=await this.olmMachine.crossSigningStatus();if(!(i.hasMaster&&i.hasUserSigning&&i.hasSelfSigning))return null;if(!t.isVerified())return null;let s;switch(e){case p.nX.Master:s=t.masterKey;break;case p.nX.SelfSigning:s=t.selfSigningKey;break;case p.nX.UserSigning:s=t.userSigningKey;break;default:return null}const r=JSON.parse(s);return Object.values(r.keys)[0]}finally{t.free()}}async bootstrapCrossSigning(e){await this.crossSigningIdentity.bootstrapCrossSigning(e)}async isSecretStorageReady(){const e=["m.cross_signing.master","m.cross_signing.user_signing","m.cross_signing.self_signing"];return null!=await this.backupManager.getActiveBackupVersion()&&e.push("m.megolm_backup.v1"),B(this.secretStorage,e)}async bootstrapSecretStorage({createSecretStorageKey:e,setupNewSecretStorage:t,setupNewKeyBackup:i}={}){const s=t||!await this.secretStorageHasAESKey();if(s){if(!e)throw new Error("unable to create a new secret storage key, createSecretStorageKey is not set");this.logger.info("bootstrapSecretStorage: creating new secret storage key");const t=await e();if(!t)throw new Error("createSecretStorageKey() callback did not return a secret storage key");await this.addSecretStorageKeyToSecretStorage(t)}const r=await this.olmMachine.exportCrossSigningKeys();!(r&&void 0!==r.masterKey&&void 0!==r.self_signing_key&&void 0!==r.userSigningKey)||!s&&await O(this.secretStorage)||(this.logger.info("bootstrapSecretStorage: cross-signing keys not yet exported; doing so now."),await this.secretStorage.store("m.cross_signing.master",r.masterKey),await this.secretStorage.store("m.cross_signing.user_signing",r.userSigningKey),await this.secretStorage.store("m.cross_signing.self_signing",r.self_signing_key)),i?await this.resetKeyBackup():await this.saveBackupKeyToStorage()}async saveBackupKeyToStorage(){const e=await this.backupManager.getServerBackupInfo();if(!e||!e.version)return void this.logger.info("Not saving backup key to secret storage: no backup info");const t=await this.olmMachine.getBackupKeys();if(!t.decryptionKey)return void this.logger.info("Not saving backup key to secret storage: no backup key");if(!L(t.decryptionKey,e))return void this.logger.info("Not saving backup key to secret storage: decryption key does not match backup info");const i=t.decryptionKey.toBase64();await this.secretStorage.store("m.megolm_backup.v1",i)}async addSecretStorageKeyToSecretStorage(e){var t,i,s,r;const n=await this.secretStorage.addKey(E.SECRET_STORAGE_ALGORITHM_V1_AES,{passphrase:null===(t=e.keyInfo)||void 0===t?void 0:t.passphrase,name:null===(i=e.keyInfo)||void 0===i?void 0:i.name,key:e.privateKey});await this.secretStorage.setDefaultKeyId(n.keyId),null===(s=(r=this.cryptoCallbacks).cacheSecretStorageKey)||void 0===s||s.call(r,n.keyId,n.keyInfo,e.privateKey)}async secretStorageHasAESKey(){const e=await this.secretStorage.getKey();if(!e)return!1;const[,t]=e;return t.algorithm===E.SECRET_STORAGE_ALGORITHM_V1_AES}async getCrossSigningStatus(){const e=await this.getOlmMachineOrThrow().getIdentity(new r.VvS(this.userId)),t=Boolean(null==e?void 0:e.masterKey)&&Boolean(null==e?void 0:e.selfSigningKey)&&Boolean(null==e?void 0:e.userSigningKey);null==e||e.free();const i=await O(this.secretStorage),s=await this.getOlmMachineOrThrow().crossSigningStatus();return{publicKeysOnDevice:t,privateKeysInSecretStorage:i,privateKeysCachedLocally:{masterKey:Boolean(null==s?void 0:s.hasMaster),userSigningKey:Boolean(null==s?void 0:s.hasUserSigning),selfSigningKey:Boolean(null==s?void 0:s.hasSelfSigning)}}}async createRecoveryKeyFromPassphrase(e){if(e){const t=(0,G.US)(32),i=await(0,p.wn)(e,t,this.RECOVERY_KEY_DERIVATION_ITERATIONS);return{keyInfo:{passphrase:{algorithm:"m.pbkdf2",iterations:this.RECOVERY_KEY_DERIVATION_ITERATIONS,salt:t}},privateKey:i,encodedPrivateKey:(0,p.jS)(i)}}{const e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),{privateKey:e,encodedPrivateKey:(0,p.jS)(e)}}}async getEncryptionInfoForEvent(e){return this.eventDecryptor.getEncryptionInfoForEvent(e)}getVerificationRequestsToDeviceInProgress(e){return this.olmMachine.getVerificationRequests(new r.VvS(e)).filter(e=>void 0===e.roomId&&!e.isCancelled()).map(e=>this.makeVerificationRequest(e))}findVerificationRequestDMInProgress(e,t){if(!t)throw new Error("missing userId");const i=this.olmMachine.getVerificationRequests(new r.VvS(t)).find(t=>{var i;return(null===(i=t.roomId)||void 0===i?void 0:i.toString())===e&&!t.isCancelled()});if(i)return this.makeVerificationRequest(i)}async requestVerificationDM(e,t){const i=await this.olmMachine.getIdentity(new r.VvS(e));if(!i)throw new Error(`unknown userId ${e}`);try{const e=this._supportedVerificationMethods.map(e=>x(e)),s=await i.verificationRequestContent(e),n=JSON.parse(s);n.msgtype="m.key.verification.request";const o=JSON.stringify(n),a=await this.sendVerificationRequestContent(t,o),c=await i.requestVerification(new r.BVS(t),new r.y1(a),e);return this.makeVerificationRequest(c)}finally{i.free()}}async sendVerificationRequestContent(e,t){const i=(0,G.US)(32),{event_id:s}=await this.http.authedRequest(h.IT.Put,`/_matrix/client/v3/rooms/${encodeURIComponent(e)}/send/m.room.message/${encodeURIComponent(i)}`,void 0,t,{prefix:""});return s}setSupportedVerificationMethods(e){this._supportedVerificationMethods=null!=e?e:se}async requestOwnUserVerification(){const e=await this.olmMachine.getIdentity(new r.VvS(this.userId));if(void 0===e)throw new Error("cannot request verification for this device when there is no existing cross-signing key");try{const[t,i]=await e.requestVerification(this._supportedVerificationMethods.map(x));return await this.outgoingRequestProcessor.makeOutgoingRequest(i),this.makeVerificationRequest(t)}finally{e.free()}}async requestDeviceVerification(e,t){const i=await this.olmMachine.getDevice(new r.VvS(e),new r._rJ(t));if(!i)throw new Error("Not a known device");try{const[e,t]=i.requestVerification(this._supportedVerificationMethods.map(x));return await this.outgoingRequestProcessor.makeOutgoingRequest(t),this.makeVerificationRequest(e)}finally{i.free()}}async getSessionBackupPrivateKey(){const e=await this.olmMachine.getBackupKeys();return e.decryptionKey?(0,f.y4)(e.decryptionKey.toBase64()):null}async storeSessionBackupPrivateKey(e,t){const i=(0,f.WG)(e);if(!t)throw new Error("storeSessionBackupPrivateKey: version is required");await this.backupManager.saveBackupDecryptionKey(r.xqv.fromBase64(i),t)}async loadSessionBackupPrivateKeyFromSecretStorage(){const e=await this.secretStorage.get("m.megolm_backup.v1");if(!e)throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: missing decryption key in secret storage");const t=await this.backupManager.getServerBackupInfo();if(!t||!t.version)throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: unable to get backup version");const i=r.xqv.fromBase64(e);if(!L(i,t))throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: decryption key does not match backup info");await this.backupManager.saveBackupDecryptionKey(i,t.version)}async getActiveSessionBackupVersion(){return await this.backupManager.getActiveBackupVersion()}async getKeyBackupInfo(){return await this.backupManager.getServerBackupInfo()||null}async isKeyBackupTrusted(e){return await this.backupManager.isKeyBackupTrusted(e)}async checkKeyBackupAndEnable(){return await this.backupManager.checkKeyBackupAndEnable(!0)}async deleteKeyBackupVersion(e){await this.backupManager.deleteKeyBackupVersion(e)}async resetKeyBackup(){const e=await this.backupManager.setupKeyBackup(e=>this.signObject(e));await this.secretStorageHasAESKey()&&await this.secretStorage.store("m.megolm_backup.v1",e.decryptionKey.toBase64()),this.checkKeyBackupAndEnable()}async disableKeyStorage(){const e=await this.getKeyBackupInfo();null!=e&&e.version?await this.deleteKeyBackupVersion(e.version):this.logger.error("Can't delete key backup version: no version available"),await this.deleteSecretStorage(),await this.dehydratedDeviceManager.delete()}async signObject(e){const t=new Map(Object.entries(e.signatures||{})),i=e.unsigned;delete e.signatures,delete e.unsigned;const s=t.get(this.userId)||{},r=o().stringify(e),n=await this.olmMachine.sign(r),a=JSON.parse(n.asJSON());t.set(this.userId,ie(ie({},s),a[this.userId])),void 0!==i&&(e.unsigned=i),e.signatures=Object.fromEntries(t.entries())}async restoreKeyBackupWithPassphrase(e,t){const i=await this.backupManager.getServerBackupInfo();if(null==i||!i.version)throw new Error("No backup info available");const s=await function(e,t){if(!e.private_key_salt||!e.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return(0,p.wn)(t,e.private_key_salt,e.private_key_iterations,e.private_key_bits)}(i.auth_data,e);return await this.storeSessionBackupPrivateKey(s,i.version),this.restoreKeyBackup(t)}async restoreKeyBackup(e){const t=await this.olmMachine.getBackupKeys(),{decryptionKey:i,backupVersion:s}=t;if(!i||!s)throw new Error("No decryption key found in crypto store");const r=(0,f.y4)(i.toBase64()),n=await this.backupManager.requestKeyBackupVersion(s);if(!n)throw new Error(`Backup version to restore ${s} not found on server`);const o=await this.getBackupDecryptor(n,r);try{var a;return null==e||null===(a=e.progressCallback)||void 0===a||a.call(e,{stage:p.wF.Fetch}),await this.backupManager.restoreKeyBackup(s,o,e)}finally{o.free()}}async isDehydrationSupported(){return await this.dehydratedDeviceManager.isSupported()}async startDehydration(e={}){if(!await this.isCrossSigningReady()||!await this.isSecretStorageReady())throw new Error("Device dehydration requires cross-signing and secret storage to be set up");return await this.dehydratedDeviceManager.start(e||{})}async importSecretsBundle(e){const t=r.gAt.from_json(e);await this.getOlmMachineOrThrow().importSecretsBundle(t)}async exportSecretsBundle(){const e=await this.getOlmMachineOrThrow().exportSecretsBundle(),t=e.to_json();return e.free(),t}async encryptToDeviceMessages(e,t,i){const s=new u.Tl(this.logger,"encryptToDeviceMessages"),n=new Set(t.map(({userId:e})=>e));await this.keyClaimManager.ensureSessionsForUsers(s,Array.from(n).map(e=>new r.VvS(e)));const o={batch:[],eventType:d.Bx.RoomMessageEncrypted};return await Promise.all(t.map(async({userId:t,deviceId:s})=>{const n=await this.olmMachine.getDevice(new r.VvS(t),new r._rJ(s));if(n){const r=JSON.parse(await n.encryptToDeviceEvent(e,i));o.batch.push({deviceId:s,userId:t,payload:r})}else this.logger.warn(`encryptToDeviceMessages: unknown device ${t}:${s}`)})),o}async resetEncryption(e){this.logger.debug("resetEncryption: resetting encryption"),this.dehydratedDeviceManager.delete(),await this.backupManager.deleteAllKeyBackupVersions(),await this.deleteSecretStorage(),await this.crossSigningIdentity.bootstrapCrossSigning({setupNewCrossSigning:!0,authUploadDeviceSigningKeys:e}),await this.resetKeyBackup(),this.logger.debug("resetEncryption: ended")}async deleteSecretStorage(){await this.secretStorage.store("m.cross_signing.master",null),await this.secretStorage.store("m.cross_signing.self_signing",null),await this.secretStorage.store("m.cross_signing.user_signing",null),await this.secretStorage.store("m.megolm_backup.v1",null);const e=await this.secretStorage.getDefaultKeyId();e&&await this.secretStorage.store(`m.secret_storage.key.${e}`,null),await this.secretStorage.setDefaultKeyId(null)}async shareRoomHistoryWithUser(e,t){const i=new u.Tl(this.logger,`shareRoomHistoryWithUser(${e}, ${t})`),s=await this.getOwnIdentity();if(null==s||!s.isVerified())return void i.warn("Not sharing message history as the current device is not verified by our cross-signing identity");i.info("Sharing message history");const n=await this.getOlmMachineOrThrow().buildRoomKeyBundle(new r.BVS(e));if(!n)return void i.info("No keys to share");const o=await this.http.uploadContent(n.encryptedData);i.info(`Uploaded encrypted key blob: ${JSON.stringify(o)}`);const a=this.getOlmMachineOrThrow().queryKeysForUsers([new r.VvS(t)]);await this.outgoingRequestProcessor.makeOutgoingRequest(a),await this.keyClaimManager.ensureSessionsForUsers(i,[new r.VvS(t)]);const c=await this.getOlmMachineOrThrow().shareRoomKeyBundleData(new r.VvS(t),new r.BVS(e),o.content_uri,n.mediaEncryptionInfo,r.EZX.identityBasedStrategy());for(const e of c)await this.outgoingRequestProcessor.makeOutgoingRequest(e)}async receiveSyncChanges({events:e,oneTimeKeysCounts:t=new Map,unusedFallbackKeys:i,devices:s=new r.K_K}){return await this.olmMachine.receiveSyncChanges(e?JSON.stringify(e):"[]",s,t,i)}async preprocessToDeviceMessages(e){const t=await this.receiveSyncChanges({events:e}),i=[];for(const e of t){const t=JSON.parse(e.rawEvent);if(t.type===d.Bx.KeyVerificationRequest){const e=t.sender,i=t.content.transaction_id;i&&e&&this.onIncomingKeyVerificationRequest(e,i)}switch(e.type){case r.U3i.Decrypted:{var s;const r=e.encryptionInfo;i.push({message:t,encryptionInfo:{sender:r.sender.toString(),senderDevice:null===(s=r.senderDevice)||void 0===s?void 0:s.toString(),senderCurve25519KeyBase64:r.senderCurve25519Key,senderVerified:r.isSenderVerified()}});break}case r.U3i.PlainText:i.push({message:t,encryptionInfo:null});case r.U3i.UnableToDecrypt:case r.U3i.Invalid:}}return i}async processKeyCounts(e,t){const i=e&&new Map(Object.entries(e)),s=t&&new Set(t);void 0===i&&void 0===s||await this.receiveSyncChanges({oneTimeKeysCounts:i,unusedFallbackKeys:s})}async processDeviceLists(e){var t,i;const s=new r.K_K(null===(t=e.changed)||void 0===t?void 0:t.map(e=>new r.VvS(e)),null===(i=e.left)||void 0===i?void 0:i.map(e=>new r.VvS(e)));await this.receiveSyncChanges({devices:s})}async onCryptoEvent(e,t){const i=t.getContent(),s=new r.lRJ;if("m.megolm.v1.aes-sha2"!==i.algorithm)return void this.logger.warn(`Room ${e.roomId}: ignoring crypto event with invalid algorithm ${i.algorithm}`);s.algorithm=r.liC.MegolmV1AesSha2,i["io.element.msc3414.encrypt_state_events"]&&this.enableEncryptedStateEvents&&(this.logger.info("crypto Enabling state event encryption..."),s.encryptStateEvents=!0);try{s.sessionRotationPeriodMs=i.rotation_period_ms,s.sessionRotationPeriodMessages=i.rotation_period_msgs,await this.olmMachine.setRoomSettings(new r.BVS(e.roomId),s)}catch(t){return void this.logger.warn(`Room ${e.roomId}: ignoring crypto event which caused error: ${t}`)}const n=this.roomEncryptors[e.roomId];n?n.onCryptoEvent(i):this.roomEncryptors[e.roomId]=new m(this.logger.getChild(`[${e.roomId} encryption]`),this.olmMachine,this.keyClaimManager,this.outgoingRequestsManager,e,i)}onSyncCompleted(e){this.outgoingRequestsManager.doProcessOutgoingRequests().catch(e=>{this.logger.warn("onSyncCompleted: Error processing outgoing requests",e)})}async markAllTrackedUsersAsDirty(){await this.olmMachine.markAllTrackedUsersAsDirty()}onIncomingKeyVerificationRequest(e,t){const i=this.olmMachine.getVerificationRequest(new r.VvS(e),t);i?this.emit(p.cr.VerificationRequestReceived,this.makeVerificationRequest(i)):this.logger.info(`Ignoring just-received verification request ${t} which did not start a rust-side verification`)}makeVerificationRequest(e){return new q(this.logger,this.olmMachine,e,this.outgoingRequestProcessor,this._supportedVerificationMethods)}onRoomMembership(e,t,i){const s=this.roomEncryptors[e.getRoomId()];s&&s.onRoomMembership(t)}async onRoomKeysUpdated(e){for(const t of e)this.onRoomKeyUpdated(t);this.backupManager.maybeUploadKey()}onRoomKeyUpdated(e){if(this.stopped)return;this.logger.debug(`Got update for session ${e.sessionId} from sender ${e.senderKey.toBase64()} in ${e.roomId.toString()}`);const t=this.eventDecryptor.getEventsPendingRoomKey(e.roomId.toString(),e.sessionId);if(0!==t.length){this.logger.debug("Retrying decryption on events:",t.map(e=>`${e.getId()}`));for(const e of t)e.attemptDecryption(this,{isRetry:!0}).catch(t=>{this.logger.info(`Still unable to decrypt event ${e.getId()} after receiving key`)})}}async onRoomKeysWithheld(e){for(const t of e){this.logger.debug(`Got withheld message for session ${t.sessionId} in ${t.roomId.toString()}`);const e=this.eventDecryptor.getEventsPendingRoomKey(t.roomId.toString(),t.sessionId);if(0===e.length)return;this.logger.debug("Retrying decryption on events:",e.map(e=>`${e.getId()}`));for(const t of e)t.attemptDecryption(this,{isRetry:!0}).catch(e=>{})}}async onUserIdentityUpdated(e){const t=await this.getUserVerificationStatus(e.toString());this.emit(p.cr.UserTrustStatusChanged,e.toString(),t),e.toString()===this.userId&&(this.emit(p.cr.KeysChanged,{}),await this.checkKeyBackupAndEnable())}async onDevicesUpdated(e){this.emit(p.cr.WillUpdateDevices,e,!1),this.emit(p.cr.DevicesUpdated,e,!1)}async handleSecretReceived(e,t){return this.logger.debug(`onReceiveSecret: Received secret ${e}`),"m.megolm_backup.v1"===e&&await this.backupManager.handleBackupSecretReceived(t)}async checkSecrets(e){const t=await this.olmMachine.getSecretsFromInbox(e);for(const i of t)if(await this.handleSecretReceived(e,i))break;await this.olmMachine.deleteSecretsFromInbox(e)}async onLiveEventFromSync(e){if(e.isState()||e.getUnsigned().transaction_id)return;const t=async t=>{(function(e){switch(e.getType()){case d.Bx.KeyVerificationCancel:case d.Bx.KeyVerificationDone:case d.Bx.KeyVerificationMac:case d.Bx.KeyVerificationStart:case d.Bx.KeyVerificationKey:case d.Bx.KeyVerificationReady:case d.Bx.KeyVerificationAccept:return!0;case d.Bx.RoomMessage:return e.getContent().msgtype===d.Wr.KeyVerificationRequest;default:return!1}})(e)&&await this.onKeyVerificationEvent(t)};if(e.isDecryptionFailure()||e.isEncrypted()){const i=setTimeout(()=>e.off(c.OQ.Decrypted,s),3e5),s=(r,n)=>{n||(clearTimeout(i),e.off(c.OQ.Decrypted,s),t(r))};e.on(c.OQ.Decrypted,s)}else await t(e)}async onKeyVerificationEvent(e){const t=e.getRoomId(),i=e.getSender();if(!t)throw new Error("missing roomId in the event");if(!i)throw new Error("missing sender in the event");this.logger.debug(`Incoming verification event ${e.getId()} type ${e.getType()} from ${e.getSender()}`);const s=e.getType()===d.Bx.RoomMessage&&e.getContent().msgtype===d.Wr.KeyVerificationRequest;if(s){const e=this.getOlmMachineOrThrow().queryKeysForUsers([new r.VvS(i)]);await this.outgoingRequestProcessor.makeOutgoingRequest(e)}await this.getOlmMachineOrThrow().receiveVerificationEvent(JSON.stringify({event_id:e.getId(),type:e.getType(),sender:i,state_key:e.getStateKey(),content:e.getContent(),origin_server_ts:e.getTs()}),new r.BVS(t)),s&&this.onIncomingKeyVerificationRequest(i,e.getId()),this.outgoingRequestsManager.doProcessOutgoingRequests().catch(e=>{this.logger.warn("onKeyVerificationRequest: Error processing outgoing requests",e)})}async getOwnIdentity(){return await this.olmMachine.getIdentity(new r.VvS(this.userId))}}class ne{constructor(e,t,i){(0,s.A)(this,"eventsPendingKey",new y.kG(()=>new y.kG(()=>new Set))),this.logger=e,this.olmMachine=t,this.perSessionBackupDownloader=i}async attemptEventDecryption(e,t){let i;switch(this.addEventToPendingList(e),t.kind){case p.YH.AllDevicesIsolationMode:i=r.wJu.Untrusted;break;case p.YH.OnlySignedDevicesIsolationMode:i=r.wJu.CrossSignedOrLegacy}try{const t=await this.olmMachine.decryptRoomEvent(oe(e),new r.BVS(e.getRoomId()),new r.fPF(i));return this.removeEventFromPendingList(e),{clearEvent:JSON.parse(t.event),claimedEd25519Key:t.senderClaimedEd25519Key,senderCurve25519Key:t.senderCurve25519Key,forwardingCurve25519KeyChain:t.forwardingCurve25519KeyChain}}catch(t){if(!(t instanceof r.Rjy))throw new g.O(p.RT.UNKNOWN_ERROR,"Unknown error");this.onMegolmDecryptionError(e,t,await this.perSessionBackupDownloader.getServerBackupInfo())}}onMegolmDecryptionError(e,t,i){const s=e.getWireContent(),n={sender_key:s.sender_key,session_id:s.session_id};if(t.code===r.Fff.MissingRoomKey||t.code===r.Fff.UnknownMessageIndex){this.perSessionBackupDownloader.onDecryptionKeyMissingError(e.getRoomId(),s.session_id);const t=e.getMembershipAtEvent();if(t&&t!==a.O.Join&&t!==a.O.Invite)throw new g.O(p.RT.HISTORICAL_MESSAGE_USER_NOT_JOINED,"This message was sent when we were not a member of the room.",n);if(e.getTs()<=this.olmMachine.deviceCreationTimeMs)throw null===i?new g.O(p.RT.HISTORICAL_MESSAGE_NO_KEY_BACKUP,"This message was sent before this device logged in, and there is no key backup on the server.",n):this.perSessionBackupDownloader.isKeyBackupDownloadConfigured()?new g.O(p.RT.HISTORICAL_MESSAGE_WORKING_BACKUP,"This message was sent before this device logged in. Key backup is working, but we still do not (yet) have the key.",n):new g.O(p.RT.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED,"This message was sent before this device logged in, and key backup is not working.",n)}if(t.maybe_withheld){const e="The sender has disabled encrypting to unverified devices."===t.maybe_withheld?p.RT.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE:p.RT.MEGOLM_KEY_WITHHELD;throw new g.O(e,t.maybe_withheld,n)}switch(t.code){case r.Fff.MissingRoomKey:throw new g.O(p.RT.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,"The sender's device has not sent us the keys for this message.",n);case r.Fff.UnknownMessageIndex:throw new g.O(p.RT.OLM_UNKNOWN_MESSAGE_INDEX,"The sender's device has not sent us the keys for this message at this index.",n);case r.Fff.SenderIdentityVerificationViolation:throw this.removeEventFromPendingList(e),new g.O(p.RT.SENDER_IDENTITY_PREVIOUSLY_VERIFIED,"The sender identity is unverified, but was previously verified.");case r.Fff.UnknownSenderDevice:throw this.removeEventFromPendingList(e),new g.O(p.RT.UNKNOWN_SENDER_DEVICE,"The sender device is not known.");case r.Fff.UnsignedSenderDevice:throw this.removeEventFromPendingList(e),new g.O(p.RT.UNSIGNED_SENDER_DEVICE,"The sender identity is not cross-signed.");default:throw new g.O(p.RT.UNKNOWN_ERROR,t.description,n)}}async getEncryptionInfoForEvent(e){if(!e.getClearContent()||e.isDecryptionFailure())return null;if(null!==e.status)return{shieldColour:p.so.NONE,shieldReason:null};const t=await this.olmMachine.getRoomEventEncryptionInfo(oe(e),new r.BVS(e.getRoomId()));return function(e,t){if(void 0===t)return null;const i=t.shieldState(!1);let s,n;switch(i.color){case r.TCc.Grey:s=p.so.GREY;break;case r.TCc.None:s=p.so.NONE;break;default:s=p.so.RED}switch(i.code){case void 0:case null:n=null;break;case r.gPr.AuthenticityNotGuaranteed:n=p.uV.AUTHENTICITY_NOT_GUARANTEED;break;case r.gPr.UnknownDevice:n=p.uV.UNKNOWN_DEVICE;break;case r.gPr.UnsignedDevice:n=p.uV.UNSIGNED_DEVICE;break;case r.gPr.UnverifiedIdentity:n=p.uV.UNVERIFIED_IDENTITY;break;case r.gPr.SentInClear:n=p.uV.SENT_IN_CLEAR;break;case r.gPr.VerificationViolation:n=p.uV.VERIFICATION_VIOLATION;break;case r.gPr.MismatchedSender:n=p.uV.MISMATCHED_SENDER;break;default:n=p.uV.UNKNOWN}return{shieldColour:s,shieldReason:n}}(this.logger,t)}getEventsPendingRoomKey(e,t){const i=this.eventsPendingKey.get(e);if(!i)return[];const s=i.get(t);return s?[...s]:[]}addEventToPendingList(e){const t=e.getRoomId();if(!t)return;this.eventsPendingKey.getOrCreate(t).getOrCreate(e.getWireContent().session_id).add(e)}removeEventFromPendingList(e){const t=e.getRoomId();if(!t)return;const i=this.eventsPendingKey.getOrCreate(t);if(!i)return;const s=i.get(e.getWireContent().session_id);s&&(s.delete(e),0===s.size&&(i.delete(e.getWireContent().session_id),0===i.size&&this.eventsPendingKey.delete(t)))}}function oe(e){return JSON.stringify({event_id:e.getId(),type:e.getWireType(),sender:e.getSender(),state_key:e.getStateKey(),content:e.getWireContent(),origin_server_ts:e.getTs()})}var ae=i("./node_modules/matrix-js-sdk/src/crypto/store/base.ts"),ce=i("./node_modules/matrix-js-sdk/src/crypto/store/indexeddb-crypto-store.ts"),ge=i("./node_modules/matrix-js-sdk/src/utils/decryptAESSecretStorageItem.ts");async function ue(e){var t;const{logger:i,legacyStore:s}=e;if(await r.VOM(),!await s.containsData())return;await s.startup();let n=null;if(await s.doTxn("readonly",[ce.y.STORE_ACCOUNT],e=>{s.getAccount(e,e=>{n=e})}),!n)return void i.debug("Legacy crypto store is not set up (no account found). Not migrating.");let o=await s.getMigrationState();if(o>=ae.Il.MEGOLM_SESSIONS_MIGRATED)return;const a=await async function(e,t){let i;return e.debug("Counting olm sessions to be migrated"),await t.doTxn("readonly",[ce.y.STORE_SESSIONS],e=>t.countEndToEndSessions(e,e=>i=e)),i}(i,s),c=await async function(e,t){return e.debug("Counting megolm sessions to be migrated"),await t.countEndToEndInboundGroupSessions()}(i,s),g=1+a+c;i.info(`Migrating data from legacy crypto store. ${a} olm sessions and ${c} megolm sessions to migrate.`);let u=0;function h(t){var i;u+=t,null===(i=e.legacyMigrationProgressListener)||void 0===i||i.call(e,u,g)}h(0);const d=(new TextEncoder).encode(e.legacyPickleKey);o===ae.Il.NOT_STARTED&&(i.info("Migrating data from legacy crypto store. Step 1: base data"),await async function(e,t,i,s,n,o,a){const c=new r.GYR;c.userId=new r.VvS(t),c.deviceId=new r._rJ(i),await s.doTxn("readonly",[ce.y.STORE_ACCOUNT],e=>s.getAccount(e,e=>{c.pickledAccount=null!=e?e:""}));const g=await he(s,n,"m.megolm_backup.v1");if(g){let t=!1,i=null;for(;!t;)try{i=await F(e),t=!0}catch(e){a.info("Failed to get backup version during migration, retrying in 2 seconds",e),await(0,y.yy)(2e3)}if(i&&"m.megolm_backup.v1.curve25519-aes-sha2"==i.algorithm)try{var u;const e=r.xqv.fromBase64(g),t=null===(u=i.auth_data)||void 0===u?void 0:u.public_key;e.megolmV1PublicKey.publicKeyBase64==t?(c.backupVersion=i.version,c.backupRecoveryKey=g):a.debug("The backup key to migrate does not match the active backup version",`Cached pub key: ${e.megolmV1PublicKey.publicKeyBase64}`,`Active pub key: ${t}`)}catch(e){a.warn("Failed to check if the backup key to migrate matches the active backup version",e)}}c.privateCrossSigningMasterKey=await he(s,n,"master"),c.privateCrossSigningSelfSigningKey=await he(s,n,"self_signing"),c.privateCrossSigningUserSigningKey=await he(s,n,"user_signing"),await r.Nhn.migrateBaseData(c,n,o,a)}(e.http,e.userId,e.deviceId,s,d,e.storeHandle,i),o=ae.Il.INITIAL_DATA_MIGRATED,await s.setMigrationState(o)),h(1),o===ae.Il.INITIAL_DATA_MIGRATED&&(i.info(`Migrating data from legacy crypto store. Step 2: olm sessions (${a} sessions to migrate).`),await async function(e,t,i,s,n){for(;;){const o=await t.getEndToEndSessionsBatch();if(null===o)return;e.debug(`Migrating batch of ${o.length} olm sessions`);const a=[];for(const e of o){const t=new r.BZT;t.senderKey=e.deviceKey,t.pickle=e.session,t.lastUseTime=t.creationTime=new Date(e.lastReceivedMessageTs),a.push(t)}await r.Nhn.migrateOlmSessions(a,i,s,e),await t.deleteEndToEndSessionsBatch(o),n(o.length)}}(i,s,d,e.storeHandle,h),o=ae.Il.OLM_SESSIONS_MIGRATED,await s.setMigrationState(o)),o===ae.Il.OLM_SESSIONS_MIGRATED&&(i.info(`Migrating data from legacy crypto store. Step 3: megolm sessions (${c} sessions to migrate).`),await async function(e,t,i,s,n){for(;;){const a=await t.getEndToEndInboundGroupSessionsBatch();if(null===a)return;e.debug(`Migrating batch of ${a.length} megolm sessions`);const c=[];for(const e of a){var o;const t=e.sessionData,i=new r.HmP;i.pickle=t.session,i.roomId=new r.BVS(t.room_id),i.senderKey=e.senderKey,i.senderSigningKey=null===(o=t.keysClaimed)||void 0===o?void 0:o.ed25519,i.backedUp=!e.needsBackup,i.imported=!0===t.untrusted,c.push(i)}await r.Nhn.migrateMegolmSessions(c,i,s,e),await t.deleteEndToEndInboundGroupSessionsBatch(a),n(a.length)}}(i,s,d,e.storeHandle,h),o=ae.Il.MEGOLM_SESSIONS_MIGRATED,await s.setMigrationState(o)),null===(t=e.legacyMigrationProgressListener)||void 0===t||t.call(e,-1,-1),i.info("Migration from legacy crypto store complete")}async function he(e,t,i){const s=await new Promise(t=>{e.doTxn("readonly",[ce.y.STORE_ACCOUNT],s=>{e.getSecretStorePrivateKey(s,t,i)})});return s&&s.ciphertext&&s.iv&&s.mac?await(0,ge.A)(s,t,i):s instanceof Uint8Array?(0,f.WG)(s):void 0}async function de(e){const{legacyCryptoStore:t,rustCrypto:i,logger:s}=e,r=await i.getOwnIdentity();if(!r)return;if(r.isVerified())return;const n=await async function(e){let t=null;return await e.doTxn("readonly","account",i=>{e.getCrossSigningKeys(i,e=>{const i=null==e?void 0:e.master;i&&0!=Object.keys(i.keys).length&&(t=Object.values(i.keys)[0])})}),t}(t);if(!n)return;const o=JSON.parse(r.masterKey);if(!o.keys||0===Object.keys(o.keys).length)return void s.error("Post Migration | Unexpected error: no master key in the rust session.");const a=Object.values(o.keys)[0];a&&a==n&&(s.info(`Post Migration: Migrating legacy trusted MSK: ${n} to locally verified.`),await r.verify())}function le(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}async function ye(e){const{logger:t}=e;let i;t.debug("Initialising Rust crypto-sdk WASM artifact"),await r.VOM(),t.debug("Opening Rust CryptoStore"),i=e.storePrefix?e.storeKey?await r.QvV.openWithKey(e.storePrefix,e.storeKey,t):await r.QvV.open(e.storePrefix,e.storePassphrase,t):await r.QvV.open(null,null,t),e.legacyCryptoStore&&await ue(function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?le(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):le(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({legacyStore:e.legacyCryptoStore,storeHandle:i},e));const n=await async function(e,t,i,s,n,o,a,c,g){e.debug("Init OlmMachine");const u=await r.W9F.initFromStore(new r.VvS(i),new r._rJ(s),a,e);c&&await async function({logger:e,legacyStore:t,olmMachine:i}){if(!await t.containsData())return;if(await t.getMigrationState()>=ae.Il.ROOM_SETTINGS_MIGRATED)return;let s={};await t.doTxn("readwrite",[ce.y.STORE_ROOMS],e=>{t.getEndToEndRooms(e,e=>{s=e})}),e.debug(`Migrating ${Object.keys(s).length} sets of room settings`);for(const[t,n]of Object.entries(s))try{const s=new r.lRJ;if("m.megolm.v1.aes-sha2"!==n.algorithm){e.warn(`Room ${t}: ignoring room with invalid algorithm ${n.algorithm}`);continue}s.algorithm=r.liC.MegolmV1AesSha2,s.sessionRotationPeriodMs=n.rotation_period_ms,s.sessionRotationPeriodMessages=n.rotation_period_msgs,await i.setRoomSettings(new r.BVS(t),s)}catch(i){e.warn(`Room ${t}: ignoring settings ${JSON.stringify(n)} which caused error ${i}`)}e.debug("Completed room settings migration"),await t.setMigrationState(ae.Il.ROOM_SETTINGS_MIGRATED)}({logger:e,legacyStore:c,olmMachine:u});u.roomKeyRequestsEnabled=!1;const h=new re(e,u,t,i,s,n,o,g);if(await u.registerRoomKeyUpdatedCallback(e=>h.onRoomKeysUpdated(e)),await u.registerRoomKeysWithheldCallback(e=>h.onRoomKeysWithheld(e)),await u.registerUserIdentityUpdatedCallback(e=>h.onUserIdentityUpdated(e)),await u.registerDevicesUpdatedCallback(e=>h.onDevicesUpdated(e)),h.checkSecrets("m.megolm_backup.v1"),await u.registerReceiveSecretCallback((e,t)=>h.checkSecrets(e)),await u.outgoingRequests(),c&&await c.containsData()){if(await c.getMigrationState()<ae.Il.INITIAL_OWN_KEY_QUERY_DONE){e.debug("Performing initial key query after migration");let t=!1;for(;!t;)try{await h.userHasCrossSigningKeys(i),t=!0}catch(t){e.error("Failed to check for cross-signing keys after migration, retrying",t)}await de({legacyCryptoStore:c,rustCrypto:h,logger:e}),await c.setMigrationState(ae.Il.INITIAL_OWN_KEY_QUERY_DONE)}}return h}(t,e.http,e.userId,e.deviceId,e.secretStorage,e.cryptoCallbacks,i,e.legacyCryptoStore,e.enableEncryptedStateEvents);return i.free(),t.debug("Completed rust crypto-sdk setup"),n}}}]);
//# sourceMappingURL=1787.js.map