@icure/api 8.6.3 → 8.6.5
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.
- package/icc-api/model/CryptoActorStub.d.ts +2 -0
- package/icc-api/model/CryptoActorStub.js.map +1 -1
- package/icc-api/model/Device.d.ts +1 -0
- package/icc-api/model/Device.js.map +1 -1
- package/icc-api/model/HealthcareParty.d.ts +1 -0
- package/icc-api/model/HealthcareParty.js.map +1 -1
- package/icc-api/model/ModelHelper.d.ts +1 -1
- package/icc-api/model/ModelHelper.js +15 -2
- package/icc-api/model/ModelHelper.js.map +1 -1
- package/icc-api/model/Patient.d.ts +1 -0
- package/icc-api/model/Patient.js.map +1 -1
- package/icc-api/model/User.d.ts +1 -0
- package/icc-api/model/User.js.map +1 -1
- package/icc-x-api/crypto/AES.js +1 -1
- package/icc-x-api/crypto/AES.js.map +1 -1
- package/icc-x-api/crypto/BaseExchangeDataManager.js +14 -14
- package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/BaseExchangeKeysManager.js +1 -1
- package/icc-x-api/crypto/BaseExchangeKeysManager.js.map +1 -1
- package/icc-x-api/crypto/CryptoPrimitives.js +3 -2
- package/icc-x-api/crypto/CryptoPrimitives.js.map +1 -1
- package/icc-x-api/crypto/CryptoStrategies.d.ts +2 -1
- package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
- package/icc-x-api/crypto/ExchangeDataManager.js +3 -3
- package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
- package/icc-x-api/crypto/KeyRecovery.js +3 -3
- package/icc-x-api/crypto/KeyRecovery.js.map +1 -1
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js +13 -13
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js.map +1 -1
- package/icc-x-api/crypto/RSA.js +2 -2
- package/icc-x-api/crypto/RSA.js.map +1 -1
- package/icc-x-api/crypto/RecoveryDataEncryption.js +5 -5
- package/icc-x-api/crypto/RecoveryDataEncryption.js.map +1 -1
- package/icc-x-api/crypto/SecureDelegationsManager.js +1 -1
- package/icc-x-api/crypto/SecureDelegationsManager.js.map +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.js +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.js +2 -2
- package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
- package/icc-x-api/crypto/utils.js +1 -1
- package/icc-x-api/crypto/utils.js.map +1 -1
- package/icc-x-api/filters/HealthElementByHcPartyCodeFilter.d.ts +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyCodeFilter.js +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyCodeFilter.js.map +1 -0
- package/icc-x-api/filters/HealthElementByHcPartyIdentifiersVersioningFilter.d.ts +22 -0
- package/icc-x-api/filters/HealthElementByHcPartyIdentifiersVersioningFilter.js +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyIdentifiersVersioningFilter.js.map +1 -0
- package/icc-x-api/filters/HealthElementByHcPartyStatusVersioningFilter.d.ts +21 -0
- package/icc-x-api/filters/HealthElementByHcPartyStatusVersioningFilter.js +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyStatusVersioningFilter.js.map +1 -0
- package/icc-x-api/filters/HealthElementByHcPartyTagFilter.d.ts +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyTagFilter.js +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyTagFilter.js.map +1 -0
- package/icc-x-api/filters/VersionFiltering.d.ts +14 -0
- package/icc-x-api/filters/VersionFiltering.js +19 -0
- package/icc-x-api/filters/VersionFiltering.js.map +1 -0
- package/icc-x-api/filters/filters.d.ts +8 -4
- package/icc-x-api/filters/filters.js +4 -0
- package/icc-x-api/filters/filters.js.map +1 -1
- package/icc-x-api/icc-receipt-x-api.js +1 -1
- package/icc-x-api/icc-receipt-x-api.js.map +1 -1
- package/icc-x-api/utils/binary-utils.js +1 -1
- package/icc-x-api/utils/binary-utils.js.map +1 -1
- package/package.json +1 -1
- package/test/icc-api/api/IccAnonymousAccessApi.js +1 -1
- package/test/icc-api/api/IccAnonymousAccessApi.js.map +1 -1
- package/test/icc-api/api/IccDocumentApi.js +13 -12
- package/test/icc-api/api/IccDocumentApi.js.map +1 -1
- package/test/icc-x-api/crud/comprehensive-crud-test.js +2 -2
- package/test/icc-x-api/crud/comprehensive-crud-test.js.map +1 -1
- package/test/icc-x-api/crypto/crypto-utils.js +1 -1
- package/test/icc-x-api/crypto/crypto-utils.js.map +1 -1
- package/test/icc-x-api/crypto/soft-deleted-data-owners.js +1 -1
- package/test/icc-x-api/crypto/soft-deleted-data-owners.js.map +1 -1
- package/test/icc-x-api/crypto/user-encryption-keys-manager-test.js +1 -1
- package/test/icc-x-api/crypto/user-encryption-keys-manager-test.js.map +1 -1
- package/test/icc-x-api/filters/healthelement.d.ts +1 -0
- package/test/icc-x-api/filters/healthelement.js +333 -0
- package/test/icc-x-api/filters/healthelement.js.map +1 -0
- package/test/icc-x-api/test-legacy-data-support.js +4 -4
- package/test/icc-x-api/test-legacy-data-support.js.map +1 -1
- package/test/support/CSM-729.d.ts +1 -0
- package/test/support/CSM-729.js +225 -0
- package/test/support/CSM-729.js.map +1 -0
- package/test/utils/TestCryptoStrategies.js +1 -1
- package/test/utils/TestCryptoStrategies.js.map +1 -1
- package/test/utils/roles.d.ts +1 -0
- package/test/utils/roles.js +1 -0
- package/test/utils/roles.js.map +1 -1
- package/test/utils/test_utils.js +2 -2
- package/test/utils/test_utils.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseExchangeDataManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeDataManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,4EAAwE;AAExE,+CA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,CAAC,CAAC;oBAEtI,OAAO,IAAI,CAAA;YACf,CAAC;YACD,OAAO,KAAK,CAAA;QACd,CAAC;KAAA;IAEa,qBAAqB,CAAC,OAAoB,EAAE,GAAc;;YACtE,OAAO,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;QAC9E,CAAC;KAAA;IAEa,uBAAuB,CAAC,OAAoB,EAAE,GAAc,EAAE,SAAiB;;YAC3F,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,EAAE,IAAA,eAAO,EAAC,SAAS,CAAC,CAAC,CAAA;QAC5F,CAAC;KAAA;CACF;AAlkBD,0DAkkBC","sourcesContent":["import { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { IccExchangeDataApi } from '../../icc-api/api/internal/IccExchangeDataApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { b64_2ua, hex2ua, ua2b64, ua2hex, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport XHRError = XHR.XHRError\n\n/**\n * @internal this class is intended for internal use only and may be modified without notice\n * Functions to create and get exchange data.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeDataManager {\n constructor(\n readonly api: IccExchangeDataApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly primitives: CryptoPrimitives,\n private readonly selfRequiresAnonymousDelegations: boolean,\n private readonly doNotUseBulkGet: boolean\n ) {}\n\n /**\n * Get all the exchange data where the current data owner is the delegator or the delegate. However, some data owners, generally HCPs, may have a\n * prohibitively high amount of exchange data. If the crypto strategies specify that the current data owner requires anonymous delegation this\n * method returns all the exchange data found for the data owner, else the method returns undefined.\n * @return all the exchange data for the current data owner or undefined if the crypto strategies don't allow to retrieve all data for the current\n * data owner.\n */\n async getAllExchangeDataForCurrentDataOwnerIfAllowed(): Promise<ExchangeData[] | undefined> {\n if (!this.selfRequiresAnonymousDelegations) return undefined\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n let latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, undefined, 1000)\n const allRetrieved = latestResult.rows ?? []\n while (latestResult.nextKeyPair?.startKeyDocId) {\n latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, latestResult.nextKeyPair.startKeyDocId, 1000)\n if (latestResult.rows) allRetrieved.push(...latestResult.rows)\n }\n return allRetrieved\n }\n\n /**\n * Get all exchange data for the provided delegator-delegate pair.\n * @param delegatorId id of a delegator data owner.\n * @param delegateId id of a delegate data owner.\n * @return all exchange data for the provided delegator-delegate pair.\n */\n async getExchangeDataByDelegatorDelegatePair(delegatorId: string, delegateId: string): Promise<ExchangeData[]> {\n return await this.api.getExchangeDataByDelegatorDelegate(delegatorId, delegateId)\n }\n\n /**\n * Get the exchange data with the provided id.\n * @param exchangeDataId id of the exchange data.\n * @return the exchange data with the provided id or undefined if no exchange data with such id could be found.\n */\n async getExchangeDataById(exchangeDataId: string): Promise<ExchangeData | undefined> {\n return await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && e.statusCode === 404) {\n return undefined\n } else throw e\n })\n }\n\n async getExchangeDataByIds(exchangeDataIds: string[]): Promise<ExchangeData[]> {\n if (this.doNotUseBulkGet) {\n const res: ExchangeData[] = []\n for (const exchangeDataId of exchangeDataIds) {\n const curr = await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && (e.statusCode === 404 || e.statusCode === 403)) {\n return undefined\n } else throw e\n })\n if (curr) res.push(curr)\n }\n return res\n } else {\n return await this.api.getExchangeDataByIds({ ids: exchangeDataIds })\n }\n }\n\n /**\n * Verifies the authenticity of the exchange data by checking the signature.\n * Note that all exchange data created by data owners other than the current data owner (including members of his hierarchy)\n * will always be unverified.\n * @param data collects the following information about the exchange data being verified:\n * - exchangeData the exchange data to verify.\n * - decryptedAccessControlSecret the access control secret decrypted from the exchange data.\n * - decryptedExchangeKey the exchange key decrypted from the exchange data.\n * - decryptedSharedSignatureKey the shared signature key decrypted from the exchange data.\n * @param verificationKeys verification keys for delegator signature by fingerprint.\n * @param verifyAsDelegator if true the method will also verify that the hmac key used for the signature was created by the delegator of the\n * exchange data. If true and the data was not created by the current data owner this method will return false.\n * @return the exchange data which could be verified given his signature and the available verification keys.\n * @throws if any of the provided exchange data has been created by a data owner other than the current data owner.\n */\n async verifyExchangeData(\n data: {\n exchangeData: ExchangeData\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n decryptedSharedSignatureKey: CryptoKey\n },\n verificationKeys: { [fp: string]: CryptoKey },\n verifyAsDelegator: boolean\n ): Promise<boolean> {\n if (verifyAsDelegator && data.exchangeData.delegator !== (await this.dataOwnerApi.getCurrentDataOwnerId())) return false\n if (verifyAsDelegator && !(await this.verifyDelegatorSignature(data.exchangeData, data.decryptedSharedSignatureKey, verificationKeys)))\n return false\n const sharedSignatureData = await this.bytesToSignForSharedSignature({\n decryptedAccessControlSecret: data.decryptedAccessControlSecret,\n decryptedExchangeKey: data.decryptedExchangeKey,\n delegator: data.exchangeData.delegator,\n delegate: data.exchangeData.delegate,\n publicKeysFingerprintsV2: [\n ...new Set([\n ...Object.keys(data.exchangeData.exchangeKey),\n ...Object.keys(data.exchangeData.accessControlSecret),\n ...Object.keys(data.exchangeData.sharedSignatureKey),\n ]),\n ],\n })\n return await this.verifyDataWithSharedKey(sharedSignatureData, data.decryptedSharedSignatureKey, data.exchangeData.sharedSignature)\n }\n\n /**\n * Extracts and decrypts the access control secret from the provided exchange data.\n * These need to be hashed together with the entity class and confidentiality level in order to get the actual access control key\n * which will be sent to the server.\n * @param exchangeData the exchange data from which to extract access control secrets.\n * @param decryptionKeys rsa key pairs to use for decryption of the access control secret.\n * @return an object composed of:\n * - successfulDecryptions: array of all successfully decrypted access control keys\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptAccessControlSecret(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: string[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.accessControlSecret,\n (d) => this.importAccessControlSecret(new Uint8Array(d))\n )\n }\n\n /**\n * Extract and decrypts the exchange keys from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptExchangeKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.exchangeKey,\n (d) => this.importExchangeKey(new Uint8Array(d))\n )\n }\n\n /**\n * Extract and decrypts the shared signature key from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptSharedSignatureKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.sharedSignatureKey,\n (d) => this.importSharedSignatureKey(new Uint8Array(d))\n )\n }\n\n private async tryDecryptExchangeData<T>(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n encryptedDataSelector: (data: ExchangeData) => { [keyPairFingerprint: string]: string },\n unmarshalDecrypted: (decrypted: ArrayBuffer) => Promise<T>\n ): Promise<{\n successfulDecryptions: T[]\n failedDecryptions: ExchangeData[]\n }> {\n const successfulDecryptions: T[] = []\n const failedDecryptions: ExchangeData[] = []\n for (const ed of exchangeData) {\n try {\n const decrypted = await this.tryDecrypt(encryptedDataSelector(ed), decryptionKeys)\n if (decrypted) {\n successfulDecryptions.push(await unmarshalDecrypted(decrypted))\n } else {\n failedDecryptions.push(ed)\n }\n } catch (e) {\n failedDecryptions.push(ed)\n }\n }\n return { successfulDecryptions, failedDecryptions }\n }\n\n private async tryDecrypt(\n encryptedData: { [keyPairFingerprintV2: string]: string },\n decryptionKeys: { [publicKeyFingerprintV1: string]: KeyPair<CryptoKey> }\n ): Promise<ArrayBuffer | undefined> {\n const decryptionKeysWithV2Fp = Object.keys(decryptionKeys).reduce((prev, fp) => {\n return {\n ...prev,\n [fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp]: decryptionKeys[fp],\n }\n }, {} as { [publicKeyFingerprint: string]: KeyPair<CryptoKey> })\n for (const [fp, encrypted] of Object.entries(encryptedData)) {\n try {\n const key = decryptionKeysWithV2Fp[fp]?.privateKey\n if (key) return await this.primitives.RSA.decrypt(key, b64_2ua(encrypted))\n } catch (e) {\n // Try with another key\n }\n }\n }\n\n /**\n * Creates exchange data from the current data owner to the provided delegate, uploading the newly created exchange data to the cloud.\n * This assumes that the keys have been verified.\n * @param delegateId id of the delegate for the new exchange data.\n * @param signatureKeys private keys to use for signing the created data.\n * @param encryptionKeys public keys to use for the encryption of the exchange data (from delegator and delegate).\n * @param optionalAttributes optional precalculated attributes for the creation of data\n * @return the newly created exchange data, and its decrypted exchange key and access control secret.\n */\n async createExchangeData(\n delegateId: string,\n signatureKeys: { [keyPairFingerprint: string]: CryptoKey },\n encryptionKeys: { [keyPairFingerprint: string]: CryptoKey },\n optionalAttributes: {\n id?: string\n } = {}\n ): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n sharedSignatureKey: CryptoKey\n }> {\n if (!Object.keys(encryptionKeys).length) {\n throw new Error('Must specify at least one encryption key ')\n }\n const exchangeKey = await this.generateExchangeKey()\n const accessControlSecret = await this.generateAccessControlSecret()\n const sharedSignatureKey = await this.generateSharedSignatureKey()\n const encryptedExchangeKey = await this.encryptDataWithKeys(exchangeKey.rawBytes, encryptionKeys)\n const encryptedAccessControlSecret = await this.encryptDataWithKeys(accessControlSecret.rawBytes, encryptionKeys)\n const encryptedSharedSignatureKey = await this.encryptDataWithKeys(sharedSignatureKey.rawBytes, encryptionKeys)\n const baseExchangeData = {\n id: optionalAttributes.id ?? this.primitives.randomUuid(),\n delegator: await this.dataOwnerApi.getCurrentDataOwnerId(),\n delegate: delegateId,\n exchangeKey: encryptedExchangeKey,\n accessControlSecret: encryptedAccessControlSecret,\n sharedSignatureKey: encryptedSharedSignatureKey,\n }\n const sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: baseExchangeData.delegate,\n delegator: baseExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret.secret,\n decryptedExchangeKey: exchangeKey.key,\n publicKeysFingerprintsV2: Object.keys(encryptionKeys).map(fingerprintV1toV2),\n }),\n sharedSignatureKey.key\n )\n const delegatorSignature = await this.signDataWithDelegatorKeys(\n await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: sharedSignatureKey.key,\n }),\n signatureKeys\n )\n const exchangeData = new ExchangeData({ ...baseExchangeData, delegatorSignature, sharedSignature })\n return {\n exchangeData: await this.api.createExchangeData(exchangeData),\n exchangeKey: exchangeKey.key,\n accessControlSecret: accessControlSecret.secret,\n sharedSignatureKey: sharedSignatureKey.key,\n }\n }\n\n async tryRawDecryptExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<\n | {\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return { rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey }\n }\n\n /**\n * Updates existing exchange data and uploads it to the cloud in order to share it also with additional public keys, useful for example in cases\n * where one of the data owners involved in the exchange data has lost one of his keys.\n * If the content of the exchange data could not be decrypted using the provided keys the method will not update anything and will return undefined.\n * This method assumes that the new encryption keys have been verified.\n * @param exchangeData exchange data to update.\n * @param decryptionKeys keys to use to extract the content of the exchange data which will be shared with the new keys.\n * @param newEncryptionKeys new keys to add to the exchange data.\n * @return the updated exchange data, and its decrypted exchange key and access control secret, or undefined if the exchange data content could not\n * be decrypted and the exchange data could not be updated.\n */\n async tryUpdateExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n newEncryptionKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<\n | {\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return await this.updateExchangeDataWithRawDecryptedContent({\n exchangeData: exchangeData,\n newEncryptionKeys: newEncryptionKeys,\n rawExchangeKey: rawExchangeKey,\n rawAccessControlSecret: rawAccessControlSecret,\n rawSharedSignatureKey: rawSharedSignatureKey,\n newDelegatorSignatureKeys: {},\n })\n }\n\n /**\n * Same as [tryUpdateExchangeData] but the decrypted content is already provided.\n */\n async updateExchangeDataWithRawDecryptedContent({\n exchangeData,\n newEncryptionKeys,\n rawExchangeKey,\n rawAccessControlSecret,\n rawSharedSignatureKey,\n newDelegatorSignatureKeys,\n }: {\n exchangeData: ExchangeData\n newEncryptionKeys: { [fp: string]: CryptoKey }\n newDelegatorSignatureKeys: { [keyPairFingerprint: string]: CryptoKey }\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n const exchangeKey = await this.importExchangeKey(new Uint8Array(rawExchangeKey))\n const accessControlSecret = await this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret))\n const sharedSignatureKey = await this.importSharedSignatureKey(new Uint8Array(rawSharedSignatureKey))\n const existingExchangeKeyEntries = new Set(Object.keys(exchangeData.exchangeKey))\n const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret))\n const existingSharedSignatureKeyEntries = new Set(Object.keys(exchangeData.sharedSignatureKey))\n const missingEntries = Object.keys(newEncryptionKeys).filter(\n (fp) => !existingAcsEntries.has(fp) || !existingExchangeKeyEntries.has(fp) || !existingSharedSignatureKeyEntries.has(fp)\n )\n const existingDelegatorSignatureEntries = new Set(Object.keys(exchangeData.delegatorSignature ?? {}))\n const missingDelegatorSignatureEntries =\n exchangeData.delegator == self ? Object.keys(newDelegatorSignatureKeys).filter((fp) => !existingDelegatorSignatureEntries.has(fp)) : []\n if (!missingEntries.length && !missingDelegatorSignatureEntries.length) return { exchangeData, exchangeKey, accessControlSecret }\n const encryptionKeysForMissingEntries = missingEntries.reduce((obj, fp) => {\n obj[fp] = newEncryptionKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n const updatedExchangeData = _.cloneDeep(exchangeData)\n updatedExchangeData.exchangeKey = {\n ...exchangeData.exchangeKey,\n ...(await this.encryptDataWithKeys(rawExchangeKey, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.accessControlSecret = {\n ...exchangeData.accessControlSecret,\n ...(await this.encryptDataWithKeys(rawAccessControlSecret, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.sharedSignatureKey = {\n ...exchangeData.sharedSignatureKey,\n ...(await this.encryptDataWithKeys(rawSharedSignatureKey, encryptionKeysForMissingEntries)),\n }\n const isVerified = await this.verifyExchangeData(\n {\n exchangeData,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n decryptedSharedSignatureKey: sharedSignatureKey,\n },\n {},\n false\n )\n if (isVerified) {\n updatedExchangeData.sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: updatedExchangeData.delegate,\n delegator: updatedExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n publicKeysFingerprintsV2: Object.keys(updatedExchangeData.exchangeKey),\n }),\n sharedSignatureKey\n )\n }\n if (missingDelegatorSignatureEntries.length > 0) {\n const bytesToSign = await this.bytesToSignForDelegatorSignature({ sharedSignatureKey })\n const newSigned = await this.signDataWithDelegatorKeys(\n bytesToSign,\n missingDelegatorSignatureEntries.reduce((obj, fp) => {\n obj[fp] = newDelegatorSignatureKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n )\n updatedExchangeData.delegatorSignature = {\n ...updatedExchangeData.delegatorSignature,\n ...newSigned,\n }\n }\n return { exchangeData: await this.api.modifyExchangeData(new ExchangeData(updatedExchangeData)), exchangeKey, accessControlSecret }\n }\n\n private async bytesToSignForSharedSignature(data: {\n delegator: string\n delegate: string\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n publicKeysFingerprintsV2: string[]\n }): Promise<ArrayBuffer> {\n // Use array of array to ensure that order is preserved regardless of how the specific js implementation orders\n // the keys of an object\n const signObject = [\n ['delegator', data.delegator],\n ['delegate', data.delegate],\n ['exchangeKey', ua2hex(await this.primitives.AES.exportKey(data.decryptedExchangeKey, 'raw'))],\n ['accessControlSecret', data.decryptedAccessControlSecret],\n ['publicKeysFingerprints', data.publicKeysFingerprintsV2.sort()],\n ]\n const signJson = JSON.stringify(signObject)\n return utf8_2ua(signJson)\n }\n\n private async bytesToSignForDelegatorSignature(data: { sharedSignatureKey: CryptoKey }): Promise<ArrayBuffer> {\n return this.primitives.sha256(await this.primitives.HMAC.exportKey(data.sharedSignatureKey))\n }\n\n // Generates a new exchange key\n private async generateExchangeKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = await this.primitives.randomBytes(32)\n return {\n key: await this.importExchangeKey(rawBytes),\n rawBytes,\n }\n }\n\n async importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.AES.importKey('raw', decryptedBytes)\n }\n\n async exportExchangeKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.AES.exportKey(key, 'raw')\n }\n\n private async generateSharedSignatureKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const key = await this.primitives.HMAC.generateKey()\n return { key, rawBytes: await this.primitives.HMAC.exportKey(key) }\n }\n\n async importSharedSignatureKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.HMAC.importKey(decryptedBytes)\n }\n\n async exportSharedSignatureKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.HMAC.exportKey(key)\n }\n\n // Generates a new access control secret\n private async generateAccessControlSecret(): Promise<{\n secret: string // the imported secret\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = this.primitives.randomBytes(16)\n return {\n secret: await this.importAccessControlSecret(rawBytes),\n rawBytes,\n }\n }\n\n importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string> {\n return Promise.resolve(ua2hex(decryptedBytes))\n }\n\n exportAccessControlSecret(secret: string): Promise<ArrayBuffer> {\n return Promise.resolve(hex2ua(secret))\n }\n\n private async encryptDataWithKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprintV1: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprintV2: string]: string }> {\n const res: { [keyPairFingerprintV2: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp] = ua2b64(await this.primitives.RSA.encrypt(key, new Uint8Array(rawData)))\n }\n return res\n }\n\n private async extractHmacFromRsaPrivate(privateRsaKey: CryptoKey): Promise<CryptoKey> {\n if (privateRsaKey.algorithm.name != 'RSA-OAEP' && !privateRsaKey.usages.includes('decrypt')) {\n throw new Error('Internal error: got unexpected key for signature/verification')\n }\n const keyBytes = await this.primitives.RSA.exportKey(privateRsaKey, 'pkcs8')\n const keyAsHmacBytes = await this.primitives.sha512(keyBytes)\n return await this.primitives.HMAC.importKey(keyAsHmacBytes, false)\n }\n\n private async signDataWithDelegatorKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprint: string]: string }> {\n const res: { [keyPairFingerprint: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintV1toV2(fp)] = ua2b64(await this.primitives.HMAC.sign(await this.extractHmacFromRsaPrivate(key), new Uint8Array(rawData)))\n }\n return res\n }\n\n private async verifyDelegatorSignature(\n exchangeData: ExchangeData,\n decryptedSharedSignatureKey: CryptoKey,\n verificationKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<Boolean> {\n const delegatorSignatureData = await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: decryptedSharedSignatureKey,\n })\n const keysByV2Fp = Object.fromEntries(Object.entries(verificationKeys).map(([fp, key]): [string, CryptoKey] => [fingerprintV1toV2(fp), key]))\n for (const [fp, signature] of Object.entries(exchangeData.delegatorSignature ?? {})) {\n const verificationKey = keysByV2Fp[fp]\n if (\n verificationKey &&\n (await this.primitives.HMAC.verify(await this.extractHmacFromRsaPrivate(verificationKey), delegatorSignatureData, b64_2ua(signature)))\n )\n return true\n }\n return false\n }\n\n private async signDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey): Promise<string> {\n return ua2b64(await this.primitives.HMAC.sign(key, new Uint8Array(rawData)))\n }\n\n private async verifyDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey, signature: string): Promise<boolean> {\n return await this.primitives.HMAC.verify(key, new Uint8Array(rawData), b64_2ua(signature))\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"BaseExchangeDataManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeDataManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,4EAAwE;AAExE,+CAA2C;AAE3C,oCAA2E;AAC3E,4BAA2B;AAC3B,mCAA4D;AAC5D,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAE9B;;;;GAIG;AACH,MAAa,uBAAuB;IAClC,YACW,GAAuB,EACf,YAA8B,EAC9B,UAA4B,EAC5B,gCAAyC,EACzC,eAAwB;QAJhC,QAAG,GAAH,GAAG,CAAoB;QACf,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,eAAU,GAAV,UAAU,CAAkB;QAC5B,qCAAgC,GAAhC,gCAAgC,CAAS;QACzC,oBAAe,GAAf,eAAe,CAAS;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AC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;QACrF,CAAC;KAAA;IAEa,uBAAuB,CAAC,OAAoB,EAAE,GAAc,EAAE,SAAiB;;YAC3F,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,IAAA,aAAK,EAAC,IAAA,eAAO,EAAC,SAAS,CAAC,CAAC,CAAC,CAAA;QAC1G,CAAC;KAAA;CACF;AAlkBD,0DAkkBC","sourcesContent":["import { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { IccExchangeDataApi } from '../../icc-api/api/internal/IccExchangeDataApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { b64_2ua, hex2ua, ua2ab, ua2b64, ua2hex, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport XHRError = XHR.XHRError\n\n/**\n * @internal this class is intended for internal use only and may be modified without notice\n * Functions to create and get exchange data.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeDataManager {\n constructor(\n readonly api: IccExchangeDataApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly primitives: CryptoPrimitives,\n private readonly selfRequiresAnonymousDelegations: boolean,\n private readonly doNotUseBulkGet: boolean\n ) {}\n\n /**\n * Get all the exchange data where the current data owner is the delegator or the delegate. However, some data owners, generally HCPs, may have a\n * prohibitively high amount of exchange data. If the crypto strategies specify that the current data owner requires anonymous delegation this\n * method returns all the exchange data found for the data owner, else the method returns undefined.\n * @return all the exchange data for the current data owner or undefined if the crypto strategies don't allow to retrieve all data for the current\n * data owner.\n */\n async getAllExchangeDataForCurrentDataOwnerIfAllowed(): Promise<ExchangeData[] | undefined> {\n if (!this.selfRequiresAnonymousDelegations) return undefined\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n let latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, undefined, 1000)\n const allRetrieved = latestResult.rows ?? []\n while (latestResult.nextKeyPair?.startKeyDocId) {\n latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, latestResult.nextKeyPair.startKeyDocId, 1000)\n if (latestResult.rows) allRetrieved.push(...latestResult.rows)\n }\n return allRetrieved\n }\n\n /**\n * Get all exchange data for the provided delegator-delegate pair.\n * @param delegatorId id of a delegator data owner.\n * @param delegateId id of a delegate data owner.\n * @return all exchange data for the provided delegator-delegate pair.\n */\n async getExchangeDataByDelegatorDelegatePair(delegatorId: string, delegateId: string): Promise<ExchangeData[]> {\n return await this.api.getExchangeDataByDelegatorDelegate(delegatorId, delegateId)\n }\n\n /**\n * Get the exchange data with the provided id.\n * @param exchangeDataId id of the exchange data.\n * @return the exchange data with the provided id or undefined if no exchange data with such id could be found.\n */\n async getExchangeDataById(exchangeDataId: string): Promise<ExchangeData | undefined> {\n return await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && e.statusCode === 404) {\n return undefined\n } else throw e\n })\n }\n\n async getExchangeDataByIds(exchangeDataIds: string[]): Promise<ExchangeData[]> {\n if (this.doNotUseBulkGet) {\n const res: ExchangeData[] = []\n for (const exchangeDataId of exchangeDataIds) {\n const curr = await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && (e.statusCode === 404 || e.statusCode === 403)) {\n return undefined\n } else throw e\n })\n if (curr) res.push(curr)\n }\n return res\n } else {\n return await this.api.getExchangeDataByIds({ ids: exchangeDataIds })\n }\n }\n\n /**\n * Verifies the authenticity of the exchange data by checking the signature.\n * Note that all exchange data created by data owners other than the current data owner (including members of his hierarchy)\n * will always be unverified.\n * @param data collects the following information about the exchange data being verified:\n * - exchangeData the exchange data to verify.\n * - decryptedAccessControlSecret the access control secret decrypted from the exchange data.\n * - decryptedExchangeKey the exchange key decrypted from the exchange data.\n * - decryptedSharedSignatureKey the shared signature key decrypted from the exchange data.\n * @param verificationKeys verification keys for delegator signature by fingerprint.\n * @param verifyAsDelegator if true the method will also verify that the hmac key used for the signature was created by the delegator of the\n * exchange data. If true and the data was not created by the current data owner this method will return false.\n * @return the exchange data which could be verified given his signature and the available verification keys.\n * @throws if any of the provided exchange data has been created by a data owner other than the current data owner.\n */\n async verifyExchangeData(\n data: {\n exchangeData: ExchangeData\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n decryptedSharedSignatureKey: CryptoKey\n },\n verificationKeys: { [fp: string]: CryptoKey },\n verifyAsDelegator: boolean\n ): Promise<boolean> {\n if (verifyAsDelegator && data.exchangeData.delegator !== (await this.dataOwnerApi.getCurrentDataOwnerId())) return false\n if (verifyAsDelegator && !(await this.verifyDelegatorSignature(data.exchangeData, data.decryptedSharedSignatureKey, verificationKeys)))\n return false\n const sharedSignatureData = await this.bytesToSignForSharedSignature({\n decryptedAccessControlSecret: data.decryptedAccessControlSecret,\n decryptedExchangeKey: data.decryptedExchangeKey,\n delegator: data.exchangeData.delegator,\n delegate: data.exchangeData.delegate,\n publicKeysFingerprintsV2: [\n ...new Set([\n ...Object.keys(data.exchangeData.exchangeKey),\n ...Object.keys(data.exchangeData.accessControlSecret),\n ...Object.keys(data.exchangeData.sharedSignatureKey),\n ]),\n ],\n })\n return await this.verifyDataWithSharedKey(sharedSignatureData, data.decryptedSharedSignatureKey, data.exchangeData.sharedSignature)\n }\n\n /**\n * Extracts and decrypts the access control secret from the provided exchange data.\n * These need to be hashed together with the entity class and confidentiality level in order to get the actual access control key\n * which will be sent to the server.\n * @param exchangeData the exchange data from which to extract access control secrets.\n * @param decryptionKeys rsa key pairs to use for decryption of the access control secret.\n * @return an object composed of:\n * - successfulDecryptions: array of all successfully decrypted access control keys\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptAccessControlSecret(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: string[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.accessControlSecret,\n (d) => this.importAccessControlSecret(new Uint8Array(d).buffer)\n )\n }\n\n /**\n * Extract and decrypts the exchange keys from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptExchangeKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.exchangeKey,\n (d) => this.importExchangeKey(new Uint8Array(d).buffer)\n )\n }\n\n /**\n * Extract and decrypts the shared signature key from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptSharedSignatureKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.sharedSignatureKey,\n (d) => this.importSharedSignatureKey(new Uint8Array(d).buffer)\n )\n }\n\n private async tryDecryptExchangeData<T>(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n encryptedDataSelector: (data: ExchangeData) => { [keyPairFingerprint: string]: string },\n unmarshalDecrypted: (decrypted: ArrayBuffer) => Promise<T>\n ): Promise<{\n successfulDecryptions: T[]\n failedDecryptions: ExchangeData[]\n }> {\n const successfulDecryptions: T[] = []\n const failedDecryptions: ExchangeData[] = []\n for (const ed of exchangeData) {\n try {\n const decrypted = await this.tryDecrypt(encryptedDataSelector(ed), decryptionKeys)\n if (decrypted) {\n successfulDecryptions.push(await unmarshalDecrypted(decrypted))\n } else {\n failedDecryptions.push(ed)\n }\n } catch (e) {\n failedDecryptions.push(ed)\n }\n }\n return { successfulDecryptions, failedDecryptions }\n }\n\n private async tryDecrypt(\n encryptedData: { [keyPairFingerprintV2: string]: string },\n decryptionKeys: { [publicKeyFingerprintV1: string]: KeyPair<CryptoKey> }\n ): Promise<ArrayBuffer | undefined> {\n const decryptionKeysWithV2Fp = Object.keys(decryptionKeys).reduce((prev, fp) => {\n return {\n ...prev,\n [fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp]: decryptionKeys[fp],\n }\n }, {} as { [publicKeyFingerprint: string]: KeyPair<CryptoKey> })\n for (const [fp, encrypted] of Object.entries(encryptedData)) {\n try {\n const key = decryptionKeysWithV2Fp[fp]?.privateKey\n if (key) return await this.primitives.RSA.decrypt(key, b64_2ua(encrypted))\n } catch (e) {\n // Try with another key\n }\n }\n }\n\n /**\n * Creates exchange data from the current data owner to the provided delegate, uploading the newly created exchange data to the cloud.\n * This assumes that the keys have been verified.\n * @param delegateId id of the delegate for the new exchange data.\n * @param signatureKeys private keys to use for signing the created data.\n * @param encryptionKeys public keys to use for the encryption of the exchange data (from delegator and delegate).\n * @param optionalAttributes optional precalculated attributes for the creation of data\n * @return the newly created exchange data, and its decrypted exchange key and access control secret.\n */\n async createExchangeData(\n delegateId: string,\n signatureKeys: { [keyPairFingerprint: string]: CryptoKey },\n encryptionKeys: { [keyPairFingerprint: string]: CryptoKey },\n optionalAttributes: {\n id?: string\n } = {}\n ): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n sharedSignatureKey: CryptoKey\n }> {\n if (!Object.keys(encryptionKeys).length) {\n throw new Error('Must specify at least one encryption key ')\n }\n const exchangeKey = await this.generateExchangeKey()\n const accessControlSecret = await this.generateAccessControlSecret()\n const sharedSignatureKey = await this.generateSharedSignatureKey()\n const encryptedExchangeKey = await this.encryptDataWithKeys(exchangeKey.rawBytes, encryptionKeys)\n const encryptedAccessControlSecret = await this.encryptDataWithKeys(accessControlSecret.rawBytes, encryptionKeys)\n const encryptedSharedSignatureKey = await this.encryptDataWithKeys(sharedSignatureKey.rawBytes, encryptionKeys)\n const baseExchangeData = {\n id: optionalAttributes.id ?? this.primitives.randomUuid(),\n delegator: await this.dataOwnerApi.getCurrentDataOwnerId(),\n delegate: delegateId,\n exchangeKey: encryptedExchangeKey,\n accessControlSecret: encryptedAccessControlSecret,\n sharedSignatureKey: encryptedSharedSignatureKey,\n }\n const sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: baseExchangeData.delegate,\n delegator: baseExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret.secret,\n decryptedExchangeKey: exchangeKey.key,\n publicKeysFingerprintsV2: Object.keys(encryptionKeys).map(fingerprintV1toV2),\n }),\n sharedSignatureKey.key\n )\n const delegatorSignature = await this.signDataWithDelegatorKeys(\n await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: sharedSignatureKey.key,\n }),\n signatureKeys\n )\n const exchangeData = new ExchangeData({ ...baseExchangeData, delegatorSignature, sharedSignature })\n return {\n exchangeData: await this.api.createExchangeData(exchangeData),\n exchangeKey: exchangeKey.key,\n accessControlSecret: accessControlSecret.secret,\n sharedSignatureKey: sharedSignatureKey.key,\n }\n }\n\n async tryRawDecryptExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<\n | {\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return { rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey }\n }\n\n /**\n * Updates existing exchange data and uploads it to the cloud in order to share it also with additional public keys, useful for example in cases\n * where one of the data owners involved in the exchange data has lost one of his keys.\n * If the content of the exchange data could not be decrypted using the provided keys the method will not update anything and will return undefined.\n * This method assumes that the new encryption keys have been verified.\n * @param exchangeData exchange data to update.\n * @param decryptionKeys keys to use to extract the content of the exchange data which will be shared with the new keys.\n * @param newEncryptionKeys new keys to add to the exchange data.\n * @return the updated exchange data, and its decrypted exchange key and access control secret, or undefined if the exchange data content could not\n * be decrypted and the exchange data could not be updated.\n */\n async tryUpdateExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n newEncryptionKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<\n | {\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return await this.updateExchangeDataWithRawDecryptedContent({\n exchangeData: exchangeData,\n newEncryptionKeys: newEncryptionKeys,\n rawExchangeKey: rawExchangeKey,\n rawAccessControlSecret: rawAccessControlSecret,\n rawSharedSignatureKey: rawSharedSignatureKey,\n newDelegatorSignatureKeys: {},\n })\n }\n\n /**\n * Same as [tryUpdateExchangeData] but the decrypted content is already provided.\n */\n async updateExchangeDataWithRawDecryptedContent({\n exchangeData,\n newEncryptionKeys,\n rawExchangeKey,\n rawAccessControlSecret,\n rawSharedSignatureKey,\n newDelegatorSignatureKeys,\n }: {\n exchangeData: ExchangeData\n newEncryptionKeys: { [fp: string]: CryptoKey }\n newDelegatorSignatureKeys: { [keyPairFingerprint: string]: CryptoKey }\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n const exchangeKey = await this.importExchangeKey(new Uint8Array(rawExchangeKey).buffer)\n const accessControlSecret = await this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret).buffer)\n const sharedSignatureKey = await this.importSharedSignatureKey(new Uint8Array(rawSharedSignatureKey).buffer)\n const existingExchangeKeyEntries = new Set(Object.keys(exchangeData.exchangeKey))\n const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret))\n const existingSharedSignatureKeyEntries = new Set(Object.keys(exchangeData.sharedSignatureKey))\n const missingEntries = Object.keys(newEncryptionKeys).filter(\n (fp) => !existingAcsEntries.has(fp) || !existingExchangeKeyEntries.has(fp) || !existingSharedSignatureKeyEntries.has(fp)\n )\n const existingDelegatorSignatureEntries = new Set(Object.keys(exchangeData.delegatorSignature ?? {}))\n const missingDelegatorSignatureEntries =\n exchangeData.delegator == self ? Object.keys(newDelegatorSignatureKeys).filter((fp) => !existingDelegatorSignatureEntries.has(fp)) : []\n if (!missingEntries.length && !missingDelegatorSignatureEntries.length) return { exchangeData, exchangeKey, accessControlSecret }\n const encryptionKeysForMissingEntries = missingEntries.reduce((obj, fp) => {\n obj[fp] = newEncryptionKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n const updatedExchangeData = _.cloneDeep(exchangeData)\n updatedExchangeData.exchangeKey = {\n ...exchangeData.exchangeKey,\n ...(await this.encryptDataWithKeys(rawExchangeKey, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.accessControlSecret = {\n ...exchangeData.accessControlSecret,\n ...(await this.encryptDataWithKeys(rawAccessControlSecret, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.sharedSignatureKey = {\n ...exchangeData.sharedSignatureKey,\n ...(await this.encryptDataWithKeys(rawSharedSignatureKey, encryptionKeysForMissingEntries)),\n }\n const isVerified = await this.verifyExchangeData(\n {\n exchangeData,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n decryptedSharedSignatureKey: sharedSignatureKey,\n },\n {},\n false\n )\n if (isVerified) {\n updatedExchangeData.sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: updatedExchangeData.delegate,\n delegator: updatedExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n publicKeysFingerprintsV2: Object.keys(updatedExchangeData.exchangeKey),\n }),\n sharedSignatureKey\n )\n }\n if (missingDelegatorSignatureEntries.length > 0) {\n const bytesToSign = await this.bytesToSignForDelegatorSignature({ sharedSignatureKey })\n const newSigned = await this.signDataWithDelegatorKeys(\n bytesToSign,\n missingDelegatorSignatureEntries.reduce((obj, fp) => {\n obj[fp] = newDelegatorSignatureKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n )\n updatedExchangeData.delegatorSignature = {\n ...updatedExchangeData.delegatorSignature,\n ...newSigned,\n }\n }\n return { exchangeData: await this.api.modifyExchangeData(new ExchangeData(updatedExchangeData)), exchangeKey, accessControlSecret }\n }\n\n private async bytesToSignForSharedSignature(data: {\n delegator: string\n delegate: string\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n publicKeysFingerprintsV2: string[]\n }): Promise<ArrayBuffer> {\n // Use array of array to ensure that order is preserved regardless of how the specific js implementation orders\n // the keys of an object\n const signObject = [\n ['delegator', data.delegator],\n ['delegate', data.delegate],\n ['exchangeKey', ua2hex(await this.primitives.AES.exportKey(data.decryptedExchangeKey, 'raw'))],\n ['accessControlSecret', data.decryptedAccessControlSecret],\n ['publicKeysFingerprints', data.publicKeysFingerprintsV2.sort()],\n ]\n const signJson = JSON.stringify(signObject)\n return ua2ab(utf8_2ua(signJson))\n }\n\n private async bytesToSignForDelegatorSignature(data: { sharedSignatureKey: CryptoKey }): Promise<ArrayBuffer> {\n return this.primitives.sha256(await this.primitives.HMAC.exportKey(data.sharedSignatureKey))\n }\n\n // Generates a new exchange key\n private async generateExchangeKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = ua2ab(this.primitives.randomBytes(32))\n return {\n key: await this.importExchangeKey(rawBytes),\n rawBytes,\n }\n }\n\n async importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.AES.importKey('raw', decryptedBytes)\n }\n\n async exportExchangeKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.AES.exportKey(key, 'raw')\n }\n\n private async generateSharedSignatureKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const key = await this.primitives.HMAC.generateKey()\n return { key, rawBytes: await this.primitives.HMAC.exportKey(key) }\n }\n\n async importSharedSignatureKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.HMAC.importKey(decryptedBytes)\n }\n\n async exportSharedSignatureKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.HMAC.exportKey(key)\n }\n\n // Generates a new access control secret\n private async generateAccessControlSecret(): Promise<{\n secret: string // the imported secret\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = ua2ab(this.primitives.randomBytes(16))\n return {\n secret: await this.importAccessControlSecret(rawBytes),\n rawBytes,\n }\n }\n\n importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string> {\n return Promise.resolve(ua2hex(decryptedBytes))\n }\n\n exportAccessControlSecret(secret: string): Promise<ArrayBuffer> {\n return Promise.resolve(ua2ab(hex2ua(secret)))\n }\n\n private async encryptDataWithKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprintV1: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprintV2: string]: string }> {\n const res: { [keyPairFingerprintV2: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp] = ua2b64(await this.primitives.RSA.encrypt(key, new Uint8Array(rawData)))\n }\n return res\n }\n\n private async extractHmacFromRsaPrivate(privateRsaKey: CryptoKey): Promise<CryptoKey> {\n if (privateRsaKey.algorithm.name != 'RSA-OAEP' && !privateRsaKey.usages.includes('decrypt')) {\n throw new Error('Internal error: got unexpected key for signature/verification')\n }\n const keyBytes = await this.primitives.RSA.exportKey(privateRsaKey, 'pkcs8')\n const keyAsHmacBytes = await this.primitives.sha512(keyBytes)\n return await this.primitives.HMAC.importKey(keyAsHmacBytes, false)\n }\n\n private async signDataWithDelegatorKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprint: string]: string }> {\n const res: { [keyPairFingerprint: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintV1toV2(fp)] = ua2b64(await this.primitives.HMAC.sign(await this.extractHmacFromRsaPrivate(key), new Uint8Array(rawData).buffer))\n }\n return res\n }\n\n private async verifyDelegatorSignature(\n exchangeData: ExchangeData,\n decryptedSharedSignatureKey: CryptoKey,\n verificationKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<Boolean> {\n const delegatorSignatureData = await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: decryptedSharedSignatureKey,\n })\n const keysByV2Fp = Object.fromEntries(Object.entries(verificationKeys).map(([fp, key]): [string, CryptoKey] => [fingerprintV1toV2(fp), key]))\n for (const [fp, signature] of Object.entries(exchangeData.delegatorSignature ?? {})) {\n const verificationKey = keysByV2Fp[fp]\n if (\n verificationKey &&\n (await this.primitives.HMAC.verify(await this.extractHmacFromRsaPrivate(verificationKey), delegatorSignatureData, ua2ab(b64_2ua(signature))))\n )\n return true\n }\n return false\n }\n\n private async signDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey): Promise<string> {\n return ua2b64(await this.primitives.HMAC.sign(key, new Uint8Array(rawData).buffer))\n }\n\n private async verifyDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey, signature: string): Promise<boolean> {\n return await this.primitives.HMAC.verify(key, new Uint8Array(rawData).buffer, ua2ab(b64_2ua(signature)))\n }\n}\n"]}
|
|
@@ -41,7 +41,7 @@ class BaseExchangeKeysManager {
|
|
|
41
41
|
const newKeyHashVersion = (0, utils_2.getShaVersionForKey)(other.stub, newDataOwnerPublicKey);
|
|
42
42
|
if (!newKeyHashVersion)
|
|
43
43
|
throw new Error(`Public key not found for data owner ${otherDataOwner}`);
|
|
44
|
-
const newPublicKey = yield this.primitives.RSA.importKey('spki', (0, utils_1.hex2ua)(newDataOwnerPublicKey), ['encrypt'], newKeyHashVersion);
|
|
44
|
+
const newPublicKey = yield this.primitives.RSA.importKey('spki', (0, utils_1.ua2ab)((0, utils_1.hex2ua)(newDataOwnerPublicKey)), ['encrypt'], newKeyHashVersion);
|
|
45
45
|
yield this.extendForGiveAccessBackTo(selfId, otherDataOwner, (0, utils_2.fingerprintV1)(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint);
|
|
46
46
|
yield this.extendForGiveAccessBackTo(otherDataOwner, selfId, (0, utils_2.fingerprintV1)(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint);
|
|
47
47
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseExchangeKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,oCAAwD;AAIxD,mCAA4D;AAI5D;;;;GAIG;AACH,MAAa,uBAAuB;IAQlC,YACE,UAA4B,EAC5B,YAA8B,EAC9B,cAA6B,EAC7B,cAA6B,EAC7B,aAA2B;QAZZ,8BAAyB,GAAwC,EAAE,CAAA;QAclF,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,cAAc,GAAG,cAAc,CAAA;QACpC,IAAI,CAAC,cAAc,GAAG,cAAc,CAAA;QACpC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAA;IACpC,CAAC;IAED;;;;;;;OAOG;IACG,gBAAgB,CACpB,cAAsB,EACtB,qBAA6B,EAC7B,qBAA6E;;YAE7E,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAA;YAC9D,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAA;YACxE,MAAM,iBAAiB,GAAG,IAAA,2BAAmB,EAAC,KAAK,CAAC,IAAI,EAAE,qBAAqB,CAAC,CAAA;YAChF,IAAI,CAAC,iBAAiB;gBAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,cAAc,EAAE,CAAC,CAAA;YAChG,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,IAAA,cAAM,EAAC,qBAAqB,CAAC,EAAE,CAAC,SAAS,CAAC,EAAE,iBAAiB,CAAC,CAAA;YAC/H,MA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QAAQ,CAAE,EAAE,CAAA,CAAC,EAAE,CAAC;wBAC7G,IAAI,CAAC;4BACH,gBAAgB,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAA;wBACpF,CAAC;wBAAC,WAAM,CAAC;4BACP,SAAS;wBACX,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,uBACE,CAAC,oBAAoB,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,MAAA,KAAK,CAAC,WAAW,mCAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,EAAE;;wBAC5F,MAAM,cAAc,GAAG,MAAA,gBAAgB,CAAC,KAAK,CAAC,0CAAE,SAAS,CAAA;wBACzD,GAAG,CAAC,KAAK,CAAC,GAAG;4BACX,CAAC,IAAA,qBAAa,EAAC,oBAAoB,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;4BAC9C,CAAC,MAAA,CAAC,cAAc,IAAI,IAAA,qBAAa,EAAC,cAAc,CAAC,CAAC,mCAAI,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;yBACnE,CAAA;wBACD,OAAO,GAAG,CAAA;oBACZ,CAAC,EAAE,EAAiE,CAAC,IAClE,CAAC,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAC,EACjC;YACH,CAAC;;gBAAM,OAAO,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAA;QAC3C,CAAC;KAAA;CACF;AA9TD,0DA8TC","sourcesContent":["import { KeyPair } from './RSA'\nimport { hex2ua, notConcurrent, ua2hex } from '../utils'\nimport { DataOwner, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../../icc-api'\nimport { fingerprintV1, getShaVersionForKey } from './utils'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * Functions to create and get exchange keys.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeKeysManager {\n private readonly generateKeyConcurrencyMap: { [key: string]: PromiseLike<any> } = {}\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly hcpartyBaseApi: IccHcpartyApi\n private readonly patientBaseApi: IccPatientApi\n private readonly deviceBaseApi: IccDeviceApi\n\n constructor(\n primitives: CryptoPrimitives,\n dataOwnerApi: IccDataOwnerXApi,\n hcpartyBaseApi: IccHcpartyApi,\n patientBaseApi: IccPatientApi,\n deviceBaseApi: IccDeviceApi\n ) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.hcpartyBaseApi = hcpartyBaseApi\n this.patientBaseApi = patientBaseApi\n this.deviceBaseApi = deviceBaseApi\n }\n\n /**\n * Updates the aes exchange keys between the current data owner and another data owner to allow the other data owner to access the exchange key\n * using his new public key. Note that this will make existing exchange keys from the other data owner to the current data owner invalid for\n * encryption.\n * @param otherDataOwner the other data owner.\n * @param newDataOwnerPublicKey a new public key of the other data owner.\n * @param keyPairsByFingerprint all available key pairs to use for the decryption of existing aes exchange keys.\n */\n async giveAccessBackTo(\n otherDataOwner: string,\n newDataOwnerPublicKey: string,\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const other = await this.dataOwnerApi.getCryptoActorStub(otherDataOwner)\n const newKeyHashVersion = getShaVersionForKey(other.stub, newDataOwnerPublicKey)\n if (!newKeyHashVersion) throw new Error(`Public key not found for data owner ${otherDataOwner}`)\n const newPublicKey = await this.primitives.RSA.importKey('spki', hex2ua(newDataOwnerPublicKey), ['encrypt'], newKeyHashVersion)\n await this.extendForGiveAccessBackTo(selfId, otherDataOwner, fingerprintV1(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint)\n await this.extendForGiveAccessBackTo(otherDataOwner, selfId, fingerprintV1(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint)\n }\n\n /**\n * Get the encrypted exchange keys for a delegator-delegate pair.\n * @param delegatorId id of the delegator data owner.\n * @param delegateId id of the delegate data owner.\n * @return an array of exchange keys from the delegator to delegate where each key is encrypted with one or more public keys.\n */\n async getEncryptedExchangeKeysFor(delegatorId: string, delegateId: string): Promise<{ [publicKeyFingerprint: string]: string }[]> {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const res: { [publicKeyFingerprint: string]: string }[] = Object.values(delegator.stub.aesExchangeKeys ?? {}).flatMap((delegateToKey) => {\n const encryptedKeyForDelegate = delegateToKey[delegateId]\n if (encryptedKeyForDelegate) {\n return [encryptedKeyForDelegate]\n } else {\n return []\n }\n })\n const legacyDelegation = delegator.stub.hcPartyKeys?.[delegateId]?.[1]\n if (legacyDelegation) res.push({ '': legacyDelegation })\n return res\n }\n\n /**\n * Get all exchange keys where the provided data owner is involved either as the delegator or as the delegate.\n * @param dataOwnerId id of a data owner.\n * @param otherOwnerTypes only exchange keys between the current data owner and data owners of this type will be included in the result. If null considers all delegates\n * @return all exchange keys involving the provided data owner. Note that there may be an overlap between some keys to and from the data owner.\n */\n async getAllExchangeKeysWith(\n dataOwnerId: string,\n otherOwnerTypes: DataOwnerTypeEnum[] | null\n ): Promise<{\n keysToOwner: { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }\n keysFromOwner: { [delegatorFp: string]: { [delegateId: string]: { [entryFp: string]: string } } }\n }> {\n if (otherOwnerTypes != null && otherOwnerTypes.length === 0) throw new Error('otherOwnerTypes must not be empty!')\n const keysToOwner = await Promise.all([\n otherOwnerTypes == null || otherOwnerTypes.find((x) => x === 'hcp')\n ? this.hcpartyBaseApi.getAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes == null || otherOwnerTypes.find((x) => x === 'patient')\n ? this.patientBaseApi.getPatientAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes == null || otherOwnerTypes.find((x) => x === 'device')\n ? this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n ]).then(([a, b, c]) => ({ ...a, ...b, ...c } as { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }))\n const dataOwner = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n const allOwnerKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(dataOwner.stub, undefined, false)\n const filteredDelegates = new Set(\n await Array.from(new Set(Object.values(allOwnerKeys).flatMap((x) => Object.keys(x)))).reduce(async (acc, ownerId) => {\n const awaitedAcc = await acc\n if (ownerId === dataOwnerId || otherOwnerTypes == null) {\n return [...awaitedAcc, ownerId]\n } else {\n try {\n const dataOwnerType: DataOwnerTypeEnum = (await this.dataOwnerApi.getCryptoActorStub(ownerId)).type\n if (otherOwnerTypes.some((x) => x === dataOwnerType)) {\n return [...awaitedAcc, ownerId]\n } else return awaitedAcc\n } catch (_) {\n return awaitedAcc\n }\n }\n }, Promise.resolve([] as string[]))\n )\n const keysFromOwner = Object.fromEntries(\n Object.entries(allOwnerKeys)\n .map(([delegatorPubKey, delegateToKeys]) => [\n delegatorPubKey,\n Object.fromEntries(\n Object.entries(delegateToKeys).filter(([delegateId]) => filteredDelegates.has(delegateId)) as [string, { [k: string]: string }][]\n ),\n ])\n .filter(([, x]) => Object.keys(x).length > 0) as [string, { [k: string]: { [k: string]: string } }][]\n )\n return { keysToOwner, keysFromOwner }\n }\n\n /**\n * Attempts to decrypt many exchange keys using any of the provided key pairs.\n * @param encryptedExchangeKeys an array of exchange keys where each key is encrypted with one or more public keys.\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return an array all successfully decrypted exchange keys and an array containing all exchange keys which could not be decrypted.\n */\n async tryDecryptExchangeKeys(\n encryptedExchangeKeys: { [publicKeyFingerprint: string]: string }[],\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n }> {\n const raws = new Set<string>()\n const res: {\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n } = { successfulDecryptions: [], failedDecryptions: [] }\n for (const encryptedExchangeKey of encryptedExchangeKeys) {\n const decrypted = await this.tryDecryptExchangeKey(encryptedExchangeKey, keyPairsByFingerprint)\n if (decrypted !== undefined && !raws.has(decrypted.raw)) {\n raws.add(decrypted.raw)\n res.successfulDecryptions.push(decrypted.key)\n } else {\n res.failedDecryptions.push(encryptedExchangeKey)\n }\n }\n return res\n }\n\n private async extendForGiveAccessBackTo(\n delegatorId: string,\n delegateId: string,\n newPublicKeyFp: string,\n newPublicKey: CryptoKey,\n decryptionKeyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n await notConcurrent(this.generateKeyConcurrencyMap, delegatorId, async () => {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n let didUpdateSomeKey = false\n const combinedKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub, true)\n const updatedExchangeKeys: { [delegatorKey: string]: { [delegateId: string]: { [keyFp: string]: string } } } = {}\n const newEncryptionKeys = { [newPublicKeyFp]: newPublicKey }\n for (const [currDelegatorKey, currDelegatesToKeys] of Object.entries(combinedKeys)) {\n const updatedDelegatesToKeys: { [delegateId: string]: { [keyFp: string]: string } } = {}\n for (const [currDelegateId, currEncryptedKey] of Object.entries(currDelegatesToKeys)) {\n if (delegateId !== currDelegateId || newPublicKeyFp in currEncryptedKey) {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n } else {\n const decrypted = await this.tryDecryptExchangeKey(currEncryptedKey, decryptionKeyPairsByFingerprint)\n if (decrypted) {\n didUpdateSomeKey = true\n updatedDelegatesToKeys[currDelegateId] = {\n ...currEncryptedKey,\n ...(await this.encryptExchangeKey(decrypted, newEncryptionKeys)).encryptedExchangeKey,\n }\n } else {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n }\n }\n }\n updatedExchangeKeys[currDelegatorKey] = updatedDelegatesToKeys\n }\n if (didUpdateSomeKey) {\n await this.dataOwnerApi.modifyCryptoActorStub({\n type: delegator.type,\n stub: {\n ...delegator.stub,\n aesExchangeKeys: updatedExchangeKeys,\n },\n })\n }\n })\n }\n\n /**\n * Attempts to decrypt an exchange key using any of the provided key pairs.\n * @param encryptedExchangeKey an encrypted exchange key, in the form publicKeyXyzFingerprint -> hex(exchangeKeyEncryptedByPrivateKeyXyz).\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided keys.\n */\n private async tryDecryptExchangeKey(\n encryptedExchangeKey: { [publicKeyFingerprint: string]: string },\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n for (const [entryKey, encrypted] of Object.entries(encryptedExchangeKey)) {\n // Due to bugs in past version the entry may actually contain the full public key instead of just the fingerprint.\n const fp = fingerprintV1(entryKey)\n const keyPair = keyPairsByFingerprint[fp]\n if (keyPair !== undefined) {\n const res = await this.tryDecryptExchangeKeyWith(encrypted, keyPair, fp)\n if (res !== undefined) return res\n }\n }\n const defaultEncryptedKey = encryptedExchangeKey['']\n if (defaultEncryptedKey !== undefined) {\n for (const keyPair of Object.values(keyPairsByFingerprint)) {\n // disable error logging, we are not sure keyPair is the correct key\n const res = await this.tryDecryptExchangeKeyWith(defaultEncryptedKey, keyPair, undefined)\n if (res !== undefined) return res\n }\n }\n return undefined\n }\n\n /**\n * Creates an encrypted exchange key for the provided public keys.\n * @param exchangeKey the exchange key in raw and imported format. If undefined a new key will be automatically created.\n * @param publicKeys additional public keys that will have access to the exchange key in spki format, hex-encoded.\n * @return the exchangeKey and an object with the exchange key encrypted with each of the provided public keys, hex-encoded, by fingerprint.\n */\n private async encryptExchangeKey(\n exchangeKey: { raw: string; key: CryptoKey } | undefined,\n publicKeys: { [keyFingerprint: string]: CryptoKey }\n ): Promise<{\n exchangeKey: CryptoKey\n encryptedExchangeKey: { [pubKeyFp: string]: string }\n }> {\n const exchangeKeyCrypto = exchangeKey?.key ?? (await this.primitives.AES.generateCryptoKey(false))\n const exchangeKeyBytes = exchangeKey !== undefined ? hex2ua(exchangeKey.raw) : await this.primitives.AES.exportKey(exchangeKeyCrypto, 'raw')\n const encryptedExchangeKey = await Object.entries(publicKeys).reduce(\n async (acc, [currKeyFp, currKey]) => ({\n ...(await acc),\n [currKeyFp]: ua2hex(await this.primitives.RSA.encrypt(currKey, new Uint8Array(exchangeKeyBytes))),\n }),\n Promise.resolve({} as { [pubKeyFp: string]: string })\n )\n return { exchangeKey: exchangeKeyCrypto, encryptedExchangeKey }\n }\n\n /**\n * Attempts to decrypt an exchange key using the provided key pairs.\n * If you are confident that the provided {@link keyPair} was used to encrypt {@link encryptedByOneKey} you should also provide {@link keyPairFp},\n * so that if the decryption fail an error will be logged to console before returning undefined.\n * @param encryptedByOneKey an exchange key which may be encrypted with {@link keyPair}.\n * @param keyPair an rsa key pair.\n * @param keyPairFp the fingerprint of the provided key pair or undefined to disable logging of error if the decryption failed.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided key.\n */\n private async tryDecryptExchangeKeyWith(\n encryptedByOneKey: string,\n keyPair: KeyPair<CryptoKey>,\n keyPairFp: string | undefined // if undefined will not log errors, when we are not sure the key to be used is the provided key.\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n try {\n const decrypted = await this.primitives.RSA.decrypt(keyPair.privateKey, hex2ua(encryptedByOneKey))\n return { raw: ua2hex(decrypted), key: await this.primitives.AES.importKey('raw', decrypted) }\n } catch (e) {\n if (keyPairFp) {\n console.error(`Failed to decrypt or import exchange key ${encryptedByOneKey} using key with fingerprint ${keyPairFp}.`, e)\n }\n }\n }\n // Copy all legacy hcp exchange keys into the new aes exchange keys\n private async combineLegacyHcpKeysWithAesExchangeKeys(\n owner: CryptoActorStub,\n delegate: CryptoActorStub | undefined,\n fillDelegateLegacyKey: boolean\n ): Promise<{ [ownerPublicKey: string]: { [delegateId: string]: { [fingerprint: string]: string } } }> {\n const ownerLegacyPublicKey = owner.publicKey\n if (ownerLegacyPublicKey != undefined && !(owner.aesExchangeKeys ?? {})[ownerLegacyPublicKey]) {\n /*\n * This condition would technically prevent new updates to the hcPartyKeys to be migrated to the aes exchange keys, but since I can only update\n * data for self data owner and parent entities this is not an issue, because I will always be using the new api from now on and I won't have\n * a situation where the legacy keys are updated but the aes exchange keys are not.\n */\n const counterPartsById: { [id: string]: CryptoActorStub } = {}\n if (fillDelegateLegacyKey) {\n counterPartsById[owner.id!] = owner\n if (delegate) {\n counterPartsById[delegate.id!] = delegate\n }\n for (const other of Object.keys(owner.hcPartyKeys ?? {}).filter((x) => x !== owner.id && x !== delegate?.id)) {\n try {\n counterPartsById[other] = (await this.dataOwnerApi.getCryptoActorStub(other)).stub\n } catch {\n // ignore\n }\n }\n }\n return {\n [ownerLegacyPublicKey]: Object.entries(owner.hcPartyKeys ?? {}).reduce((acc, [hcpId, keys]) => {\n const counterpartKey = counterPartsById[hcpId]?.publicKey\n acc[hcpId] = {\n [fingerprintV1(ownerLegacyPublicKey)]: keys[0],\n [(counterpartKey && fingerprintV1(counterpartKey)) ?? '']: keys[1],\n }\n return acc\n }, {} as { [delegateId: string]: { [fingerprint: string]: string } }),\n ...(owner.aesExchangeKeys ?? {}),\n }\n } else return ow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G,IAAI,CAAC;4BACH,gBAAgB,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAA;wBACpF,CAAC;wBAAC,WAAM,CAAC;4BACP,SAAS;wBACX,CAAC;oBACH,CAAC;gBACH,CAAC;gBACD,uBACE,CAAC,oBAAoB,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,MAAA,KAAK,CAAC,WAAW,mCAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,EAAE;;wBAC5F,MAAM,cAAc,GAAG,MAAA,gBAAgB,CAAC,KAAK,CAAC,0CAAE,SAAS,CAAA;wBACzD,GAAG,CAAC,KAAK,CAAC,GAAG;4BACX,CAAC,IAAA,qBAAa,EAAC,oBAAoB,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;4BAC9C,CAAC,MAAA,CAAC,cAAc,IAAI,IAAA,qBAAa,EAAC,cAAc,CAAC,CAAC,mCAAI,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;yBACnE,CAAA;wBACD,OAAO,GAAG,CAAA;oBACZ,CAAC,EAAE,EAAiE,CAAC,IAClE,CAAC,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAC,EACjC;YACH,CAAC;;gBAAM,OAAO,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAA;QAC3C,CAAC;KAAA;CACF;AA9TD,0DA8TC","sourcesContent":["import { KeyPair } from './RSA'\nimport { hex2ua, notConcurrent, ua2ab, ua2hex } from '../utils'\nimport { DataOwner, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../../icc-api'\nimport { fingerprintV1, getShaVersionForKey } from './utils'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * Functions to create and get exchange keys.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeKeysManager {\n private readonly generateKeyConcurrencyMap: { [key: string]: PromiseLike<any> } = {}\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly hcpartyBaseApi: IccHcpartyApi\n private readonly patientBaseApi: IccPatientApi\n private readonly deviceBaseApi: IccDeviceApi\n\n constructor(\n primitives: CryptoPrimitives,\n dataOwnerApi: IccDataOwnerXApi,\n hcpartyBaseApi: IccHcpartyApi,\n patientBaseApi: IccPatientApi,\n deviceBaseApi: IccDeviceApi\n ) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.hcpartyBaseApi = hcpartyBaseApi\n this.patientBaseApi = patientBaseApi\n this.deviceBaseApi = deviceBaseApi\n }\n\n /**\n * Updates the aes exchange keys between the current data owner and another data owner to allow the other data owner to access the exchange key\n * using his new public key. Note that this will make existing exchange keys from the other data owner to the current data owner invalid for\n * encryption.\n * @param otherDataOwner the other data owner.\n * @param newDataOwnerPublicKey a new public key of the other data owner.\n * @param keyPairsByFingerprint all available key pairs to use for the decryption of existing aes exchange keys.\n */\n async giveAccessBackTo(\n otherDataOwner: string,\n newDataOwnerPublicKey: string,\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const other = await this.dataOwnerApi.getCryptoActorStub(otherDataOwner)\n const newKeyHashVersion = getShaVersionForKey(other.stub, newDataOwnerPublicKey)\n if (!newKeyHashVersion) throw new Error(`Public key not found for data owner ${otherDataOwner}`)\n const newPublicKey = await this.primitives.RSA.importKey('spki', ua2ab(hex2ua(newDataOwnerPublicKey)), ['encrypt'], newKeyHashVersion)\n await this.extendForGiveAccessBackTo(selfId, otherDataOwner, fingerprintV1(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint)\n await this.extendForGiveAccessBackTo(otherDataOwner, selfId, fingerprintV1(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint)\n }\n\n /**\n * Get the encrypted exchange keys for a delegator-delegate pair.\n * @param delegatorId id of the delegator data owner.\n * @param delegateId id of the delegate data owner.\n * @return an array of exchange keys from the delegator to delegate where each key is encrypted with one or more public keys.\n */\n async getEncryptedExchangeKeysFor(delegatorId: string, delegateId: string): Promise<{ [publicKeyFingerprint: string]: string }[]> {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const res: { [publicKeyFingerprint: string]: string }[] = Object.values(delegator.stub.aesExchangeKeys ?? {}).flatMap((delegateToKey) => {\n const encryptedKeyForDelegate = delegateToKey[delegateId]\n if (encryptedKeyForDelegate) {\n return [encryptedKeyForDelegate]\n } else {\n return []\n }\n })\n const legacyDelegation = delegator.stub.hcPartyKeys?.[delegateId]?.[1]\n if (legacyDelegation) res.push({ '': legacyDelegation })\n return res\n }\n\n /**\n * Get all exchange keys where the provided data owner is involved either as the delegator or as the delegate.\n * @param dataOwnerId id of a data owner.\n * @param otherOwnerTypes only exchange keys between the current data owner and data owners of this type will be included in the result. If null considers all delegates\n * @return all exchange keys involving the provided data owner. Note that there may be an overlap between some keys to and from the data owner.\n */\n async getAllExchangeKeysWith(\n dataOwnerId: string,\n otherOwnerTypes: DataOwnerTypeEnum[] | null\n ): Promise<{\n keysToOwner: { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }\n keysFromOwner: { [delegatorFp: string]: { [delegateId: string]: { [entryFp: string]: string } } }\n }> {\n if (otherOwnerTypes != null && otherOwnerTypes.length === 0) throw new Error('otherOwnerTypes must not be empty!')\n const keysToOwner = await Promise.all([\n otherOwnerTypes == null || otherOwnerTypes.find((x) => x === 'hcp')\n ? this.hcpartyBaseApi.getAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes == null || otherOwnerTypes.find((x) => x === 'patient')\n ? this.patientBaseApi.getPatientAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes == null || otherOwnerTypes.find((x) => x === 'device')\n ? this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n ]).then(([a, b, c]) => ({ ...a, ...b, ...c } as { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }))\n const dataOwner = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n const allOwnerKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(dataOwner.stub, undefined, false)\n const filteredDelegates = new Set(\n await Array.from(new Set(Object.values(allOwnerKeys).flatMap((x) => Object.keys(x)))).reduce(async (acc, ownerId) => {\n const awaitedAcc = await acc\n if (ownerId === dataOwnerId || otherOwnerTypes == null) {\n return [...awaitedAcc, ownerId]\n } else {\n try {\n const dataOwnerType: DataOwnerTypeEnum = (await this.dataOwnerApi.getCryptoActorStub(ownerId)).type\n if (otherOwnerTypes.some((x) => x === dataOwnerType)) {\n return [...awaitedAcc, ownerId]\n } else return awaitedAcc\n } catch (_) {\n return awaitedAcc\n }\n }\n }, Promise.resolve([] as string[]))\n )\n const keysFromOwner = Object.fromEntries(\n Object.entries(allOwnerKeys)\n .map(([delegatorPubKey, delegateToKeys]) => [\n delegatorPubKey,\n Object.fromEntries(\n Object.entries(delegateToKeys).filter(([delegateId]) => filteredDelegates.has(delegateId)) as [string, { [k: string]: string }][]\n ),\n ])\n .filter(([, x]) => Object.keys(x).length > 0) as [string, { [k: string]: { [k: string]: string } }][]\n )\n return { keysToOwner, keysFromOwner }\n }\n\n /**\n * Attempts to decrypt many exchange keys using any of the provided key pairs.\n * @param encryptedExchangeKeys an array of exchange keys where each key is encrypted with one or more public keys.\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return an array all successfully decrypted exchange keys and an array containing all exchange keys which could not be decrypted.\n */\n async tryDecryptExchangeKeys(\n encryptedExchangeKeys: { [publicKeyFingerprint: string]: string }[],\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n }> {\n const raws = new Set<string>()\n const res: {\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n } = { successfulDecryptions: [], failedDecryptions: [] }\n for (const encryptedExchangeKey of encryptedExchangeKeys) {\n const decrypted = await this.tryDecryptExchangeKey(encryptedExchangeKey, keyPairsByFingerprint)\n if (decrypted !== undefined && !raws.has(decrypted.raw)) {\n raws.add(decrypted.raw)\n res.successfulDecryptions.push(decrypted.key)\n } else {\n res.failedDecryptions.push(encryptedExchangeKey)\n }\n }\n return res\n }\n\n private async extendForGiveAccessBackTo(\n delegatorId: string,\n delegateId: string,\n newPublicKeyFp: string,\n newPublicKey: CryptoKey,\n decryptionKeyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n await notConcurrent(this.generateKeyConcurrencyMap, delegatorId, async () => {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n let didUpdateSomeKey = false\n const combinedKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub, true)\n const updatedExchangeKeys: { [delegatorKey: string]: { [delegateId: string]: { [keyFp: string]: string } } } = {}\n const newEncryptionKeys = { [newPublicKeyFp]: newPublicKey }\n for (const [currDelegatorKey, currDelegatesToKeys] of Object.entries(combinedKeys)) {\n const updatedDelegatesToKeys: { [delegateId: string]: { [keyFp: string]: string } } = {}\n for (const [currDelegateId, currEncryptedKey] of Object.entries(currDelegatesToKeys)) {\n if (delegateId !== currDelegateId || newPublicKeyFp in currEncryptedKey) {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n } else {\n const decrypted = await this.tryDecryptExchangeKey(currEncryptedKey, decryptionKeyPairsByFingerprint)\n if (decrypted) {\n didUpdateSomeKey = true\n updatedDelegatesToKeys[currDelegateId] = {\n ...currEncryptedKey,\n ...(await this.encryptExchangeKey(decrypted, newEncryptionKeys)).encryptedExchangeKey,\n }\n } else {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n }\n }\n }\n updatedExchangeKeys[currDelegatorKey] = updatedDelegatesToKeys\n }\n if (didUpdateSomeKey) {\n await this.dataOwnerApi.modifyCryptoActorStub({\n type: delegator.type,\n stub: {\n ...delegator.stub,\n aesExchangeKeys: updatedExchangeKeys,\n },\n })\n }\n })\n }\n\n /**\n * Attempts to decrypt an exchange key using any of the provided key pairs.\n * @param encryptedExchangeKey an encrypted exchange key, in the form publicKeyXyzFingerprint -> hex(exchangeKeyEncryptedByPrivateKeyXyz).\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided keys.\n */\n private async tryDecryptExchangeKey(\n encryptedExchangeKey: { [publicKeyFingerprint: string]: string },\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n for (const [entryKey, encrypted] of Object.entries(encryptedExchangeKey)) {\n // Due to bugs in past version the entry may actually contain the full public key instead of just the fingerprint.\n const fp = fingerprintV1(entryKey)\n const keyPair = keyPairsByFingerprint[fp]\n if (keyPair !== undefined) {\n const res = await this.tryDecryptExchangeKeyWith(encrypted, keyPair, fp)\n if (res !== undefined) return res\n }\n }\n const defaultEncryptedKey = encryptedExchangeKey['']\n if (defaultEncryptedKey !== undefined) {\n for (const keyPair of Object.values(keyPairsByFingerprint)) {\n // disable error logging, we are not sure keyPair is the correct key\n const res = await this.tryDecryptExchangeKeyWith(defaultEncryptedKey, keyPair, undefined)\n if (res !== undefined) return res\n }\n }\n return undefined\n }\n\n /**\n * Creates an encrypted exchange key for the provided public keys.\n * @param exchangeKey the exchange key in raw and imported format. If undefined a new key will be automatically created.\n * @param publicKeys additional public keys that will have access to the exchange key in spki format, hex-encoded.\n * @return the exchangeKey and an object with the exchange key encrypted with each of the provided public keys, hex-encoded, by fingerprint.\n */\n private async encryptExchangeKey(\n exchangeKey: { raw: string; key: CryptoKey } | undefined,\n publicKeys: { [keyFingerprint: string]: CryptoKey }\n ): Promise<{\n exchangeKey: CryptoKey\n encryptedExchangeKey: { [pubKeyFp: string]: string }\n }> {\n const exchangeKeyCrypto = exchangeKey?.key ?? (await this.primitives.AES.generateCryptoKey(false))\n const exchangeKeyBytes = exchangeKey !== undefined ? hex2ua(exchangeKey.raw) : await this.primitives.AES.exportKey(exchangeKeyCrypto, 'raw')\n const encryptedExchangeKey = await Object.entries(publicKeys).reduce(\n async (acc, [currKeyFp, currKey]) => ({\n ...(await acc),\n [currKeyFp]: ua2hex(await this.primitives.RSA.encrypt(currKey, new Uint8Array(exchangeKeyBytes))),\n }),\n Promise.resolve({} as { [pubKeyFp: string]: string })\n )\n return { exchangeKey: exchangeKeyCrypto, encryptedExchangeKey }\n }\n\n /**\n * Attempts to decrypt an exchange key using the provided key pairs.\n * If you are confident that the provided {@link keyPair} was used to encrypt {@link encryptedByOneKey} you should also provide {@link keyPairFp},\n * so that if the decryption fail an error will be logged to console before returning undefined.\n * @param encryptedByOneKey an exchange key which may be encrypted with {@link keyPair}.\n * @param keyPair an rsa key pair.\n * @param keyPairFp the fingerprint of the provided key pair or undefined to disable logging of error if the decryption failed.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided key.\n */\n private async tryDecryptExchangeKeyWith(\n encryptedByOneKey: string,\n keyPair: KeyPair<CryptoKey>,\n keyPairFp: string | undefined // if undefined will not log errors, when we are not sure the key to be used is the provided key.\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n try {\n const decrypted = await this.primitives.RSA.decrypt(keyPair.privateKey, hex2ua(encryptedByOneKey))\n return { raw: ua2hex(decrypted), key: await this.primitives.AES.importKey('raw', decrypted) }\n } catch (e) {\n if (keyPairFp) {\n console.error(`Failed to decrypt or import exchange key ${encryptedByOneKey} using key with fingerprint ${keyPairFp}.`, e)\n }\n }\n }\n // Copy all legacy hcp exchange keys into the new aes exchange keys\n private async combineLegacyHcpKeysWithAesExchangeKeys(\n owner: CryptoActorStub,\n delegate: CryptoActorStub | undefined,\n fillDelegateLegacyKey: boolean\n ): Promise<{ [ownerPublicKey: string]: { [delegateId: string]: { [fingerprint: string]: string } } }> {\n const ownerLegacyPublicKey = owner.publicKey\n if (ownerLegacyPublicKey != undefined && !(owner.aesExchangeKeys ?? {})[ownerLegacyPublicKey]) {\n /*\n * This condition would technically prevent new updates to the hcPartyKeys to be migrated to the aes exchange keys, but since I can only update\n * data for self data owner and parent entities this is not an issue, because I will always be using the new api from now on and I won't have\n * a situation where the legacy keys are updated but the aes exchange keys are not.\n */\n const counterPartsById: { [id: string]: CryptoActorStub } = {}\n if (fillDelegateLegacyKey) {\n counterPartsById[owner.id!] = owner\n if (delegate) {\n counterPartsById[delegate.id!] = delegate\n }\n for (const other of Object.keys(owner.hcPartyKeys ?? {}).filter((x) => x !== owner.id && x !== delegate?.id)) {\n try {\n counterPartsById[other] = (await this.dataOwnerApi.getCryptoActorStub(other)).stub\n } catch {\n // ignore\n }\n }\n }\n return {\n [ownerLegacyPublicKey]: Object.entries(owner.hcPartyKeys ?? {}).reduce((acc, [hcpId, keys]) => {\n const counterpartKey = counterPartsById[hcpId]?.publicKey\n acc[hcpId] = {\n [fingerprintV1(ownerLegacyPublicKey)]: keys[0],\n [(counterpartKey && fingerprintV1(counterpartKey)) ?? '']: keys[1],\n }\n return acc\n }, {} as { [delegateId: string]: { [fingerprint: string]: string } }),\n ...(owner.aesExchangeKeys ?? {}),\n }\n } else return owner.aesExchangeKeys ?? {}\n }\n}\n"]}
|
|
@@ -5,6 +5,7 @@ const RSA_1 = require("./RSA");
|
|
|
5
5
|
const AES_1 = require("./AES");
|
|
6
6
|
const shamir_1 = require("./shamir");
|
|
7
7
|
const HMACUtils_1 = require("./HMACUtils");
|
|
8
|
+
const utils_1 = require("../utils");
|
|
8
9
|
/**
|
|
9
10
|
* Gives access to cryptographic primitives.
|
|
10
11
|
*/
|
|
@@ -37,10 +38,10 @@ class WebCryptoPrimitives {
|
|
|
37
38
|
(c) => (Number(c) ^ (this.crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (Number(c) / 4)))).toString(16));
|
|
38
39
|
}
|
|
39
40
|
sha256(data) {
|
|
40
|
-
return this.crypto.subtle.digest('SHA-256', data);
|
|
41
|
+
return this.crypto.subtle.digest('SHA-256', (0, utils_1.ua2ab)(data));
|
|
41
42
|
}
|
|
42
43
|
sha512(data) {
|
|
43
|
-
return this.crypto.subtle.digest('SHA-512', data);
|
|
44
|
+
return this.crypto.subtle.digest('SHA-512', (0, utils_1.ua2ab)(data));
|
|
44
45
|
}
|
|
45
46
|
randomBytes(n) {
|
|
46
47
|
const res = new Uint8Array(n);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CryptoPrimitives.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoPrimitives.ts"],"names":[],"mappings":";;;AAAA,+BAA8C;AAC9C,+BAA8C;AAC9C,qCAAuD;AACvD,2CAAsD;
|
|
1
|
+
{"version":3,"file":"CryptoPrimitives.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoPrimitives.ts"],"names":[],"mappings":";;;AAAA,+BAA8C;AAC9C,+BAA8C;AAC9C,qCAAuD;AACvD,2CAAsD;AACtD,oCAAgC;AAwBhC;;GAEG;AACH,MAAa,mBAAmB;IAO9B,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;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AAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAA,aAAK,EAAC,IAAI,CAAC,CAAC,CAAA;IAC1D,CAAC;IAED,MAAM,CAAC,IAA8B;QACnC,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAA,aAAK,EAAC,IAAI,CAAC,CAAC,CAAA;IAC1D,CAAC;IAED,WAAW,CAAC,CAAS;QACnB,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAA;QAC7B,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,CAAA;QAChC,OAAO,GAAG,CAAA;IACZ,CAAC;CACF;AAxDD,kDAwDC","sourcesContent":["import { RSAUtils, RSAUtilsImpl } from './RSA'\nimport { AESUtils, AESUtilsImpl } from './AES'\nimport { ShamirClass, WebcryptoShamir } from './shamir'\nimport { HMACUtils, HMACUtilsImpl } from './HMACUtils'\nimport { ua2ab } from '../utils'\n\nexport interface CryptoPrimitives {\n readonly shamir: ShamirClass\n readonly RSA: RSAUtils\n readonly AES: AESUtils\n readonly HMAC: HMACUtils\n /**\n * Generates a UUID using a cryptographically secure random number generator.\n */\n randomUuid(): string\n /**\n * @param data some data\n * @return the sha256 hash of {@link data}\n */\n sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n sha512(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n /**\n * @param n how many bytes to generate\n * @return an array with n random bytes\n */\n randomBytes(n: number): Uint8Array\n}\n\n/**\n * Gives access to cryptographic primitives.\n */\nexport class WebCryptoPrimitives implements CryptoPrimitives {\n private readonly _rsa: RSAUtils\n private readonly _aes: AESUtils\n private readonly _shamir: ShamirClass\n private readonly _crypto: Crypto\n private readonly _hmac: HMACUtils\n\n get crypto(): Crypto {\n return this._crypto\n }\n\n get shamir(): ShamirClass {\n return this._shamir\n }\n\n get RSA(): RSAUtils {\n return this._rsa\n }\n\n get AES(): AESUtils {\n return this._aes\n }\n\n get HMAC(): HMACUtils {\n return this._hmac\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this._crypto = crypto\n this._rsa = new RSAUtilsImpl(crypto)\n this._aes = new AESUtilsImpl(crypto)\n this._shamir = new WebcryptoShamir(crypto)\n this._hmac = new HMACUtilsImpl(crypto)\n }\n\n randomUuid() {\n return ((1e7).toString() + -1e3 + -4e3 + -8e3 + -1e11).replace(\n /[018]/g,\n //Keep next inlined or you will lose the random\n (c) => (Number(c) ^ ((this.crypto.getRandomValues(new Uint8Array(1))! as Uint8Array)[0] & (15 >> (Number(c) / 4)))).toString(16)\n )\n }\n\n sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.crypto.subtle.digest('SHA-256', ua2ab(data))\n }\n\n sha512(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.crypto.subtle.digest('SHA-512', ua2ab(data))\n }\n\n randomBytes(n: number): Uint8Array {\n const res = new Uint8Array(n)\n this.crypto.getRandomValues(res)\n return res\n }\n}\n"]}
|
|
@@ -29,7 +29,8 @@ export interface CryptoStrategies {
|
|
|
29
29
|
* (partially or completely) with `unknownKeys`.
|
|
30
30
|
*
|
|
31
31
|
* The returned value must be an object associating to each data owner id an object with:
|
|
32
|
-
* - `recoveredKeys`: all recovered keys
|
|
32
|
+
* - `recoveredKeys`: all recovered keys, by fingerprint. Will be automatically considered as authentic/trusted unless explicitly marked as unverified in
|
|
33
|
+
* the `keyAuthenticity` object.
|
|
33
34
|
* - `keyAuthenticity`: an object associating to each public key fingerprint its authenticity. Note that if any of the keys from `unknownKeys` is
|
|
34
35
|
* completely missing from this object the key will be considered as unverified in this api instance (same as if associated to false), but this
|
|
35
36
|
* value won't be cached (will be again part of `unknownKeys` in future instances.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CryptoStrategies.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoStrategies.ts"],"names":[],"mappings":"","sourcesContent":["import { KeyPair } from './RSA'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\n/**\n * Allows to customise the behaviour of the crypto api to set keys management, keys recovery, keys trusting in a way that better suits your needs.\n */\nexport interface CryptoStrategies {\n /**\n *\n * The iCure API has an internal mechanism to store private keys. This API stores the private keys in the storage facade you have provided.\n * In a browser, you typically use the LocalStorageFacade, which stores the keys in the browser's local storage.\n *\n * Method called during initialisation of the crypto API to validate keys recovered through iCure's recovery methods and/or to allow recovery of\n * missing keys using means external to iCure.\n * On startup the iCure sdk will try to load all keys for the current data owner and its parent hierarchy: if the sdk can't find some of the keys\n * for any of the data owners (according to the public keys for the data owner in the iCure server) and/or the sdk could recover some private keys\n * but can't verify the authenticity of the key pairs this method will be called.\n * The recovered and verified keys will automatically be cached using the current api {@link KeyStorageFacade} and {@link StorageFacade}\n *\n * The input is an array containing an object for each data owner part of the current data owner hierarchy. The objects are ordered from the data\n * for the topmost parent of the current data owner hierarchy (first element) to the data for the current data owner (last element). Each object\n * contains:\n * - dataOwner: the data owner entity that this object refers to\n * - unknownKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the authenticity status (verified or unverified) is unknown\n * (no result was cached from a previous api instantiation and the key was not generated on the current device).\n * - unavailableKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the sdk could not recover a private key. May overlap\n * (partially or completely) with `unknownKeys`.\n *\n * The returned value must be an object associating to each data owner id an object with:\n * - `recoveredKeys`: all recovered keys
|
|
1
|
+
{"version":3,"file":"CryptoStrategies.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoStrategies.ts"],"names":[],"mappings":"","sourcesContent":["import { KeyPair } from './RSA'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\n/**\n * Allows to customise the behaviour of the crypto api to set keys management, keys recovery, keys trusting in a way that better suits your needs.\n */\nexport interface CryptoStrategies {\n /**\n *\n * The iCure API has an internal mechanism to store private keys. This API stores the private keys in the storage facade you have provided.\n * In a browser, you typically use the LocalStorageFacade, which stores the keys in the browser's local storage.\n *\n * Method called during initialisation of the crypto API to validate keys recovered through iCure's recovery methods and/or to allow recovery of\n * missing keys using means external to iCure.\n * On startup the iCure sdk will try to load all keys for the current data owner and its parent hierarchy: if the sdk can't find some of the keys\n * for any of the data owners (according to the public keys for the data owner in the iCure server) and/or the sdk could recover some private keys\n * but can't verify the authenticity of the key pairs this method will be called.\n * The recovered and verified keys will automatically be cached using the current api {@link KeyStorageFacade} and {@link StorageFacade}\n *\n * The input is an array containing an object for each data owner part of the current data owner hierarchy. The objects are ordered from the data\n * for the topmost parent of the current data owner hierarchy (first element) to the data for the current data owner (last element). Each object\n * contains:\n * - dataOwner: the data owner entity that this object refers to\n * - unknownKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the authenticity status (verified or unverified) is unknown\n * (no result was cached from a previous api instantiation and the key was not generated on the current device).\n * - unavailableKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the sdk could not recover a private key. May overlap\n * (partially or completely) with `unknownKeys`.\n *\n * The returned value must be an object associating to each data owner id an object with:\n * - `recoveredKeys`: all recovered keys, by fingerprint. Will be automatically considered as authentic/trusted unless explicitly marked as unverified in\n * the `keyAuthenticity` object.\n * - `keyAuthenticity`: an object associating to each public key fingerprint its authenticity. Note that if any of the keys from `unknownKeys` is\n * completely missing from this object the key will be considered as unverified in this api instance (same as if associated to false), but this\n * value won't be cached (will be again part of `unknownKeys` in future instances.\n * @param keysData all information on unknown and unavailable keys for each data owner part of the current data owner hierarchy.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @param keyPairRecoverer a key pair recoverer.\n * @return all recovered keys and key authenticity information, by data owner.\n */\n recoverAndVerifySelfHierarchyKeys(\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[],\n cryptoPrimitives: CryptoPrimitives,\n keyPairRecoverer: KeyPairRecoverer\n ): Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }>\n\n /**\n * The correct initialisation of the crypto API requires that at least 1 verified (or device) key pair is available for each data owner part of the\n * current data owner hierarchy. If no verified key is available for any of the data owner parents the api initialisation will automatically fail,\n * however if there is no verified key for the current data owner you can instead create a new crypto key.\n * @param self the current data owner.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @return depending on which values you return the api initialisation will proceed differently:\n * - If this method returns true a new key will be automatically generated by the sdk.\n * - If this method returns a key pair the crypto api loads the key pair and considers it as a device key.\n * - If this method returns false the initialisation will fail with a predefined error.\n * - If this method throws an error the initialisation will propagate the error.\n * - If this method return the string \"keyless\" the api will be initialized in keyless mode.\n */\n generateNewKeyForDataOwner(self: DataOwnerWithType, cryptoPrimitives: CryptoPrimitives): Promise<KeyPair<CryptoKey> | boolean | 'keyless'>\n\n /**\n * Verifies if the public keys of a data owner which will be the delegate of a new exchange key do actually belong to the person the data owner\n * represents. This method is not called when the delegate would be the current data owner for the api.\n *\n * The user will have to obtain the verified public keys of the delegate from outside iCure, for example by email with another hcp, by checking the\n * personal website of the other user, or by scanning verification qr codes at the doctor office...\n *\n * As long as one of the public keys is verified the creation of a new exchange key will succeed. If no public key is verified the operation will\n * fail.\n * @param delegate the potential data owner delegate.\n * @param publicKeys public keys requiring verification, in spki hex-encoded format.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @return all verified public keys, in spki hex-encoded format.\n */\n verifyDelegatePublicKeys(delegate: CryptoActorStubWithType, publicKeys: string[], cryptoPrimitives: CryptoPrimitives): Promise<string[]>\n\n /**\n * Specifies if a data owner requires anonymous delegations, i.e. his id should not appear unencrypted in new secure delegations. This should always\n * be the case for patient data owners.\n * @param dataOwner a data owner.\n * @return true if the delegations for the provided data owner should be anonymous.\n */\n dataOwnerRequiresAnonymousDelegation(dataOwner: CryptoActorStubWithType): boolean\n}\n"]}
|
|
@@ -100,10 +100,10 @@ class AbstractExchangeDataManager {
|
|
|
100
100
|
throw new Error(`Could not create exchange data to ${delegateId} as no public key for the delegate could be verified.`);
|
|
101
101
|
for (const delegateKey of allVerifiedDelegateKeys) {
|
|
102
102
|
if (sha1KeysOfDelegate.has(delegateKey)) {
|
|
103
|
-
encryptionKeys[(0, utils_1.fingerprintV1)(delegateKey)] = yield this.primitives.RSA.importKey('spki', (0, utils_2.hex2ua)(delegateKey), ['encrypt'], RSA_1.ShaVersion.Sha1);
|
|
103
|
+
encryptionKeys[(0, utils_1.fingerprintV1)(delegateKey)] = yield this.primitives.RSA.importKey('spki', (0, utils_2.ua2ab)((0, utils_2.hex2ua)(delegateKey)), ['encrypt'], RSA_1.ShaVersion.Sha1);
|
|
104
104
|
}
|
|
105
105
|
else if (sha256KeysOfDelegate.has(delegateKey)) {
|
|
106
|
-
encryptionKeys[(0, utils_1.fingerprintV1)(delegateKey)] = yield this.primitives.RSA.importKey('spki', (0, utils_2.hex2ua)(delegateKey), ['encrypt'], RSA_1.ShaVersion.Sha256);
|
|
106
|
+
encryptionKeys[(0, utils_1.fingerprintV1)(delegateKey)] = yield this.primitives.RSA.importKey('spki', (0, utils_2.ua2ab)((0, utils_2.hex2ua)(delegateKey)), ['encrypt'], RSA_1.ShaVersion.Sha256);
|
|
107
107
|
}
|
|
108
108
|
else
|
|
109
109
|
throw new Error('Illegal state: verified keys should contain only keys for OAPE-SHA1 or OAPE-SHA256.');
|
|
@@ -126,7 +126,7 @@ class AbstractExchangeDataManager {
|
|
|
126
126
|
const newKeyHashVersion = (0, utils_1.getShaVersionForKey)(other.stub, newDataOwnerPublicKey);
|
|
127
127
|
if (!newKeyHashVersion)
|
|
128
128
|
throw new Error(`Public key not found for data owner ${otherDataOwner}`);
|
|
129
|
-
const importedNewKey = yield this.primitives.RSA.importKey('spki', (0, utils_2.hex2ua)(newDataOwnerPublicKey), ['encrypt'], newKeyHashVersion);
|
|
129
|
+
const importedNewKey = yield this.primitives.RSA.importKey('spki', (0, utils_2.ua2ab)((0, utils_2.hex2ua)(newDataOwnerPublicKey)), ['encrypt'], newKeyHashVersion);
|
|
130
130
|
const decryptionKeys = this.encryptionKeys.getDecryptionKeys();
|
|
131
131
|
const allExchangeDataToUpdate = self == otherDataOwner
|
|
132
132
|
? yield this.base.getExchangeDataByDelegatorDelegatePair(self, self)
|