@element-hq/element-call-embedded 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- import{d as Mr,e as c,g as Ir,h as g,K as se,L as cr,j as M,D as oe,E as b,H as Y,T as W,k as p,m,n as pe,o as ae,p as Cr,q as Dr,s as P,r as te,u as ur,v as dr,w as lr,I as A,M as gr,x as j,A as Br,y as Or,z as fe,B as qr,U as Ve,F as $,S as Ne,G as xe,J as ue,N as Ae,O as _,P as S,Q as ie,R as C,V as J,W as R,X as Tr}from"./index-BraSv6wc.js";import{U as v,E as Pr,a as G,C as Le,R as w,H as z,D as Fe,b as B,K as Ur,c as Vr,d as Nr,S as xr,e as Ar,T as Lr,f as Fr,g as jr,P as Gr,V as Z,h as je,Q as Ge,i as O,j as Wr,k as U,B as V,l as Jr,L as We,O as Hr,m as Qr,n as Yr,o as $r,p as Je,q as X,r as yr,s as He,t as zr,M as Zr,u as q,v as Qe,w as T,x as hr,y as Xr,z as qe,A as et,F as rt,G as de,I as tt}from"./matrix-sdk-crypto-wasm-DlvlUyhf.js";try{let s=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="566462ba-f36f-4894-bb56-700f81bb6c6e",s._sentryDebugIdIdentifier="sentry-dbid-566462ba-f36f-4894-bb56-700f81bb6c6e")}catch{}var L=function(s){return s.Change="change",s}({}),k=function(s){return s[s.Unsent=1]="Unsent",s[s.Requested=2]="Requested",s[s.Ready=3]="Ready",s[s.Started=4]="Started",s[s.Cancelled=5]="Cancelled",s[s.Done=6]="Done",s}({}),pr=function(s){return s.Cancel="cancel",s.ShowSas="show_sas",s.ShowReciprocateQr="show_reciprocate_qr",s}({}),le=[139,1];function Ye(s){var e,r=new Uint8Array(le.length+s.length+1);r.set(le,0),r.set(s,le.length);for(var t=0,i=0;i<r.length-1;++i)t^=r[i];r[r.length-1]=t;var n=Mr.encode(r);return(e=n.match(/.{1,4}/g))===null||e===void 0?void 0:e.join(" ")}var it=256;function fr(s,e,r){return ve.apply(this,arguments)}function ve(){return ve=c(function*(s,e,r){var t=arguments.length>3&&arguments[3]!==void 0?arguments[3]:it;if(!globalThis.crypto.subtle||!TextEncoder)throw new Error("Password-based backup is not available on this platform");var i=yield globalThis.crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"PBKDF2"},!1,["deriveBits"]),n=yield globalThis.crypto.subtle.deriveBits({name:"PBKDF2",salt:new TextEncoder().encode(e),iterations:r,hash:"SHA-512"},i,t);return new Uint8Array(n)}),ve.apply(this,arguments)}var ge,$e;function nt(){if($e)return ge;$e=1;for(var s=/[\\\"\x00-\x1F]/g,e={},r=0;r<32;++r)e[String.fromCharCode(r)]="\\U"+("0000"+r.toString(16)).slice(-4).toUpperCase();e["\b"]="\\b",e[" "]="\\t",e[`
1
+ import{d as Mr,e as c,g as Ir,h as g,K as se,L as cr,j as M,D as oe,E as b,H as Y,T as W,k as p,m,n as pe,o as ae,p as Cr,q as Dr,s as P,r as te,u as ur,v as dr,w as lr,I as A,M as gr,x as j,A as Br,y as Or,z as fe,B as qr,U as Ve,F as $,S as Ne,G as xe,J as ue,N as Ae,O as _,P as S,Q as ie,R as C,V as J,W as R,X as Tr}from"./index-VC5-R1Nr.js";import{U as v,E as Pr,a as G,C as Le,R as w,H as z,D as Fe,b as B,K as Ur,c as Vr,d as Nr,S as xr,e as Ar,T as Lr,f as Fr,g as jr,P as Gr,V as Z,h as je,Q as Ge,i as O,j as Wr,k as U,B as V,l as Jr,L as We,O as Hr,m as Qr,n as Yr,o as $r,p as Je,q as X,r as yr,s as He,t as zr,M as Zr,u as q,v as Qe,w as T,x as hr,y as Xr,z as qe,A as et,F as rt,G as de,I as tt}from"./matrix-sdk-crypto-wasm-DlvlUyhf.js";try{let s=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="566462ba-f36f-4894-bb56-700f81bb6c6e",s._sentryDebugIdIdentifier="sentry-dbid-566462ba-f36f-4894-bb56-700f81bb6c6e")}catch{}var L=function(s){return s.Change="change",s}({}),k=function(s){return s[s.Unsent=1]="Unsent",s[s.Requested=2]="Requested",s[s.Ready=3]="Ready",s[s.Started=4]="Started",s[s.Cancelled=5]="Cancelled",s[s.Done=6]="Done",s}({}),pr=function(s){return s.Cancel="cancel",s.ShowSas="show_sas",s.ShowReciprocateQr="show_reciprocate_qr",s}({}),le=[139,1];function Ye(s){var e,r=new Uint8Array(le.length+s.length+1);r.set(le,0),r.set(s,le.length);for(var t=0,i=0;i<r.length-1;++i)t^=r[i];r[r.length-1]=t;var n=Mr.encode(r);return(e=n.match(/.{1,4}/g))===null||e===void 0?void 0:e.join(" ")}var it=256;function fr(s,e,r){return ve.apply(this,arguments)}function ve(){return ve=c(function*(s,e,r){var t=arguments.length>3&&arguments[3]!==void 0?arguments[3]:it;if(!globalThis.crypto.subtle||!TextEncoder)throw new Error("Password-based backup is not available on this platform");var i=yield globalThis.crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"PBKDF2"},!1,["deriveBits"]),n=yield globalThis.crypto.subtle.deriveBits({name:"PBKDF2",salt:new TextEncoder().encode(e),iterations:r,hash:"SHA-512"},i,t);return new Uint8Array(n)}),ve.apply(this,arguments)}var ge,$e;function nt(){if($e)return ge;$e=1;for(var s=/[\\\"\x00-\x1F]/g,e={},r=0;r<32;++r)e[String.fromCharCode(r)]="\\U"+("0000"+r.toString(16)).slice(-4).toUpperCase();e["\b"]="\\b",e[" "]="\\t",e[`
2
2
  `]="\\n",e["\f"]="\\f",e["\r"]="\\r",e['"']='\\"',e["\\"]="\\\\";function t(a){return s.lastIndex=0,a.replace(s,function(u){return e[u]})}function i(a){switch(typeof a){case"string":return'"'+t(a)+'"';case"number":return isFinite(a)?a:"null";case"boolean":return a;case"object":return a===null?"null":Array.isArray(a)?n(a):o(a);default:throw new Error("Cannot stringify: "+typeof a)}}function n(a){for(var u="[",d="",l=0;l<a.length;++l)d+=u,u=",",d+=i(a[l]);return u!=","?"[]":d+"]"}function o(a){var u="{",d="",l=Object.keys(a);l.sort();for(var h=0;h<l.length;++h){var y=l[h];d+=u+'"'+t(y)+'":',u=",",d+=i(a[y])}return u!=","?"{}":d+"}"}return ge={stringify:i},ge}var st=nt();const ot=Ir(st);class at{constructor(e,r,t,i,n,o){this.prefixedLogger=e,this.olmMachine=r,this.keyClaimManager=t,this.outgoingRequestManager=i,this.room=n,this.encryptionSettings=o,g(this,"lazyLoadedMembersResolved",!1),g(this,"currentEncryptionPromise",Promise.resolve());var a=n.getJoinedMembers();this.olmMachine.updateTrackedUsers(a.map(u=>new v(u.userId))).catch(u=>this.prefixedLogger.error("Error initializing tracked users",u))}onCryptoEvent(e){if(JSON.stringify(this.encryptionSettings)!=JSON.stringify(e))throw new Error("Cannot reconfigure an active RoomEncryptor")}onRoomMembership(e){(e.membership==se.Join||e.membership==se.Invite&&this.room.shouldEncryptForInvitedMembers())&&this.olmMachine.updateTrackedUsers([new v(e.userId)]).catch(r=>{this.prefixedLogger.error("Unable to update tracked users",r)})}prepareForEncryption(e,r){var t=this;return c(function*(){yield t.encryptEvent(null,e,r)})()}encryptEvent(e,r,t){var i,n=this,o=new cr(this.prefixedLogger,e?(i=e.getTxnId())!==null&&i!==void 0?i:"":"prepareForEncryption"),a=this.currentEncryptionPromise.catch(()=>{}).then(c(function*(){yield M(o,"ensureEncryptionSession",c(function*(){yield n.ensureEncryptionSession(o,r,t)})),e&&(yield M(o,"encryptEventInner",c(function*(){yield n.encryptEventInner(o,e)})))}));return this.currentEncryptionPromise=a,a}ensureEncryptionSession(e,r,t){var i=this;return c(function*(){if(i.encryptionSettings.algorithm!=="m.megolm.v1.aes-sha2")throw new Error("Cannot encrypt in ".concat(i.room.roomId," for unsupported algorithm '").concat(i.encryptionSettings.algorithm,"'"));e.debug("Starting encryption");var n=yield i.room.getEncryptionTargetMembers();i.lazyLoadedMembersResolved?(e.debug("Processing outgoing requests in background"),i.outgoingRequestManager.doProcessOutgoingRequests()):(yield M(e,"loadMembersIfNeeded: updateTrackedUsers",c(function*(){yield i.olmMachine.updateTrackedUsers(n.map(l=>new v(l.userId)))})),e.debug("Updated tracked users"),i.lazyLoadedMembersResolved=!0,e.debug("Processing outgoing requests"),yield M(e,"doProcessOutgoingRequests",c(function*(){yield i.outgoingRequestManager.doProcessOutgoingRequests()}))),e.debug("Encrypting for users (shouldEncryptForInvitedMembers: ".concat(i.room.shouldEncryptForInvitedMembers(),"):"),n.map(l=>"".concat(l.userId," (").concat(l.membership,")")));var o=n.map(l=>new v(l.userId));yield M(e,"ensureSessionsForUsers",c(function*(){yield i.keyClaimManager.ensureSessionsForUsers(e,o)}));var a=new Pr;switch(a.historyVisibility=ct(i.room.getHistoryVisibility()),a.algorithm=G.MegolmV1AesSha2,typeof i.encryptionSettings.rotation_period_ms=="number"&&(a.rotationPeriod=BigInt(i.encryptionSettings.rotation_period_ms*1e3)),typeof i.encryptionSettings.rotation_period_msgs=="number"&&(a.rotationPeriodMessages=BigInt(i.encryptionSettings.rotation_period_msgs)),t.kind){case oe.AllDevicesIsolationMode:{var u,d=(u=i.room.getBlacklistUnverifiedDevices())!==null&&u!==void 0?u:r;a.sharingStrategy=Le.deviceBasedStrategy(d,t.errorOnVerifiedUserProblems)}break;case oe.OnlySignedDevicesIsolationMode:a.sharingStrategy=Le.identityBasedStrategy();break}yield M(e,"shareRoomKey",c(function*(){var l=yield i.olmMachine.shareRoomKey(new w(i.room.roomId),o,a);if(l)for(var h of l)yield i.outgoingRequestManager.outgoingRequestProcessor.makeOutgoingRequest(h)}))})()}forceDiscardSession(){var e=this;return c(function*(){var r=yield e.olmMachine.invalidateGroupSession(new w(e.room.roomId));r&&e.prefixedLogger.info("Discarded existing group session")})()}encryptEventInner(e,r){var t=this;return c(function*(){e.debug("Encrypting actual message content");var i=yield t.olmMachine.encryptRoomEvent(new w(t.room.roomId),r.getType(),JSON.stringify(r.getContent()));r.makeEncrypted(b.RoomMessageEncrypted,JSON.parse(i),t.olmMachine.identityKeys.curve25519.toBase64(),t.olmMachine.identityKeys.ed25519.toBase64()),e.debug("Encrypted event successfully")})()}}function ct(s){switch(s){case Y.Invited:return z.Invited;case Y.Joined:return z.Joined;case Y.Shared:return z.Shared;case Y.WorldReadable:return z.WorldReadable}}var F="/_matrix/client/unstable/org.matrix.msc3814.v1",ye="org.matrix.msc3814",ut=7*24*60*60*1e3;class dt extends W{constructor(e,r,t,i,n){super(),this.logger=e,this.olmMachine=r,this.http=t,this.outgoingRequestProcessor=i,this.secretStorage=n,g(this,"intervalId",void 0)}cacheKey(e){var r=this;return c(function*(){yield r.olmMachine.dehydratedDevices().saveDehydratedDeviceKey(e),r.emit(p.DehydrationKeyCached)})()}isSupported(){var e=this;return c(function*(){try{yield e.http.authedRequest(m.Get,"/dehydrated_device",void 0,void 0,{prefix:F})}catch(t){var r=t;if(r.errcode==="M_UNRECOGNIZED")return!1;if(r.errcode==="M_NOT_FOUND")return!0;throw t}return!0})()}start(){var e=arguments,r=this;return c(function*(){var t=e.length>0&&e[0]!==void 0?e[0]:{};if(typeof t=="boolean"&&(t={createNewKey:t}),!(t.onlyIfKeyCached&&!(yield r.olmMachine.dehydratedDevices().getDehydratedDeviceKey()))){if(r.stop(),t.rehydrate!==!1)try{yield r.rehydrateDeviceIfAvailable()}catch(i){r.logger.info("dehydration: Error rehydrating device:",i),r.emit(p.RehydrationError,i.message)}t.createNewKey&&(yield r.resetKey()),yield r.scheduleDeviceDehydration()}})()}isKeyStored(){var e=this;return c(function*(){return!!(yield e.secretStorage.isStored(ye))})()}resetKey(){var e=this;return c(function*(){var r=Fe.createRandomKey();return yield e.secretStorage.store(ye,r.toBase64()),yield e.cacheKey(r),r})()}getKey(e){var r=this;return c(function*(){var t=yield r.olmMachine.dehydratedDevices().getDehydratedDeviceKey();if(t)return t;var i=yield r.secretStorage.get(ye);if(i===void 0)return e?yield r.resetKey():null;var n=pe(i);try{var o=Fe.createKeyFromArray(n);return yield r.cacheKey(o),o}finally{n.fill(0)}})()}rehydrateDeviceIfAvailable(){var e=this;return c(function*(){var r=yield e.getKey(!1);if(!r)return!1;var t;try{t=yield e.http.authedRequest(m.Get,"/dehydrated_device",void 0,void 0,{prefix:F})}catch(y){var i=y;if(i.errcode==="M_NOT_FOUND"||i.errcode==="M_UNRECOGNIZED")return e.logger.info("dehydration: No dehydrated device"),!1;throw i}e.logger.info("dehydration: dehydrated device found"),e.emit(p.RehydrationStarted);var n=yield e.olmMachine.dehydratedDevices().rehydrate(r,new B(t.device_id),JSON.stringify(t.device_data));e.logger.info("dehydration: device rehydrated");for(var o=void 0,a=0,u=0,d=ae("/dehydrated_device/$device_id/events",{$device_id:t.device_id});;){var l=yield e.http.authedRequest(m.Post,d,void 0,o?{next_batch:o}:{},{prefix:F});if(l.events.length===0)break;a+=l.events.length,o=l.next_batch;var h=yield n.receiveEvents(JSON.stringify(l.events));u+=h.length,e.emit(p.RehydrationProgress,u,a)}return e.logger.info("dehydration: received ".concat(u," room keys from ").concat(a," to-device events")),e.emit(p.RehydrationCompleted),!0})()}createAndUploadDehydratedDevice(){var e=this;return c(function*(){var r=yield e.getKey(!0),t=yield e.olmMachine.dehydratedDevices().create();e.emit(p.DehydratedDeviceCreated);var i=yield t.keysForUpload("Dehydrated device",r);yield e.outgoingRequestProcessor.makeOutgoingRequest(i),e.emit(p.DehydratedDeviceUploaded),e.logger.info("dehydration: uploaded device")})()}scheduleDeviceDehydration(){var e=this;return c(function*(){e.stop(),yield e.createAndUploadDehydratedDevice(),e.intervalId=setInterval(()=>{e.createAndUploadDehydratedDevice().catch(r=>{e.emit(p.DehydratedDeviceRotationError,r.message),e.logger.error("Error creating dehydrated device:",r)})},ut)})()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}delete(){var e=this;return c(function*(){e.stop();try{yield e.http.authedRequest(m.Delete,"/dehydrated_device",void 0,{},{prefix:F})}catch(t){var r=t;if(r.errcode==="M_UNRECOGNIZED")return;if(r.errcode==="M_NOT_FOUND")return;throw t}})()}}function ze(s,e){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(s);e&&(t=t.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),r.push.apply(r,t)}return r}function lt(s){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?ze(Object(r),!0).forEach(function(t){g(s,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(r)):ze(Object(r)).forEach(function(t){Object.defineProperty(s,t,Object.getOwnPropertyDescriptor(r,t))})}return s}class gt{constructor(e,r,t){this.logger=e,this.olmMachine=r,this.http=t}makeOutgoingRequest(e,r){var t=this;return c(function*(){var i;if(e instanceof Ur)i=yield t.requestWithRetry(m.Post,"/_matrix/client/v3/keys/upload",{},e.body);else if(e instanceof Vr)i=yield t.requestWithRetry(m.Post,"/_matrix/client/v3/keys/query",{},e.body);else if(e instanceof Nr)i=yield t.requestWithRetry(m.Post,"/_matrix/client/v3/keys/claim",{},e.body);else if(e instanceof xr)i=yield t.requestWithRetry(m.Post,"/_matrix/client/v3/keys/signatures/upload",{},e.body);else if(e instanceof Ar)i=yield t.requestWithRetry(m.Put,"/_matrix/client/v3/room_keys/keys",{version:e.version},e.body);else if(e instanceof Lr)i=yield t.sendToDeviceRequest(e);else if(e instanceof Fr){var n="/_matrix/client/v3/rooms/".concat(encodeURIComponent(e.room_id),"/send/")+"".concat(encodeURIComponent(e.event_type),"/").concat(encodeURIComponent(e.txn_id));i=yield t.requestWithRetry(m.Put,n,{},e.body)}else if(e instanceof jr){yield t.makeRequestWithUIA(m.Post,"/_matrix/client/v3/keys/device_signing/upload",{},e.body,r);return}else if(e instanceof Gr){var o=F+"/dehydrated_device";yield t.rawJsonRequest(m.Put,o,{},e.body);return}else t.logger.warn("Unsupported outgoing message",Object.getPrototypeOf(e)),i="";if(e.id)try{yield M(t.logger,"Mark Request as sent ".concat(e.type),c(function*(){yield t.olmMachine.markRequestAsSent(e.id,e.type,i)}))}catch(a){if(a instanceof Error&&(a.message==="Attempt to use a moved value"||a.message==="null pointer passed to rust"))t.logger.debug("Ignoring error '".concat(a.message,"': client is likely shutting down"));else throw a}else t.logger.trace("Outgoing request type:".concat(e.type," does not have an ID"))})()}sendToDeviceRequest(e){var r=this;return c(function*(){var t=JSON.parse(e.body),i=[];for(var[n,o]of Object.entries(t.messages))for(var[a,u]of Object.entries(o))i.push("".concat(n,"/").concat(a," (msgid ").concat(u[Cr],")"));r.logger.info("Sending batch of to-device messages. type=".concat(e.event_type," txnid=").concat(e.txn_id),i);var d="/_matrix/client/v3/sendToDevice/".concat(encodeURIComponent(e.event_type),"/")+encodeURIComponent(e.txn_id);return yield r.requestWithRetry(m.Put,d,{},e.body)})()}makeRequestWithUIA(e,r,t,i,n){var o=this;return c(function*(){if(!n)return yield o.requestWithRetry(e,r,t,i);var a=JSON.parse(i),u=function(){var l=c(function*(h){var y=lt({},a);h!==null&&(y.auth=h);var f=yield o.requestWithRetry(e,r,t,JSON.stringify(y));return JSON.parse(f)});return function(y){return l.apply(this,arguments)}}(),d=yield n(u);return JSON.stringify(d)})()}requestWithRetry(e,r,t,i){var n=this;return c(function*(){for(var o=0;;)try{return yield n.rawJsonRequest(e,r,t,i)}catch(u){o++;var a=Dr(u,o,!0);if(a<0)throw u;yield P(a)}})()}rawJsonRequest(e,r,t,i){var n=this;return c(function*(){var o={json:!1,headers:{"Content-Type":"application/json",Accept:"application/json"},prefix:"",localTimeoutMs:6e4};return yield n.http.authedRequest(e,r,t,i,o)})()}}class yt{constructor(e,r){this.olmMachine=e,this.outgoingRequestProcessor=r,g(this,"currentClaimPromise",void 0),g(this,"stopped",!1),this.currentClaimPromise=Promise.resolve()}stop(){this.stopped=!0}ensureSessionsForUsers(e,r){var t=this.currentClaimPromise.catch(()=>{}).then(()=>this.ensureSessionsForUsersInner(e,r));return this.currentClaimPromise=t,t}ensureSessionsForUsersInner(e,r){var t=this;return c(function*(){if(t.stopped)throw new Error("Cannot ensure Olm sessions: shutting down");e.info("Checking for missing Olm sessions");var i=yield t.olmMachine.getMissingSessions(r.map(n=>n.clone()));i&&(e.info("Making /keys/claim request"),yield t.outgoingRequestProcessor.makeOutgoingRequest(i)),e.info("Olm sessions prepared")})()}}function ht(s,e){var r=new Map;for(var[t,i]of s.keys.entries())r.set(t.toString(),i.toBase64());var n=te.Unverified;s.isBlacklisted()?n=te.Blocked:s.isVerified()&&(n=te.Verified);var o=new Map,a=s.signatures.get(e);if(a){var u=new Map;for(var[d,l]of a.entries())l.isValid()&&l.signature&&u.set(d,l.signature.toBase64());o.set(e.toString(),u)}var h=s.algorithms,y=new Set;return h.forEach(f=>{switch(f){case G.MegolmV1AesSha2:y.add("m.megolm.v1.aes-sha2");break;case G.OlmV1Curve25519AesSha2:default:y.add("m.olm.v1.curve25519-aes-sha2");break}}),new ur({deviceId:s.deviceId.toString(),userId:e.toString(),keys:r,algorithms:Array.from(y),verified:n,signatures:o,displayName:s.displayName,dehydrated:s.isDehydrated})}function pt(s){return new Map(Object.entries(s).map(e=>{var[r,t]=e;return[r,ft(t)]}))}function ft(s){var e,r=new Map(Object.entries(s.keys)),t=(e=s.unsigned)===null||e===void 0?void 0:e.device_display_name,i=new Map;if(s.signatures)for(var n in s.signatures)i.set(n,new Map(Object.entries(s.signatures[n])));return new ur({deviceId:s.device_id,userId:s.user_id,keys:r,algorithms:s.algorithms,verified:te.Unverified,signatures:i,displayName:t})}class vt{constructor(e,r,t,i){this.logger=e,this.olmMachine=r,this.outgoingRequestProcessor=t,this.secretStorage=i}bootstrapCrossSigning(e){var r=this;return c(function*(){if(e.setupNewCrossSigning){yield r.resetCrossSigning(e.authUploadDeviceSigningKeys);return}var t=yield r.olmMachine.crossSigningStatus(),i=yield r.secretStorage.get("m.cross_signing.master"),n=yield r.secretStorage.get("m.cross_signing.self_signing"),o=yield r.secretStorage.get("m.cross_signing.user_signing"),a=!!(i&&n&&o),u=t.hasMaster&&t.hasUserSigning&&t.hasSelfSigning;if(r.logger.debug("bootstrapCrossSigning: starting",{setupNewCrossSigning:e.setupNewCrossSigning,olmDeviceHasMaster:t.hasMaster,olmDeviceHasUserSigning:t.hasUserSigning,olmDeviceHasSelfSigning:t.hasSelfSigning,privateKeysInSecretStorage:a}),u)(yield r.secretStorage.hasKey())?a?r.logger.debug("bootstrapCrossSigning: Olm device has private keys and they are saved in secret storage; doing nothing"):(r.logger.debug("bootstrapCrossSigning: Olm device has private keys: exporting to secret storage"),yield r.exportCrossSigningKeysToStorage()):r.logger.warn("bootstrapCrossSigning: Olm device has private keys, but secret storage is not yet set up; doing nothing for now.");else if(a){r.logger.debug("bootstrapCrossSigning: Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally");var d=yield r.olmMachine.importCrossSigningKeys(i,n,o);if(!d.hasMaster||!d.hasSelfSigning||!d.hasUserSigning)throw new Error("importCrossSigningKeys failed to import the keys");var l=yield r.olmMachine.getDevice(r.olmMachine.userId,r.olmMachine.deviceId);try{var h=yield l.verify();yield r.outgoingRequestProcessor.makeOutgoingRequest(h)}finally{l.free()}}else r.logger.debug("bootstrapCrossSigning: Cross-signing private keys not found locally or in secret storage, creating new keys"),yield r.resetCrossSigning(e.authUploadDeviceSigningKeys);r.logger.debug("bootstrapCrossSigning: complete")})()}resetCrossSigning(e){var r=this;return c(function*(){var t=yield r.olmMachine.bootstrapCrossSigning(!0);(yield r.secretStorage.hasKey())?(r.logger.debug("resetCrossSigning: exporting private keys to secret storage"),yield r.exportCrossSigningKeysToStorage()):r.logger.warn("resetCrossSigning: Secret storage is not yet set up; not exporting keys to secret storage yet."),r.logger.debug("resetCrossSigning: publishing public keys to server");for(var i of[t.uploadKeysRequest,t.uploadSigningKeysRequest,t.uploadSignaturesRequest])i&&(yield r.outgoingRequestProcessor.makeOutgoingRequest(i,e))})()}exportCrossSigningKeysToStorage(){var e=this;return c(function*(){var r=yield e.olmMachine.exportCrossSigningKeys();r!=null&&r.masterKey?yield e.secretStorage.store("m.cross_signing.master",r.masterKey):e.logger.error("Cannot export MSK to secret storage, private key unknown"),r!=null&&r.self_signing_key?yield e.secretStorage.store("m.cross_signing.self_signing",r.self_signing_key):e.logger.error("Cannot export SSK to secret storage, private key unknown"),r!=null&&r.userSigningKey?yield e.secretStorage.store("m.cross_signing.user_signing",r.userSigningKey):e.logger.error("Cannot export USK to secret storage, private key unknown")})()}}function Ze(s){return me.apply(this,arguments)}function me(){return me=c(function*(s){return vr(s,["m.cross_signing.master","m.cross_signing.user_signing","m.cross_signing.self_signing"])}),me.apply(this,arguments)}function vr(s,e){return ke.apply(this,arguments)}function ke(){return ke=c(function*(s,e){var r=yield s.getDefaultKeyId();if(!r)return!1;for(var t of e){var i=(yield s.isStored(t))||{};if(!(r in i))return!1}return!0}),ke.apply(this,arguments)}var K=function(s){return s.Sas="m.sas.v1",s.ShowQrCode="m.qr_code.show.v1",s.ScanQrCode="m.qr_code.scan.v1",s.Reciprocate="m.reciprocate.v1",s}({});class mt extends W{constructor(e,r,t,i,n){super(),this.logger=e,this.olmMachine=r,this.inner=t,this.outgoingRequestProcessor=i,this.supportedVerificationMethods=n,g(this,"reEmitter",void 0),g(this,"_accepting",!1),g(this,"_cancelling",!1),g(this,"_verifier",void 0),this.reEmitter=new dr(this);var o=new WeakRef(this);t.registerChangesCallback(c(function*(){var a;return(a=o.deref())===null||a===void 0?void 0:a.onChange()}))}onChange(){var e=this.inner.getVerification();e instanceof je?this._verifier===void 0||this._verifier instanceof Xe?this.setVerifier(new er(e,this,this.outgoingRequestProcessor)):this._verifier instanceof er&&this._verifier.replaceInner(e):e instanceof Ge&&this._verifier===void 0&&this.setVerifier(new Xe(e,this.outgoingRequestProcessor)),this.emit(L.Change)}setVerifier(e){this._verifier&&this.reEmitter.stopReEmitting(this._verifier,[L.Change]),this._verifier=e,this.reEmitter.reEmit(this._verifier,[L.Change])}get transactionId(){return this.inner.flowId}get roomId(){var e;return(e=this.inner.roomId)===null||e===void 0?void 0:e.toString()}get initiatedByMe(){return this.inner.weStarted()}get otherUserId(){return this.inner.otherUserId.toString()}get otherDeviceId(){var e;return(e=this.inner.otherDeviceId)===null||e===void 0?void 0:e.toString()}getOtherDevice(){var e=this;return c(function*(){var r=e.inner.otherDeviceId;if(r)return yield e.olmMachine.getDevice(e.inner.otherUserId,r,5)})()}get isSelfVerification(){return this.inner.isSelfVerification()}get phase(){var e=this.inner.phase();switch(e){case O.Created:case O.Requested:return k.Requested;case O.Ready:return this._accepting?k.Requested:k.Ready;case O.Transitioned:if(!this._verifier)throw new Error("VerificationRequest: inner phase == Transitioned but no verifier!");return this._verifier.verificationPhase;case O.Done:return k.Done;case O.Cancelled:return k.Cancelled}throw new Error("Unknown verification phase ".concat(e))}get pending(){if(this.inner.isPassive())return!1;var e=this.phase;return e!==k.Done&&e!==k.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!==k.Started)return null;var e=this.inner.getVerification();return e instanceof je?K.Sas:e instanceof Ge?K.Reciprocate:null}otherPartySupportsMethod(e){var r=this.inner.theirSupportedMethods;if(r===void 0)return!1;var t=kr[e];return r.some(i=>i===t)}accept(){var e=this;return c(function*(){if(e.inner.phase()!==O.Requested||e._accepting)throw new Error("Cannot accept a verification request in phase ".concat(e.phase));e._accepting=!0;try{var r=e.inner.acceptWithMethods(e.supportedVerificationMethods.map(ne));r&&(yield e.outgoingRequestProcessor.makeOutgoingRequest(r))}finally{e._accepting=!1}e.emit(L.Change)})()}cancel(e){var r=this;return c(function*(){if(!r._cancelling){r.logger.info("Cancelling verification request with params:",e),r._cancelling=!0;try{var t=r.inner.cancel();t&&(yield r.outgoingRequestProcessor.makeOutgoingRequest(t))}finally{r._cancelling=!1}}})()}beginKeyVerification(e,r){throw new Error("not implemented")}startVerification(e){var r=this;return c(function*(){if(e!==K.Sas)throw new Error("Unsupported verification method ".concat(e));if(!(yield r.getOtherDevice()))throw new Error("startVerification(): other device is unknown");var t=yield r.inner.startSas();if(t){var[,i]=t;yield r.outgoingRequestProcessor.makeOutgoingRequest(i)}if(!r._verifier)throw new Error("Still no verifier after startSas() call");return r._verifier})()}scanQRCode(e){var r=this;return c(function*(){var t=Wr.fromBytes(e),i=yield r.inner.scanQrCode(t);if(!r._verifier)throw new Error("Still no verifier after scanQrCode() call");var n=i.reciprocate();return n&&(yield r.outgoingRequestProcessor.makeOutgoingRequest(n)),r._verifier})()}get verifier(){return this.phase===k.Started?this._verifier:void 0}getQRCodeBytes(){throw new Error("getQRCodeBytes() unsupported in Rust Crypto; use generateQRCode() instead.")}generateQRCode(){var e=this;return c(function*(){if(!(yield e.getOtherDevice()))throw new Error("generateQRCode(): other device is unknown");var r=yield e.inner.generateQrCode();if(r)return r.toBytes()})()}get cancellationCode(){var e,r;return(e=(r=this.inner.cancelInfo)===null||r===void 0?void 0:r.cancelCode())!==null&&e!==void 0?e:null}get cancellingUserId(){var e=this.inner.cancelInfo;if(e)return e.cancelledbyUs()?this.olmMachine.userId.toString():this.inner.otherUserId.toString()}}class mr extends W{constructor(e,r){super(),this.inner=e,this.outgoingRequestProcessor=r,g(this,"completionDeferred",void 0),this.completionDeferred=Promise.withResolvers();var t=new WeakRef(this);e.registerChangesCallback(c(function*(){var i;return(i=t.deref())===null||i===void 0?void 0:i.onChange()})),this.completionDeferred.promise.catch(()=>null)}onChange(){if(this.inner.isDone())this.completionDeferred.resolve(void 0);else if(this.inner.isCancelled()){var e=this.inner.cancelInfo();this.completionDeferred.reject(new Error("Verification cancelled by ".concat(e.cancelledbyUs()?"us":"them"," with code ").concat(e.cancelCode(),": ").concat(e.reason())))}this.emit(L.Change)}get hasBeenCancelled(){return this.inner.isCancelled()}get userId(){return this.inner.otherUserId.toString()}cancel(e){var r=this.inner.cancel();r&&this.outgoingRequestProcessor.makeOutgoingRequest(r)}getShowSasCallbacks(){return null}getReciprocateQrCodeCallbacks(){return null}}class Xe extends mr{constructor(e,r){super(e,r),g(this,"callbacks",null)}onChange(){this.callbacks===null&&this.inner.hasBeenScanned()&&(this.callbacks={confirm:()=>{this.confirmScanning()},cancel:()=>this.cancel()}),super.onChange()}verify(){var e=this;return c(function*(){e.callbacks!==null&&e.emit(pr.ShowReciprocateQr,e.callbacks),yield e.completionDeferred.promise})()}get verificationPhase(){switch(this.inner.state()){case U.Created:return k.Ready;case U.Scanned:return k.Started;case U.Confirmed:return k.Started;case U.Reciprocated:return k.Started;case U.Done:return k.Done;case U.Cancelled:return k.Cancelled;default:throw new Error("Unknown qr code state ".concat(this.inner.state()))}}getReciprocateQrCodeCallbacks(){return this.callbacks}confirmScanning(){var e=this;return c(function*(){var r=e.inner.confirmScanning();r&&(yield e.outgoingRequestProcessor.makeOutgoingRequest(r))})()}}class er extends mr{constructor(e,r,t){super(e,t),g(this,"callbacks",null)}verify(){var e=this;return c(function*(){yield e.sendAccept(),yield e.completionDeferred.promise})()}sendAccept(){var e=this;return c(function*(){var r=e.inner.accept();r&&(yield e.outgoingRequestProcessor.makeOutgoingRequest(r))})()}onChange(){var e=this;if(super.onChange(),this.callbacks===null){var r=this.inner.emoji(),t=this.inner.decimals();if(r===void 0&&t===void 0)return;var i={};r&&(i.emoji=r.map(n=>[n.symbol,n.description])),t&&(i.decimal=[t[0],t[1],t[2]]),this.callbacks={sas:i,confirm:function(){var n=c(function*(){var a=yield e.inner.confirm();for(var u of a)yield e.outgoingRequestProcessor.makeOutgoingRequest(u)});function o(){return n.apply(this,arguments)}return o}(),mismatch:()=>{var n=this.inner.cancelWithCode("m.mismatched_sas");n&&this.outgoingRequestProcessor.makeOutgoingRequest(n)},cancel:()=>{var n=this.inner.cancelWithCode("m.user");n&&this.outgoingRequestProcessor.makeOutgoingRequest(n)}},this.emit(pr.ShowSas,this.callbacks)}}get verificationPhase(){return k.Started}getShowSasCallbacks(){return this.callbacks}replaceInner(e){if(this.inner!=e){this.inner=e;var r=new WeakRef(this);e.registerChangesCallback(c(function*(){var t;return(t=r.deref())===null||t===void 0?void 0:t.onChange()})),this.sendAccept(),this.onChange()}}}var kr={[K.Sas]:Z.SasV1,[K.ScanQrCode]:Z.QrCodeScanV1,[K.ShowQrCode]:Z.QrCodeShowV1,[K.Reciprocate]:Z.ReciprocateV1};function ne(s){var e=kr[s];if(e===void 0)throw new Error("Unknown verification method ".concat(s));return e}function kt(s){switch(s.getType()){case b.KeyVerificationCancel:case b.KeyVerificationDone:case b.KeyVerificationMac:case b.KeyVerificationStart:case b.KeyVerificationKey:case b.KeyVerificationReady:case b.KeyVerificationAccept:return!0;case b.RoomMessage:return s.getContent().msgtype===lr.KeyVerificationRequest;default:return!1}}class St extends W{constructor(e,r,t,i){super(),this.logger=e,this.olmMachine=r,this.http=t,this.outgoingRequestProcessor=i,g(this,"checkedForBackup",!1),g(this,"serverBackupInfo",void 0),g(this,"activeBackupVersion",null),g(this,"stopped",!1),g(this,"backupKeysLoopRunning",!1),g(this,"keyBackupCheckInProgress",null)}stop(){this.stopped=!0}getActiveBackupVersion(){var e=this;return c(function*(){return(yield e.olmMachine.isBackupEnabled())?e.activeBackupVersion:null})()}getServerBackupInfo(){var e=this;return c(function*(){return yield e.checkKeyBackupAndEnable(!1),e.serverBackupInfo})()}isKeyBackupTrusted(e){var r=this;return c(function*(){var t=yield r.olmMachine.verifyBackup(e),i=yield r.olmMachine.getBackupKeys(),n=i==null?void 0:i.decryptionKey,o=!!n&&r.backupInfoMatchesBackupDecryptionKey(e,n);return{matchesDecryptionKey:o,trusted:t.trusted()}})()}checkKeyBackupAndEnable(e){return!e&&this.checkedForBackup?Promise.resolve(null):(this.keyBackupCheckInProgress||(this.keyBackupCheckInProgress=this.doCheckKeyBackup().finally(()=>{this.keyBackupCheckInProgress=null})),this.keyBackupCheckInProgress)}handleBackupSecretReceived(e){var r=this;return c(function*(){var t,i;try{i=yield r.requestKeyBackupVersion()}catch(a){return r.logger.warn("handleBackupSecretReceived: Error checking for latest key backup",a),!1}if(!((t=i)!==null&&t!==void 0&&t.version))return r.logger.warn("handleBackupSecretReceived: Received a backup decryption key, but there is no trusted server-side key backup"),!1;try{var n=V.fromBase64(e),o=r.backupInfoMatchesBackupDecryptionKey(i,n);return o?(r.logger.info("handleBackupSecretReceived: A valid backup decryption key has been received and stored in cache."),yield r.saveBackupDecryptionKey(n,i.version),!0):(r.logger.warn("handleBackupSecretReceived: Private decryption key does not match the public key of the current remote backup."),!1)}catch(a){r.logger.warn("handleBackupSecretReceived: Invalid backup decryption key",a)}return!1})()}saveBackupDecryptionKey(e,r){var t=this;return c(function*(){yield t.olmMachine.saveBackupDecryptionKey(e,r),t.emit(p.KeyBackupDecryptionKeyCached,r)})()}importRoomKeys(e,r){var t=this;return c(function*(){yield t.importRoomKeysAsJson(JSON.stringify(e),r)})()}importRoomKeysAsJson(e,r){var t=this;return c(function*(){yield t.olmMachine.importExportedRoomKeys(e,(i,n)=>{var o,a={total:Number(n),successes:Number(i),stage:A.LoadKeys,failures:0};r==null||(o=r.progressCallback)===null||o===void 0||o.call(r,a)})})()}importBackedUpRoomKeys(e,r,t){var i=this;return c(function*(){var n=new Map;for(var o of e){var a=new w(o.room_id);n.has(a)||n.set(a,new Map),n.get(a).set(o.session_id,o)}yield i.olmMachine.importBackedUpRoomKeys(n,(u,d,l)=>{var h,y={total:Number(d),successes:Number(u),stage:A.LoadKeys,failures:Number(l)};t==null||(h=t.progressCallback)===null||h===void 0||h.call(t,y)},r)})()}doCheckKeyBackup(){var e=this;return c(function*(){e.logger.debug("Checking key backup status...");var r;try{r=yield e.requestKeyBackupVersion()}catch(n){return e.logger.warn("Error checking for active key backup",n),e.serverBackupInfo=void 0,null}e.checkedForBackup=!0,r&&!r.version&&(e.logger.warn("active backup lacks a useful 'version'; ignoring it"),r=void 0),e.serverBackupInfo=r;var t=yield e.getActiveBackupVersion();if(!r)return t!==null?(e.logger.debug("No key backup present on server: disabling key backup"),yield e.disableKeyBackup()):e.logger.debug("No key backup present on server: not enabling key backup"),null;var i=yield e.isKeyBackupTrusted(r);return!i.matchesDecryptionKey&&!i.trusted?t!==null?(e.logger.debug("Key backup present on server but not trusted: disabling key backup"),yield e.disableKeyBackup()):e.logger.debug("Key backup present on server but not trusted: not enabling key backup"):t===null?(e.logger.debug("Found usable key backup v".concat(r.version,": enabling key backups")),yield e.enableKeyBackup(r)):t!==r.version?(e.logger.debug("On backup version ".concat(t," but found version ").concat(r.version,": switching.")),yield e.disableKeyBackup(),yield e.enableKeyBackup(r)):e.logger.debug("Backup version ".concat(r.version," still current")),{backupInfo:r,trustInfo:i}})()}enableKeyBackup(e){var r=this;return c(function*(){yield r.olmMachine.enableBackupV1(e.auth_data.public_key,e.version),r.activeBackupVersion=e.version,r.emit(p.KeyBackupStatus,!0),r.backupKeysLoop()})()}maybeUploadKey(){var e=this;return c(function*(){e.activeBackupVersion!=null&&e.backupKeysLoop()})()}disableKeyBackup(){var e=this;return c(function*(){yield e.olmMachine.disableBackup(),e.activeBackupVersion=null,e.emit(p.KeyBackupStatus,!1)})()}backupKeysLoop(){var e=arguments,r=this;return c(function*(){var t=e.length>0&&e[0]!==void 0?e[0]:1e4;if(r.backupKeysLoopRunning){r.logger.debug("Backup loop already running");return}r.backupKeysLoopRunning=!0,r.logger.debug("Backup: Starting keys upload loop for backup version:".concat(r.activeBackupVersion,"."));var i=Math.random()*t;yield P(i);try{for(var n=0,o=null,a=!0;!r.stopped;){var u=void 0;try{u=yield M(r.logger,"BackupRoomKeys: Get keys to backup from rust crypto-sdk",c(function*(){return yield r.olmMachine.backupRoomKeys()}))}catch(f){r.logger.error("Backup: Failed to get keys to backup from rust crypto-sdk",f)}if(!u||r.stopped||!r.activeBackupVersion){r.logger.debug("Backup: Ending loop for version ".concat(r.activeBackupVersion,".")),u||r.emit(p.KeyBackupSessionsRemaining,0);return}try{if(yield r.outgoingRequestProcessor.makeOutgoingRequest(u),n=0,r.stopped)break;if(!a&&o===null)try{var d=yield r.olmMachine.roomKeyCounts();o=d.total-d.backedUp}catch(f){r.logger.error("Backup: Failed to get key counts from rust crypto-sdk",f)}if(o!==null){r.emit(p.KeyBackupSessionsRemaining,o);var l=r.keysCountInBatch(u);o=Math.max(o-l,0)}}catch(f){if(n++,r.logger.error("Backup: Error processing backup request for rust crypto-sdk",f),f instanceof gr){var h=f.data.errcode;if(h=="M_NOT_FOUND"||h=="M_WRONG_ROOM_KEYS_VERSION"){r.logger.debug("Backup: Failed to upload keys to current vesion: ".concat(h,"."));try{yield r.disableKeyBackup()}catch(E){r.logger.error("Backup: An error occurred while disabling key backup:",E)}r.emit(p.KeyBackupFailed,f.data.errcode),r.backupKeysLoopRunning=!1,r.checkKeyBackupAndEnable(!0);return}else if(f.isRateLimitError())try{var y=f.getRetryAfterMs();if(y&&y>0){yield P(y);continue}}catch(E){r.logger.warn("Backup: An error occurred while retrieving a rate-limit retry delay",E)}}yield P(1e3*Math.pow(2,Math.min(n-1,4)))}a=!1}}finally{r.backupKeysLoopRunning=!1}})()}keysCountInBatch(e){var r=JSON.parse(e.body);return rr(r)}requestKeyBackupVersion(e){var r=this;return c(function*(){return yield Sr(r.http,e)})()}setupKeyBackup(e){var r=this;return c(function*(){yield r.deleteAllKeyBackupVersions();var t=V.createRandomKey(),i=t.megolmV1PublicKey,n={public_key:i.publicKeyBase64};yield e(n);var o=yield r.http.authedRequest(m.Post,"/room_keys/version",void 0,{algorithm:i.algorithm,auth_data:n},{prefix:j.V3});return yield r.saveBackupDecryptionKey(t,o.version),{version:o.version,algorithm:i.algorithm,authData:n,decryptionKey:t}})()}deleteAllKeyBackupVersions(){var e=this;return c(function*(){for(var r,t,i=(r=(t=yield e.requestKeyBackupVersion())===null||t===void 0?void 0:t.version)!==null&&r!==void 0?r:null;i!=null;){var n,o;yield e.deleteKeyBackupVersion(i),i=(n=(o=yield e.requestKeyBackupVersion())===null||o===void 0?void 0:o.version)!==null&&n!==void 0?n:null}})()}deleteKeyBackupVersion(e){var r=this;return c(function*(){r.logger.debug("deleteKeyBackupVersion v:".concat(e));var t=ae("/room_keys/version/$version",{$version:e});yield r.http.authedRequest(m.Delete,t,void 0,void 0,{prefix:j.V3}),r.activeBackupVersion===e&&(r.serverBackupInfo=null,yield r.disableKeyBackup())})()}createBackupDecryptor(e){return new _t(this.logger,e)}restoreKeyBackup(e,r,t){var i=this;return c(function*(){var n=yield i.downloadKeyBackup(e);return i.importKeyBackup(n,e,r,t)})()}downloadKeyBackup(e){return this.http.authedRequest(m.Get,"/room_keys/keys",{version:e},void 0,{prefix:j.V3})}importKeyBackup(e,r,t,i){var n=this;return c(function*(){var o,a=200,u=rr(e),d=0,l=0;i==null||(o=i.progressCallback)===null||o===void 0||o.call(i,{total:u,successes:d,stage:A.LoadKeys,failures:l});var h=function(){var wr=c(function*(ce){var H,Q=[],Rr=function*(Pe){var Er=yield t.decryptSessions(ce.get(Pe));Er.forEach(Ue=>{Ue.room_id=Pe,Q.push(Ue)})};for(var Kr of ce.keys())yield*Rr(Kr);try{yield n.importBackedUpRoomKeys(Q,r),d+=Q.length}catch(Te){l+=Q.length,n.logger.error("Error importing keys from backup",Te)}i==null||(H=i.progressCallback)===null||H===void 0||H.call(i,{total:u,successes:d,stage:A.LoadKeys,failures:l})});return function(H){return wr.apply(this,arguments)}}(),y=0,f=new Map;for(var[E,I]of Object.entries(e.rooms))if(I.sessions){f.set(E,{});for(var[N,_r]of Object.entries(I.sessions)){var br=f.get(E);br[N]=_r,y+=1,y>=a&&(yield h(f),f=new Map,f.set(E,{}),y=0)}}return y>0&&(yield h(f)),{total:u,imported:d}})()}backupInfoMatchesBackupDecryptionKey(e,r){var t;return e.algorithm!=="m.megolm_backup.v1.curve25519-aes-sha2"?(this.logger.warn("backupMatchesPrivateKey: Unsupported backup algorithm",e.algorithm),!1):((t=e.auth_data)===null||t===void 0?void 0:t.public_key)===r.megolmV1PublicKey.publicKeyBase64}}class _t{constructor(e,r){this.logger=e,g(this,"decryptionKey",void 0),g(this,"sourceTrusted",void 0),this.decryptionKey=r,this.sourceTrusted=!1}decryptSessions(e){var r=this;return c(function*(){var t=[];for(var[i,n]of Object.entries(e))try{var o=JSON.parse(r.decryptionKey.decryptV1(n.session_data.ephemeral,n.session_data.mac,n.session_data.ciphertext));o.session_id=i,t.push(o)}catch(a){r.logger.debug("Failed to decrypt megolm session from backup",a,n)}return t})()}free(){this.decryptionKey.free()}}function Sr(s,e){return Se.apply(this,arguments)}function Se(){return Se=c(function*(s,e){try{var r=e?ae("/room_keys/version/$version",{$version:e}):"/room_keys/version";return yield s.authedRequest(m.Get,r,void 0,void 0,{prefix:j.V3})}catch(t){if(t.errcode==="M_NOT_FOUND")return null;throw t}}),Se.apply(this,arguments)}function he(s,e){var r=e.auth_data;return r.public_key===s.megolmV1PublicKey.publicKeyBase64}function rr(s){var e=0;for(var{sessions:r}of Object.values(s.rooms))e+=Object.keys(r).length;return e}class bt{constructor(e,r,t){this.logger=e,this.olmMachine=r,this.outgoingRequestProcessor=t,g(this,"stopped",!1),g(this,"outgoingRequestLoopRunning",!1),g(this,"nextLoopDeferred",void 0)}stop(){this.stopped=!0}doProcessOutgoingRequests(){this.nextLoopDeferred||(this.nextLoopDeferred=Promise.withResolvers());var e=this.nextLoopDeferred.promise;return this.outgoingRequestLoopRunning||this.outgoingRequestLoop().catch(r=>{this.logger.error("Uncaught error in outgoing request loop",r)}),e}outgoingRequestLoop(){var e=this;return c(function*(){if(e.outgoingRequestLoopRunning)throw new Error("Cannot run two outgoing request loops");e.outgoingRequestLoopRunning=!0;try{for(;!e.stopped&&e.nextLoopDeferred;){var r=e.nextLoopDeferred;e.nextLoopDeferred=void 0,yield e.processOutgoingRequests().then(r.resolve,r.reject)}}finally{e.outgoingRequestLoopRunning=!1}e.nextLoopDeferred&&e.nextLoopDeferred.reject(new Error("OutgoingRequestsManager was stopped"))})()}processOutgoingRequests(){var e=this;return c(function*(){if(!e.stopped){var r=yield e.olmMachine.outgoingRequests(),t=function*(a){if(e.stopped)return{v:void 0};try{yield M(e.logger,"Make outgoing request ".concat(a.type),c(function*(){yield e.outgoingRequestProcessor.makeOutgoingRequest(a)}))}catch(u){e.logger.error("Failed to process outgoing request ".concat(a.type,": ").concat(u))}},i;for(var n of r)if(i=yield*t(n),i)return i.v}})()}}var ee=5e3,D=function(s){return s.MISSING_DECRYPTION_KEY="MISSING_DECRYPTION_KEY",s.NETWORK_ERROR="NETWORK_ERROR",s.STOPPED="STOPPED",s}(D||{});class x extends Error{constructor(e){super("Failed to get key from backup: ".concat(e)),this.code=e,this.name="KeyDownloadError"}}class tr extends Error{constructor(e){super("Failed to get key from backup: rate limited"),this.retryMillis=e,this.name="KeyDownloadRateLimitError"}}class wt{constructor(e,r,t,i){this.olmMachine=r,this.http=t,this.backupManager=i,g(this,"stopped",!1),g(this,"configuration",null),g(this,"sessionLastCheckAttemptedTime",new Map),g(this,"logger",void 0),g(this,"downloadLoopRunning",!1),g(this,"queuedRequests",[]),g(this,"hasConfigurationProblem",!1),g(this,"currentBackupVersionCheck",null),g(this,"onBackupStatusChanged",()=>{this.hasConfigurationProblem=!1,this.configuration=null,this.getOrCreateBackupConfiguration().then(n=>{n&&this.downloadKeysLoop()})}),this.logger=e.getChild("[PerSessionKeyBackupDownloader]"),i.on(p.KeyBackupStatus,this.onBackupStatusChanged),i.on(p.KeyBackupFailed,this.onBackupStatusChanged),i.on(p.KeyBackupDecryptionKeyCached,this.onBackupStatusChanged)}isKeyBackupDownloadConfigured(){return this.configuration!==null}getServerBackupInfo(){var e=this;return c(function*(){return yield e.backupManager.getServerBackupInfo()})()}onDecryptionKeyMissingError(e,r){if(this.isAlreadyInQueue(e,r)){this.logger.trace("Not checking key backup for session ".concat(r," as it is already queued"));return}if(this.wasRequestedRecently(r)){this.logger.trace("Not checking key backup for session ".concat(r," as it was already requested recently"));return}this.queuedRequests.push({roomId:e,megolmSessionId:r}),this.downloadKeysLoop()}stop(){this.stopped=!0,this.backupManager.off(p.KeyBackupStatus,this.onBackupStatusChanged),this.backupManager.off(p.KeyBackupFailed,this.onBackupStatusChanged),this.backupManager.off(p.KeyBackupDecryptionKeyCached,this.onBackupStatusChanged)}isAlreadyInQueue(e,r){return this.queuedRequests.some(t=>t.roomId==e&&t.megolmSessionId==r)}markAsNotFoundInBackup(e){var r=Date.now();this.sessionLastCheckAttemptedTime.set(e,r),this.sessionLastCheckAttemptedTime.size>100&&(this.sessionLastCheckAttemptedTime=new Map(Array.from(this.sessionLastCheckAttemptedTime).filter((t,i)=>Math.max(r-i,0)<ee)))}wasRequestedRecently(e){var r=this.sessionLastCheckAttemptedTime.get(e);return r?Math.max(Date.now()-r,0)<ee:!1}getBackupDecryptionKey(){var e=this;return c(function*(){try{return yield e.olmMachine.getBackupKeys()}catch{return null}})()}requestRoomKeyFromBackup(e,r,t){var i=this;return c(function*(){var n=ae("/room_keys/keys/$roomId/$sessionId",{$roomId:r,$sessionId:t});return yield i.http.authedRequest(m.Get,n,{version:e},void 0,{prefix:j.V3})})()}downloadKeysLoop(){var e=this;return c(function*(){if(!e.downloadLoopRunning&&!e.hasConfigurationProblem){e.downloadLoopRunning=!0;try{for(;e.queuedRequests.length>0;){var r=e.queuedRequests[0];try{var t=yield e.getOrCreateBackupConfiguration();if(!t){e.downloadLoopRunning=!1;return}var i=yield e.queryKeyBackup(r.roomId,r.megolmSessionId,t);if(e.stopped)return;try{yield e.decryptAndImport(r,i,t)}catch(n){e.logger.error("Error while decrypting and importing key backup for session ".concat(r.megolmSessionId),n)}e.queuedRequests.shift()}catch(n){if(n instanceof x)switch(n.code){case D.MISSING_DECRYPTION_KEY:e.markAsNotFoundInBackup(r.megolmSessionId),e.queuedRequests.shift();break;case D.NETWORK_ERROR:yield P(ee);break;case D.STOPPED:e.downloadLoopRunning=!1;return}else n instanceof tr&&(yield P(n.retryMillis))}}}finally{e.downloadLoopRunning=!1}}})()}queryKeyBackup(e,r,t){var i=this;return c(function*(){if(i.logger.debug("Checking key backup for session ".concat(r)),i.stopped)throw new x(D.STOPPED);try{var n=yield i.requestRoomKeyFromBackup(t.backupVersion,e,r);return i.logger.debug("Got key from backup for sessionId:".concat(r)),n}catch(d){if(i.stopped)throw new x(D.STOPPED);if(i.logger.info("No luck requesting key backup for session ".concat(r,": ").concat(d)),d instanceof gr){var o=d.data.errcode;if(o=="M_NOT_FOUND")throw new x(D.MISSING_DECRYPTION_KEY);if(d.isRateLimitError()){var a;try{var u;a=(u=d.getRetryAfterMs())!==null&&u!==void 0?u:void 0}catch(l){i.logger.warn("Error while retrieving a rate-limit retry delay",l)}throw a&&a>0&&i.logger.info("Rate limited by server, waiting ".concat(a,"ms")),new tr(a??ee)}}throw new x(D.NETWORK_ERROR)}})()}decryptAndImport(e,r,t){var i=this;return c(function*(){var n={[e.megolmSessionId]:r},o=yield t.decryptor.decryptSessions(n);for(var a of o)a.room_id=e.roomId;yield i.backupManager.importBackedUpRoomKeys(o,t.backupVersion)})()}getOrCreateBackupConfiguration(){var e=this;return c(function*(){if(e.configuration)return e.configuration;if(e.hasConfigurationProblem)return null;if(e.currentBackupVersionCheck!=null)return e.logger.debug("Already checking server version, use current promise"),yield e.currentBackupVersionCheck;e.currentBackupVersionCheck=e.internalCheckFromServer();try{return yield e.currentBackupVersionCheck}finally{e.currentBackupVersionCheck=null}})()}internalCheckFromServer(){var e=this;return c(function*(){var r,t,i,n=null;try{n=yield e.backupManager.getServerBackupInfo()}catch(h){return e.logger.debug("Backup: error while checking server version: ".concat(h)),e.hasConfigurationProblem=!0,null}if(e.logger.debug("Got current backup version from server: ".concat((r=n)===null||r===void 0?void 0:r.version)),((t=n)===null||t===void 0?void 0:t.algorithm)!="m.megolm_backup.v1.curve25519-aes-sha2"){var o;return e.logger.info("Unsupported algorithm ".concat((o=n)===null||o===void 0?void 0:o.algorithm)),e.hasConfigurationProblem=!0,null}if(!((i=n)!==null&&i!==void 0&&i.version))return e.logger.info("No current key backup"),e.hasConfigurationProblem=!0,null;var a=yield e.backupManager.getActiveBackupVersion();if(a==null||n.version!=a)return e.logger.info("The current backup version on the server (".concat(n.version,") is not trusted. Version we are currently backing up to: ").concat(a)),e.hasConfigurationProblem=!0,null;var u=yield e.getBackupDecryptionKey();if(!(u!=null&&u.decryptionKey))return e.logger.debug("Not checking key backup for session (no decryption key)"),e.hasConfigurationProblem=!0,null;if(a!=u.backupVersion)return e.logger.debug("Version for which we have a decryption key (".concat(u.backupVersion,") doesn't match the version we are backing up to (").concat(a,")")),e.hasConfigurationProblem=!0,null;var d=n.auth_data;if(d.public_key!=u.decryptionKey.megolmV1PublicKey.publicKeyBase64)return e.logger.debug("Key backup on server does not match our decryption key"),e.hasConfigurationProblem=!0,null;var l=e.backupManager.createBackupDecryptor(u.decryptionKey);return e.hasConfigurationProblem=!1,e.configuration={decryptor:l,backupVersion:a},e.configuration})()}}function Rt(s,e){if(!s.private_key_salt||!s.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return fr(e,s.private_key_salt,s.private_key_iterations,s.private_key_bits)}function ir(s,e){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(s);e&&(t=t.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),r.push.apply(r,t)}return r}function nr(s){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?ir(Object(r),!0).forEach(function(t){g(s,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(r)):ir(Object(r)).forEach(function(t){Object.defineProperty(s,t,Object.getOwnPropertyDescriptor(r,t))})}return s}var sr=[K.Sas,K.ScanQrCode,K.ShowQrCode,K.Reciprocate];class Kt extends W{constructor(e,r,t,i,n,o,a){super(),this.logger=e,this.olmMachine=r,this.http=t,this.userId=i,this.secretStorage=o,this.cryptoCallbacks=a,g(this,"RECOVERY_KEY_DERIVATION_ITERATIONS",5e5),g(this,"_trustCrossSignedDevices",!0),g(this,"deviceIsolationMode",new Br(!1)),g(this,"stopped",!1),g(this,"roomEncryptors",{}),g(this,"eventDecryptor",void 0),g(this,"keyClaimManager",void 0),g(this,"outgoingRequestProcessor",void 0),g(this,"crossSigningIdentity",void 0),g(this,"backupManager",void 0),g(this,"outgoingRequestsManager",void 0),g(this,"perSessionBackupDownloader",void 0),g(this,"dehydratedDeviceManager",void 0),g(this,"reemitter",new dr(this)),g(this,"globalBlacklistUnverifiedDevices",!1),g(this,"_supportedVerificationMethods",sr),this.outgoingRequestProcessor=new gt(e,r,t),this.outgoingRequestsManager=new bt(this.logger,r,this.outgoingRequestProcessor),this.keyClaimManager=new yt(r,this.outgoingRequestProcessor),this.backupManager=new St(e,r,t,this.outgoingRequestProcessor),this.perSessionBackupDownloader=new wt(this.logger,this.olmMachine,this.http,this.backupManager),this.dehydratedDeviceManager=new dt(this.logger,r,t,this.outgoingRequestProcessor,o),this.eventDecryptor=new Et(this.logger,r,this.perSessionBackupDownloader),this.reemitter.reEmit(this.backupManager,[p.KeyBackupStatus,p.KeyBackupSessionsRemaining,p.KeyBackupFailed,p.KeyBackupDecryptionKeyCached]),this.reemitter.reEmit(this.dehydratedDeviceManager,[p.DehydratedDeviceCreated,p.DehydratedDeviceUploaded,p.RehydrationStarted,p.RehydrationProgress,p.RehydrationCompleted,p.RehydrationError,p.DehydrationKeyCached,p.DehydratedDeviceRotationError]),this.crossSigningIdentity=new vt(e,r,this.outgoingRequestProcessor,o),this.checkKeyBackupAndEnable()}getOlmMachineOrThrow(){if(this.stopped)throw new Or;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())}encryptEvent(e,r){var t=this;return c(function*(){var i=e.getRoomId(),n=t.roomEncryptors[i];if(!n)throw new Error("Cannot encrypt event in unconfigured room ".concat(i));yield n.encryptEvent(e,t.globalBlacklistUnverifiedDevices,t.deviceIsolationMode)})()}decryptEvent(e){var r=this;return c(function*(){var t=e.getRoomId();if(!t)throw new Error("to-device event was not decrypted in preprocessToDeviceMessages");return yield r.eventDecryptor.attemptEventDecryption(e,r.deviceIsolationMode)})()}getBackupDecryptor(e,r){var t=this;return c(function*(){if(!(r instanceof Uint8Array))throw new Error("getBackupDecryptor: expects Uint8Array");if(e.algorithm!="m.megolm_backup.v1.curve25519-aes-sha2")throw new Error("getBackupDecryptor: Unsupported algorithm ".concat(e.algorithm));var i=V.fromBase64(fe(r));if(!he(i,e))throw new Error("getBackupDecryptor: key backup on server does not match the decryption key");return t.backupManager.createBackupDecryptor(i)})()}importBackedUpRoomKeys(e,r,t){var i=this;return c(function*(){return yield i.backupManager.importBackedUpRoomKeys(e,r,t)})()}getVersion(){var e=Jr();return"Rust SDK ".concat(e.matrix_sdk_crypto," (").concat(e.git_sha,"), Vodozemac ").concat(e.vodozemac)}setDeviceIsolationMode(e){this.deviceIsolationMode=e}isEncryptionEnabledInRoom(e){var r=this;return c(function*(){var t=yield r.olmMachine.getRoomSettings(new w(e));return!!(t!=null&&t.algorithm)})()}getOwnDeviceKeys(){var e=this;return c(function*(){var r=e.olmMachine.identityKeys;return{ed25519:r.ed25519.toBase64(),curve25519:r.curve25519.toBase64()}})()}prepareToEncrypt(e){var r=this.roomEncryptors[e.roomId];r&&r.prepareForEncryption(this.globalBlacklistUnverifiedDevices,this.deviceIsolationMode)}forceDiscardSession(e){var r;return(r=this.roomEncryptors[e])===null||r===void 0?void 0:r.forceDiscardSession()}exportRoomKeys(){var e=this;return c(function*(){var r=yield e.olmMachine.exportRoomKeys(()=>!0);return JSON.parse(r)})()}exportRoomKeysAsJson(){var e=this;return c(function*(){return yield e.olmMachine.exportRoomKeys(()=>!0)})()}importRoomKeys(e,r){var t=this;return c(function*(){return yield t.backupManager.importRoomKeys(e,r)})()}importRoomKeysAsJson(e,r){var t=this;return c(function*(){return yield t.backupManager.importRoomKeysAsJson(e,r)})()}userHasCrossSigningKeys(){var e=arguments,r=this;return c(function*(){var t=e.length>0&&e[0]!==void 0?e[0]:r.userId,i=e.length>1&&e[1]!==void 0?e[1]:!1,n=yield r.olmMachine.trackedUsers(),o;for(var a of n)if(t===a.toString()){o=a;break}if(o!==void 0){if(t===r.userId){var u=r.olmMachine.queryKeysForUsers([o.clone()]);yield r.outgoingRequestProcessor.makeOutgoingRequest(u)}var d=yield r.olmMachine.getIdentity(o);return d==null||d.free(),d!==void 0}else if(i){var l,h=yield r.downloadDeviceList(new Set([t])),y=(l=h.master_keys)===null||l===void 0?void 0:l[t];return y?!!Object.values(y.keys)[0]:!1}else return!1})()}getUserDeviceInfo(e){var r=arguments,t=this;return c(function*(){var i=r.length>1&&r[1]!==void 0?r[1]:!1,n=new Map,o=yield t.getOlmMachineOrThrow().trackedUsers(),a=new Set;o.forEach(h=>a.add(h.toString()));var u=new Set;for(var d of e)a.has(d)?n.set(d,yield t.getUserDevices(d)):u.add(d);if(i&&u.size>=1){var l=yield t.downloadDeviceList(u);Object.entries(l.device_keys).forEach(h=>{var[y,f]=h;return n.set(y,pt(f))})}return n})()}getUserDevices(e){var r=this;return c(function*(){var t=new v(e),i=yield r.olmMachine.getUserDevices(t,1);try{var n=i.devices();try{return new Map(n.map(o=>[o.deviceId.toString(),ht(o,t)]))}finally{n.forEach(o=>o.free())}}finally{i.free()}})()}downloadDeviceList(e){var r=this;return c(function*(){var t={device_keys:{}};return e.forEach(i=>t.device_keys[i]=[]),yield r.http.authedRequest(m.Post,"/_matrix/client/v3/keys/query",void 0,t,{prefix:""})})()}getTrustCrossSignedDevices(){return this._trustCrossSignedDevices}setTrustCrossSignedDevices(e){this._trustCrossSignedDevices=e}setDeviceVerified(e,r){var t=arguments,i=this;return c(function*(){var n=t.length>2&&t[2]!==void 0?t[2]:!0,o=yield i.olmMachine.getDevice(new v(e),new B(r));if(!o)throw new Error("Unknown device ".concat(e,"|").concat(r));try{yield o.setLocalTrust(n?We.Verified:We.Unset)}finally{o.free()}})()}crossSignDevice(e){var r=this;return c(function*(){var t=yield r.olmMachine.getDevice(new v(r.userId),new B(e));if(!t)throw new Error("Unknown device ".concat(e));try{var i=yield t.verify();yield r.outgoingRequestProcessor.makeOutgoingRequest(i)}finally{t.free()}})()}getDeviceVerificationStatus(e,r){var t=this;return c(function*(){var i=yield t.olmMachine.getDevice(new v(e),new B(r));if(!i)return null;try{return new qr({signedByOwner:i.isCrossSignedByOwner(),crossSigningVerified:i.isCrossSigningTrusted(),localVerified:i.isLocallyTrusted(),trustCrossSignedDevices:t._trustCrossSignedDevices})}finally{i.free()}})()}getUserVerificationStatus(e){var r=this;return c(function*(){var t=yield r.getOlmMachineOrThrow().getIdentity(new v(e));if(t===void 0)return new Ve(!1,!1,!1);var i=t.isVerified(),n=t.wasPreviouslyVerified(),o=t instanceof Hr?t.identityNeedsUserApproval():!1;return t.free(),new Ve(i,n,!1,o)})()}pinCurrentUserIdentity(e){var r=this;return c(function*(){var t=yield r.getOlmMachineOrThrow().getIdentity(new v(e));if(t===void 0)throw new Error("Cannot pin identity of unknown user");if(t instanceof Qr)throw new Error("Cannot pin identity of own user");yield t.pinCurrentMasterKey()})()}withdrawVerificationRequirement(e){var r=this;return c(function*(){var t=yield r.getOlmMachineOrThrow().getIdentity(new v(e));if(t===void 0)throw new Error("Cannot withdraw verification of unknown user");yield t.withdrawVerification()})()}isCrossSigningReady(){var e=this;return c(function*(){var{privateKeysInSecretStorage:r,privateKeysCachedLocally:t}=yield e.getCrossSigningStatus(),i=!!t.masterKey&&!!t.selfSigningKey&&!!t.userSigningKey,n=yield e.getOwnIdentity();return!!(n!=null&&n.isVerified())&&(i||r)})()}getCrossSigningKeyId(){var e=arguments,r=this;return c(function*(){var t=e.length>0&&e[0]!==void 0?e[0]:$.Master,i=yield r.olmMachine.getIdentity(new v(r.userId));if(!i)return null;try{var n=yield r.olmMachine.crossSigningStatus(),o=n.hasMaster&&n.hasUserSigning&&n.hasSelfSigning;if(!o||!i.isVerified())return null;var a;switch(t){case $.Master:a=i.masterKey;break;case $.SelfSigning:a=i.selfSigningKey;break;case $.UserSigning:a=i.userSigningKey;break;default:return null}var u=JSON.parse(a);return Object.values(u.keys)[0]}finally{i.free()}})()}bootstrapCrossSigning(e){var r=this;return c(function*(){yield r.crossSigningIdentity.bootstrapCrossSigning(e)})()}isSecretStorageReady(){var e=this;return c(function*(){var r=["m.cross_signing.master","m.cross_signing.user_signing","m.cross_signing.self_signing"],t=(yield e.backupManager.getActiveBackupVersion())!=null;return t&&r.push("m.megolm_backup.v1"),vr(e.secretStorage,r)})()}bootstrapSecretStorage(){var e=arguments,r=this;return c(function*(){var{createSecretStorageKey:t,setupNewSecretStorage:i,setupNewKeyBackup:n}=e.length>0&&e[0]!==void 0?e[0]:{},o=i||!(yield r.secretStorageHasAESKey());if(o){if(!t)throw new Error("unable to create a new secret storage key, createSecretStorageKey is not set");r.logger.info("bootstrapSecretStorage: creating new secret storage key");var a=yield t();if(!a)throw new Error("createSecretStorageKey() callback did not return a secret storage key");yield r.addSecretStorageKeyToSecretStorage(a)}var u=yield r.olmMachine.exportCrossSigningKeys(),d=u&&u.masterKey!==void 0&&u.self_signing_key!==void 0&&u.userSigningKey!==void 0;d&&(o||!(yield Ze(r.secretStorage)))&&(r.logger.info("bootstrapSecretStorage: cross-signing keys not yet exported; doing so now."),yield r.secretStorage.store("m.cross_signing.master",u.masterKey),yield r.secretStorage.store("m.cross_signing.user_signing",u.userSigningKey),yield r.secretStorage.store("m.cross_signing.self_signing",u.self_signing_key)),n?yield r.resetKeyBackup():yield r.saveBackupKeyToStorage()})()}saveBackupKeyToStorage(){var e=this;return c(function*(){var r=yield e.backupManager.getServerBackupInfo();if(!r||!r.version){e.logger.info("Not saving backup key to secret storage: no backup info");return}var t=yield e.olmMachine.getBackupKeys();if(!t.decryptionKey){e.logger.info("Not saving backup key to secret storage: no backup key");return}if(!he(t.decryptionKey,r)){e.logger.info("Not saving backup key to secret storage: decryption key does not match backup info");return}var i=t.decryptionKey.toBase64();yield e.secretStorage.store("m.megolm_backup.v1",i)})()}addSecretStorageKeyToSecretStorage(e){var r=this;return c(function*(){var t,i,n,o,a=yield r.secretStorage.addKey(Ne,{passphrase:(t=e.keyInfo)===null||t===void 0?void 0:t.passphrase,name:(i=e.keyInfo)===null||i===void 0?void 0:i.name,key:e.privateKey});yield r.secretStorage.setDefaultKeyId(a.keyId),(n=(o=r.cryptoCallbacks).cacheSecretStorageKey)===null||n===void 0||n.call(o,a.keyId,a.keyInfo,e.privateKey)})()}secretStorageHasAESKey(){var e=this;return c(function*(){var r=yield e.secretStorage.getKey();if(!r)return!1;var[,t]=r;return t.algorithm===Ne})()}getCrossSigningStatus(){var e=this;return c(function*(){var r=yield e.getOlmMachineOrThrow().getIdentity(new v(e.userId)),t=!!(r!=null&&r.masterKey)&&!!(r!=null&&r.selfSigningKey)&&!!(r!=null&&r.userSigningKey);r==null||r.free();var i=yield Ze(e.secretStorage),n=yield e.getOlmMachineOrThrow().crossSigningStatus();return{publicKeysOnDevice:t,privateKeysInSecretStorage:i,privateKeysCachedLocally:{masterKey:!!(n!=null&&n.hasMaster),userSigningKey:!!(n!=null&&n.hasUserSigning),selfSigningKey:!!(n!=null&&n.hasSelfSigning)}}})()}createRecoveryKeyFromPassphrase(e){var r=this;return c(function*(){if(e){var t=xe(32),i=yield fr(e,t,r.RECOVERY_KEY_DERIVATION_ITERATIONS);return{keyInfo:{passphrase:{algorithm:"m.pbkdf2",iterations:r.RECOVERY_KEY_DERIVATION_ITERATIONS,salt:t}},privateKey:i,encodedPrivateKey:Ye(i)}}else{var n=new Uint8Array(32);return globalThis.crypto.getRandomValues(n),{privateKey:n,encodedPrivateKey:Ye(n)}}})()}getEncryptionInfoForEvent(e){var r=this;return c(function*(){return r.eventDecryptor.getEncryptionInfoForEvent(e)})()}getVerificationRequestsToDeviceInProgress(e){var r=this.olmMachine.getVerificationRequests(new v(e));return r.filter(t=>t.roomId===void 0).map(t=>this.makeVerificationRequest(t))}findVerificationRequestDMInProgress(e,r){if(!r)throw new Error("missing userId");var t=this.olmMachine.getVerificationRequests(new v(r)),i=t.find(n=>{var o;return((o=n.roomId)===null||o===void 0?void 0:o.toString())===e});if(i)return this.makeVerificationRequest(i)}requestVerificationDM(e,r){var t=this;return c(function*(){var i=yield t.olmMachine.getIdentity(new v(e));if(!i)throw new Error("unknown userId ".concat(e));try{var n=t._supportedVerificationMethods.map(d=>ne(d)),o=yield i.verificationRequestContent(n),a=yield t.sendVerificationRequestContent(r,o),u=yield i.requestVerification(new w(r),new Yr(a),n);return t.makeVerificationRequest(u)}finally{i.free()}})()}sendVerificationRequestContent(e,r){var t=this;return c(function*(){var i=xe(32),{event_id:n}=yield t.http.authedRequest(m.Put,"/_matrix/client/v3/rooms/".concat(encodeURIComponent(e),"/send/m.room.message/").concat(encodeURIComponent(i)),void 0,r,{prefix:""});return n})()}setSupportedVerificationMethods(e){this._supportedVerificationMethods=e??sr}requestOwnUserVerification(){var e=this;return c(function*(){var r=yield e.olmMachine.getIdentity(new v(e.userId));if(r===void 0)throw new Error("cannot request verification for this device when there is no existing cross-signing key");try{var[t,i]=yield r.requestVerification(e._supportedVerificationMethods.map(ne));return yield e.outgoingRequestProcessor.makeOutgoingRequest(i),e.makeVerificationRequest(t)}finally{r.free()}})()}requestDeviceVerification(e,r){var t=this;return c(function*(){var i=yield t.olmMachine.getDevice(new v(e),new B(r));if(!i)throw new Error("Not a known device");try{var[n,o]=i.requestVerification(t._supportedVerificationMethods.map(ne));return yield t.outgoingRequestProcessor.makeOutgoingRequest(o),t.makeVerificationRequest(n)}finally{i.free()}})()}getSessionBackupPrivateKey(){var e=this;return c(function*(){var r=yield e.olmMachine.getBackupKeys();return r.decryptionKey?pe(r.decryptionKey.toBase64()):null})()}storeSessionBackupPrivateKey(e,r){var t=this;return c(function*(){var i=fe(e);if(!r)throw new Error("storeSessionBackupPrivateKey: version is required");yield t.backupManager.saveBackupDecryptionKey(V.fromBase64(i),r)})()}loadSessionBackupPrivateKeyFromSecretStorage(){var e=this;return c(function*(){var r=yield e.secretStorage.get("m.megolm_backup.v1");if(!r)throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: missing decryption key in secret storage");var t=yield e.backupManager.getServerBackupInfo();if(!t||!t.version)throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: unable to get backup version");var i=V.fromBase64(r);if(!he(i,t))throw new Error("loadSessionBackupPrivateKeyFromSecretStorage: decryption key does not match backup info");yield e.backupManager.saveBackupDecryptionKey(i,t.version)})()}getActiveSessionBackupVersion(){var e=this;return c(function*(){return yield e.backupManager.getActiveBackupVersion()})()}getKeyBackupInfo(){var e=this;return c(function*(){return(yield e.backupManager.getServerBackupInfo())||null})()}isKeyBackupTrusted(e){var r=this;return c(function*(){return yield r.backupManager.isKeyBackupTrusted(e)})()}checkKeyBackupAndEnable(){var e=this;return c(function*(){return yield e.backupManager.checkKeyBackupAndEnable(!0)})()}deleteKeyBackupVersion(e){var r=this;return c(function*(){yield r.backupManager.deleteKeyBackupVersion(e)})()}resetKeyBackup(){var e=this;return c(function*(){var r=yield e.backupManager.setupKeyBackup(t=>e.signObject(t));(yield e.secretStorageHasAESKey())&&(yield e.secretStorage.store("m.megolm_backup.v1",r.decryptionKey.toBase64())),e.checkKeyBackupAndEnable()})()}disableKeyStorage(){var e=this;return c(function*(){var r=yield e.getKeyBackupInfo();r!=null&&r.version?yield e.deleteKeyBackupVersion(r.version):e.logger.error("Can't delete key backup version: no version available"),yield e.deleteSecretStorage(),yield e.dehydratedDeviceManager.delete()})()}signObject(e){var r=this;return c(function*(){var t=new Map(Object.entries(e.signatures||{})),i=e.unsigned;delete e.signatures,delete e.unsigned;var n=t.get(r.userId)||{},o=ot.stringify(e),a=yield r.olmMachine.sign(o),u=JSON.parse(a.asJSON());t.set(r.userId,nr(nr({},n),u[r.userId])),i!==void 0&&(e.unsigned=i),e.signatures=Object.fromEntries(t.entries())})()}restoreKeyBackupWithPassphrase(e,r){var t=this;return c(function*(){var i=yield t.backupManager.getServerBackupInfo();if(!(i!=null&&i.version))throw new Error("No backup info available");var n=yield Rt(i.auth_data,e);return yield t.storeSessionBackupPrivateKey(n,i.version),t.restoreKeyBackup(r)})()}restoreKeyBackup(e){var r=this;return c(function*(){var t=yield r.olmMachine.getBackupKeys(),{decryptionKey:i,backupVersion:n}=t;if(!i||!n)throw new Error("No decryption key found in crypto store");var o=pe(i.toBase64()),a=yield r.backupManager.requestKeyBackupVersion(n);if(!a)throw new Error("Backup version to restore ".concat(n," not found on server"));var u=yield r.getBackupDecryptor(a,o);try{var d;return e==null||(d=e.progressCallback)===null||d===void 0||d.call(e,{stage:A.Fetch}),yield r.backupManager.restoreKeyBackup(n,u,e)}finally{u.free()}})()}isDehydrationSupported(){var e=this;return c(function*(){return yield e.dehydratedDeviceManager.isSupported()})()}startDehydration(){var e=arguments,r=this;return c(function*(){var t=e.length>0&&e[0]!==void 0?e[0]:{};if(!(yield r.isCrossSigningReady())||!(yield r.isSecretStorageReady()))throw new Error("Device dehydration requires cross-signing and secret storage to be set up");return yield r.dehydratedDeviceManager.start(t||{})})()}importSecretsBundle(e){var r=this;return c(function*(){var t=$r.from_json(e);yield r.getOlmMachineOrThrow().importSecretsBundle(t)})()}exportSecretsBundle(){var e=this;return c(function*(){var r=yield e.getOlmMachineOrThrow().exportSecretsBundle(),t=r.to_json();return r.free(),t})()}encryptToDeviceMessages(e,r,t){var i=this;return c(function*(){var n=new cr(i.logger,"encryptToDeviceMessages"),o=new Set(r.map(u=>{var{userId:d}=u;return d}));yield i.keyClaimManager.ensureSessionsForUsers(n,Array.from(o).map(u=>new v(u)));var a={batch:[],eventType:b.RoomMessageEncrypted};return yield Promise.all(r.map(function(){var u=c(function*(d){var{userId:l,deviceId:h}=d,y=yield i.olmMachine.getDevice(new v(l),new B(h));if(y){var f=JSON.parse(yield y.encryptToDeviceEvent(e,t));a.batch.push({deviceId:h,userId:l,payload:f})}else i.logger.warn("encryptToDeviceMessages: unknown device ".concat(l,":").concat(h))});return function(d){return u.apply(this,arguments)}}())),a})()}resetEncryption(e){var r=this;return c(function*(){r.logger.debug("resetEncryption: resetting encryption"),r.dehydratedDeviceManager.delete(),yield r.backupManager.deleteAllKeyBackupVersions(),yield r.deleteSecretStorage(),yield r.crossSigningIdentity.bootstrapCrossSigning({setupNewCrossSigning:!0,authUploadDeviceSigningKeys:e}),yield r.resetKeyBackup(),r.logger.debug("resetEncryption: ended")})()}deleteSecretStorage(){var e=this;return c(function*(){yield e.secretStorage.store("m.cross_signing.master",null),yield e.secretStorage.store("m.cross_signing.self_signing",null),yield e.secretStorage.store("m.cross_signing.user_signing",null),yield e.secretStorage.store("m.megolm_backup.v1",null);var r=yield e.secretStorage.getDefaultKeyId();r&&(yield e.secretStorage.store("m.secret_storage.key.".concat(r),null)),yield e.secretStorage.setDefaultKeyId(null)})()}receiveSyncChanges(e){var r=this;return c(function*(){var{events:t,oneTimeKeysCounts:i=new Map,unusedFallbackKeys:n,devices:o=new Je}=e;return yield r.olmMachine.receiveSyncChanges(t?JSON.stringify(t):"[]",o,i,n)})()}preprocessToDeviceMessages(e){var r=this;return c(function*(){var t=yield r.receiveSyncChanges({events:e}),i=[];for(var n of t){var o=JSON.parse(n.rawEvent);if(o.type===b.KeyVerificationRequest){var a=o.sender,u=o.content.transaction_id;u&&a&&r.onIncomingKeyVerificationRequest(a,u)}switch(n.type){case X.Decrypted:{var d,l=n.encryptionInfo;i.push({message:o,encryptionInfo:{sender:l.sender.toString(),senderDevice:(d=l.senderDevice)===null||d===void 0?void 0:d.toString(),senderCurve25519KeyBase64:l.senderCurve25519Key,senderVerified:l.isSenderVerified()}});break}case X.PlainText:{i.push({message:o,encryptionInfo:null});break}case X.UnableToDecrypt:break;case X.Invalid:break}}return i})()}processKeyCounts(e,r){var t=this;return c(function*(){var i=e&&new Map(Object.entries(e)),n=r&&new Set(r);(i!==void 0||n!==void 0)&&(yield t.receiveSyncChanges({oneTimeKeysCounts:i,unusedFallbackKeys:n}))})()}processDeviceLists(e){var r=this;return c(function*(){var t,i,n=new Je((t=e.changed)===null||t===void 0?void 0:t.map(o=>new v(o)),(i=e.left)===null||i===void 0?void 0:i.map(o=>new v(o)));yield r.receiveSyncChanges({devices:n})})()}onCryptoEvent(e,r){var t=this;return c(function*(){var i=r.getContent(),n=new yr;if(i.algorithm==="m.megolm.v1.aes-sha2")n.algorithm=G.MegolmV1AesSha2;else{t.logger.warn("Room ".concat(e.roomId,": ignoring crypto event with invalid algorithm ").concat(i.algorithm));return}try{n.sessionRotationPeriodMs=i.rotation_period_ms,n.sessionRotationPeriodMessages=i.rotation_period_msgs,yield t.olmMachine.setRoomSettings(new w(e.roomId),n)}catch(a){t.logger.warn("Room ".concat(e.roomId,": ignoring crypto event which caused error: ").concat(a));return}var o=t.roomEncryptors[e.roomId];o?o.onCryptoEvent(i):t.roomEncryptors[e.roomId]=new at(t.logger.getChild("[".concat(e.roomId," encryption]")),t.olmMachine,t.keyClaimManager,t.outgoingRequestsManager,e,i)})()}onSyncCompleted(e){this.outgoingRequestsManager.doProcessOutgoingRequests().catch(r=>{this.logger.warn("onSyncCompleted: Error processing outgoing requests",r)})}markAllTrackedUsersAsDirty(){var e=this;return c(function*(){yield e.olmMachine.markAllTrackedUsersAsDirty()})()}onIncomingKeyVerificationRequest(e,r){var t=this.olmMachine.getVerificationRequest(new v(e),r);t?this.emit(p.VerificationRequestReceived,this.makeVerificationRequest(t)):this.logger.info("Ignoring just-received verification request ".concat(r," which did not start a rust-side verification"))}makeVerificationRequest(e){return new mt(this.logger,this.olmMachine,e,this.outgoingRequestProcessor,this._supportedVerificationMethods)}onRoomMembership(e,r,t){var i=this.roomEncryptors[e.getRoomId()];i&&i.onRoomMembership(r)}onRoomKeysUpdated(e){var r=this;return c(function*(){for(var t of e)r.onRoomKeyUpdated(t);r.backupManager.maybeUploadKey()})()}onRoomKeyUpdated(e){var r=this;if(!this.stopped){this.logger.debug("Got update for session ".concat(e.sessionId," from sender ").concat(e.senderKey.toBase64()," in ").concat(e.roomId.toString()));var t=this.eventDecryptor.getEventsPendingRoomKey(e.roomId.toString(),e.sessionId);if(t.length!==0){this.logger.debug("Retrying decryption on events:",t.map(o=>"".concat(o.getId())));var i=function(a){a.attemptDecryption(r,{isRetry:!0}).catch(u=>{r.logger.info("Still unable to decrypt event ".concat(a.getId()," after receiving key"))})};for(var n of t)i(n)}}}onRoomKeysWithheld(e){var r=this;return c(function*(){for(var t of e){r.logger.debug("Got withheld message for session ".concat(t.sessionId," in ").concat(t.roomId.toString()));var i=r.eventDecryptor.getEventsPendingRoomKey(t.roomId.toString(),t.sessionId);if(i.length===0)return;r.logger.debug("Retrying decryption on events:",i.map(o=>"".concat(o.getId())));for(var n of i)n.attemptDecryption(r,{isRetry:!0}).catch(o=>{})}})()}onUserIdentityUpdated(e){var r=this;return c(function*(){var t=yield r.getUserVerificationStatus(e.toString());r.emit(p.UserTrustStatusChanged,e.toString(),t),e.toString()===r.userId&&(r.emit(p.KeysChanged,{}),yield r.checkKeyBackupAndEnable())})()}onDevicesUpdated(e){var r=this;return c(function*(){r.emit(p.WillUpdateDevices,e,!1),r.emit(p.DevicesUpdated,e,!1)})()}handleSecretReceived(e,r){var t=this;return c(function*(){return t.logger.debug("onReceiveSecret: Received secret ".concat(e)),e==="m.megolm_backup.v1"?yield t.backupManager.handleBackupSecretReceived(r):!1})()}checkSecrets(e){var r=this;return c(function*(){var t=yield r.olmMachine.getSecretsFromInbox(e);for(var i of t)if(yield r.handleSecretReceived(e,i))break;yield r.olmMachine.deleteSecretsFromInbox(e)})()}onLiveEventFromSync(e){var r=this;return c(function*(){if(!(e.isState()||e.getUnsigned().transaction_id)){var t=function(){var a=c(function*(u){kt(e)&&(yield r.onKeyVerificationEvent(u))});return function(d){return a.apply(this,arguments)}}();if(e.isDecryptionFailure()||e.isEncrypted()){var i=3e5,n=setTimeout(()=>e.off(ue.Decrypted,o),i),o=(a,u)=>{u||(clearTimeout(n),e.off(ue.Decrypted,o),t(a))};e.on(ue.Decrypted,o)}else yield t(e)}})()}onKeyVerificationEvent(e){var r=this;return c(function*(){var t=e.getRoomId();if(!t)throw new Error("missing roomId in the event");r.logger.debug("Incoming verification event ".concat(e.getId()," type ").concat(e.getType()," from ").concat(e.getSender())),yield r.olmMachine.receiveVerificationEvent(JSON.stringify({event_id:e.getId(),type:e.getType(),sender:e.getSender(),state_key:e.getStateKey(),content:e.getContent(),origin_server_ts:e.getTs()}),new w(t)),e.getType()===b.RoomMessage&&e.getContent().msgtype===lr.KeyVerificationRequest&&r.onIncomingKeyVerificationRequest(e.getSender(),e.getId()),r.outgoingRequestsManager.doProcessOutgoingRequests().catch(i=>{r.logger.warn("onKeyVerificationRequest: Error processing outgoing requests",i)})})()}getOwnIdentity(){var e=this;return c(function*(){return yield e.olmMachine.getIdentity(new v(e.userId))})()}}class Et{constructor(e,r,t){this.logger=e,this.olmMachine=r,this.perSessionBackupDownloader=t,g(this,"eventsPendingKey",new Ae(()=>new Ae(()=>new Set)))}attemptEventDecryption(e,r){var t=this;return c(function*(){t.addEventToPendingList(e);var i;switch(r.kind){case oe.AllDevicesIsolationMode:i=He.Untrusted;break;case oe.OnlySignedDevicesIsolationMode:i=He.CrossSignedOrLegacy;break}try{var n=yield t.olmMachine.decryptRoomEvent(or(e),new w(e.getRoomId()),new zr(i));return t.removeEventFromPendingList(e),{clearEvent:JSON.parse(n.event),claimedEd25519Key:n.senderClaimedEd25519Key,senderCurve25519Key:n.senderCurve25519Key,forwardingCurve25519KeyChain:n.forwardingCurve25519KeyChain}}catch(o){if(o instanceof Zr)t.onMegolmDecryptionError(e,o,yield t.perSessionBackupDownloader.getServerBackupInfo());else throw new _(S.UNKNOWN_ERROR,"Unknown error")}})()}onMegolmDecryptionError(e,r,t){var i=e.getWireContent(),n={sender_key:i.sender_key,session_id:i.session_id};if(r.code===q.MissingRoomKey||r.code===q.UnknownMessageIndex){this.perSessionBackupDownloader.onDecryptionKeyMissingError(e.getRoomId(),i.session_id);var o=e.getMembershipAtEvent();if(o&&o!==se.Join&&o!==se.Invite)throw new _(S.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 t===null?new _(S.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 _(S.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 _(S.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED,"This message was sent before this device logged in, and key backup is not working.",n)}if(r.maybe_withheld){var a=r.maybe_withheld==="The sender has disabled encrypting to unverified devices."?S.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE:S.MEGOLM_KEY_WITHHELD;throw new _(a,r.maybe_withheld,n)}switch(r.code){case q.MissingRoomKey:throw new _(S.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,"The sender's device has not sent us the keys for this message.",n);case q.UnknownMessageIndex:throw new _(S.OLM_UNKNOWN_MESSAGE_INDEX,"The sender's device has not sent us the keys for this message at this index.",n);case q.SenderIdentityVerificationViolation:throw this.removeEventFromPendingList(e),new _(S.SENDER_IDENTITY_PREVIOUSLY_VERIFIED,"The sender identity is unverified, but was previously verified.");case q.UnknownSenderDevice:throw this.removeEventFromPendingList(e),new _(S.UNKNOWN_SENDER_DEVICE,"The sender device is not known.");case q.UnsignedSenderDevice:throw this.removeEventFromPendingList(e),new _(S.UNSIGNED_SENDER_DEVICE,"The sender identity is not cross-signed.");default:throw new _(S.UNKNOWN_ERROR,r.description,n)}}getEncryptionInfoForEvent(e){var r=this;return c(function*(){if(!e.getClearContent()||e.isDecryptionFailure())return null;if(e.status!==null)return{shieldColour:ie.NONE,shieldReason:null};var t=yield r.olmMachine.getRoomEventEncryptionInfo(or(e),new w(e.getRoomId()));return Mt(r.logger,t)})()}getEventsPendingRoomKey(e,r){var t=this.eventsPendingKey.get(e);if(!t)return[];var i=t.get(r);return i?[...i]:[]}addEventToPendingList(e){var r=e.getRoomId();if(r){var t=this.eventsPendingKey.getOrCreate(r),i=t.getOrCreate(e.getWireContent().session_id);i.add(e)}}removeEventFromPendingList(e){var r=e.getRoomId();if(r){var t=this.eventsPendingKey.getOrCreate(r);if(t){var i=t.get(e.getWireContent().session_id);i&&(i.delete(e),i.size===0&&(t.delete(e.getWireContent().session_id),t.size===0&&this.eventsPendingKey.delete(r)))}}}}function or(s){return JSON.stringify({event_id:s.getId(),type:s.getWireType(),sender:s.getSender(),state_key:s.getStateKey(),content:s.getWireContent(),origin_server_ts:s.getTs()})}function Mt(s,e){if(e===void 0)return null;var r=e.shieldState(!1),t;switch(r.color){case Qe.Grey:t=ie.GREY;break;case Qe.None:t=ie.NONE;break;default:t=ie.RED}var i;switch(r.code){case void 0:case null:i=null;break;case T.AuthenticityNotGuaranteed:i=C.AUTHENTICITY_NOT_GUARANTEED;break;case T.UnknownDevice:i=C.UNKNOWN_DEVICE;break;case T.UnsignedDevice:i=C.UNSIGNED_DEVICE;break;case T.UnverifiedIdentity:i=C.UNVERIFIED_IDENTITY;break;case T.SentInClear:i=C.SENT_IN_CLEAR;break;case T.VerificationViolation:i=C.VERIFICATION_VIOLATION;break;case T.MismatchedSender:i=C.MISMATCHED_SENDER;break;default:i=C.UNKNOWN;break}return{shieldColour:t,shieldReason:i}}function It(s){return _e.apply(this,arguments)}function _e(){return _e=c(function*(s){var e,{logger:r,legacyStore:t}=s;if(yield hr(),!(yield t.containsData()))return;yield t.startup();var i=null;if(yield t.doTxn("readonly",[J.STORE_ACCOUNT],y=>{t.getAccount(y,f=>{i=f})}),!i){r.debug("Legacy crypto store is not set up (no account found). Not migrating.");return}var n=yield t.getMigrationState();if(n>=R.MEGOLM_SESSIONS_MIGRATED)return;var o=yield Dt(r,t),a=yield Bt(r,t),u=1+o+a;r.info("Migrating data from legacy crypto store. ".concat(o," olm sessions and ").concat(a," megolm sessions to migrate."));var d=0;function l(y){var f;d+=y,(f=s.legacyMigrationProgressListener)===null||f===void 0||f.call(s,d,u)}l(0);var h=new TextEncoder().encode(s.legacyPickleKey);n===R.NOT_STARTED&&(r.info("Migrating data from legacy crypto store. Step 1: base data"),yield Ct(s.http,s.userId,s.deviceId,t,h,s.storeHandle,r),n=R.INITIAL_DATA_MIGRATED,yield t.setMigrationState(n)),l(1),n===R.INITIAL_DATA_MIGRATED&&(r.info("Migrating data from legacy crypto store. Step 2: olm sessions (".concat(o," sessions to migrate).")),yield Ot(r,t,h,s.storeHandle,l),n=R.OLM_SESSIONS_MIGRATED,yield t.setMigrationState(n)),n===R.OLM_SESSIONS_MIGRATED&&(r.info("Migrating data from legacy crypto store. Step 3: megolm sessions (".concat(a," sessions to migrate).")),yield qt(r,t,h,s.storeHandle,l),n=R.MEGOLM_SESSIONS_MIGRATED,yield t.setMigrationState(n)),(e=s.legacyMigrationProgressListener)===null||e===void 0||e.call(s,-1,-1),r.info("Migration from legacy crypto store complete")}),_e.apply(this,arguments)}function Ct(s,e,r,t,i,n,o){return be.apply(this,arguments)}function be(){return be=c(function*(s,e,r,t,i,n,o){var a=new Xr;a.userId=new v(e),a.deviceId=new B(r),yield t.doTxn("readonly",[J.STORE_ACCOUNT],I=>t.getAccount(I,N=>{a.pickledAccount=N??""}));var u=yield re(t,i,"m.megolm_backup.v1");if(u){for(var d=!1,l=null;!d;)try{l=yield Sr(s),d=!0}catch(I){o.info("Failed to get backup version during migration, retrying in 2 seconds",I),yield P(2e3)}if(l&&l.algorithm=="m.megolm_backup.v1.curve25519-aes-sha2")try{var h,y=V.fromBase64(u),f=(h=l.auth_data)===null||h===void 0?void 0:h.public_key,E=y.megolmV1PublicKey.publicKeyBase64==f;E?(a.backupVersion=l.version,a.backupRecoveryKey=u):o.debug("The backup key to migrate does not match the active backup version","Cached pub key: ".concat(y.megolmV1PublicKey.publicKeyBase64),"Active pub key: ".concat(f))}catch(I){o.warn("Failed to check if the backup key to migrate matches the active backup version",I)}}a.privateCrossSigningMasterKey=yield re(t,i,"master"),a.privateCrossSigningSelfSigningKey=yield re(t,i,"self_signing"),a.privateCrossSigningUserSigningKey=yield re(t,i,"user_signing"),yield qe.migrateBaseData(a,i,n,o)}),be.apply(this,arguments)}function Dt(s,e){return we.apply(this,arguments)}function we(){return we=c(function*(s,e){s.debug("Counting olm sessions to be migrated");var r;return yield e.doTxn("readonly",[J.STORE_SESSIONS],t=>e.countEndToEndSessions(t,i=>r=i)),r}),we.apply(this,arguments)}function Bt(s,e){return Re.apply(this,arguments)}function Re(){return Re=c(function*(s,e){return s.debug("Counting megolm sessions to be migrated"),yield e.countEndToEndInboundGroupSessions()}),Re.apply(this,arguments)}function Ot(s,e,r,t,i){return Ke.apply(this,arguments)}function Ke(){return Ke=c(function*(s,e,r,t,i){for(;;){var n=yield e.getEndToEndSessionsBatch();if(n===null)return;s.debug("Migrating batch of ".concat(n.length," olm sessions"));var o=[];for(var a of n){var u=new et;u.senderKey=a.deviceKey,u.pickle=a.session,u.lastUseTime=u.creationTime=new Date(a.lastReceivedMessageTs),o.push(u)}yield qe.migrateOlmSessions(o,r,t,s),yield e.deleteEndToEndSessionsBatch(n),i(n.length)}}),Ke.apply(this,arguments)}function qt(s,e,r,t,i){return Ee.apply(this,arguments)}function Ee(){return Ee=c(function*(s,e,r,t,i){for(;;){var n=yield e.getEndToEndInboundGroupSessionsBatch();if(n===null)return;s.debug("Migrating batch of ".concat(n.length," megolm sessions"));var o=[];for(var a of n){var u,d=a.sessionData,l=new rt;l.pickle=d.session,l.roomId=new w(d.room_id),l.senderKey=a.senderKey,l.senderSigningKey=(u=d.keysClaimed)===null||u===void 0?void 0:u.ed25519,l.backedUp=!a.needsBackup,l.imported=d.untrusted===!0,o.push(l)}yield qe.migrateMegolmSessions(o,r,t,s),yield e.deleteEndToEndInboundGroupSessionsBatch(n),i(n.length)}}),Ee.apply(this,arguments)}function Tt(s){return Me.apply(this,arguments)}function Me(){return Me=c(function*(s){var{logger:e,legacyStore:r,olmMachine:t}=s;if(yield r.containsData()){var i=yield r.getMigrationState();if(!(i>=R.ROOM_SETTINGS_MIGRATED)){var n={};yield r.doTxn("readwrite",[J.STORE_ROOMS],d=>{r.getEndToEndRooms(d,l=>{n=l})}),e.debug("Migrating ".concat(Object.keys(n).length," sets of room settings"));for(var[o,a]of Object.entries(n))try{var u=new yr;if(a.algorithm!=="m.megolm.v1.aes-sha2"){e.warn("Room ".concat(o,": ignoring room with invalid algorithm ").concat(a.algorithm));continue}u.algorithm=G.MegolmV1AesSha2,u.sessionRotationPeriodMs=a.rotation_period_ms,u.sessionRotationPeriodMessages=a.rotation_period_msgs,yield t.setRoomSettings(new w(o),u)}catch(d){e.warn("Room ".concat(o,": ignoring settings ").concat(JSON.stringify(a)," which caused error ").concat(d))}e.debug("Completed room settings migration"),yield r.setMigrationState(R.ROOM_SETTINGS_MIGRATED)}}}),Me.apply(this,arguments)}function re(s,e,r){return Ie.apply(this,arguments)}function Ie(){return Ie=c(function*(s,e,r){var t=yield new Promise(i=>{s.doTxn("readonly",[J.STORE_ACCOUNT],n=>{s.getSecretStorePrivateKey(n,i,r)})});return t&&t.ciphertext&&t.iv&&t.mac?yield Tr(t,e,r):t instanceof Uint8Array?fe(t):void 0}),Ie.apply(this,arguments)}function Pt(s){return Ce.apply(this,arguments)}function Ce(){return Ce=c(function*(s){var{legacyCryptoStore:e,rustCrypto:r,logger:t}=s,i=yield r.getOwnIdentity();if(i&&!i.isVerified()){var n=yield Ut(e);if(n){var o=JSON.parse(i.masterKey);if(!o.keys||Object.keys(o.keys).length===0){t.error("Post Migration | Unexpected error: no master key in the rust session.");return}var a=Object.values(o.keys)[0];a&&a==n&&(t.info("Post Migration: Migrating legacy trusted MSK: ".concat(n," to locally verified.")),yield i.verify())}}}),Ce.apply(this,arguments)}function Ut(s){return De.apply(this,arguments)}function De(){return De=c(function*(s){var e=null;return yield s.doTxn("readonly","account",r=>{s.getCrossSigningKeys(r,t=>{var i=t==null?void 0:t.master;i&&Object.keys(i.keys).length!=0&&(e=Object.values(i.keys)[0])})}),e}),De.apply(this,arguments)}function ar(s,e){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(s);e&&(t=t.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),r.push.apply(r,t)}return r}function Vt(s){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?ar(Object(r),!0).forEach(function(t){g(s,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(r)):ar(Object(r)).forEach(function(t){Object.defineProperty(s,t,Object.getOwnPropertyDescriptor(r,t))})}return s}function Lt(s){return Be.apply(this,arguments)}function Be(){return Be=c(function*(s){var{logger:e}=s;e.debug("Initialising Rust crypto-sdk WASM artifact"),yield hr(),e.debug("Opening Rust CryptoStore");var r;s.storePrefix?s.storeKey?r=yield de.openWithKey(s.storePrefix,s.storeKey,e):r=yield de.open(s.storePrefix,s.storePassphrase,e):r=yield de.open(null,null,e),s.legacyCryptoStore&&(yield It(Vt({legacyStore:s.legacyCryptoStore,storeHandle:r},s)));var t=yield Nt(e,s.http,s.userId,s.deviceId,s.secretStorage,s.cryptoCallbacks,r,s.legacyCryptoStore);return r.free(),e.debug("Completed rust crypto-sdk setup"),t}),Be.apply(this,arguments)}function Nt(s,e,r,t,i,n,o,a){return Oe.apply(this,arguments)}function Oe(){return Oe=c(function*(s,e,r,t,i,n,o,a){s.debug("Init OlmMachine");var u=yield tt.initFromStore(new v(r),new B(t),o,s);a&&(yield Tt({logger:s,legacyStore:a,olmMachine:u})),u.roomKeyRequestsEnabled=!1;var d=new Kt(s,u,e,r,t,i,n);if(yield u.registerRoomKeyUpdatedCallback(y=>d.onRoomKeysUpdated(y)),yield u.registerRoomKeysWithheldCallback(y=>d.onRoomKeysWithheld(y)),yield u.registerUserIdentityUpdatedCallback(y=>d.onUserIdentityUpdated(y)),yield u.registerDevicesUpdatedCallback(y=>d.onDevicesUpdated(y)),d.checkSecrets("m.megolm_backup.v1"),yield u.registerReceiveSecretCallback((y,f)=>d.checkSecrets(y)),yield u.outgoingRequests(),a&&(yield a.containsData())){var l=yield a.getMigrationState();if(l<R.INITIAL_OWN_KEY_QUERY_DONE){s.debug("Performing initial key query after migration");for(var h=!1;!h;)try{yield d.userHasCrossSigningKeys(r),h=!0}catch(y){s.error("Failed to check for cross-signing keys after migration, retrying",y)}yield Pt({legacyCryptoStore:a,rustCrypto:d,logger:s}),yield a.setMigrationState(R.INITIAL_OWN_KEY_QUERY_DONE)}}return d}),Oe.apply(this,arguments)}export{Lt as initRustCrypto};
3
- //# sourceMappingURL=index-CmKv4Ftn.js.map
3
+ //# sourceMappingURL=index-BuLS5UUE.js.map