{"version":3,"file":"CrossSigning.js","names":["_olmlib","require","_logger","_indexeddbCryptoStore","_aes","KEY_REQUEST_TIMEOUT_MS","publicKeyFromKeyInfo","keyInfo","Object","values","keys","CrossSigningInfo","constructor","userId","callbacks","cacheCallbacks","_defineProperty2","default","fromStorage","obj","res","prop","hasOwnProperty","toStorage","firstUse","crossSigningVerifiedBefore","getCrossSigningKey","type","expectedPubkey","shouldCache","indexOf","Error","undefined","getId","validateKey","key","signing","global","Olm","PkSigning","gotPubkey","init_with_seed","free","privkey","getCrossSigningKeyCache","cacheresult","result","storeCrossSigningKeyCache","isStoredInSecretStorage","secretStorage","stored","isStored","intersect","s","k","length","storeInSecretStorage","privateKey","encodedKey","encodeBase64","store","getFromSecretStorage","get","decodeBase64","isStoredInKeyCache","types","t","_cacheCallbacks$getCr","call","getCrossSigningKeysFromCache","Map","_cacheCallbacks$getCr2","privKey","set","resetKeys","level","saveCrossSigningKeys","CrossSigningLevel","MASTER","master","USER_SIGNING","SELF_SIGNING","privateKeys","masterSigning","masterPub","generate_seed","user_id","usage","sskSigning","self_signing","sskPub","pkSign","uskSigning","user_signing","uskPub","assign","clearKeys","setKeys","signingKeys","error","logger","masterKey","pkVerify","e","updateCrossSigningVerifiedBefore","isCrossSigningVerified","signObject","data","pubkey","signUser","info","signDevice","device","algorithms","device_id","deviceId","checkUserTrust","userCrossSigning","UserTrustLevel","userTrusted","userMaster","uskId","checkDeviceTrust","localTrust","trustCrossSignedDevices","userTrust","userSSK","DeviceTrustLevel","deviceObj","deviceToObject","fromUserTrustLevel","getCacheCallbacks","exports","signatures","crossSigningVerified","tofu","isVerified","wasCrossSigningVerified","isTofu","localVerified","userTrustLevel","Boolean","isLocallyVerified","createCryptoStoreCacheCallbacks","olmDevice","_expectedPublicKey","Promise","resolve","doTxn","IndexedDBCryptoStore","STORE_ACCOUNT","txn","getSecretStorePrivateKey","ciphertext","pickleKey","Buffer","from","decrypted","decryptAES","Uint8Array","encryptedKey","encryptAES","storeSecretStorePrivateKey","requestKeysDuringVerification","baseApis","getUserId","log","reject","client","original","crypto","crossSigningInfo","crossSigning","debug","promise","requestSecret","decoded","timeout","setTimeout","backupKeyPromise","cachedKey","getSessionBackupPrivateKey","secretReq","base64Key","decodedKey","storeSessionBackupPrivateKey","backupInfo","getKeyBackupVersion","restoreKeyBackupWithCache","then","race","all","catch","warn"],"sources":["../../src/crypto/CrossSigning.ts"],"sourcesContent":["/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Cross signing methods\n */\n\nimport { PkSigning } from \"@matrix-org/olm\";\n\nimport { decodeBase64, encodeBase64, IObject, pkSign, pkVerify } from \"./olmlib\";\nimport { logger } from \"../logger\";\nimport { IndexedDBCryptoStore } from \"../crypto/store/indexeddb-crypto-store\";\nimport { decryptAES, encryptAES } from \"./aes\";\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { SecretStorage } from \"./SecretStorage\";\nimport { ICrossSigningKey, ISignedKey, MatrixClient } from \"../client\";\nimport { OlmDevice } from \"./OlmDevice\";\nimport { ICryptoCallbacks } from \".\";\nimport { ISignatures } from \"../@types/signed\";\nimport { CryptoStore, SecretStorePrivateKeys } from \"./store/base\";\nimport { SecretStorageKeyDescription } from \"../secret-storage\";\n\nconst KEY_REQUEST_TIMEOUT_MS = 1000 * 60;\n\nfunction publicKeyFromKeyInfo(keyInfo: ICrossSigningKey): string {\n // `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }\n // We assume only a single key, and we want the bare form without type\n // prefix, so we select the values.\n return Object.values(keyInfo.keys)[0];\n}\n\nexport interface ICacheCallbacks {\n getCrossSigningKeyCache?(type: string, expectedPublicKey?: string): Promise;\n storeCrossSigningKeyCache?(type: string, key?: Uint8Array): Promise;\n}\n\nexport interface ICrossSigningInfo {\n keys: Record;\n firstUse: boolean;\n crossSigningVerifiedBefore: boolean;\n}\n\nexport class CrossSigningInfo {\n public keys: Record = {};\n public firstUse = true;\n // This tracks whether we've ever verified this user with any identity.\n // When you verify a user, any devices online at the time that receive\n // the verifying signature via the homeserver will latch this to true\n // and can use it in the future to detect cases where the user has\n // become unverified later for any reason.\n private crossSigningVerifiedBefore = false;\n\n /**\n * Information about a user's cross-signing keys\n *\n * @param userId - the user that the information is about\n * @param callbacks - Callbacks used to interact with the app\n * Requires getCrossSigningKey and saveCrossSigningKeys\n * @param cacheCallbacks - Callbacks used to interact with the cache\n */\n public constructor(\n public readonly userId: string,\n private callbacks: ICryptoCallbacks = {},\n private cacheCallbacks: ICacheCallbacks = {},\n ) {}\n\n public static fromStorage(obj: ICrossSigningInfo, userId: string): CrossSigningInfo {\n const res = new CrossSigningInfo(userId);\n for (const prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n // @ts-ignore - ts doesn't like this and nor should we\n res[prop] = obj[prop];\n }\n }\n return res;\n }\n\n public toStorage(): ICrossSigningInfo {\n return {\n keys: this.keys,\n firstUse: this.firstUse,\n crossSigningVerifiedBefore: this.crossSigningVerifiedBefore,\n };\n }\n\n /**\n * Calls the app callback to ask for a private key\n *\n * @param type - The key type (\"master\", \"self_signing\", or \"user_signing\")\n * @param expectedPubkey - The matching public key or undefined to use\n * the stored public key for the given key type.\n * @returns An array with [ public key, Olm.PkSigning ]\n */\n public async getCrossSigningKey(type: string, expectedPubkey?: string): Promise<[string, PkSigning]> {\n const shouldCache = [\"master\", \"self_signing\", \"user_signing\"].indexOf(type) >= 0;\n\n if (!this.callbacks.getCrossSigningKey) {\n throw new Error(\"No getCrossSigningKey callback supplied\");\n }\n\n if (expectedPubkey === undefined) {\n expectedPubkey = this.getId(type)!;\n }\n\n function validateKey(key: Uint8Array | null): [string, PkSigning] | undefined {\n if (!key) return;\n const signing = new global.Olm.PkSigning();\n const gotPubkey = signing.init_with_seed(key);\n if (gotPubkey === expectedPubkey) {\n return [gotPubkey, signing];\n }\n signing.free();\n }\n\n let privkey: Uint8Array | null = null;\n if (this.cacheCallbacks.getCrossSigningKeyCache && shouldCache) {\n privkey = await this.cacheCallbacks.getCrossSigningKeyCache(type, expectedPubkey);\n }\n\n const cacheresult = validateKey(privkey);\n if (cacheresult) {\n return cacheresult;\n }\n\n privkey = await this.callbacks.getCrossSigningKey(type, expectedPubkey);\n const result = validateKey(privkey);\n if (result) {\n if (this.cacheCallbacks.storeCrossSigningKeyCache && shouldCache) {\n await this.cacheCallbacks.storeCrossSigningKeyCache(type, privkey!);\n }\n return result;\n }\n\n /* No keysource even returned a key */\n if (!privkey) {\n throw new Error(\"getCrossSigningKey callback for \" + type + \" returned falsey\");\n }\n\n /* We got some keys from the keysource, but none of them were valid */\n throw new Error(\"Key type \" + type + \" from getCrossSigningKey callback did not match\");\n }\n\n /**\n * Check whether the private keys exist in secret storage.\n * XXX: This could be static, be we often seem to have an instance when we\n * want to know this anyway...\n *\n * @param secretStorage - The secret store using account data\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n public async isStoredInSecretStorage(\n secretStorage: SecretStorage,\n ): Promise | null> {\n // check what SSSS keys have encrypted the master key (if any)\n const stored = (await secretStorage.isStored(\"m.cross_signing.master\")) || {};\n // then check which of those SSSS keys have also encrypted the SSK and USK\n function intersect(s: Record): void {\n for (const k of Object.keys(stored)) {\n if (!s[k]) {\n delete stored[k];\n }\n }\n }\n for (const type of [\"self_signing\", \"user_signing\"]) {\n intersect((await secretStorage.isStored(`m.cross_signing.${type}`)) || {});\n }\n return Object.keys(stored).length ? stored : null;\n }\n\n /**\n * Store private keys in secret storage for use by other devices. This is\n * typically called in conjunction with the creation of new cross-signing\n * keys.\n *\n * @param keys - The keys to store\n * @param secretStorage - The secret store using account data\n */\n public static async storeInSecretStorage(\n keys: Map,\n secretStorage: SecretStorage,\n ): Promise {\n for (const [type, privateKey] of keys) {\n const encodedKey = encodeBase64(privateKey);\n await secretStorage.store(`m.cross_signing.${type}`, encodedKey);\n }\n }\n\n /**\n * Get private keys from secret storage created by some other device. This\n * also passes the private keys to the app-specific callback.\n *\n * @param type - The type of key to get. One of \"master\",\n * \"self_signing\", or \"user_signing\".\n * @param secretStorage - The secret store using account data\n * @returns The private key\n */\n public static async getFromSecretStorage(type: string, secretStorage: SecretStorage): Promise {\n const encodedKey = await secretStorage.get(`m.cross_signing.${type}`);\n if (!encodedKey) {\n return null;\n }\n return decodeBase64(encodedKey);\n }\n\n /**\n * Check whether the private keys exist in the local key cache.\n *\n * @param type - The type of key to get. One of \"master\",\n * \"self_signing\", or \"user_signing\". Optional, will check all by default.\n * @returns True if all keys are stored in the local cache.\n */\n public async isStoredInKeyCache(type?: string): Promise {\n const cacheCallbacks = this.cacheCallbacks;\n if (!cacheCallbacks) return false;\n const types = type ? [type] : [\"master\", \"self_signing\", \"user_signing\"];\n for (const t of types) {\n if (!(await cacheCallbacks.getCrossSigningKeyCache?.(t))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Get cross-signing private keys from the local cache.\n *\n * @returns A map from key type (string) to private key (Uint8Array)\n */\n public async getCrossSigningKeysFromCache(): Promise> {\n const keys = new Map();\n const cacheCallbacks = this.cacheCallbacks;\n if (!cacheCallbacks) return keys;\n for (const type of [\"master\", \"self_signing\", \"user_signing\"]) {\n const privKey = await cacheCallbacks.getCrossSigningKeyCache?.(type);\n if (!privKey) {\n continue;\n }\n keys.set(type, privKey);\n }\n return keys;\n }\n\n /**\n * Get the ID used to identify the user. This can also be used to test for\n * the existence of a given key type.\n *\n * @param type - The type of key to get the ID of. One of \"master\",\n * \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @returns the ID\n */\n public getId(type = \"master\"): string | null {\n if (!this.keys[type]) return null;\n const keyInfo = this.keys[type];\n return publicKeyFromKeyInfo(keyInfo);\n }\n\n /**\n * Create new cross-signing keys for the given key types. The public keys\n * will be held in this class, while the private keys are passed off to the\n * `saveCrossSigningKeys` application callback.\n *\n * @param level - The key types to reset\n */\n public async resetKeys(level?: CrossSigningLevel): Promise {\n if (!this.callbacks.saveCrossSigningKeys) {\n throw new Error(\"No saveCrossSigningKeys callback supplied\");\n }\n\n // If we're resetting the master key, we reset all keys\n if (level === undefined || level & CrossSigningLevel.MASTER || !this.keys.master) {\n level = CrossSigningLevel.MASTER | CrossSigningLevel.USER_SIGNING | CrossSigningLevel.SELF_SIGNING;\n } else if (level === (0 as CrossSigningLevel)) {\n return;\n }\n\n const privateKeys: Record = {};\n const keys: Record = {};\n let masterSigning;\n let masterPub;\n\n try {\n if (level & CrossSigningLevel.MASTER) {\n masterSigning = new global.Olm.PkSigning();\n privateKeys.master = masterSigning.generate_seed();\n masterPub = masterSigning.init_with_seed(privateKeys.master);\n keys.master = {\n user_id: this.userId,\n usage: [\"master\"],\n keys: {\n [\"ed25519:\" + masterPub]: masterPub,\n },\n };\n } else {\n [masterPub, masterSigning] = await this.getCrossSigningKey(\"master\");\n }\n\n if (level & CrossSigningLevel.SELF_SIGNING) {\n const sskSigning = new global.Olm.PkSigning();\n try {\n privateKeys.self_signing = sskSigning.generate_seed();\n const sskPub = sskSigning.init_with_seed(privateKeys.self_signing);\n keys.self_signing = {\n user_id: this.userId,\n usage: [\"self_signing\"],\n keys: {\n [\"ed25519:\" + sskPub]: sskPub,\n },\n };\n pkSign(keys.self_signing, masterSigning, this.userId, masterPub);\n } finally {\n sskSigning.free();\n }\n }\n\n if (level & CrossSigningLevel.USER_SIGNING) {\n const uskSigning = new global.Olm.PkSigning();\n try {\n privateKeys.user_signing = uskSigning.generate_seed();\n const uskPub = uskSigning.init_with_seed(privateKeys.user_signing);\n keys.user_signing = {\n user_id: this.userId,\n usage: [\"user_signing\"],\n keys: {\n [\"ed25519:\" + uskPub]: uskPub,\n },\n };\n pkSign(keys.user_signing, masterSigning, this.userId, masterPub);\n } finally {\n uskSigning.free();\n }\n }\n\n Object.assign(this.keys, keys);\n this.callbacks.saveCrossSigningKeys(privateKeys);\n } finally {\n if (masterSigning) {\n masterSigning.free();\n }\n }\n }\n\n /**\n * unsets the keys, used when another session has reset the keys, to disable cross-signing\n */\n public clearKeys(): void {\n this.keys = {};\n }\n\n public setKeys(keys: Record): void {\n const signingKeys: Record = {};\n if (keys.master) {\n if (keys.master.user_id !== this.userId) {\n const error = \"Mismatched user ID \" + keys.master.user_id + \" in master key from \" + this.userId;\n logger.error(error);\n throw new Error(error);\n }\n if (!this.keys.master) {\n // this is the first key we've seen, so first-use is true\n this.firstUse = true;\n } else if (publicKeyFromKeyInfo(keys.master) !== this.getId()) {\n // this is a different key, so first-use is false\n this.firstUse = false;\n } // otherwise, same key, so no change\n signingKeys.master = keys.master;\n } else if (this.keys.master) {\n signingKeys.master = this.keys.master;\n } else {\n throw new Error(\"Tried to set cross-signing keys without a master key\");\n }\n const masterKey = publicKeyFromKeyInfo(signingKeys.master);\n\n // verify signatures\n if (keys.user_signing) {\n if (keys.user_signing.user_id !== this.userId) {\n const error = \"Mismatched user ID \" + keys.master.user_id + \" in user_signing key from \" + this.userId;\n logger.error(error);\n throw new Error(error);\n }\n try {\n pkVerify(keys.user_signing, masterKey, this.userId);\n } catch (e) {\n logger.error(\"invalid signature on user-signing key\");\n // FIXME: what do we want to do here?\n throw e;\n }\n }\n if (keys.self_signing) {\n if (keys.self_signing.user_id !== this.userId) {\n const error = \"Mismatched user ID \" + keys.master.user_id + \" in self_signing key from \" + this.userId;\n logger.error(error);\n throw new Error(error);\n }\n try {\n pkVerify(keys.self_signing, masterKey, this.userId);\n } catch (e) {\n logger.error(\"invalid signature on self-signing key\");\n // FIXME: what do we want to do here?\n throw e;\n }\n }\n\n // if everything checks out, then save the keys\n if (keys.master) {\n this.keys.master = keys.master;\n // if the master key is set, then the old self-signing and user-signing keys are obsolete\n delete this.keys[\"self_signing\"];\n delete this.keys[\"user_signing\"];\n }\n if (keys.self_signing) {\n this.keys.self_signing = keys.self_signing;\n }\n if (keys.user_signing) {\n this.keys.user_signing = keys.user_signing;\n }\n }\n\n public updateCrossSigningVerifiedBefore(isCrossSigningVerified: boolean): void {\n // It is critical that this value latches forward from false to true but\n // never back to false to avoid a downgrade attack.\n if (!this.crossSigningVerifiedBefore && isCrossSigningVerified) {\n this.crossSigningVerifiedBefore = true;\n }\n }\n\n public async signObject(data: T, type: string): Promise {\n if (!this.keys[type]) {\n throw new Error(\"Attempted to sign with \" + type + \" key but no such key present\");\n }\n const [pubkey, signing] = await this.getCrossSigningKey(type);\n try {\n pkSign(data, signing, this.userId, pubkey);\n return data as T & { signatures: ISignatures };\n } finally {\n signing.free();\n }\n }\n\n public async signUser(key: CrossSigningInfo): Promise {\n if (!this.keys.user_signing) {\n logger.info(\"No user signing key: not signing user\");\n return;\n }\n return this.signObject(key.keys.master, \"user_signing\");\n }\n\n public async signDevice(userId: string, device: DeviceInfo): Promise {\n if (userId !== this.userId) {\n throw new Error(`Trying to sign ${userId}'s device; can only sign our own device`);\n }\n if (!this.keys.self_signing) {\n logger.info(\"No self signing key: not signing device\");\n return;\n }\n return this.signObject>(\n {\n algorithms: device.algorithms,\n keys: device.keys,\n device_id: device.deviceId,\n user_id: userId,\n },\n \"self_signing\",\n );\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * @param userCrossSigning - Cross signing info for user\n *\n * @returns\n */\n public checkUserTrust(userCrossSigning: CrossSigningInfo): UserTrustLevel {\n // if we're checking our own key, then it's trusted if the master key\n // and self-signing key match\n if (\n this.userId === userCrossSigning.userId &&\n this.getId() &&\n this.getId() === userCrossSigning.getId() &&\n this.getId(\"self_signing\") &&\n this.getId(\"self_signing\") === userCrossSigning.getId(\"self_signing\")\n ) {\n return new UserTrustLevel(true, true, this.firstUse);\n }\n\n if (!this.keys.user_signing) {\n // If there's no user signing key, they can't possibly be verified.\n // They may be TOFU trusted though.\n return new UserTrustLevel(false, false, userCrossSigning.firstUse);\n }\n\n let userTrusted: boolean;\n const userMaster = userCrossSigning.keys.master;\n const uskId = this.getId(\"user_signing\")!;\n try {\n pkVerify(userMaster, uskId, this.userId);\n userTrusted = true;\n } catch (e) {\n userTrusted = false;\n }\n return new UserTrustLevel(userTrusted, userCrossSigning.crossSigningVerifiedBefore, userCrossSigning.firstUse);\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * @param userCrossSigning - Cross signing info for user\n * @param device - The device to check\n * @param localTrust - Whether the device is trusted locally\n * @param trustCrossSignedDevices - Whether we trust cross signed devices\n *\n * @returns\n */\n public checkDeviceTrust(\n userCrossSigning: CrossSigningInfo,\n device: DeviceInfo,\n localTrust: boolean,\n trustCrossSignedDevices: boolean,\n ): DeviceTrustLevel {\n const userTrust = this.checkUserTrust(userCrossSigning);\n\n const userSSK = userCrossSigning.keys.self_signing;\n if (!userSSK) {\n // if the user has no self-signing key then we cannot make any\n // trust assertions about this device from cross-signing\n return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices);\n }\n\n const deviceObj = deviceToObject(device, userCrossSigning.userId);\n try {\n // if we can verify the user's SSK from their master key...\n pkVerify(userSSK, userCrossSigning.getId()!, userCrossSigning.userId);\n // ...and this device's key from their SSK...\n pkVerify(deviceObj, publicKeyFromKeyInfo(userSSK), userCrossSigning.userId);\n // ...then we trust this device as much as far as we trust the user\n return DeviceTrustLevel.fromUserTrustLevel(userTrust, localTrust, trustCrossSignedDevices);\n } catch (e) {\n return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices);\n }\n }\n\n /**\n * @returns Cache callbacks\n */\n public getCacheCallbacks(): ICacheCallbacks {\n return this.cacheCallbacks;\n }\n}\n\ninterface DeviceObject extends IObject {\n algorithms: string[];\n keys: Record;\n device_id: string;\n user_id: string;\n}\n\nfunction deviceToObject(device: DeviceInfo, userId: string): DeviceObject {\n return {\n algorithms: device.algorithms,\n keys: device.keys,\n device_id: device.deviceId,\n user_id: userId,\n signatures: device.signatures,\n };\n}\n\nexport enum CrossSigningLevel {\n MASTER = 4,\n USER_SIGNING = 2,\n SELF_SIGNING = 1,\n}\n\n/**\n * Represents the ways in which we trust a user\n */\nexport class UserTrustLevel {\n public constructor(\n private readonly crossSigningVerified: boolean,\n private readonly crossSigningVerifiedBefore: boolean,\n private readonly tofu: boolean,\n ) {}\n\n /**\n * @returns true if this user is verified via any means\n */\n public isVerified(): boolean {\n return this.isCrossSigningVerified();\n }\n\n /**\n * @returns true if this user is verified via cross signing\n */\n public isCrossSigningVerified(): boolean {\n return this.crossSigningVerified;\n }\n\n /**\n * @returns true if we ever verified this user before (at least for\n * the history of verifications observed by this device).\n */\n public wasCrossSigningVerified(): boolean {\n return this.crossSigningVerifiedBefore;\n }\n\n /**\n * @returns true if this user's key is trusted on first use\n */\n public isTofu(): boolean {\n return this.tofu;\n }\n}\n\n/**\n * Represents the ways in which we trust a device\n */\nexport class DeviceTrustLevel {\n public constructor(\n public readonly crossSigningVerified: boolean,\n public readonly tofu: boolean,\n private readonly localVerified: boolean,\n private readonly trustCrossSignedDevices: boolean,\n ) {}\n\n public static fromUserTrustLevel(\n userTrustLevel: UserTrustLevel,\n localVerified: boolean,\n trustCrossSignedDevices: boolean,\n ): DeviceTrustLevel {\n return new DeviceTrustLevel(\n userTrustLevel.isCrossSigningVerified(),\n userTrustLevel.isTofu(),\n localVerified,\n trustCrossSignedDevices,\n );\n }\n\n /**\n * @returns true if this device is verified via any means\n */\n public isVerified(): boolean {\n return Boolean(this.isLocallyVerified() || (this.trustCrossSignedDevices && this.isCrossSigningVerified()));\n }\n\n /**\n * @returns true if this device is verified via cross signing\n */\n public isCrossSigningVerified(): boolean {\n return this.crossSigningVerified;\n }\n\n /**\n * @returns true if this device is verified locally\n */\n public isLocallyVerified(): boolean {\n return this.localVerified;\n }\n\n /**\n * @returns true if this device is trusted from a user's key\n * that is trusted on first use\n */\n public isTofu(): boolean {\n return this.tofu;\n }\n}\n\nexport function createCryptoStoreCacheCallbacks(store: CryptoStore, olmDevice: OlmDevice): ICacheCallbacks {\n return {\n getCrossSigningKeyCache: async function (\n type: keyof SecretStorePrivateKeys,\n _expectedPublicKey: string,\n ): Promise {\n const key = await new Promise((resolve) => {\n return store.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n store.getSecretStorePrivateKey(txn, resolve, type);\n });\n });\n\n if (key && key.ciphertext) {\n const pickleKey = Buffer.from(olmDevice.pickleKey);\n const decrypted = await decryptAES(key, pickleKey, type);\n return decodeBase64(decrypted);\n } else {\n return key;\n }\n },\n storeCrossSigningKeyCache: async function (\n type: keyof SecretStorePrivateKeys,\n key?: Uint8Array,\n ): Promise {\n if (!(key instanceof Uint8Array)) {\n throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${key}`);\n }\n const pickleKey = Buffer.from(olmDevice.pickleKey);\n const encryptedKey = await encryptAES(encodeBase64(key), pickleKey, type);\n return store.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n store.storeSecretStorePrivateKey(txn, type, encryptedKey);\n });\n },\n };\n}\n\nexport type KeysDuringVerification = [[string, PkSigning], [string, PkSigning], [string, PkSigning], void];\n\n/**\n * Request cross-signing keys from another device during verification.\n *\n * @param baseApis - base Matrix API interface\n * @param userId - The user ID being verified\n * @param deviceId - The device ID being verified\n */\nexport async function requestKeysDuringVerification(\n baseApis: MatrixClient,\n userId: string,\n deviceId: string,\n): Promise {\n // If this is a self-verification, ask the other party for keys\n if (baseApis.getUserId() !== userId) {\n return;\n }\n logger.log(\"Cross-signing: Self-verification done; requesting keys\");\n // This happens asynchronously, and we're not concerned about waiting for\n // it. We return here in order to test.\n return new Promise((resolve, reject) => {\n const client = baseApis;\n const original = client.crypto!.crossSigningInfo;\n\n // We already have all of the infrastructure we need to validate and\n // cache cross-signing keys, so instead of replicating that, here we set\n // up callbacks that request them from the other device and call\n // CrossSigningInfo.getCrossSigningKey() to validate/cache\n const crossSigning = new CrossSigningInfo(\n original.userId,\n {\n getCrossSigningKey: async (type): Promise => {\n logger.debug(\"Cross-signing: requesting secret\", type, deviceId);\n const { promise } = client.requestSecret(`m.cross_signing.${type}`, [deviceId]);\n const result = await promise;\n const decoded = decodeBase64(result);\n return Uint8Array.from(decoded);\n },\n },\n original.getCacheCallbacks(),\n );\n crossSigning.keys = original.keys;\n\n // XXX: get all keys out if we get one key out\n // https://github.com/vector-im/element-web/issues/12604\n // then change here to reject on the timeout\n // Requests can be ignored, so don't wait around forever\n const timeout = new Promise((resolve) => {\n setTimeout(resolve, KEY_REQUEST_TIMEOUT_MS, new Error(\"Timeout\"));\n });\n\n // also request and cache the key backup key\n const backupKeyPromise = (async (): Promise => {\n const cachedKey = await client.crypto!.getSessionBackupPrivateKey();\n if (!cachedKey) {\n logger.info(\"No cached backup key found. Requesting...\");\n const secretReq = client.requestSecret(\"m.megolm_backup.v1\", [deviceId]);\n const base64Key = await secretReq.promise;\n logger.info(\"Got key backup key, decoding...\");\n const decodedKey = decodeBase64(base64Key);\n logger.info(\"Decoded backup key, storing...\");\n await client.crypto!.storeSessionBackupPrivateKey(Uint8Array.from(decodedKey));\n logger.info(\"Backup key stored. Starting backup restore...\");\n const backupInfo = await client.getKeyBackupVersion();\n // no need to await for this - just let it go in the bg\n client.restoreKeyBackupWithCache(undefined, undefined, backupInfo!).then(() => {\n logger.info(\"Backup restored.\");\n });\n }\n })();\n\n // We call getCrossSigningKey() for its side-effects\n return Promise.race([\n Promise.all([\n crossSigning.getCrossSigningKey(\"master\"),\n crossSigning.getCrossSigningKey(\"self_signing\"),\n crossSigning.getCrossSigningKey(\"user_signing\"),\n backupKeyPromise,\n ]) as Promise,\n timeout,\n ]).then(resolve, reject);\n }).catch((e) => {\n logger.warn(\"Cross-signing: failure while requesting keys:\", e);\n });\n}\n"],"mappings":";;;;;;;;;;AAsBA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AACA,I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