@element-hq/element-call-embedded 0.9.0-release-test.10 → 0.9.0-release-test.11

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