@icure/api 7.1.8 → 7.1.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 +1 @@
1
- {"version":3,"file":"KeyManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/KeyManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAiC;AAGjC,mCAAsE;AAsBtE;;GAEG;AACH,MAAa,UAAU;IAKrB,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,YAAgC,EAChC,WAAwB,EACxB,sBAA+C,EAC/C,UAA4B,EAC5B,oBAA6B;QAN7B,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,iBAAY,GAAZ,YAAY,CAAoB;QAChC,gBAAW,GAAX,WAAW,CAAa;QACxB,2BAAsB,GAAtB,sBAAsB,CAAyB;QAC/C,eAAU,GAAV,UAAU,CAAkB;QAC5B,yBAAoB,GAApB,oBAAoB,CAAS;QATxC,cAAS,GAA2F,SAAS,CAAA;IAUlH,CAAC;IAEJ;;;;;;;OAOG;IACG,oCAAoC,CAAC,YAAqB;;YAC9D,IAAI,CAAC,iBAAiB,EAAE,CAAA;YACxB,IAAI,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,SAAU,CAAC,IAAI,CAAC,MAAO,CAAC,CAAC,CAAA;YAC/D,IAAI,YAAY,EAAE;gBAChB,YAAY,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAA;aAC/E;YACD,OAAO,MAAM,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,CAAO,OAAO,EAAE,EAAE,gDAAC,OAAA,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS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AC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IACnF,CAAC;IAEO,cAAc,CAAC,QAAuC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AA7VD,gCA6VC","sourcesContent":["import { DataOwner, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { fingerprintToPublicKeysMapOf, loadPublicKeys } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class KeyManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly baseExchangeKeyManager: BaseExchangeKeysManager,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean\n ) {}\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(\n (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n ),\n (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n }\n )\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey?.slice(-32)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwner): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from(this.dataOwnerApi.getHexPublicKeysOf(dataOwner)).filter((key) => {\n const fp = key.slice(-32)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchy()\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {\n const availableKeys = await this.loadAndRecoverKeysFor(dowt)\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dowt.dataOwner)\n const fpToFullMap = fingerprintToPublicKeysMapOf(dowt.dataOwner)\n const unavailableKeys = Object.keys(availableKeys).flatMap((fp) => {\n const fullPublicKey = fpToFullMap[fp]\n return allPublicKeys.has(fullPublicKey) ? [] : [fullPublicKey]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(x.slice(-32) in verifiedKeysMap) && !(availableKeys?.[x.slice(-32)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryAndVerificationResult = await keyRecovererAndVerifier(\n keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n )\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (const keyData of keysData) {\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp],\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(keyData.dowt, this.plainKeysByFingerprint(keysWithExternallyRecovered))\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair())\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const publicKeyFingerprint = publicKeyHex.slice(-32)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n const verifiedPublicKeysMap = await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const { updatedDelegator } = await this.baseExchangeKeyManager.createOrUpdateEncryptedExchangeKeyTo(\n selfDataOwner.dataOwner.id!,\n keyPair,\n await loadPublicKeys(\n this.primitives.RSA,\n Array.from(this.dataOwnerApi.getHexPublicKeysOf(selfDataOwner.dataOwner)).filter((x) => verifiedPublicKeysMap[x.slice(-32)])\n )\n )\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf: updatedDelegator }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: string[]\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n return await pubKeysFingerprints.reduce(async (acc, currentFingerprint) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair('jwk', storedKeypair.pair.privateKey, 'jwk', storedKeypair.pair.publicKey)\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(dataOwner: DataOwnerWithType): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const selfPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dataOwner.dataOwner)\n const pubKeysFingerprints = Array.from(selfPublicKeys).map((x) => x.slice(-32))\n const loadedKeys = pubKeysFingerprints.length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (loadedKeysFingerprints.length !== pubKeysFingerprints.length && loadedKeysFingerprints.length > 0) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint(loadedKeys))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k.slice(-32), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}
1
+ {"version":3,"file":"KeyManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/KeyManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAiC;AAGjC,mCAAsE;AAoBtE,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAAC,CAAC,MAAM,CACN,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAG,CAAC,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE,eAAe,EAAE,EAAE,EAAE,IAAG,EAC3G,EAKC,CACF,CACF,CAAA;AAGH;;GAEG;AACH,MAAa,UAAU;IAKrB,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,YAAgC,EAChC,WAAwB,EACxB,sBAA+C,EAC/C,UAA4B,EAC5B,oBAA6B;QAN7B,eAAU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AC,CAAC,EAAE,CAAA;YAClH,MAAM,sBAAsB,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;YACtD,IAAI,sBAAsB,CAAC,MAAM,KAAK,mBAAmB,CAAC,MAAM,IAAI,sBAAsB,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrG,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,SAAS,EAAE,IAAI,CAAC,sBAAsB,CAAC,UAAU,CAAC,CAAC,CAAA;gBACxG,KAAK,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;oBACtD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAA;iBAC3C;aACF;YACD,OAAO,UAAU,CAAA;QACnB,CAAC;KAAA;IAEO,qBAAqB,CAAI,GAAyC;QACxE,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IACnF,CAAC;IAEO,cAAc,CAAC,QAAuC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AAnXD,gCAmXC","sourcesContent":["import { DataOwner, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { fingerprintToPublicKeysMapOf, loadPublicKeys } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class KeyManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly baseExchangeKeyManager: BaseExchangeKeysManager,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey> }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair }) => ({ pair })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey?.slice(-32)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwner): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from(this.dataOwnerApi.getHexPublicKeysOf(dataOwner)).filter((key) => {\n const fp = key.slice(-32)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchy()\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {\n const availableKeys = await this.loadAndRecoverKeysFor(dowt)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dowt.dataOwner)\n const fpToFullMap = fingerprintToPublicKeysMapOf(dowt.dataOwner)\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(key.slice(-32)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(x.slice(-32) in verifiedKeysMap) && !(availableKeys?.[x.slice(-32)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (const keyData of keysData) {\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp],\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(keyData.dowt, this.plainKeysByFingerprint(keysWithExternallyRecovered))\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair())\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const publicKeyFingerprint = publicKeyHex.slice(-32)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n const verifiedPublicKeysMap = await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const { updatedDelegator } = await this.baseExchangeKeyManager.createOrUpdateEncryptedExchangeKeyTo(\n selfDataOwner.dataOwner.id!,\n keyPair,\n await loadPublicKeys(\n this.primitives.RSA,\n Array.from(this.dataOwnerApi.getHexPublicKeysOf(selfDataOwner.dataOwner)).filter((x) => verifiedPublicKeysMap[x.slice(-32)])\n )\n )\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf: updatedDelegator }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: string[]\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n return await pubKeysFingerprints.reduce(async (acc, currentFingerprint) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair('jwk', storedKeypair.pair.privateKey, 'jwk', storedKeypair.pair.publicKey)\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(dataOwner: DataOwnerWithType): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const selfPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dataOwner.dataOwner)\n const pubKeysFingerprints = Array.from(selfPublicKeys).map((x) => x.slice(-32))\n const loadedKeys = pubKeysFingerprints.length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (loadedKeysFingerprints.length !== pubKeysFingerprints.length && loadedKeysFingerprints.length > 0) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint(loadedKeys))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k.slice(-32), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}
@@ -90,6 +90,29 @@ export declare class IccCryptoXApi {
90
90
  * the current user for the first time.
91
91
  */
92
92
  forceReload(): Promise<void>;
93
+ /**
94
+ * Get all key pairs available for the decrpytion and encryption of data to the current data owner. These include the key pairs from the data owner
95
+ * and his parents.
96
+ * @return an object with:
97
+ * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.
98
+ * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the
99
+ * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).
100
+ */
101
+ getEncryptionDecryptionKeypairsForDataOwnerHierarchy(): Promise<{
102
+ self: {
103
+ dataOwnerId: string;
104
+ keys: {
105
+ pair: KeyPair<CryptoKey>;
106
+ verified: boolean;
107
+ }[];
108
+ };
109
+ parents: {
110
+ dataOwnerId: string;
111
+ keys: {
112
+ pair: KeyPair<CryptoKey>;
113
+ }[];
114
+ }[];
115
+ }>;
93
116
  /**
94
117
  * Get a key pair with the provided fingerprint if present.
95
118
  * @param fingerprint a key-pair/public-key fingerprint
@@ -116,6 +116,17 @@ class IccCryptoXApi {
116
116
  yield this.keyManager.reloadKeys();
117
117
  });
118
118
  }
119
+ /**
120
+ * Get all key pairs available for the decrpytion and encryption of data to the current data owner. These include the key pairs from the data owner
121
+ * and his parents.
122
+ * @return an object with:
123
+ * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.
124
+ * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the
125
+ * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).
126
+ */
127
+ getEncryptionDecryptionKeypairsForDataOwnerHierarchy() {
128
+ return this.keyManager.getCurrentUserHierarchyAvailableKeypairs();
129
+ }
119
130
  /**
120
131
  * Get a key pair with the provided fingerprint if present.
121
132
  * @param fingerprint a key-pair/public-key fingerprint
@@ -1 +1 @@
1
- {"version":3,"file":"icc-crypto-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-crypto-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,4BAA2B;AAE3B,uDAA6G;AAC7G,mCAAyE;AAoBzE,MAAa,aAAa;IAmBxB,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,gBAAgB,CAAA;IAC9B,CAAC;IAED;;OAEG;IACH,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,mBAAmB,CAAA;IACjC,CAAC;IAED;;OAEG;IACH,IAAI,M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AO,CAAC,CAAA;iBACjE;gBAAC,OAAO,CAAC,EAAE;oBACV,OAAO,OAAO,CAAA;iBACf;aACF;YAED,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,cAAe,EAAE,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,iBAAkB,CAAC,CAAA;YACtG,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,KAAK,EAAE,IAAA,qBAAM,EAAC,cAAc,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;YAC7G,IAAI;gBACF,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,aAAa,EAAE,OAAO,CAAC,CAAA;aACjE;YAAC,OAAO,CAAC,EAAE;gBACV,OAAO,OAAO,CAAA;aACf;QACH,CAAC;KAAA;IAED;;OAEG;IACH,YAAY,CAAC,EAAU,EAAE,OAA4C;QACnE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,GAAG,EAAE,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAA;IACjF,CAAC;CACF;AA54BD,sCA44BC","sourcesContent":["/* eslint-disable */\nimport { AESUtils } from './crypto/AES'\nimport { KeyPair, RSAUtils } from './crypto/RSA'\nimport { ShamirClass } from './crypto/shamir'\nimport * as _ from 'lodash'\nimport { Delegation, Device, Document, EncryptedEntity, EncryptedParentEntity, HealthcareParty, Patient, User } from '../icc-api/model/models'\nimport { b2a, b64_2uas, hex2ua, string2ua, ua2hex, ua2string, ua2utf8, utf8_2ua } from './utils/binary-utils'\nimport { keyPairFromPrivateKeyJwk, pkcs8ToJwk, spkiToJwk } from './utils'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\nimport { ExchangeKeysManager } from './crypto/ExchangeKeysManager'\nimport { CryptoPrimitives } from './crypto/CryptoPrimitives'\nimport { KeyManager } from './crypto/KeyManager'\nimport { DataOwner, IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { EntitiesEncryption } from './crypto/EntitiesEncryption'\nimport { IcureStorageFacade } from './storage/IcureStorageFacade'\nimport { ShamirKeysManager } from './crypto/ShamirKeysManager'\nimport { IccHcpartyApi } from '../icc-api'\nimport { StorageEntryKeysFactory } from './storage/StorageEntryKeysFactory'\nimport { ConfidentialEntities } from './crypto/ConfidentialEntities'\n\ninterface DelegatorAndKeys {\n delegatorId: string\n key: CryptoKey\n rawKey: string\n}\n\nexport class IccCryptoXApi {\n keychainLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain.'\n keychainValidityDateLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain-date.'\n hcpPreferenceKeyEhealthCert = 'eHealthCRTCrypt'\n hcpPreferenceKeyEhealthCertDate = 'eHealthCRTDate'\n rsaLocalStoreIdPrefix = 'org.taktik.icure.rsa.'\n private readonly exchangeKeysManager: ExchangeKeysManager\n private readonly cryptoPrimitives: CryptoPrimitives\n private readonly keyManager: KeyManager\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly entitiesEncrypiton: EntitiesEncryption\n private readonly confidentialEntities: ConfidentialEntities\n private readonly icureStorage: IcureStorageFacade\n private readonly shamirManager: ShamirKeysManager\n private readonly _storage: StorageFacade<string>\n private readonly _keyStorage: KeyStorageFacade\n\n private readonly hcpartyBaseApi: IccHcpartyApi\n\n get primitives(): CryptoPrimitives {\n return this.cryptoPrimitives\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n get exchangeKeys(): ExchangeKeysManager {\n return this.exchangeKeysManager\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.crypto} at {@link primitives}.\n */\n get crypto(): Crypto {\n return this.cryptoPrimitives.crypto\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.shamir} at {@link primitives}.\n */\n get shamir(): ShamirClass {\n return this.cryptoPrimitives.shamir\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.RSA} at {@link primitives}.\n */\n get RSA(): RSAUtils {\n return this.cryptoPrimitives.RSA\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.AES} at {@link primitives}.\n */\n get AES(): AESUtils {\n return this.cryptoPrimitives.AES\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get keyStorage(): KeyStorageFacade {\n return this._keyStorage\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get storage(): StorageFacade<string> {\n return this._storage\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get entities(): EntitiesEncryption {\n return this.entitiesEncrypiton\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get confidential(): ConfidentialEntities {\n return this.confidentialEntities\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get userKeysManager(): KeyManager {\n return this.keyManager\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get shamirKeysManager(): ShamirKeysManager {\n return this.shamirManager\n }\n\n /**\n * @internal\n */\n constructor(\n exchangeKeysManager: ExchangeKeysManager,\n cryptoPrimitives: CryptoPrimitives,\n keyManager: KeyManager,\n dataOwnerApi: IccDataOwnerXApi,\n entitiesEncrypiton: EntitiesEncryption,\n shamirManager: ShamirKeysManager,\n storage: StorageFacade<string>,\n keyStorage: KeyStorageFacade,\n icureStorageFacade: IcureStorageFacade,\n hcPartyBaseApi: IccHcpartyApi,\n confidentialEntities: ConfidentialEntities\n ) {\n this.exchangeKeysManager = exchangeKeysManager\n this.cryptoPrimitives = cryptoPrimitives\n this.keyManager = keyManager\n this.dataOwnerApi = dataOwnerApi\n this.entitiesEncrypiton = entitiesEncrypiton\n this.shamirManager = shamirManager\n this._storage = storage\n this._keyStorage = keyStorage\n this.icureStorage = icureStorageFacade\n this.hcpartyBaseApi = hcPartyBaseApi\n this.confidentialEntities = confidentialEntities\n }\n\n /**\n * Deletes values cached by the crypto api, to allow to detect changes in stored key pairs, exchange keys and/or current data owner details.\n * This method may be useful in cases where a user is logged in from multiple devices or in cases where other users have just shared some data with\n * the current user for the first time.\n */\n async forceReload() {\n this.exchangeKeysManager.clearCache(true)\n this.dataOwnerApi.clearCurrentDataOwnerIdsCache()\n await this.keyManager.reloadKeys()\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n return this.keyManager.getKeyPairForFingerprint(fingerprint)\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return this.keyManager.getCurrentUserHierarchyAvailablePublicKeysHex()\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n return this.keyManager.getCurrentUserAvailablePublicKeysHex(verifiedOnly)\n }\n\n /**\n * @deprecated depending on your use case you should delete the calls to this method or call {@link forceReload}:\n * - Replace with `forceReload()` if one of the following parts of the current data owner may have been modified from a different api instance:\n * - Hcp hierarchy\n * - Key recovery data (transfer keys or shamir)\n * - Exchange keys (formerly hcp keys)\n * - Remove the call if the main goal was to force reload the data owner: data owner are not cached anymore.\n */\n emptyHcpCache(hcpartyId: string) {\n this.exchangeKeysManager.clearCache(false)\n }\n\n /**\n * @deprecated you should not need this method anymore to deal with the encryption of iCure entities because everything related to entities\n * encryption should be done either through the entity-specific extended api or through the extended apis.\n * Note that keys returned by the current implementation of this method may not be safe for encryption/sharing.\n * If instead you are using this method to retrieve key pairs for other purposes, for example because you want to reuse the user keys in iCure for\n * other services consider the following alternatives:\n * - If you want to use all iCure facilities including key recovery and key verification you can use {@link getKeyPairForFingerprint}.\n * Note that this solution can only give access to keys for the data owner of the instantiated api and his parents.\n * - Alternatively you can use directly your choice of {@link KeyStorageFacade} and {@link StorageEntryKeysFactory}: if these are the same you use\n * for the iCure API client the keys will be shared with it. Note however that the iCure api client uses\n * {@link StorageEntryKeysFactory.cachedRecoveredKeypairOfDataOwner} to cache recovered keys of a data owner which may not have originated from\n * this device, so you should only use {@link StorageEntryKeysFactory.deviceKeypairOfDataOwner} if you want to make sure the keys you use are safe\n * for encryption.\n */\n async getCachedRsaKeyPairForFingerprint(\n dataOwnerId: string,\n pubKeyOrFingerprint: string\n ): Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }> {\n const fingerprint = pubKeyOrFingerprint.slice(-32)\n const res = this.keyManager.getDecryptionKeys()[fingerprint]\n if (!res) console.warn(`Could not find any keypair for fingerprint ${fingerprint}`)\n return res\n }\n\n /**\n * @deprecated You do not need this method to encrypt/decrypt data of iCure, but if you want to reuse the iCure keys for the user for other purposes\n * you have different options to replace this method, depending on what you actually need. All options return the hex-encoded spki representation of\n * the public keys.\n * - If you want only the public keys for which we have a private key available\n * - you can replicate the current behaviour using {@link getCurrentUserHierarchyAvailablePublicKeysHex}. This includes keys for the current user\n * and his parents.\n * - use {@link getCurrentUserAvailablePublicKeysHex} to get public keys only for the current data owner, ignoring any keys of the\n * parent hierarchy. In this case you can also apply a filter to only get verified keys (safe for encryption).\n * - If you need all public keys for the data owner, including those for which there is no corresponding private key available on the device use\n * {@link IccDataOwnerXApi.getHexPublicKeysOf} with the current data owner. If you don't have it available you may get it from\n * {@link IccDataOwnerXApi.getCurrentDataOwner}, but this will require to do a request to the iCure server (other options use only cached data).\n */\n async getPublicKeys(): Promise<string[]> {\n return this.userKeysManager.getCurrentUserHierarchyAvailablePublicKeysHex()\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.randomUuid} at {@link primitives}.\n */\n randomUuid() {\n return this.primitives.randomUuid()\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.sha256} at {@link primitives}.\n */\n sha256(data: ArrayBuffer | Uint8Array) {\n return this.primitives.sha256(data)\n }\n\n /**\n * @deprecated Use {@link ShamirKeysManager.updateSelfSplits} from {@link shamirKeysManager} instead. Note that the new method completely replaces\n * all current values if a split for the provided key already exists.\n */\n async encryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>, threshold?: number): Promise<HealthcareParty> {\n const legacyKeyFp = hcp.publicKey?.slice(-32)\n if (!legacyKeyFp) throw new Error(`No legacy/default key for hcp ${hcp.id}`)\n await this.shamirKeysManager.updateSelfSplits(\n { [legacyKeyFp]: { notariesIds: notaries.map((x) => x.id!), minShares: threshold ?? notaries.length } },\n []\n )\n return (await this.dataOwnerApi.getDataOwner(hcp.id!)).dataOwner as HealthcareParty\n }\n\n /**\n * @deprecated You should not need this method anymore because the api will automatically try to recover the available shamir keys on startup.\n */\n async decryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>): Promise<void> {\n try {\n const publicKeys = await this.getPublicKeys()\n const nLen = notaries.length\n let decryptedPrivatedKey\n if (nLen == 1) {\n const notaryHcPartyId = notaries[0].id!\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notaryHcPartyId)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notaryHcPartyId, hcp.id!, notaryHcPartyId, idPubKey, keysMap, publicKeys)\n )\n )\n const cryptedPrivatedKey = hcp.privateKeyShamirPartitions![notaryHcPartyId]\n decryptedPrivatedKey = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(cryptedPrivatedKey)\n )\n )\n } else {\n const decryptedShares: string[] = await _.reduce(\n notaries,\n (queue, notary) => {\n return queue.then(async (shares: string[]) => {\n try {\n // now, we get the encrypted shares in db and decrypt them. This assumes that the\n // the notaries' private keys are in localstorage. We should implement a way for the notaries to\n // give hcp the decrypted shares without having to also share their private keys.\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notary.id!)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notary.id!, hcp.id!, notary.id!, idPubKey, keysMap, publicKeys)\n )\n )\n const encryptedShare = hcp.privateKeyShamirPartitions![notary.id!]\n const decryptedShamirPartition = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(encryptedShare)\n )\n )\n shares.push(decryptedShamirPartition)\n } catch (e) {\n console.log('Error during encryptedShamirRSAKey', notary.id, e)\n }\n return shares\n })\n },\n Promise.resolve([] as string[])\n )\n\n decryptedPrivatedKey = this.primitives.shamir.combine(decryptedShares)\n }\n\n const importedPrivateKey = await this.primitives.RSA.importKey('pkcs8', hex2ua(decryptedPrivatedKey), ['decrypt'])\n const importedPublicKey = await this.primitives.RSA.importKey('spki', hex2ua(hcp.publicKey!), ['encrypt'])\n\n const exportedKeyPair = await this.primitives.RSA.exportKeys({ publicKey: importedPublicKey, privateKey: importedPrivateKey }, 'jwk', 'jwk')\n await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${hcp.id!}`, exportedKeyPair)\n } catch (e) {\n console.log('Cannot decrypt shamir RSA key')\n }\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n * Note that currently this method does not cache results anymore (but the updated methods do).\n */\n async decryptHcPartyKey(\n loggedHcPartyId: string,\n delegatorId: string,\n delegateHcPartyId: string,\n publicKey: string,\n encryptedHcPartyKeys: { [key: string]: string },\n publicKeys: string[]\n ): Promise<DelegatorAndKeys> {\n if (!publicKeys.length) {\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: no public key`\n console.warn(reason)\n throw new Error(reason)\n }\n const keysFpSet = new Set(publicKeys.map((x) => x.slice(-32)))\n const filteredKeys = Object.fromEntries(Object.entries(this.keyManager.getDecryptionKeys()).filter(([fp]) => keysFpSet.has(fp)))\n const decrypted = await this.exchangeKeysManager.base.tryDecryptExchangeKeys([encryptedHcPartyKeys], filteredKeys)\n const res = decrypted.successfulDecryptions[0]\n if (!res) {\n const error =\n `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: impossible to decrypt. ` +\n 'No private key was found or could be used to decrypt the aes exchange keys`'\n console.warn(error)\n throw new Error(error)\n }\n return {\n delegatorId,\n key: res,\n rawKey: ua2hex(await this.primitives.AES.exportKey(res, 'raw')),\n }\n }\n\n /**\n * @deprecated you should not need this method anymore. The new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If no verified key (safe for encryption) can be found during the instantiation\n * of the API, depending on the parameters passed to the factory one of two scenarios will happen:\n * - A new key will be automatically created on the device and stored using the key storage facade.\n * - The api instantiation fails with an exception. This is ideal if you want to try to recover an existing key pair before creating a new one.\n *\n * If you were using this method to allow the user to recover an existing key that is not available in the storage facade nor recoverable through\n * transfer keys or shamir split (for example by scanning a qr code, or by loading a file from the computer to the web browser's local storage)\n * you will have to move that logic in your implementation of CryptoStrategies.\n * It is currently not allowed to create new key pairs if a verified key pair is already available on the device, as this would be wasteful.\n * If you want to convert a `JsonWebKey` pair to a `CryptoKey` pair you should use directly the method in `primitives.RSA`.\n */\n async cacheKeyPair(keyPairInJwk: KeyPair<JsonWebKey>): Promise<KeyPair<CryptoKey>> {\n const cryptoKeyPair = await this.primitives.RSA.importKeyPair('jwk', keyPairInJwk.privateKey, 'jwk', keyPairInJwk.publicKey)\n const pubHex = ua2hex(await this.primitives.RSA.exportKey(cryptoKeyPair.publicKey, 'spki'))\n const fingerprint = pubHex.slice(-32)\n if (!this.keyManager.getDecryptionKeys()[fingerprint]) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const selfKeys = this.dataOwnerApi.getHexPublicKeysOf((await this.dataOwnerApi.getCurrentDataOwner()).dataOwner)\n if (!selfKeys.has(pubHex))\n throw new Error(\n `Impossible to add key pair with fingerprint ${fingerprint} to data owner ${selfId}: the data owner has no matching public key`\n )\n await this.icureStorage.saveKey(selfId, fingerprint, keyPairInJwk, true)\n // Force reload to check if more private keys can be recovered or more exchange keys become available.\n await this.forceReload()\n }\n return cryptoKeyPair\n }\n\n /**\n * @deprecated Usually you should not need this method, since the preferred sfk is automatically chosen by the extended entity apis when creating a\n * new instance of the entity.\n */\n async extractPreferredSfk(parent: EncryptedParentEntity, hcpartyId: string, confidential: boolean) {\n return confidential ? this.confidential.getConfidentialSecretId(parent, hcpartyId) : this.confidential.getAnySecretIdSharedWithParents(parent)\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n */\n async decryptAndImportAesHcPartyKeysForDelegators(\n delegatorsHcPartyIdsSet: Array<string>,\n delegateHcPartyId: string,\n minCacheDurationInSeconds: number = 60\n ): Promise<Array<DelegatorAndKeys>> {\n return await delegatorsHcPartyIdsSet.reduce(async (acc, delegator) => {\n const awaitedAcc = await acc\n const keys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegator, delegateHcPartyId)\n const keysForDelegator = await keys.reduce(async (accForKey, cryptoKey) => {\n const awaitedAccForKey = await accForKey\n const rawKey = ua2hex(await this.primitives.RSA.exportKey(cryptoKey, 'spki'))\n return [\n ...awaitedAccForKey,\n {\n key: cryptoKey,\n delegatorId: delegator,\n rawKey: rawKey,\n },\n ]\n }, Promise.resolve([] as DelegatorAndKeys[]))\n return [...awaitedAcc, ...keysForDelegator]\n }, Promise.resolve([] as DelegatorAndKeys[]))\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n * Note that currently this method does not cache results anymore (but the updated methods do).\n */\n async getEncryptedAesExchangeKeys(\n owner: DataOwner,\n delegateId: string\n ): Promise<{ [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } }> {\n const publicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(owner))\n const mapOfAesExchangeKeys = Object.entries(owner.aesExchangeKeys ?? {})\n .filter((e) => e[1][delegateId] && Object.keys(e[1][delegateId]).some((k1) => publicKeys.some((pk) => pk.endsWith(k1))))\n .reduce((map, e) => {\n const candidates = Object.entries(e[1][delegateId]) //[fingerprint of delegate pub key, key], [fingerprint of owner pub key, key]\n const [publicKeyFingerprint, encryptedAesExchangeKey] = candidates[candidates.findIndex(([k, v]) => publicKeys.some((pk) => pk.endsWith(k)))]\n return { ...map, [e[0]]: { [publicKeyFingerprint]: encryptedAesExchangeKey } }\n }, {} as { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } })\n\n if (!owner.publicKey || mapOfAesExchangeKeys[owner.publicKey] || !owner.hcPartyKeys?.[delegateId]) {\n return mapOfAesExchangeKeys\n }\n const delegate = (await this.dataOwnerApi.getDataOwner(delegateId)).dataOwner\n if (delegate.publicKey && publicKeys.includes(delegate.publicKey)) {\n return {\n ...mapOfAesExchangeKeys,\n [owner.publicKey]: { [delegate.publicKey!.slice(-32)]: owner.hcPartyKeys[delegateId][1] },\n }\n } else if (publicKeys.includes(owner.publicKey)) {\n return { ...mapOfAesExchangeKeys, [owner.publicKey]: { [owner.publicKey.slice(-32)]: owner.hcPartyKeys[delegateId][0] } }\n }\n return mapOfAesExchangeKeys\n }\n\n /**\n * @deprecated you should not use this method because initialisation of encrypted entities keys is done automatically by the entity-specific\n * extended api. Also note that it is now forbidden to initialise an entity as a data owner which is not the current data owner: you should instead\n * create the entity as the current data owner then create a delegation to the other data owner.\n */\n async initEncryptionKeys(\n createdObject: any,\n ownerId: string\n ): Promise<{\n encryptionKeys: any\n secretId: string\n }> {\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n throw new Error('Impossible to initialise keys as a data owner which is not the current data owner')\n }\n const { updatedEntity, rawEncryptionKey } = await this.entities.entityWithInitialisedEncryptedMetadata(\n {\n ...createdObject,\n delegations: undefined,\n encryptionKeys: undefined,\n cryptedForeignKeys: undefined,\n secretForeignKeys: undefined,\n } as EncryptedEntity,\n undefined,\n undefined,\n true\n )\n return {\n encryptionKeys: updatedEntity.encryptionKeys,\n secretId: rawEncryptionKey!,\n }\n }\n\n /**\n * @deprecated You should use:\n * - {@link IccPatientXApi.decryptSecretIdsOf} or {@link IccMessageXApi.decryptSecretIdsOf} to get the delegation sfks (now caleld secret ids).\n * - {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds} to get the full hierarchy for the current data owner (cached). The first element is\n * the id of the topmost parent, while the last is the current data owner.\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractDelegationsSFKs(document: EncryptedEntity | null, hcpartyId?: string): Promise<{ extractedKeys: Array<string>; hcpartyId?: string }> {\n if (!document || !hcpartyId) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const delegationsForAllDelegates = document.delegations\n if (!delegationsForAllDelegates || !Object.keys(delegationsForAllDelegates).length) {\n console.log(`There is no delegation in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.secretIdsOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated (light) You should use:\n * - {@link IccHelementXApi.decryptPatientIdOf}, {@link IccDocumentXApi.decryptMessageIdOf}, ... to get the crypted foreign keys.\n * - {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds} to get the full hierarchy for the current data owner (cached). The first element is\n * the id of the topmost parent, while the last is the current data owner.\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractCryptedFKs(document: EncryptedEntity | null, hcpartyId: string): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document || !document.cryptedForeignKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const cfksForAllDelegates = document.cryptedForeignKeys\n if (!cfksForAllDelegates || !Object.keys(cfksForAllDelegates).length) {\n console.log(`There is no cryptedForeignKeys in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.owningEntityIdsOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated You should use the extended apis methods to encrypt/decrypt entities or their attachments\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractEncryptionsSKs(document: EncryptedEntity, hcpartyId: string): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document.encryptionKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const eckeysForAllDelegates = document.encryptionKeys\n if (!eckeysForAllDelegates || !Object.keys(eckeysForAllDelegates).length) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.encryptionKeysOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated You should not use this method anymore, depending on what you were passing as {@link delegations} you should replace this method as\n * explained in {@link extractEncryptionsSKs} (if you were passing encryptionKeys), {@link extractCryptedFKs} (cryptedForeignKeys), or\n * {@link extractDelegationsSFKs} (delegations).\n */\n async extractKeysFromDelegationsForHcpHierarchy(\n dataOwnerId: string,\n objectId: string,\n delegations: { [key: string]: Array<Delegation> }\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n return {\n extractedKeys: await this.entities.extractMergedHierarchyFromDelegationAndOwner(\n delegations,\n dataOwnerId,\n (x) => !!x,\n () => Promise.resolve(true)\n ),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n * You can convert the private key pkcs8 array to a jwk key using {@link pkcs8ToJwk} then you can extract the full key pair using\n * {@link keyPairFromPrivateKeyJwk}.\n */\n async loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId: string, privateKey: Uint8Array) {\n await this.cacheKeyPair(keyPairFromPrivateKeyJwk(pkcs8ToJwk(privateKey)))\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n * You can extract the full key pair using {@link keyPairFromPrivateKeyJwk}.\n */\n async loadKeyPairsAsJwkInBrowserLocalStorage(healthcarePartyId: string, privateKey: JsonWebKey) {\n await this.cacheKeyPair(keyPairFromPrivateKeyJwk(privateKey))\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n */\n loadKeyPairsInBrowserLocalStorage(healthcarePartyId: string, file: Blob): Promise<void> {\n const fr = new FileReader()\n return new Promise((resolve, reject) => {\n fr.onerror = reject\n fr.onabort = reject\n fr.onload = (e: any) => {\n const privateKey = e.target.result as string\n this.loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId, hex2ua(privateKey))\n .then(() => resolve())\n .catch(reject)\n }\n fr.readAsText(file)\n })\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n saveKeychainInBrowserLocalStorage(id: string, keychain: number) {\n this._storage.setItem(\n this.keychainLocalStoreIdPrefix + id,\n b2a(new Uint8Array(keychain).reduce((data, byte) => data + String.fromCharCode(byte), ''))\n )\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n saveKeychainInBrowserLocalStorageAsBase64(id: string, keyChainB64: string) {\n this._storage.setItem(this.keychainLocalStoreIdPrefix + id, keyChainB64)\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n async saveKeychainValidityDateInBrowserLocalStorage(id: string, date: string) {\n if (!id) return\n\n if (!date) {\n await this._storage.removeItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n } else {\n await this._storage.setItem(this.keychainValidityDateLocalStoreIdPrefix + id, date)\n }\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n *\n * Populate the HCP.options dict with an encrypted eHealth certificate and unencryped expiry date.\n * Any potentially unencrypted certificates will be pruned from the HCP.\n * @param hcpId Id of the hcp to modify\n * @returns modified HCP\n */\n async saveKeyChainInHCPFromLocalStorage(hcpId: string): Promise<HealthcareParty> {\n return await this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let aesKey: CryptoKey | null = null\n try {\n aesKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!aesKey) {\n console.error('No encryption key!')\n }\n\n const opts = hcp.options || {}\n\n const crt = await this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!!)\n if (!!aesKey && !!crt) {\n let crtEncrypted: ArrayBuffer | null = null\n try {\n crtEncrypted = await this.AES.encrypt(aesKey, new Uint8Array(string2ua(atob(crt))))\n } catch (e) {\n console.error('Error while encrypting the certificate', e)\n }\n\n // add the encrypted certificate to the options\n _.set(opts, this.hcpPreferenceKeyEhealthCert, ua2string(new Uint8Array(crtEncrypted!)))\n }\n\n const crtValidityDate = this.getKeychainValidityDateInBrowserLocalStorage(hcp.id!!)\n if (!!crtValidityDate) {\n _.set(opts, this.hcpPreferenceKeyEhealthCertDate, crtValidityDate)\n }\n\n hcp.options = opts\n return hcp\n })\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n importKeychainInBrowserFromHCP(hcpId: string): Promise<void> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let crtCryp: Uint8Array | null = null\n if (!!hcp.options && !!hcp.options[this.hcpPreferenceKeyEhealthCert]) {\n crtCryp = string2ua(hcp.options[this.hcpPreferenceKeyEhealthCert])\n }\n\n const crtValidityDate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCertDate)\n\n // store the validity date\n if (!!crtValidityDate) {\n this.saveKeychainValidityDateInBrowserLocalStorage(hcp.id!!, crtValidityDate)\n }\n\n let crt: ArrayBuffer | null = null\n let decryptionKey: CryptoKey | null = null\n try {\n decryptionKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!decryptionKey) {\n throw new Error('No encryption key! eHealth certificate cannot be decrypted.')\n }\n\n if (!!crtCryp && decryptionKey) {\n try {\n crt = await this.AES.decrypt(decryptionKey, crtCryp)\n } catch (e) {\n console.error(e)\n }\n }\n\n if (!crt) {\n throw new Error(`Error while saving certificate in browser local storage! Hcp ${hcp.id} has no certificate.`)\n } else {\n this.saveKeychainInBrowserLocalStorageAsBase64(hcp.id!!, btoa(String.fromCharCode.apply(null, Array.from(new Uint8Array(crt)))))\n }\n\n return\n })\n }\n\n /**\n * @deprecated e-health certificates and keychains are not part of iCure's api: this method will be removed.\n *\n * Synchronizes the eHealth certificate from the database into the LocalStorage, returning information on the presence\n * of certificate data in either place.\n *\n * @param hcpId The healthcare party id\n * @returns A Promise for an object that represents the existence of a certificate in local storage and in the DB,\n * through the two boolean properties \"local\" and \"remote\".\n */\n syncEhealthCertificateFromDatabase(hcpId: string): Promise<{ remote: boolean; local: boolean }> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then((hcp: HealthcareParty) => {\n const remoteCertificate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCert)\n const localCertificate = this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!)\n\n if (remoteCertificate) {\n return this.importKeychainInBrowserFromHCP(hcp.id!)\n .then(() => ({ local: true, remote: true }))\n .catch(() => ({ local: !!localCertificate, remote: true }))\n } else {\n return { local: !!localCertificate, remote: !!remoteCertificate }\n }\n })\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n getKeychainInBrowserLocalStorageAsBase64(id: string) {\n return this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n getKeychainValidityDateInBrowserLocalStorage(id: string) {\n return this._storage.getItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n async loadKeychainFromBrowserLocalStorage(id: string) {\n const lsItem = await this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n return lsItem !== undefined ? b64_2uas(lsItem) : null\n }\n\n /**\n * @deprecated you should not need this method anymore to deal with the encryption of iCure entities because everything related to entities\n * encryption should be done through the entity-specific extended api.\n * If instead you were using the method for other reasons check {@link getCachedRsaKeyPairForFingerprint} to get an idea of possible replacements.\n */\n async loadKeyPairNotImported(id: string, publicKeyFingerPrint?: string): Promise<{ publicKey: JsonWebKey; privateKey: JsonWebKey } | undefined> {\n if (publicKeyFingerPrint) {\n const cached = this.keyManager.getKeyPairForFingerprint(publicKeyFingerPrint)?.pair\n if (cached) {\n return this.primitives.RSA.exportKeys(cached, 'jwk', 'jwk')\n }\n } else {\n const defaultKey = await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id)\n if (defaultKey) return defaultKey\n }\n console.warn(`No key can be found in local storage for id ${id} and publicKeyFingerPrint ${publicKeyFingerPrint}`)\n }\n\n /**\n * @deprecated use {@link IccIcureMaintenanceXApi.applyKeyPairUpdate} instead.\n */\n async giveAccessBackTo(delegateUser: User, ownerId: string, ownerNewPublicKey: string): Promise<DataOwner> {\n await this.exchangeKeys.base.giveAccessBackTo(ownerId, ownerNewPublicKey, this.userKeysManager.getDecryptionKeys())\n return this.dataOwnerApi.getDataOwner(ownerId).then((x) => x.dataOwner)\n }\n /**\n * @deprecated You don't need to manually generate exchange keys as they will be automatically created by the api when needed.\n * Note that this method has some changes compared to previous version:\n * - The method may return any data owner (including devices)\n * - The method will throw an exception if the provided ownerId does not match the current data owner\n */\n async generateKeyForDelegate(ownerId: string, delegateId: string): Promise<DataOwner> {\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n throw new Error('You can only create delegation where the delegator is the current data owner')\n }\n return (await this.dataOwnerApi.getDataOwner(ownerId)).dataOwner\n }\n\n /**\n * @deprecated replace with {@link IccDataOwnerXApi.getDataOwner}. Note that data owners are not cached anymore.\n */\n getDataOwner(ownerId: string, loadIfMissingFromCache: boolean = true) {\n return this.dataOwnerApi.getDataOwner(ownerId)\n }\n\n /**\n * @deprecated the crypto api will automatically verify on startup the validity of private keys, but in some cases you may want to verify the\n * validity of keys recovered in your implementation of {@link CryptoStrategies}: in this case the method has been replaced with\n * {@link RSA.checkKeyPairValidity}\n */\n async checkPrivateKeyValidity(dataOwner: DataOwner): Promise<boolean> {\n const publicKeys = Array.from(new Set([dataOwner.publicKey].concat(Object.keys(dataOwner.aesExchangeKeys ?? {})).filter((x) => !!x))) as string[]\n\n return await publicKeys.reduce(async (pres, publicKey) => {\n const res = await pres\n try {\n const k = await this.primitives.RSA.importKey('jwk', spkiToJwk(hex2ua(publicKey)), ['encrypt'])\n const cipher = await this.primitives.RSA.encrypt(k, utf8_2ua('shibboleth'))\n const ikp = await this.getCachedRsaKeyPairForFingerprint(dataOwner.id!, publicKey.slice(-32))\n const plainText = ua2utf8(await this.primitives.RSA.decrypt(ikp.privateKey, new Uint8Array(cipher)))\n return plainText === 'shibboleth' || res\n } catch (e) {\n return res\n }\n }, Promise.resolve(false))\n }\n\n /**\n * @deprecated (See {@link extractEncryptionsSKs} for a detailed explanation).\n */\n async getEncryptionDecryptionKeys(dataOwnerId: string, document: EncryptedEntity): Promise<Array<string> | undefined> {\n return this.entities.encryptionKeysOf(document, dataOwnerId)\n }\n\n /**\n * @deprecated For the encryption/decryption of iCure entities and attachments you should rely solely on the extended apis methods.\n */\n async encryptDecrypt(\n method: 'encrypt' | 'decrypt',\n content: Uint8Array | ArrayBuffer,\n edKey?: string,\n user?: User,\n documentObject?: Document\n ): Promise<Uint8Array | Array<any> | any> {\n if (!content || !(edKey || (user?.healthcarePartyId && documentObject))) return content\n\n if (edKey) {\n const importedEdKey = await this.primitives.AES.importKey('raw', hex2ua(edKey.replace(/-/g, '')))\n try {\n return await this.primitives.AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n const encryptionKeys = await this.entities.encryptionKeysOf(documentObject!, user?.healthcarePartyId!)\n const importedEdKey = await this.primitives.AES.importKey('raw', hex2ua(encryptionKeys[0].replace(/-/g, '')))\n try {\n return await this.primitives.AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n /**\n * @deprecated you should not need to interact directly with the storage instance used by the iCure sdk.\n */\n storeKeyPair(id: string, keyPair: { publicKey: any; privateKey: any }) {\n this._storage.setItem(this.rsaLocalStoreIdPrefix + id, JSON.stringify(keyPair))\n }\n}\n"]}
1
+ {"version":3,"file":"icc-crypto-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-crypto-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,4BAA2B;AAE3B,uDAA6G;AAC7G,mCAAyE;AAoBzE,MAAa,aAAa;IAmBxB,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,gBAAgB,CAAA;IAC9B,CAAC;IAED;;OAEG;IACH,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,mBAAmB,CAAA;IACjC,CAAC;IAED;;OAEG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAA;IACrC,CAAC;IAED;;OAEG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAA;IACrC,CAAC;IAED;;OAEG;IACH,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAA;IAClC,CAAC;IAED;;OAEG;IACH,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAA;IAClC,CAAC;IAED;;OAEG;IACH,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,WAAW,CAAA;IACzB,CAAC;IAED;;OAEG;IACH,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAA;IACtB,CAAC;IAED;;OAEG;IACH,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,kBAAkB,CAAA;IAChC,CAAC;IAED;;OAEG;IACH,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,oBAAoB,CAAA;IAClC,CAAC;IAED;;OAEG;IACH,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,UAAU,CAAA;IACxB,CAAC;IAED;;OAEG;IACH,IAAI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AE,OAA4C;QACnE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,GAAG,EAAE,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAA;IACjF,CAAC;CACF;AAj6BD,sCAi6BC","sourcesContent":["/* eslint-disable */\nimport { AESUtils } from './crypto/AES'\nimport { KeyPair, RSAUtils } from './crypto/RSA'\nimport { ShamirClass } from './crypto/shamir'\nimport * as _ from 'lodash'\nimport { Delegation, Device, Document, EncryptedEntity, EncryptedParentEntity, HealthcareParty, Patient, User } from '../icc-api/model/models'\nimport { b2a, b64_2uas, hex2ua, string2ua, ua2hex, ua2string, ua2utf8, utf8_2ua } from './utils/binary-utils'\nimport { keyPairFromPrivateKeyJwk, pkcs8ToJwk, spkiToJwk } from './utils'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\nimport { ExchangeKeysManager } from './crypto/ExchangeKeysManager'\nimport { CryptoPrimitives } from './crypto/CryptoPrimitives'\nimport { KeyManager } from './crypto/KeyManager'\nimport { DataOwner, IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { EntitiesEncryption } from './crypto/EntitiesEncryption'\nimport { IcureStorageFacade } from './storage/IcureStorageFacade'\nimport { ShamirKeysManager } from './crypto/ShamirKeysManager'\nimport { IccHcpartyApi } from '../icc-api'\nimport { StorageEntryKeysFactory } from './storage/StorageEntryKeysFactory'\nimport { ConfidentialEntities } from './crypto/ConfidentialEntities'\n\ninterface DelegatorAndKeys {\n delegatorId: string\n key: CryptoKey\n rawKey: string\n}\n\nexport class IccCryptoXApi {\n keychainLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain.'\n keychainValidityDateLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain-date.'\n hcpPreferenceKeyEhealthCert = 'eHealthCRTCrypt'\n hcpPreferenceKeyEhealthCertDate = 'eHealthCRTDate'\n rsaLocalStoreIdPrefix = 'org.taktik.icure.rsa.'\n private readonly exchangeKeysManager: ExchangeKeysManager\n private readonly cryptoPrimitives: CryptoPrimitives\n private readonly keyManager: KeyManager\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly entitiesEncrypiton: EntitiesEncryption\n private readonly confidentialEntities: ConfidentialEntities\n private readonly icureStorage: IcureStorageFacade\n private readonly shamirManager: ShamirKeysManager\n private readonly _storage: StorageFacade<string>\n private readonly _keyStorage: KeyStorageFacade\n\n private readonly hcpartyBaseApi: IccHcpartyApi\n\n get primitives(): CryptoPrimitives {\n return this.cryptoPrimitives\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n get exchangeKeys(): ExchangeKeysManager {\n return this.exchangeKeysManager\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.crypto} at {@link primitives}.\n */\n get crypto(): Crypto {\n return this.cryptoPrimitives.crypto\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.shamir} at {@link primitives}.\n */\n get shamir(): ShamirClass {\n return this.cryptoPrimitives.shamir\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.RSA} at {@link primitives}.\n */\n get RSA(): RSAUtils {\n return this.cryptoPrimitives.RSA\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.AES} at {@link primitives}.\n */\n get AES(): AESUtils {\n return this.cryptoPrimitives.AES\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get keyStorage(): KeyStorageFacade {\n return this._keyStorage\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get storage(): StorageFacade<string> {\n return this._storage\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get entities(): EntitiesEncryption {\n return this.entitiesEncrypiton\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get confidential(): ConfidentialEntities {\n return this.confidentialEntities\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get userKeysManager(): KeyManager {\n return this.keyManager\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get shamirKeysManager(): ShamirKeysManager {\n return this.shamirManager\n }\n\n /**\n * @internal\n */\n constructor(\n exchangeKeysManager: ExchangeKeysManager,\n cryptoPrimitives: CryptoPrimitives,\n keyManager: KeyManager,\n dataOwnerApi: IccDataOwnerXApi,\n entitiesEncrypiton: EntitiesEncryption,\n shamirManager: ShamirKeysManager,\n storage: StorageFacade<string>,\n keyStorage: KeyStorageFacade,\n icureStorageFacade: IcureStorageFacade,\n hcPartyBaseApi: IccHcpartyApi,\n confidentialEntities: ConfidentialEntities\n ) {\n this.exchangeKeysManager = exchangeKeysManager\n this.cryptoPrimitives = cryptoPrimitives\n this.keyManager = keyManager\n this.dataOwnerApi = dataOwnerApi\n this.entitiesEncrypiton = entitiesEncrypiton\n this.shamirManager = shamirManager\n this._storage = storage\n this._keyStorage = keyStorage\n this.icureStorage = icureStorageFacade\n this.hcpartyBaseApi = hcPartyBaseApi\n this.confidentialEntities = confidentialEntities\n }\n\n /**\n * Deletes values cached by the crypto api, to allow to detect changes in stored key pairs, exchange keys and/or current data owner details.\n * This method may be useful in cases where a user is logged in from multiple devices or in cases where other users have just shared some data with\n * the current user for the first time.\n */\n async forceReload() {\n this.exchangeKeysManager.clearCache(true)\n this.dataOwnerApi.clearCurrentDataOwnerIdsCache()\n await this.keyManager.reloadKeys()\n }\n\n /**\n * Get all key pairs available for the decrpytion and encryption of data to the current data owner. These include the key pairs from the data owner\n * and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n getEncryptionDecryptionKeypairsForDataOwnerHierarchy(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey> }[]\n }[]\n }> {\n return this.keyManager.getCurrentUserHierarchyAvailableKeypairs()\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n return this.keyManager.getKeyPairForFingerprint(fingerprint)\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return this.keyManager.getCurrentUserHierarchyAvailablePublicKeysHex()\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n return this.keyManager.getCurrentUserAvailablePublicKeysHex(verifiedOnly)\n }\n\n /**\n * @deprecated depending on your use case you should delete the calls to this method or call {@link forceReload}:\n * - Replace with `forceReload()` if one of the following parts of the current data owner may have been modified from a different api instance:\n * - Hcp hierarchy\n * - Key recovery data (transfer keys or shamir)\n * - Exchange keys (formerly hcp keys)\n * - Remove the call if the main goal was to force reload the data owner: data owner are not cached anymore.\n */\n emptyHcpCache(hcpartyId: string) {\n this.exchangeKeysManager.clearCache(false)\n }\n\n /**\n * @deprecated you should not need this method anymore to deal with the encryption of iCure entities because everything related to entities\n * encryption should be done either through the entity-specific extended api or through the extended apis.\n * Note that keys returned by the current implementation of this method may not be safe for encryption/sharing.\n * If instead you are using this method to retrieve key pairs for other purposes, for example because you want to reuse the user keys in iCure for\n * other services consider the following alternatives:\n * - If you want to use all iCure facilities including key recovery and key verification you can use {@link getKeyPairForFingerprint}.\n * Note that this solution can only give access to keys for the data owner of the instantiated api and his parents.\n * - Alternatively you can use directly your choice of {@link KeyStorageFacade} and {@link StorageEntryKeysFactory}: if these are the same you use\n * for the iCure API client the keys will be shared with it. Note however that the iCure api client uses\n * {@link StorageEntryKeysFactory.cachedRecoveredKeypairOfDataOwner} to cache recovered keys of a data owner which may not have originated from\n * this device, so you should only use {@link StorageEntryKeysFactory.deviceKeypairOfDataOwner} if you want to make sure the keys you use are safe\n * for encryption.\n */\n async getCachedRsaKeyPairForFingerprint(\n dataOwnerId: string,\n pubKeyOrFingerprint: string\n ): Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }> {\n const fingerprint = pubKeyOrFingerprint.slice(-32)\n const res = this.keyManager.getDecryptionKeys()[fingerprint]\n if (!res) console.warn(`Could not find any keypair for fingerprint ${fingerprint}`)\n return res\n }\n\n /**\n * @deprecated You do not need this method to encrypt/decrypt data of iCure, but if you want to reuse the iCure keys for the user for other purposes\n * you have different options to replace this method, depending on what you actually need. All options return the hex-encoded spki representation of\n * the public keys.\n * - If you want only the public keys for which we have a private key available\n * - you can replicate the current behaviour using {@link getCurrentUserHierarchyAvailablePublicKeysHex}. This includes keys for the current user\n * and his parents.\n * - use {@link getCurrentUserAvailablePublicKeysHex} to get public keys only for the current data owner, ignoring any keys of the\n * parent hierarchy. In this case you can also apply a filter to only get verified keys (safe for encryption).\n * - If you need all public keys for the data owner, including those for which there is no corresponding private key available on the device use\n * {@link IccDataOwnerXApi.getHexPublicKeysOf} with the current data owner. If you don't have it available you may get it from\n * {@link IccDataOwnerXApi.getCurrentDataOwner}, but this will require to do a request to the iCure server (other options use only cached data).\n */\n async getPublicKeys(): Promise<string[]> {\n return this.userKeysManager.getCurrentUserHierarchyAvailablePublicKeysHex()\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.randomUuid} at {@link primitives}.\n */\n randomUuid() {\n return this.primitives.randomUuid()\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.sha256} at {@link primitives}.\n */\n sha256(data: ArrayBuffer | Uint8Array) {\n return this.primitives.sha256(data)\n }\n\n /**\n * @deprecated Use {@link ShamirKeysManager.updateSelfSplits} from {@link shamirKeysManager} instead. Note that the new method completely replaces\n * all current values if a split for the provided key already exists.\n */\n async encryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>, threshold?: number): Promise<HealthcareParty> {\n const legacyKeyFp = hcp.publicKey?.slice(-32)\n if (!legacyKeyFp) throw new Error(`No legacy/default key for hcp ${hcp.id}`)\n await this.shamirKeysManager.updateSelfSplits(\n { [legacyKeyFp]: { notariesIds: notaries.map((x) => x.id!), minShares: threshold ?? notaries.length } },\n []\n )\n return (await this.dataOwnerApi.getDataOwner(hcp.id!)).dataOwner as HealthcareParty\n }\n\n /**\n * @deprecated You should not need this method anymore because the api will automatically try to recover the available shamir keys on startup.\n */\n async decryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>): Promise<void> {\n try {\n const publicKeys = await this.getPublicKeys()\n const nLen = notaries.length\n let decryptedPrivatedKey\n if (nLen == 1) {\n const notaryHcPartyId = notaries[0].id!\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notaryHcPartyId)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notaryHcPartyId, hcp.id!, notaryHcPartyId, idPubKey, keysMap, publicKeys)\n )\n )\n const cryptedPrivatedKey = hcp.privateKeyShamirPartitions![notaryHcPartyId]\n decryptedPrivatedKey = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(cryptedPrivatedKey)\n )\n )\n } else {\n const decryptedShares: string[] = await _.reduce(\n notaries,\n (queue, notary) => {\n return queue.then(async (shares: string[]) => {\n try {\n // now, we get the encrypted shares in db and decrypt them. This assumes that the\n // the notaries' private keys are in localstorage. We should implement a way for the notaries to\n // give hcp the decrypted shares without having to also share their private keys.\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notary.id!)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notary.id!, hcp.id!, notary.id!, idPubKey, keysMap, publicKeys)\n )\n )\n const encryptedShare = hcp.privateKeyShamirPartitions![notary.id!]\n const decryptedShamirPartition = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(encryptedShare)\n )\n )\n shares.push(decryptedShamirPartition)\n } catch (e) {\n console.log('Error during encryptedShamirRSAKey', notary.id, e)\n }\n return shares\n })\n },\n Promise.resolve([] as string[])\n )\n\n decryptedPrivatedKey = this.primitives.shamir.combine(decryptedShares)\n }\n\n const importedPrivateKey = await this.primitives.RSA.importKey('pkcs8', hex2ua(decryptedPrivatedKey), ['decrypt'])\n const importedPublicKey = await this.primitives.RSA.importKey('spki', hex2ua(hcp.publicKey!), ['encrypt'])\n\n const exportedKeyPair = await this.primitives.RSA.exportKeys({ publicKey: importedPublicKey, privateKey: importedPrivateKey }, 'jwk', 'jwk')\n await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${hcp.id!}`, exportedKeyPair)\n } catch (e) {\n console.log('Cannot decrypt shamir RSA key')\n }\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n * Note that currently this method does not cache results anymore (but the updated methods do).\n */\n async decryptHcPartyKey(\n loggedHcPartyId: string,\n delegatorId: string,\n delegateHcPartyId: string,\n publicKey: string,\n encryptedHcPartyKeys: { [key: string]: string },\n publicKeys: string[]\n ): Promise<DelegatorAndKeys> {\n if (!publicKeys.length) {\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: no public key`\n console.warn(reason)\n throw new Error(reason)\n }\n const keysFpSet = new Set(publicKeys.map((x) => x.slice(-32)))\n const filteredKeys = Object.fromEntries(Object.entries(this.keyManager.getDecryptionKeys()).filter(([fp]) => keysFpSet.has(fp)))\n const decrypted = await this.exchangeKeysManager.base.tryDecryptExchangeKeys([encryptedHcPartyKeys], filteredKeys)\n const res = decrypted.successfulDecryptions[0]\n if (!res) {\n const error =\n `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: impossible to decrypt. ` +\n 'No private key was found or could be used to decrypt the aes exchange keys`'\n console.warn(error)\n throw new Error(error)\n }\n return {\n delegatorId,\n key: res,\n rawKey: ua2hex(await this.primitives.AES.exportKey(res, 'raw')),\n }\n }\n\n /**\n * @deprecated you should not need this method anymore. The new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If no verified key (safe for encryption) can be found during the instantiation\n * of the API, depending on the parameters passed to the factory one of two scenarios will happen:\n * - A new key will be automatically created on the device and stored using the key storage facade.\n * - The api instantiation fails with an exception. This is ideal if you want to try to recover an existing key pair before creating a new one.\n *\n * If you were using this method to allow the user to recover an existing key that is not available in the storage facade nor recoverable through\n * transfer keys or shamir split (for example by scanning a qr code, or by loading a file from the computer to the web browser's local storage)\n * you will have to move that logic in your implementation of CryptoStrategies.\n * It is currently not allowed to create new key pairs if a verified key pair is already available on the device, as this would be wasteful.\n * If you want to convert a `JsonWebKey` pair to a `CryptoKey` pair you should use directly the method in `primitives.RSA`.\n */\n async cacheKeyPair(keyPairInJwk: KeyPair<JsonWebKey>): Promise<KeyPair<CryptoKey>> {\n const cryptoKeyPair = await this.primitives.RSA.importKeyPair('jwk', keyPairInJwk.privateKey, 'jwk', keyPairInJwk.publicKey)\n const pubHex = ua2hex(await this.primitives.RSA.exportKey(cryptoKeyPair.publicKey, 'spki'))\n const fingerprint = pubHex.slice(-32)\n if (!this.keyManager.getDecryptionKeys()[fingerprint]) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const selfKeys = this.dataOwnerApi.getHexPublicKeysOf((await this.dataOwnerApi.getCurrentDataOwner()).dataOwner)\n if (!selfKeys.has(pubHex))\n throw new Error(\n `Impossible to add key pair with fingerprint ${fingerprint} to data owner ${selfId}: the data owner has no matching public key`\n )\n await this.icureStorage.saveKey(selfId, fingerprint, keyPairInJwk, true)\n // Force reload to check if more private keys can be recovered or more exchange keys become available.\n await this.forceReload()\n }\n return cryptoKeyPair\n }\n\n /**\n * @deprecated Usually you should not need this method, since the preferred sfk is automatically chosen by the extended entity apis when creating a\n * new instance of the entity.\n */\n async extractPreferredSfk(parent: EncryptedParentEntity, hcpartyId: string, confidential: boolean) {\n return confidential ? this.confidential.getConfidentialSecretId(parent, hcpartyId) : this.confidential.getAnySecretIdSharedWithParents(parent)\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n */\n async decryptAndImportAesHcPartyKeysForDelegators(\n delegatorsHcPartyIdsSet: Array<string>,\n delegateHcPartyId: string,\n minCacheDurationInSeconds: number = 60\n ): Promise<Array<DelegatorAndKeys>> {\n return await delegatorsHcPartyIdsSet.reduce(async (acc, delegator) => {\n const awaitedAcc = await acc\n const keys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegator, delegateHcPartyId)\n const keysForDelegator = await keys.reduce(async (accForKey, cryptoKey) => {\n const awaitedAccForKey = await accForKey\n const rawKey = ua2hex(await this.primitives.RSA.exportKey(cryptoKey, 'spki'))\n return [\n ...awaitedAccForKey,\n {\n key: cryptoKey,\n delegatorId: delegator,\n rawKey: rawKey,\n },\n ]\n }, Promise.resolve([] as DelegatorAndKeys[]))\n return [...awaitedAcc, ...keysForDelegator]\n }, Promise.resolve([] as DelegatorAndKeys[]))\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n * Note that currently this method does not cache results anymore (but the updated methods do).\n */\n async getEncryptedAesExchangeKeys(\n owner: DataOwner,\n delegateId: string\n ): Promise<{ [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } }> {\n const publicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(owner))\n const mapOfAesExchangeKeys = Object.entries(owner.aesExchangeKeys ?? {})\n .filter((e) => e[1][delegateId] && Object.keys(e[1][delegateId]).some((k1) => publicKeys.some((pk) => pk.endsWith(k1))))\n .reduce((map, e) => {\n const candidates = Object.entries(e[1][delegateId]) //[fingerprint of delegate pub key, key], [fingerprint of owner pub key, key]\n const [publicKeyFingerprint, encryptedAesExchangeKey] = candidates[candidates.findIndex(([k, v]) => publicKeys.some((pk) => pk.endsWith(k)))]\n return { ...map, [e[0]]: { [publicKeyFingerprint]: encryptedAesExchangeKey } }\n }, {} as { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } })\n\n if (!owner.publicKey || mapOfAesExchangeKeys[owner.publicKey] || !owner.hcPartyKeys?.[delegateId]) {\n return mapOfAesExchangeKeys\n }\n const delegate = (await this.dataOwnerApi.getDataOwner(delegateId)).dataOwner\n if (delegate.publicKey && publicKeys.includes(delegate.publicKey)) {\n return {\n ...mapOfAesExchangeKeys,\n [owner.publicKey]: { [delegate.publicKey!.slice(-32)]: owner.hcPartyKeys[delegateId][1] },\n }\n } else if (publicKeys.includes(owner.publicKey)) {\n return { ...mapOfAesExchangeKeys, [owner.publicKey]: { [owner.publicKey.slice(-32)]: owner.hcPartyKeys[delegateId][0] } }\n }\n return mapOfAesExchangeKeys\n }\n\n /**\n * @deprecated you should not use this method because initialisation of encrypted entities keys is done automatically by the entity-specific\n * extended api. Also note that it is now forbidden to initialise an entity as a data owner which is not the current data owner: you should instead\n * create the entity as the current data owner then create a delegation to the other data owner.\n */\n async initEncryptionKeys(\n createdObject: any,\n ownerId: string\n ): Promise<{\n encryptionKeys: any\n secretId: string\n }> {\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n throw new Error('Impossible to initialise keys as a data owner which is not the current data owner')\n }\n const { updatedEntity, rawEncryptionKey } = await this.entities.entityWithInitialisedEncryptedMetadata(\n {\n ...createdObject,\n delegations: undefined,\n encryptionKeys: undefined,\n cryptedForeignKeys: undefined,\n secretForeignKeys: undefined,\n } as EncryptedEntity,\n undefined,\n undefined,\n true\n )\n return {\n encryptionKeys: updatedEntity.encryptionKeys,\n secretId: rawEncryptionKey!,\n }\n }\n\n /**\n * @deprecated You should use:\n * - {@link IccPatientXApi.decryptSecretIdsOf} or {@link IccMessageXApi.decryptSecretIdsOf} to get the delegation sfks (now caleld secret ids).\n * - {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds} to get the full hierarchy for the current data owner (cached). The first element is\n * the id of the topmost parent, while the last is the current data owner.\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractDelegationsSFKs(document: EncryptedEntity | null, hcpartyId?: string): Promise<{ extractedKeys: Array<string>; hcpartyId?: string }> {\n if (!document || !hcpartyId) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const delegationsForAllDelegates = document.delegations\n if (!delegationsForAllDelegates || !Object.keys(delegationsForAllDelegates).length) {\n console.log(`There is no delegation in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.secretIdsOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated (light) You should use:\n * - {@link IccHelementXApi.decryptPatientIdOf}, {@link IccDocumentXApi.decryptMessageIdOf}, ... to get the crypted foreign keys.\n * - {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds} to get the full hierarchy for the current data owner (cached). The first element is\n * the id of the topmost parent, while the last is the current data owner.\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractCryptedFKs(document: EncryptedEntity | null, hcpartyId: string): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document || !document.cryptedForeignKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const cfksForAllDelegates = document.cryptedForeignKeys\n if (!cfksForAllDelegates || !Object.keys(cfksForAllDelegates).length) {\n console.log(`There is no cryptedForeignKeys in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.owningEntityIdsOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated You should use the extended apis methods to encrypt/decrypt entities or their attachments\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractEncryptionsSKs(document: EncryptedEntity, hcpartyId: string): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document.encryptionKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const eckeysForAllDelegates = document.encryptionKeys\n if (!eckeysForAllDelegates || !Object.keys(eckeysForAllDelegates).length) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.encryptionKeysOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated You should not use this method anymore, depending on what you were passing as {@link delegations} you should replace this method as\n * explained in {@link extractEncryptionsSKs} (if you were passing encryptionKeys), {@link extractCryptedFKs} (cryptedForeignKeys), or\n * {@link extractDelegationsSFKs} (delegations).\n */\n async extractKeysFromDelegationsForHcpHierarchy(\n dataOwnerId: string,\n objectId: string,\n delegations: { [key: string]: Array<Delegation> }\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n return {\n extractedKeys: await this.entities.extractMergedHierarchyFromDelegationAndOwner(\n delegations,\n dataOwnerId,\n (x) => !!x,\n () => Promise.resolve(true)\n ),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n * You can convert the private key pkcs8 array to a jwk key using {@link pkcs8ToJwk} then you can extract the full key pair using\n * {@link keyPairFromPrivateKeyJwk}.\n */\n async loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId: string, privateKey: Uint8Array) {\n await this.cacheKeyPair(keyPairFromPrivateKeyJwk(pkcs8ToJwk(privateKey)))\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n * You can extract the full key pair using {@link keyPairFromPrivateKeyJwk}.\n */\n async loadKeyPairsAsJwkInBrowserLocalStorage(healthcarePartyId: string, privateKey: JsonWebKey) {\n await this.cacheKeyPair(keyPairFromPrivateKeyJwk(privateKey))\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n */\n loadKeyPairsInBrowserLocalStorage(healthcarePartyId: string, file: Blob): Promise<void> {\n const fr = new FileReader()\n return new Promise((resolve, reject) => {\n fr.onerror = reject\n fr.onabort = reject\n fr.onload = (e: any) => {\n const privateKey = e.target.result as string\n this.loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId, hex2ua(privateKey))\n .then(() => resolve())\n .catch(reject)\n }\n fr.readAsText(file)\n })\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n saveKeychainInBrowserLocalStorage(id: string, keychain: number) {\n this._storage.setItem(\n this.keychainLocalStoreIdPrefix + id,\n b2a(new Uint8Array(keychain).reduce((data, byte) => data + String.fromCharCode(byte), ''))\n )\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n saveKeychainInBrowserLocalStorageAsBase64(id: string, keyChainB64: string) {\n this._storage.setItem(this.keychainLocalStoreIdPrefix + id, keyChainB64)\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n async saveKeychainValidityDateInBrowserLocalStorage(id: string, date: string) {\n if (!id) return\n\n if (!date) {\n await this._storage.removeItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n } else {\n await this._storage.setItem(this.keychainValidityDateLocalStoreIdPrefix + id, date)\n }\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n *\n * Populate the HCP.options dict with an encrypted eHealth certificate and unencryped expiry date.\n * Any potentially unencrypted certificates will be pruned from the HCP.\n * @param hcpId Id of the hcp to modify\n * @returns modified HCP\n */\n async saveKeyChainInHCPFromLocalStorage(hcpId: string): Promise<HealthcareParty> {\n return await this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let aesKey: CryptoKey | null = null\n try {\n aesKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!aesKey) {\n console.error('No encryption key!')\n }\n\n const opts = hcp.options || {}\n\n const crt = await this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!!)\n if (!!aesKey && !!crt) {\n let crtEncrypted: ArrayBuffer | null = null\n try {\n crtEncrypted = await this.AES.encrypt(aesKey, new Uint8Array(string2ua(atob(crt))))\n } catch (e) {\n console.error('Error while encrypting the certificate', e)\n }\n\n // add the encrypted certificate to the options\n _.set(opts, this.hcpPreferenceKeyEhealthCert, ua2string(new Uint8Array(crtEncrypted!)))\n }\n\n const crtValidityDate = this.getKeychainValidityDateInBrowserLocalStorage(hcp.id!!)\n if (!!crtValidityDate) {\n _.set(opts, this.hcpPreferenceKeyEhealthCertDate, crtValidityDate)\n }\n\n hcp.options = opts\n return hcp\n })\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n importKeychainInBrowserFromHCP(hcpId: string): Promise<void> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let crtCryp: Uint8Array | null = null\n if (!!hcp.options && !!hcp.options[this.hcpPreferenceKeyEhealthCert]) {\n crtCryp = string2ua(hcp.options[this.hcpPreferenceKeyEhealthCert])\n }\n\n const crtValidityDate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCertDate)\n\n // store the validity date\n if (!!crtValidityDate) {\n this.saveKeychainValidityDateInBrowserLocalStorage(hcp.id!!, crtValidityDate)\n }\n\n let crt: ArrayBuffer | null = null\n let decryptionKey: CryptoKey | null = null\n try {\n decryptionKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!decryptionKey) {\n throw new Error('No encryption key! eHealth certificate cannot be decrypted.')\n }\n\n if (!!crtCryp && decryptionKey) {\n try {\n crt = await this.AES.decrypt(decryptionKey, crtCryp)\n } catch (e) {\n console.error(e)\n }\n }\n\n if (!crt) {\n throw new Error(`Error while saving certificate in browser local storage! Hcp ${hcp.id} has no certificate.`)\n } else {\n this.saveKeychainInBrowserLocalStorageAsBase64(hcp.id!!, btoa(String.fromCharCode.apply(null, Array.from(new Uint8Array(crt)))))\n }\n\n return\n })\n }\n\n /**\n * @deprecated e-health certificates and keychains are not part of iCure's api: this method will be removed.\n *\n * Synchronizes the eHealth certificate from the database into the LocalStorage, returning information on the presence\n * of certificate data in either place.\n *\n * @param hcpId The healthcare party id\n * @returns A Promise for an object that represents the existence of a certificate in local storage and in the DB,\n * through the two boolean properties \"local\" and \"remote\".\n */\n syncEhealthCertificateFromDatabase(hcpId: string): Promise<{ remote: boolean; local: boolean }> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then((hcp: HealthcareParty) => {\n const remoteCertificate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCert)\n const localCertificate = this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!)\n\n if (remoteCertificate) {\n return this.importKeychainInBrowserFromHCP(hcp.id!)\n .then(() => ({ local: true, remote: true }))\n .catch(() => ({ local: !!localCertificate, remote: true }))\n } else {\n return { local: !!localCertificate, remote: !!remoteCertificate }\n }\n })\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n getKeychainInBrowserLocalStorageAsBase64(id: string) {\n return this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n getKeychainValidityDateInBrowserLocalStorage(id: string) {\n return this._storage.getItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n async loadKeychainFromBrowserLocalStorage(id: string) {\n const lsItem = await this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n return lsItem !== undefined ? b64_2uas(lsItem) : null\n }\n\n /**\n * @deprecated you should not need this method anymore to deal with the encryption of iCure entities because everything related to entities\n * encryption should be done through the entity-specific extended api.\n * If instead you were using the method for other reasons check {@link getCachedRsaKeyPairForFingerprint} to get an idea of possible replacements.\n */\n async loadKeyPairNotImported(id: string, publicKeyFingerPrint?: string): Promise<{ publicKey: JsonWebKey; privateKey: JsonWebKey } | undefined> {\n if (publicKeyFingerPrint) {\n const cached = this.keyManager.getKeyPairForFingerprint(publicKeyFingerPrint)?.pair\n if (cached) {\n return this.primitives.RSA.exportKeys(cached, 'jwk', 'jwk')\n }\n } else {\n const defaultKey = await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id)\n if (defaultKey) return defaultKey\n }\n console.warn(`No key can be found in local storage for id ${id} and publicKeyFingerPrint ${publicKeyFingerPrint}`)\n }\n\n /**\n * @deprecated use {@link IccIcureMaintenanceXApi.applyKeyPairUpdate} instead.\n */\n async giveAccessBackTo(delegateUser: User, ownerId: string, ownerNewPublicKey: string): Promise<DataOwner> {\n await this.exchangeKeys.base.giveAccessBackTo(ownerId, ownerNewPublicKey, this.userKeysManager.getDecryptionKeys())\n return this.dataOwnerApi.getDataOwner(ownerId).then((x) => x.dataOwner)\n }\n /**\n * @deprecated You don't need to manually generate exchange keys as they will be automatically created by the api when needed.\n * Note that this method has some changes compared to previous version:\n * - The method may return any data owner (including devices)\n * - The method will throw an exception if the provided ownerId does not match the current data owner\n */\n async generateKeyForDelegate(ownerId: string, delegateId: string): Promise<DataOwner> {\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n throw new Error('You can only create delegation where the delegator is the current data owner')\n }\n return (await this.dataOwnerApi.getDataOwner(ownerId)).dataOwner\n }\n\n /**\n * @deprecated replace with {@link IccDataOwnerXApi.getDataOwner}. Note that data owners are not cached anymore.\n */\n getDataOwner(ownerId: string, loadIfMissingFromCache: boolean = true) {\n return this.dataOwnerApi.getDataOwner(ownerId)\n }\n\n /**\n * @deprecated the crypto api will automatically verify on startup the validity of private keys, but in some cases you may want to verify the\n * validity of keys recovered in your implementation of {@link CryptoStrategies}: in this case the method has been replaced with\n * {@link RSA.checkKeyPairValidity}\n */\n async checkPrivateKeyValidity(dataOwner: DataOwner): Promise<boolean> {\n const publicKeys = Array.from(new Set([dataOwner.publicKey].concat(Object.keys(dataOwner.aesExchangeKeys ?? {})).filter((x) => !!x))) as string[]\n\n return await publicKeys.reduce(async (pres, publicKey) => {\n const res = await pres\n try {\n const k = await this.primitives.RSA.importKey('jwk', spkiToJwk(hex2ua(publicKey)), ['encrypt'])\n const cipher = await this.primitives.RSA.encrypt(k, utf8_2ua('shibboleth'))\n const ikp = await this.getCachedRsaKeyPairForFingerprint(dataOwner.id!, publicKey.slice(-32))\n const plainText = ua2utf8(await this.primitives.RSA.decrypt(ikp.privateKey, new Uint8Array(cipher)))\n return plainText === 'shibboleth' || res\n } catch (e) {\n return res\n }\n }, Promise.resolve(false))\n }\n\n /**\n * @deprecated (See {@link extractEncryptionsSKs} for a detailed explanation).\n */\n async getEncryptionDecryptionKeys(dataOwnerId: string, document: EncryptedEntity): Promise<Array<string> | undefined> {\n return this.entities.encryptionKeysOf(document, dataOwnerId)\n }\n\n /**\n * @deprecated For the encryption/decryption of iCure entities and attachments you should rely solely on the extended apis methods.\n */\n async encryptDecrypt(\n method: 'encrypt' | 'decrypt',\n content: Uint8Array | ArrayBuffer,\n edKey?: string,\n user?: User,\n documentObject?: Document\n ): Promise<Uint8Array | Array<any> | any> {\n if (!content || !(edKey || (user?.healthcarePartyId && documentObject))) return content\n\n if (edKey) {\n const importedEdKey = await this.primitives.AES.importKey('raw', hex2ua(edKey.replace(/-/g, '')))\n try {\n return await this.primitives.AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n const encryptionKeys = await this.entities.encryptionKeysOf(documentObject!, user?.healthcarePartyId!)\n const importedEdKey = await this.primitives.AES.importKey('raw', hex2ua(encryptionKeys[0].replace(/-/g, '')))\n try {\n return await this.primitives.AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n /**\n * @deprecated you should not need to interact directly with the storage instance used by the iCure sdk.\n */\n storeKeyPair(id: string, keyPair: { publicKey: any; privateKey: any }) {\n this._storage.setItem(this.rsaLocalStoreIdPrefix + id, JSON.stringify(keyPair))\n }\n}\n"]}
@@ -45,7 +45,13 @@ export * from './icc-patient-x-api';
45
45
  export * from './icc-user-x-api';
46
46
  export * from './icc-time-table-x-api';
47
47
  export * from './icc-receipt-x-api';
48
+ export * from './icc-data-owner-x-api';
49
+ export * from './icc-icure-maintenance-x-api';
50
+ export * from './icc-maintenance-task-x-api';
48
51
  export * from './utils';
52
+ export * from './crypto/RSA';
53
+ export * from './crypto/CryptoPrimitives';
54
+ export * from './auth/AuthenticationProvider';
49
55
  export { KeyStorageFacade } from './storage/KeyStorageFacade';
50
56
  export { LocalStorageImpl } from './storage/LocalStorageImpl';
51
57
  export { StorageFacade } from './storage/StorageFacade';
@@ -81,7 +81,13 @@ __exportStar(require("./icc-patient-x-api"), exports);
81
81
  __exportStar(require("./icc-user-x-api"), exports);
82
82
  __exportStar(require("./icc-time-table-x-api"), exports);
83
83
  __exportStar(require("./icc-receipt-x-api"), exports);
84
+ __exportStar(require("./icc-data-owner-x-api"), exports);
85
+ __exportStar(require("./icc-icure-maintenance-x-api"), exports);
86
+ __exportStar(require("./icc-maintenance-task-x-api"), exports);
84
87
  __exportStar(require("./utils"), exports);
88
+ __exportStar(require("./crypto/RSA"), exports);
89
+ __exportStar(require("./crypto/CryptoPrimitives"), exports);
90
+ __exportStar(require("./auth/AuthenticationProvider"), exports);
85
91
  var LocalStorageImpl_2 = require("./storage/LocalStorageImpl");
86
92
  Object.defineProperty(exports, "LocalStorageImpl", { enumerable: true, get: function () { return LocalStorageImpl_2.LocalStorageImpl; } });
87
93
  var KeyStorageImpl_2 = require("./storage/KeyStorageImpl");