@icure/api 8.1.7 → 8.1.9

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.
@@ -62,7 +62,7 @@ export declare class ExchangeData {
62
62
  * sign it with his own private key.
63
63
  * This field will contain the signature by fingerprint of the public key to use for verification.
64
64
  */
65
- delegatorSignature: {
65
+ delegatorSignature?: {
66
66
  [keyPairFingerprint: string]: string;
67
67
  };
68
68
  /**
@@ -6,13 +6,7 @@ exports.ExchangeData = void 0;
6
6
  */
7
7
  class ExchangeData {
8
8
  constructor(json) {
9
- if (!json.delegator ||
10
- !json.delegate ||
11
- !json.exchangeKey ||
12
- !json.accessControlSecret ||
13
- !json.sharedSignatureKey ||
14
- !json.sharedSignature ||
15
- !json.delegatorSignature)
9
+ if (!json.delegator || !json.delegate || !json.exchangeKey || !json.accessControlSecret || !json.sharedSignatureKey || !json.sharedSignature)
16
10
  throw new Error(`Exchange data json is missing required properties.\n${JSON.stringify(json, undefined, 2)}`);
17
11
  Object.assign(this, json);
18
12
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ExchangeData.js","sourceRoot":"","sources":["../../../../icc-api/model/internal/ExchangeData.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,YAAY;IACvB,YAAY,IAAgB;QAC1B,IACE,CAAC,IAAI,CAAC,SAAS;YACf,CAAC,IAAI,CAAC,QAAQ;YACd,CAAC,IAAI,CAAC,WAAW;YACjB,CAAC,IAAI,CAAC,mBAAmB;YACzB,CAAC,IAAI,CAAC,kBAAkB;YACxB,CAAC,IAAI,CAAC,eAAe;YACrB,CAAC,IAAI,CAAC,kBAAkB;YAExB,MAAM,IAAI,KAAK,CAAC,uDAAuD,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC,EAAE,CAAC,CAAA;QAC9G,MAAM,CAAC,MAAM,CAAC,IAAoB,EAAE,IAAI,CAAC,CAAA;IAC3C,CAAC;CAoEF;AAjFD,oCAiFC","sourcesContent":["/**\n * @internal this entity is meant for internal use only\n */\nexport class ExchangeData {\n constructor(json: JSON | any) {\n if (\n !json.delegator ||\n !json.delegate ||\n !json.exchangeKey ||\n !json.accessControlSecret ||\n !json.sharedSignatureKey ||\n !json.sharedSignature ||\n !json.delegatorSignature\n )\n throw new Error(`Exchange data json is missing required properties.\\n${JSON.stringify(json, undefined, 2)}`)\n Object.assign(this as ExchangeData, json)\n }\n\n /**\n * the Id of the exchange data. We encourage using either a v4 UUID or a HL7 Id.\n */\n id?: string\n /**\n * the revision of the exchange data in the database, used for conflict management / optimistic locking.\n */\n rev?: string\n /**\n * ID of the data owner which created this exchange data, in order to share some data with the [delegate].\n */\n delegator!: string\n /**\n * ID of a data owner which can use this exchange data to access data shared with him by [delegator].\n */\n delegate!: string\n /**\n * Aes key to use for sharing data from the delegator to the delegate, encrypted with the public keys of both delegate\n * and delegator. This key should never be sent decrypted to the server, as it allows to read medical data.\n */\n exchangeKey!: { [keyPairFingerprint: string]: string }\n /**\n * Key used for access control to data shared from the delegator to the delegate, encrypted with the public keys of both\n * delegate and delegator.\n *\n * This key will be used by the client to calculate the keys of [HasSecureDelegationsAccessControl.securityMetadata] which\n * allows to implement a form of access control where the identity of data owners with access to a specific entity can't be\n * deduced from the database alone. This is useful for example to allow patients to access their medical data without creating\n * a deducible link between the patient and the medical data in the database.\n *\n * There are no strict requirements on how the client should use this secret to create the security metadata key, but for\n * authentication the client must be able to provide a 128 bit long access control key (see [DataOwnerAuthenticationDetails.accessControlKeys])\n * which once hashed using sha256 will give the key of the security metadata.\n * However, in order to avoid introducing undesired links between entities which could be detrimental to the patients privacy\n * the access control keys should be created also using information on the entity class and confidentiality level of information\n * in applications where hcps share information using a hierarchical structure.\n * ```\n * accessControlKey = sha256Bytes(accessControlSecret + entityClass + confidentialityLevel).take(16)\n * securityMetadataKey = sha256Hex(accessControlKey)\n * ```\n */\n accessControlSecret!: { [keyPairFingerprint: string]: string }\n /**\n * Encrypted signature key (hmac-sha256) shared between delegate and delegator, to allow either of them to modify\n * the exchange data, without voiding the authenticity guarantee.\n */\n sharedSignatureKey!: { [keyPairFingerprint: string]: string }\n /**\n * Signature to ensure the key data has not been tampered with by third parties (any actor without access to the\n * keypair of the delegator/delegate): when creating new exchange data the delegator will create a new hmac key and\n * sign it with his own private key.\n * This field will contain the signature by fingerprint of the public key to use for verification.\n */\n delegatorSignature!: { [keyPairFingerprint: string]: string }\n /**\n * Base 64 signature of the exchange data, to ensure it was not tampered by third parties. This signature validates:\n * - The (decrypted) exchange key\n * - The (decrypted) access control secret\n * - The delegator and delegates being part of the exchange data\n * - The public keys used in the exchange data (allows to consider them as verified in a second moment).\n */\n sharedSignature!: string\n /**\n * hard delete (unix epoch in ms) timestamp of the object. Filled automatically when the delete method is called.\n */\n deletionDate?: number\n}\n"]}
1
+ {"version":3,"file":"ExchangeData.js","sourceRoot":"","sources":["../../../../icc-api/model/internal/ExchangeData.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,YAAY;IACvB,YAAY,IAAgB;QAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,mBAAmB,IAAI,CAAC,IAAI,CAAC,kBAAkB,IAAI,CAAC,IAAI,CAAC,eAAe;YAC1I,MAAM,IAAI,KAAK,CAAC,uDAAuD,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC,EAAE,CAAC,CAAA;QAC9G,MAAM,CAAC,MAAM,CAAC,IAAoB,EAAE,IAAI,CAAC,CAAA;IAC3C,CAAC;CAoEF;AAzED,oCAyEC","sourcesContent":["/**\n * @internal this entity is meant for internal use only\n */\nexport class ExchangeData {\n constructor(json: JSON | any) {\n if (!json.delegator || !json.delegate || !json.exchangeKey || !json.accessControlSecret || !json.sharedSignatureKey || !json.sharedSignature)\n throw new Error(`Exchange data json is missing required properties.\\n${JSON.stringify(json, undefined, 2)}`)\n Object.assign(this as ExchangeData, json)\n }\n\n /**\n * the Id of the exchange data. We encourage using either a v4 UUID or a HL7 Id.\n */\n id?: string\n /**\n * the revision of the exchange data in the database, used for conflict management / optimistic locking.\n */\n rev?: string\n /**\n * ID of the data owner which created this exchange data, in order to share some data with the [delegate].\n */\n delegator!: string\n /**\n * ID of a data owner which can use this exchange data to access data shared with him by [delegator].\n */\n delegate!: string\n /**\n * Aes key to use for sharing data from the delegator to the delegate, encrypted with the public keys of both delegate\n * and delegator. This key should never be sent decrypted to the server, as it allows to read medical data.\n */\n exchangeKey!: { [keyPairFingerprint: string]: string }\n /**\n * Key used for access control to data shared from the delegator to the delegate, encrypted with the public keys of both\n * delegate and delegator.\n *\n * This key will be used by the client to calculate the keys of [HasSecureDelegationsAccessControl.securityMetadata] which\n * allows to implement a form of access control where the identity of data owners with access to a specific entity can't be\n * deduced from the database alone. This is useful for example to allow patients to access their medical data without creating\n * a deducible link between the patient and the medical data in the database.\n *\n * There are no strict requirements on how the client should use this secret to create the security metadata key, but for\n * authentication the client must be able to provide a 128 bit long access control key (see [DataOwnerAuthenticationDetails.accessControlKeys])\n * which once hashed using sha256 will give the key of the security metadata.\n * However, in order to avoid introducing undesired links between entities which could be detrimental to the patients privacy\n * the access control keys should be created also using information on the entity class and confidentiality level of information\n * in applications where hcps share information using a hierarchical structure.\n * ```\n * accessControlKey = sha256Bytes(accessControlSecret + entityClass + confidentialityLevel).take(16)\n * securityMetadataKey = sha256Hex(accessControlKey)\n * ```\n */\n accessControlSecret!: { [keyPairFingerprint: string]: string }\n /**\n * Encrypted signature key (hmac-sha256) shared between delegate and delegator, to allow either of them to modify\n * the exchange data, without voiding the authenticity guarantee.\n */\n sharedSignatureKey!: { [keyPairFingerprint: string]: string }\n /**\n * Signature to ensure the key data has not been tampered with by third parties (any actor without access to the\n * keypair of the delegator/delegate): when creating new exchange data the delegator will create a new hmac key and\n * sign it with his own private key.\n * This field will contain the signature by fingerprint of the public key to use for verification.\n */\n delegatorSignature?: { [keyPairFingerprint: string]: string }\n /**\n * Base 64 signature of the exchange data, to ensure it was not tampered by third parties. This signature validates:\n * - The (decrypted) exchange key\n * - The (decrypted) access control secret\n * - The delegator and delegates being part of the exchange data\n * - The public keys used in the exchange data (allows to consider them as verified in a second moment).\n */\n sharedSignature!: string\n /**\n * hard delete (unix epoch in ms) timestamp of the object. Filled automatically when the delete method is called.\n */\n deletionDate?: number\n}\n"]}
@@ -437,12 +437,13 @@ class BaseExchangeDataManager {
437
437
  });
438
438
  }
439
439
  verifyDelegatorSignature(exchangeData, decryptedSharedSignatureKey, verificationKeys) {
440
+ var _a;
440
441
  return __awaiter(this, void 0, void 0, function* () {
441
442
  const delegatorSignatureData = yield this.bytesToSignForDelegatorSignature({
442
443
  sharedSignatureKey: decryptedSharedSignatureKey,
443
444
  });
444
445
  const keysByV2Fp = Object.fromEntries(Object.entries(verificationKeys).map(([fp, key]) => [(0, utils_2.fingerprintV1toV2)(fp), key]));
445
- for (const [fp, signature] of Object.entries(exchangeData.delegatorSignature)) {
446
+ for (const [fp, signature] of Object.entries((_a = exchangeData.delegatorSignature) !== null && _a !== void 0 ? _a : {})) {
446
447
  const verificationKey = keysByV2Fp[fp];
447
448
  if (verificationKey &&
448
449
  (yield this.primitives.HMAC.verify(yield this.extractHmacFromRsaPrivate(verificationKey), delegatorSignatureData, (0, utils_1.b64_2ua)(signature))))
@@ -1 +1 @@
1
- {"version":3,"file":"BaseExchangeDataManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeDataManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,4EAAwE;AAExE,+CAA2C;AAE3C,oCAAoE;AACpE,4BAA2B;AAC3B,mCAA4D;AAC5D,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAE9B;;;;GAIG;AACH,MAAa,uBAAuB;IAClC,YACW,GAAuB,EACf,YAA8B,EAC9B,UAA4B,EAC5B,gCAAy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,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;AAriBD,0DAqiBC","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 }> {\n if (!Object.keys(signatureKeys).length || !Object.keys(encryptionKeys).length) {\n throw new Error('Must specify at least one signature key and ')\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 }\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,\n newEncryptionKeys,\n rawExchangeKey,\n rawAccessControlSecret,\n rawSharedSignatureKey\n )\n }\n\n /**\n * Same as [tryUpdateExchangeData] but the decrypted content is already provided.\n */\n async updateExchangeDataWithRawDecryptedContent(\n exchangeData: ExchangeData,\n newEncryptionKeys: { [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 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 if (!missingEntries.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 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 private async importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.AES.importKey('raw', decryptedBytes)\n }\n\n private 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 private async importSharedSignatureKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.HMAC.importKey(decryptedBytes)\n }\n\n private 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 private importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string> {\n return Promise.resolve(ua2hex(decryptedBytes))\n }\n\n private 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,oCAAoE;AACpE,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,CAA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AAU,CAAC,OAAO,CAAC,EAAE,IAAA,eAAO,EAAC,SAAS,CAAC,CAAC,CAAA;QAC5F,CAAC;KAAA;CACF;AAriBD,0DAqiBC","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 }> {\n if (!Object.keys(signatureKeys).length || !Object.keys(encryptionKeys).length) {\n throw new Error('Must specify at least one signature key and ')\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 }\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,\n newEncryptionKeys,\n rawExchangeKey,\n rawAccessControlSecret,\n rawSharedSignatureKey\n )\n }\n\n /**\n * Same as [tryUpdateExchangeData] but the decrypted content is already provided.\n */\n async updateExchangeDataWithRawDecryptedContent(\n exchangeData: ExchangeData,\n newEncryptionKeys: { [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 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 if (!missingEntries.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 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 private async importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.AES.importKey('raw', decryptedBytes)\n }\n\n private 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 private async importSharedSignatureKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.HMAC.importKey(decryptedBytes)\n }\n\n private 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 private importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string> {\n return Promise.resolve(ua2hex(decryptedBytes))\n }\n\n private 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"]}
@@ -58,7 +58,7 @@ class IccBekmehrXApi extends icc_api_1.IccBekmehrApi {
58
58
  const that = this;
59
59
  const send = (command, uuid, body) => {
60
60
  const data = JSON.stringify({ command, uuid, body });
61
- socket.send(data.length > 65000 ? (0, binary_utils_1.string2ua)(data).buffer : data);
61
+ socket.send(data.length > 65000 ? (0, binary_utils_1.utf8_2ua)(data).buffer : data);
62
62
  };
63
63
  const messageHandler = (msg, event) => {
64
64
  if (msg.command === 'decrypt') {
@@ -1 +1 @@
1
- {"version":3,"file":"icc-bekmehr-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-bekmehr-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AACA,wCAA0C;AAI1C,uDAA2D;AAC3D,oDAAmF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,SAAS,EAAE,SAAS;wBACpB,QAAQ,EAAE,QAAQ;wBAClB,aAAa,EAAE,aAAa;wBAC5B,OAAO,EAAE,OAAO;wBAChB,IAAI,EAAE,IAAI;qBACX;iBACF,CAAC,CACH,CAAA;YACH,CAAC,CAAC,CAAA;YACF,sBAAsB;YACtB,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAA;QACpH,CAAC,CAAC,CACL,CAAA;IACH,CAAC;CACF;AApRD,wCAoRC","sourcesContent":["import * as models from '../icc-api/model/models'\nimport { IccBekmehrApi } from '../icc-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { string2ua, ua2string } from './utils/binary-utils'\nimport { Contact, Document, HealthElement, Service } from '../icc-api/model/models'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport type Patcher = ContactPatcher | HealthElementPatcher | DocumentPatcher | ServicePatcher\nexport interface ContactPatcher {\n type: 'ContactDto'\n patch: (contacts: Contact[]) => Promise<Contact[]>\n}\nexport interface HealthElementPatcher {\n type: 'HealthElementDto'\n patch: (patients: HealthElement[]) => Promise<HealthElement[]>\n}\nexport interface DocumentPatcher {\n type: 'DocumentDto'\n patch: (documents: Document[]) => Promise<Document[]>\n}\nexport interface ServicePatcher {\n type: 'ServiceDto'\n patch: (documents: Service[]) => Promise<Service[]>\n}\n\nexport class IccBekmehrXApi extends IccBekmehrApi {\n private readonly ctcApi: IccContactXApi\n private readonly helementApi: IccHelementXApi\n private readonly documentApi: IccDocumentXApi\n private readonly wssHost: string\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n ctcApi: IccContactXApi,\n helementApi: IccHelementXApi,\n documentApi: IccDocumentXApi,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.ctcApi = ctcApi\n this.helementApi = helementApi\n this.documentApi = documentApi\n\n this.wssHost = new URL(this.host, typeof window !== 'undefined' ? window.location.href : undefined).href\n .replace(/^http/, 'ws')\n .replace(/\\/rest\\/v.+/, '/ws')\n }\n\n private async getJwt(): Promise<string> {\n const authService = this.authenticationProvider.getAuthService()\n if (!!authService.jwtGetter) {\n const tokens = await authService.jwtGetter()\n if (!tokens) {\n throw new Error('Missing JWT')\n }\n return tokens.token\n } else {\n throw new Error('The existing provider is not a JWT provider')\n }\n }\n\n socketEventListener(\n socket: WebSocket,\n healthcarePartyId: string,\n resolve: (value: Blob) => void,\n reject: (reason?: any) => void,\n patchers: Patcher[],\n progressCallback?: (progress: number) => void\n ) {\n const that = this\n\n const send = (command: string, uuid: string, body: any) => {\n const data = JSON.stringify({ command, uuid, body })\n socket.send(data.length > 65000 ? string2ua(data).buffer : data)\n }\n\n const messageHandler = (msg: any, event: any) => {\n if (msg.command === 'decrypt') {\n if (msg.type === 'ContactDto') {\n that.ctcApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ContactDto')\n .reduce(async (p, patcher) => (patcher as ContactPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'HealthElementDto') {\n that.helementApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'HealthElementDto')\n .reduce(async (p, patcher) => (patcher as HealthElementPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'DocumentDto') {\n that.documentApi\n .decrypt(\n healthcarePartyId,\n msg.body.map((d: JSON) => new Document(d))\n )\n .then((res) =>\n patchers\n .filter((p) => p.type === 'DocumentDto')\n .reduce(async (p, patcher) => (patcher as DocumentPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) =>\n send(\n 'decryptResponse',\n msg.uuid,\n res?.map((d) => {\n const de = d.decryptedAttachment\n const { encryptedAttachment, ...stripped } = d\n return de ? { ...stripped, decryptedAttachment: btoa(ua2string(de)) } : stripped\n })\n )\n )\n } else if (msg.type === 'ServiceDto') {\n that.ctcApi\n .decryptServices(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ServiceDto')\n .reduce(async (p, patcher) => (patcher as ServicePatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n }\n } else if (msg.command === 'progress') {\n if (progressCallback && msg.body && msg.body[0]) {\n progressCallback(msg.body[0].progress)\n }\n } else {\n console.error('error received from backend:' + event.data)\n reject('websocket error: ' + event.data)\n socket.close(4000, 'backend error')\n }\n }\n\n return (event: MessageEvent) => {\n if (typeof event.data === 'string') {\n const msg = JSON.parse(event.data)\n messageHandler(msg, event)\n } else {\n const blob: Blob = event.data\n const subBlob = blob.slice(0, 1)\n const br = new FileReader()\n br.onload = function (e) {\n const firstChar = e.target && new Uint8Array((e.target as any).result as ArrayBuffer)[0]\n\n if (firstChar === 0x7b) {\n const tr = new FileReader()\n tr.onload = function (e) {\n const msg = e.target && JSON.parse((e.target as any).result as string)\n messageHandler(msg, event)\n }\n tr.readAsBinaryString(blob)\n } else {\n resolve(blob)\n socket.close(1000, 'Ok')\n }\n }\n br.readAsArrayBuffer(subBlob)\n }\n }\n }\n\n generateSmfExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SoftwareMedicalFileExport,\n progressCallback?: (progress: number) => void,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSmf?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers, progressCallback))\n })\n )\n }\n\n generateSumehrExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehr?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateSumehrV2ExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehrV2?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateDiaryNoteExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateDiaryNote?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateMedicationSchemeWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n recipientSafe: string,\n version: number,\n body: models.MedicationSchemeExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateMedicationScheme?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: {\n patientId: patientId,\n language: language,\n recipientSafe: recipientSafe,\n version: version,\n info: body,\n },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n}\n"]}
1
+ {"version":3,"file":"icc-bekmehr-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-bekmehr-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AACA,wCAA0C;AAI1C,uDAA0D;AAC1D,oDAAmF;AACnF,0EAAgG;AAoBhG,MAAa,cAAe,SAAQ,uBAAa;IAM/C,YACE,IAAY,EACZ,OAAkC,EAClC,MAAsB,EACtB,WAA4B,EAC5B,WAA4B,EAC5B,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QACvD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,WAAW,GAAG,WAA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AAE,IAAI,EAAE,IAAI,EAAE;iBACrE,CAAC,CACH,CAAA;YACH,CAAC,CAAC,CAAA;YACF,sBAAsB;YACtB,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAA;QACpH,CAAC,CAAC,CACL,CAAA;IACH,CAAC;IAED,6CAA6C,CAC3C,SAAiB,EACjB,iBAAyB,EACzB,QAAgB,EAChB,aAAqB,EACrB,OAAe,EACf,IAAuC,EACvC,WAAsB,EAAE;QAExB,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,CACvB,CAAC,GAAG,EAAE,EAAE,CACN,IAAI,OAAO,CAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAChD,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,GAAG,IAAI,CAAC,OAAO,0CAA0C,GAAG,EAAE,CAAC,CAAA;YAC5F,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE;gBAC9B,MAAM,CAAC,IAAI,CACT,IAAI,CAAC,SAAS,CAAC;oBACb,UAAU,EAAE;wBACV,SAAS,EAAE,SAAS;wBACpB,QAAQ,EAAE,QAAQ;wBAClB,aAAa,EAAE,aAAa;wBAC5B,OAAO,EAAE,OAAO;wBAChB,IAAI,EAAE,IAAI;qBACX;iBACF,CAAC,CACH,CAAA;YACH,CAAC,CAAC,CAAA;YACF,sBAAsB;YACtB,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAA;QACpH,CAAC,CAAC,CACL,CAAA;IACH,CAAC;CACF;AApRD,wCAoRC","sourcesContent":["import * as models from '../icc-api/model/models'\nimport { IccBekmehrApi } from '../icc-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { ua2string, utf8_2ua } from './utils/binary-utils'\nimport { Contact, Document, HealthElement, Service } from '../icc-api/model/models'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport type Patcher = ContactPatcher | HealthElementPatcher | DocumentPatcher | ServicePatcher\nexport interface ContactPatcher {\n type: 'ContactDto'\n patch: (contacts: Contact[]) => Promise<Contact[]>\n}\nexport interface HealthElementPatcher {\n type: 'HealthElementDto'\n patch: (patients: HealthElement[]) => Promise<HealthElement[]>\n}\nexport interface DocumentPatcher {\n type: 'DocumentDto'\n patch: (documents: Document[]) => Promise<Document[]>\n}\nexport interface ServicePatcher {\n type: 'ServiceDto'\n patch: (documents: Service[]) => Promise<Service[]>\n}\n\nexport class IccBekmehrXApi extends IccBekmehrApi {\n private readonly ctcApi: IccContactXApi\n private readonly helementApi: IccHelementXApi\n private readonly documentApi: IccDocumentXApi\n private readonly wssHost: string\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n ctcApi: IccContactXApi,\n helementApi: IccHelementXApi,\n documentApi: IccDocumentXApi,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.ctcApi = ctcApi\n this.helementApi = helementApi\n this.documentApi = documentApi\n\n this.wssHost = new URL(this.host, typeof window !== 'undefined' ? window.location.href : undefined).href\n .replace(/^http/, 'ws')\n .replace(/\\/rest\\/v.+/, '/ws')\n }\n\n private async getJwt(): Promise<string> {\n const authService = this.authenticationProvider.getAuthService()\n if (!!authService.jwtGetter) {\n const tokens = await authService.jwtGetter()\n if (!tokens) {\n throw new Error('Missing JWT')\n }\n return tokens.token\n } else {\n throw new Error('The existing provider is not a JWT provider')\n }\n }\n\n socketEventListener(\n socket: WebSocket,\n healthcarePartyId: string,\n resolve: (value: Blob) => void,\n reject: (reason?: any) => void,\n patchers: Patcher[],\n progressCallback?: (progress: number) => void\n ) {\n const that = this\n\n const send = (command: string, uuid: string, body: any) => {\n const data = JSON.stringify({ command, uuid, body })\n socket.send(data.length > 65000 ? utf8_2ua(data).buffer : data)\n }\n\n const messageHandler = (msg: any, event: any) => {\n if (msg.command === 'decrypt') {\n if (msg.type === 'ContactDto') {\n that.ctcApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ContactDto')\n .reduce(async (p, patcher) => (patcher as ContactPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'HealthElementDto') {\n that.helementApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'HealthElementDto')\n .reduce(async (p, patcher) => (patcher as HealthElementPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'DocumentDto') {\n that.documentApi\n .decrypt(\n healthcarePartyId,\n msg.body.map((d: JSON) => new Document(d))\n )\n .then((res) =>\n patchers\n .filter((p) => p.type === 'DocumentDto')\n .reduce(async (p, patcher) => (patcher as DocumentPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) =>\n send(\n 'decryptResponse',\n msg.uuid,\n res?.map((d) => {\n const de = d.decryptedAttachment\n const { encryptedAttachment, ...stripped } = d\n return de ? { ...stripped, decryptedAttachment: btoa(ua2string(de)) } : stripped\n })\n )\n )\n } else if (msg.type === 'ServiceDto') {\n that.ctcApi\n .decryptServices(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ServiceDto')\n .reduce(async (p, patcher) => (patcher as ServicePatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n }\n } else if (msg.command === 'progress') {\n if (progressCallback && msg.body && msg.body[0]) {\n progressCallback(msg.body[0].progress)\n }\n } else {\n console.error('error received from backend:' + event.data)\n reject('websocket error: ' + event.data)\n socket.close(4000, 'backend error')\n }\n }\n\n return (event: MessageEvent) => {\n if (typeof event.data === 'string') {\n const msg = JSON.parse(event.data)\n messageHandler(msg, event)\n } else {\n const blob: Blob = event.data\n const subBlob = blob.slice(0, 1)\n const br = new FileReader()\n br.onload = function (e) {\n const firstChar = e.target && new Uint8Array((e.target as any).result as ArrayBuffer)[0]\n\n if (firstChar === 0x7b) {\n const tr = new FileReader()\n tr.onload = function (e) {\n const msg = e.target && JSON.parse((e.target as any).result as string)\n messageHandler(msg, event)\n }\n tr.readAsBinaryString(blob)\n } else {\n resolve(blob)\n socket.close(1000, 'Ok')\n }\n }\n br.readAsArrayBuffer(subBlob)\n }\n }\n }\n\n generateSmfExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SoftwareMedicalFileExport,\n progressCallback?: (progress: number) => void,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSmf?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers, progressCallback))\n })\n )\n }\n\n generateSumehrExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehr?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateSumehrV2ExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehrV2?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateDiaryNoteExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateDiaryNote?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateMedicationSchemeWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n recipientSafe: string,\n version: number,\n body: models.MedicationSchemeExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateMedicationScheme?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: {\n patientId: patientId,\n language: language,\n recipientSafe: recipientSafe,\n version: version,\n info: body,\n },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icure/api",
3
- "version": "8.1.7",
3
+ "version": "8.1.9",
4
4
  "description": "Typescript version of iCure standalone API client",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -176,6 +176,7 @@ const IccExchangeDataApi_1 = require("../../../icc-api/api/internal/IccExchangeD
176
176
  it('should create new encryption keys when none is available', function () {
177
177
  return __awaiter(this, void 0, void 0, function* () {
178
178
  function doTest(allowFullExchangeDataLoad) {
179
+ var _a;
179
180
  return __awaiter(this, void 0, void 0, function* () {
180
181
  yield initialiseComponents(allowFullExchangeDataLoad);
181
182
  const sfk = primitives.randomUuid();
@@ -199,7 +200,7 @@ const IccExchangeDataApi_1 = require("../../../icc-api/api/internal/IccExchangeD
199
200
  (0, chai_1.expect)(decryptedAccessControlSecretByDelegate.successfulDecryptions[0]).to.equal(createdData.accessControlSecret);
200
201
  (0, chai_1.expect)(retrievedCachedData.exchangeData.delegator).to.equal(selfId);
201
202
  (0, chai_1.expect)(retrievedCachedData.exchangeData.delegate).to.equal(delegateId);
202
- (0, chai_1.expect)(Object.keys(retrievedCachedData.exchangeData.delegatorSignature)).to.have.length(1);
203
+ (0, chai_1.expect)(Object.keys((_a = retrievedCachedData.exchangeData.delegatorSignature) !== null && _a !== void 0 ? _a : {})).to.have.length(1);
203
204
  (0, chai_1.expect)(Object.keys(retrievedCachedData.exchangeData.exchangeKey)).to.have.length(2);
204
205
  (0, chai_1.expect)(Object.keys(retrievedCachedData.exchangeData.accessControlSecret)).to.have.length(2);
205
206
  (0, chai_1.expect)(Object.keys(retrievedCachedData.exchangeData.sharedSignatureKey)).to.have.length(2);
@@ -212,12 +213,13 @@ const IccExchangeDataApi_1 = require("../../../icc-api/api/internal/IccExchangeD
212
213
  it('should create encryption keys to self when none is available', function () {
213
214
  return __awaiter(this, void 0, void 0, function* () {
214
215
  function doTest(allowFullExchangeDataLoad) {
216
+ var _a;
215
217
  return __awaiter(this, void 0, void 0, function* () {
216
218
  yield initialiseComponents(allowFullExchangeDataLoad);
217
219
  const createdData = yield exchangeData.getOrCreateEncryptionDataTo(selfId, false);
218
220
  (0, chai_1.expect)(createdData.exchangeData.delegator).to.equal(selfId);
219
221
  (0, chai_1.expect)(createdData.exchangeData.delegate).to.equal(selfId);
220
- (0, chai_1.expect)(Object.keys(createdData.exchangeData.delegatorSignature)).to.have.length(1);
222
+ (0, chai_1.expect)(Object.keys((_a = createdData.exchangeData.delegatorSignature) !== null && _a !== void 0 ? _a : {})).to.have.length(1);
221
223
  (0, chai_1.expect)(Object.keys(createdData.exchangeData.sharedSignatureKey)).to.have.length(1);
222
224
  (0, chai_1.expect)(Object.keys(createdData.exchangeData.exchangeKey)).to.have.length(1);
223
225
  (0, chai_1.expect)(Object.keys(createdData.exchangeData.accessControlSecret)).to.have.length(1);
@@ -1 +1 @@
1
- {"version":3,"file":"exchange-data-manager-test.js","sourceRoot":"","sources":["../../../../test/icc-x-api/crypto/exchange-data-manager-test.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,iCAAgC;AAChC,uFAIsD;AACtD,iFAAgF;AAChF,mCAAkC;AAClC,+FAA2F;AAC3F,yEAAqE;AACrE,mEAA+D;AAC/D,2EAAuE;AACvE,kDAA6F;AAC7F,qFAAiF;AACjF,iGAA6F;AAC7F,+EAA2E;AAC3E,+BAA6B;AAC7B,gFAAqE;AAErE,4BAA2B;AAC3B,2DAAiG;AACjG,gFAA4E;AAC5E,mDAAmE;AACnE,uDAAoG;AACpG,4BAAyB;AACzB,yFAAqF;AAErF,IAAA,4BAAe,EAAC,KAAK,CAAC,CAAA;AAEtB,IAAA,gBAAQ,EAAC,8BAA8B,EAAE;;QACvC,MAAM,UAAU,GAAG,IAAI,sCAAmB,CAAC,kBAAgB,CAAC,CAAA;QAC5D,MAA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AC,mBAAmB,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAA;gBAC5D,MAAM,WAAW,GAAG,CAAC,MAAM,WAAW,CAAC,GAAG,CAAC,SAAS,CAAC,YAAY,CAAC,yBAAyB,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,EAAG,CAAC,EAAE,IAAI,CAAC,CAAC,CAC3H,MAAM,CAAC,YAAY,CAAC,EAAG,CACxB,CAAA;gBACD,IAAA,aAAM,EAAC,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAA;gBACvC,IAAA,aAAM,EAAC,WAAY,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAA;gBACpD,IAAA,aAAM,EAAC,WAAY,CAAC,mBAAmB,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAA;YAC9D,CAAC;SAAA,CAAC,CAAA;IACJ,CAAC;CAAA,CAAC,CAAA","sourcesContent":["import { describe } from 'mocha'\nimport {\n ExchangeDataManager,\n ExchangeDataManagerOptionalParameters,\n initialiseExchangeDataManagerForCurrentDataOwner,\n} from '../../../icc-x-api/crypto/ExchangeDataManager'\nimport { WebCryptoPrimitives } from '../../../icc-x-api/crypto/CryptoPrimitives'\nimport { webcrypto } from 'crypto'\nimport { BaseExchangeDataManager } from '../../../icc-x-api/crypto/BaseExchangeDataManager'\nimport { FakeExchangeDataApi } from '../../utils/FakeExchangeDataApi'\nimport { FakeDataOwnerApi } from '../../utils/FakeDataOwnerApi'\nimport { TestCryptoStrategies } from '../../utils/TestCryptoStrategies'\nimport { EntityWithDelegationTypeName, ShaVersion, ua2b64, ua2hex } from '../../../icc-x-api'\nimport { FakeEncryptionKeysManager } from '../../utils/FakeEncryptionKeysManager'\nimport { AccessControlSecretUtils } from '../../../icc-x-api/crypto/AccessControlSecretUtils'\nimport { ExchangeData } from '../../../icc-api/model/internal/ExchangeData'\nimport { expect } from 'chai'\nimport { setEquals } from '../../../icc-x-api/utils/collection-utils'\nimport { KeyPair } from '../../../icc-x-api/crypto/RSA'\nimport * as _ from 'lodash'\nimport { fingerprintV1, fingerprintV1toV2, fingerprintV2 } from '../../../icc-x-api/crypto/utils'\nimport { DataOwnerTypeEnum } from '../../../icc-api/model/DataOwnerTypeEnum'\nimport { getEnvVariables, TestVars } from '@icure/test-setup/types'\nimport { createNewHcpApi, getEnvironmentInitializer, setLocalStorage } from '../../utils/test_utils'\nimport 'isomorphic-fetch'\nimport { IccExchangeDataApi } from '../../../icc-api/api/internal/IccExchangeDataApi'\n\nsetLocalStorage(fetch)\n\ndescribe('Exchange data manager - unit', async function () {\n const primitives = new WebCryptoPrimitives(webcrypto as any)\n const accessControlSecretUtils = new AccessControlSecretUtils(primitives)\n let selfId: string\n let selfKeyFpV1: string\n let selfKeyFpV2: string\n let selfKeypair: KeyPair<CryptoKey>\n let delegateId: string\n let delegateKeyFp: string\n let delegateKeypair: KeyPair<CryptoKey>\n let delegate2Id: string\n let delegate2KeyFp: string\n let delegate2Keypair: KeyPair<CryptoKey>\n let dataOwnerApi: FakeDataOwnerApi\n let exchangeDataApi: FakeExchangeDataApi\n let baseExchangeData: BaseExchangeDataManager\n let exchangeData: ExchangeDataManager\n let encryptionKeysManager: FakeEncryptionKeysManager\n\n async function initialiseComponents(\n allowFullExchangeDataLoad: boolean,\n optionalParameters: ExchangeDataManagerOptionalParameters & { verifiedDelegateKeys?: Set<string> } = {}\n ) {\n const dataOwnerType = allowFullExchangeDataLoad ? DataOwnerTypeEnum.Patient : DataOwnerTypeEnum.Hcp\n selfId = primitives.randomUuid()\n selfKeypair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n selfKeyFpV1 = fingerprintV1(ua2hex(await primitives.RSA.exportKey(selfKeypair.publicKey, 'spki')))\n selfKeyFpV2 = fingerprintV1toV2(selfKeyFpV1)\n delegateId = primitives.randomUuid()\n delegateKeypair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n delegateKeyFp = fingerprintV1(ua2hex(await primitives.RSA.exportKey(delegateKeypair.publicKey, 'spki')))\n delegate2Id = primitives.randomUuid()\n delegate2Keypair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n delegate2KeyFp = fingerprintV1(ua2hex(await primitives.RSA.exportKey(delegate2Keypair.publicKey, 'spki')))\n dataOwnerApi = new FakeDataOwnerApi(\n {\n id: selfId,\n type: dataOwnerType,\n publicKeysForOaepWithSha256: [ua2hex(await primitives.RSA.exportKey(selfKeypair.publicKey, 'spki'))],\n },\n [\n {\n id: delegateId,\n type: dataOwnerType,\n publicKeysForOaepWithSha256: [ua2hex(await primitives.RSA.exportKey(delegateKeypair.publicKey, 'spki'))],\n },\n {\n id: delegate2Id,\n type: dataOwnerType,\n publicKeysForOaepWithSha256: [ua2hex(await primitives.RSA.exportKey(delegate2Keypair.publicKey, 'spki'))],\n },\n ]\n )\n const cryptoStrategies = new TestCryptoStrategies(undefined, undefined, optionalParameters.verifiedDelegateKeys)\n exchangeDataApi = new FakeExchangeDataApi()\n baseExchangeData = new BaseExchangeDataManager(exchangeDataApi, dataOwnerApi, primitives, allowFullExchangeDataLoad, false)\n encryptionKeysManager = await FakeEncryptionKeysManager.create(primitives, [selfKeypair])\n exchangeData = await initialiseExchangeDataManagerForCurrentDataOwner(\n baseExchangeData,\n encryptionKeysManager,\n accessControlSecretUtils,\n cryptoStrategies,\n dataOwnerApi,\n primitives,\n true,\n optionalParameters\n )\n }\n\n async function checkDataEqual(\n actual: { exchangeData: ExchangeData; accessControlSecret?: string; exchangeKey: CryptoKey | undefined } | undefined,\n expected: { exchangeData: ExchangeData; accessControlSecret?: string; exchangeKey: CryptoKey | undefined }\n ) {\n expect(actual).to.not.be.undefined\n expect(_.isEqual(_.omit(expected.exchangeData, ['rev']), _.omit(actual!.exchangeData, ['rev']))).to.equal(\n true,\n `Data should be equivalent\\nExpected: ${JSON.stringify(expected.exchangeData, undefined, 2)}\\nActual: ${JSON.stringify(\n actual!.exchangeData,\n undefined,\n 2\n )}\\n`\n )\n expect(expected.accessControlSecret).to.equal(actual!.accessControlSecret)\n await checkAesKeysEquality(actual!.exchangeKey, expected.exchangeKey)\n }\n\n async function checkAesKeysEquality(actual: CryptoKey | undefined, expected: CryptoKey | undefined) {\n if (!actual && !expected) return\n expect(!actual).to.equal(!expected, !expected ? 'Key should not have been decrypted' : 'Key should have been decrypted')\n expect(ua2hex(await primitives.AES.exportKey(expected!, 'raw'))).to.equal(ua2hex(await primitives.AES.exportKey(actual!, 'raw')))\n }\n\n async function createDataFromRandomToSelf(): Promise<{ exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string }> {\n const encryptionKey = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const encryptionFp = ua2hex(await primitives.RSA.exportKey(encryptionKey.publicKey, 'spki')).slice(-32)\n const signatureKey = await primitives.RSA.generateKeyPair(ShaVersion.Sha1)\n const signatureFp = ua2hex(await primitives.RSA.exportKey(signatureKey.publicKey, 'spki')).slice(-32)\n const created = await baseExchangeData.createExchangeData(\n selfId,\n { [signatureFp]: signatureKey.privateKey },\n { [encryptionFp]: encryptionKey.publicKey, [selfKeyFpV1]: selfKeypair.publicKey }\n )\n const modified = await exchangeDataApi.modifyExchangeData(\n new ExchangeData({\n ...created.exchangeData,\n delegator: primitives.randomUuid(),\n })\n )\n return { exchangeData: modified, exchangeKey: created.exchangeKey, accessControlSecret: created.accessControlSecret }\n }\n\n async function generateEncryptionKeys(n: number): Promise<{ pair: KeyPair<CryptoKey>; fingerprintV2: string; hexPub: string }[]> {\n return await Promise.all(\n Array(n)\n .fill(null)\n .map(async () => {\n const pair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const hexPub = ua2hex(await primitives.RSA.exportKey(pair.publicKey, 'spki'))\n const fingerprint = fingerprintV2(hexPub)\n return { pair, fingerprintV2: fingerprint, hexPub }\n })\n )\n }\n\n it('base should be able to retrieve all exchange data for the current data owner if allowed by the crypto strategies', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const expectedData = await Promise.all(\n Array.from(Array(3500), async (_, i) => {\n const data = new ExchangeData({\n id: primitives.randomUuid(),\n delegate: i % 2 === 0 ? selfId : primitives.randomUuid(),\n delegator: i % 2 === 0 ? primitives.randomUuid() : selfId,\n exchangeKey: { not: 'important' },\n accessControlSecret: { not: 'important' },\n sharedSignatureKey: { not: 'important' },\n delegatorSignature: { not: 'important' },\n sharedSignature: 'not important',\n })\n await exchangeDataApi.createExchangeData(data)\n return data\n })\n )\n await Promise.all(\n Array.from(Array(500), async () => {\n // Should not be in result\n const data = new ExchangeData({\n id: primitives.randomUuid(),\n delegate: primitives.randomUuid(),\n delegator: primitives.randomUuid(),\n exchangeKey: { not: 'important' },\n accessControlSecret: { not: 'important' },\n sharedSignatureKey: { not: 'important' },\n delegatorSignature: { not: 'important' },\n sharedSignature: 'not important',\n })\n await exchangeDataApi.createExchangeData(data)\n })\n )\n const retrieved = await baseExchangeData.getAllExchangeDataForCurrentDataOwnerIfAllowed()\n if (allowFullExchangeDataLoad) {\n expect(retrieved).to.not.be.undefined\n expect(retrieved).to.have.length(expectedData.length)\n expect(setEquals(new Set(expectedData.map((x) => x.id)), new Set(retrieved!.map((x) => x.id))), 'Retrieved and expected ids').to.be.true\n } else {\n expect(retrieved).to.be.undefined\n }\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should create new encryption keys when none is available', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const sfk = primitives.randomUuid()\n const initialisedCount = exchangeDataApi.callCount\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const retrievedCachedData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n exchangeDataApi.compareCallCountFromBaseline(initialisedCount, {\n createExchangeData: 1,\n // If we could fully preload we already know whether the exchange key already exists or not, otherwise we have to request from the api\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 1,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n await checkDataEqual(retrievedCachedData, createdData)\n const decryptedKeyByDelegate = await baseExchangeData.tryDecryptExchangeKeys([createdData.exchangeData], { [delegateKeyFp]: delegateKeypair })\n const decryptedAccessControlSecretByDelegate = await baseExchangeData.tryDecryptAccessControlSecret([createdData.exchangeData], {\n [delegateKeyFp]: delegateKeypair,\n })\n await checkAesKeysEquality(decryptedKeyByDelegate.successfulDecryptions[0], createdData.exchangeKey)\n expect(decryptedAccessControlSecretByDelegate.successfulDecryptions[0]).to.equal(createdData.accessControlSecret)\n expect(retrievedCachedData.exchangeData.delegator).to.equal(selfId)\n expect(retrievedCachedData.exchangeData.delegate).to.equal(delegateId)\n expect(Object.keys(retrievedCachedData.exchangeData.delegatorSignature)).to.have.length(1)\n expect(Object.keys(retrievedCachedData.exchangeData.exchangeKey)).to.have.length(2)\n expect(Object.keys(retrievedCachedData.exchangeData.accessControlSecret)).to.have.length(2)\n expect(Object.keys(retrievedCachedData.exchangeData.sharedSignatureKey)).to.have.length(2)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should create encryption keys to self when none is available', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n expect(createdData.exchangeData.delegator).to.equal(selfId)\n expect(createdData.exchangeData.delegate).to.equal(selfId)\n expect(Object.keys(createdData.exchangeData.delegatorSignature)).to.have.length(1)\n expect(Object.keys(createdData.exchangeData.sharedSignatureKey)).to.have.length(1)\n expect(Object.keys(createdData.exchangeData.exchangeKey)).to.have.length(1)\n expect(Object.keys(createdData.exchangeData.accessControlSecret)).to.have.length(1)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should ignore unverified keys when creating new exchange data', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n const delegateVerifiedKeys = await generateEncryptionKeys(5)\n const extraDelegateUnverifiedKeys = await generateEncryptionKeys(5)\n const extraDelegatorVerifiedKeys = await generateEncryptionKeys(5)\n const delegatorUnverifiedKeys = await generateEncryptionKeys(5)\n await initialiseComponents(allowFullExchangeDataLoad, { verifiedDelegateKeys: new Set(delegateVerifiedKeys.map((x) => x.hexPub)) })\n for (const keyData of [...delegateVerifiedKeys, ...extraDelegateUnverifiedKeys]) {\n await dataOwnerApi.addPublicKeyForOwner(delegateId, keyData.pair)\n }\n for (const keyData of extraDelegatorVerifiedKeys) {\n await dataOwnerApi.addPublicKeyForOwner(selfId, keyData.pair)\n await encryptionKeysManager.addOrUpdateKey(primitives, keyData.pair, true)\n }\n for (const keyData of delegatorUnverifiedKeys) {\n await dataOwnerApi.addPublicKeyForOwner(selfId, keyData.pair)\n await encryptionKeysManager.addOrUpdateKey(primitives, keyData.pair, false)\n }\n const created = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n expect(\n setEquals(new Set(Object.keys(created.exchangeData.exchangeKey)), new Set(Object.keys(created.exchangeData.accessControlSecret))),\n 'Keys used for encryption of exchange key and access control secret must be the same.'\n ).to.be.true\n expect(\n setEquals(\n new Set(Object.keys(created.exchangeData.exchangeKey)),\n new Set([...delegateVerifiedKeys.map((x) => x.fingerprintV2), ...extraDelegatorVerifiedKeys.map((x) => x.fingerprintV2), selfKeyFpV2])\n ),\n 'Only verified keys of delegate and delegator should be used for encryption of exchange key and access control secret.'\n ).to.be.true\n for (const keyData of [{ pair: selfKeypair, fingerprintV2: selfKeyFpV1 }, ...extraDelegatorVerifiedKeys, ...delegateVerifiedKeys]) {\n await checkAesKeysEquality(\n (\n await baseExchangeData.tryDecryptExchangeKeys([created.exchangeData], { [keyData.fingerprintV2]: keyData.pair })\n ).successfulDecryptions[0],\n created.exchangeKey\n )\n expect(\n (await baseExchangeData.tryDecryptAccessControlSecret([created.exchangeData], { [keyData.fingerprintV2]: keyData.pair }))\n .successfulDecryptions[0]\n ).to.equal(created.accessControlSecret)\n }\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should reuse existing exchange data for encryption when it can be verified', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n await exchangeData.clearOrRepopulateCache()\n const countAfterCacheClear = exchangeDataApi.callCount\n const reloadedData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n exchangeDataApi.compareCallCountFromBaseline(countAfterCacheClear, {\n createExchangeData: 0,\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 1,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n await checkDataEqual(reloadedData, createdData)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should create new exchange data for encryption when the existing data can not be verified due to unavailable verification key', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n await encryptionKeysManager.unverifyExistingKeysAndCreateNewVerified(primitives)\n await exchangeData.clearOrRepopulateCache()\n const countAfterCacheClear = exchangeDataApi.callCount\n const newData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n exchangeDataApi.compareCallCountFromBaseline(countAfterCacheClear, {\n createExchangeData: 1,\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 1,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n expect(_.isEqual(_.omit(createdData.exchangeData, ['rev']), _.omit(newData.exchangeData, ['rev']))).to.equal(\n false,\n 'Exchange data manager should have created new exchange data for encryption'\n )\n expect(ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))).to.not.equal(\n ua2hex(await primitives.AES.exportKey(newData.exchangeKey, 'raw'))\n )\n expect(createdData.accessControlSecret).to.not.equal(newData.accessControlSecret)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should create new exchange data for encryption when the existing data can not be verified due to tampering of the encrypted access control secret and/or encrypted exchange key', async function () {\n async function doTest(\n allowFullExchangeDataLoad: boolean,\n tamper: (exchangeData: ExchangeData, selfKeyPair: KeyPair<CryptoKey>, selfKeyFp: string) => Promise<ExchangeData>\n ) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const sfk = primitives.randomUuid()\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n // Tamper with exchange data\n await exchangeDataApi.modifyExchangeData(await tamper(createdData.exchangeData, selfKeypair, selfKeyFpV2))\n await exchangeData.clearOrRepopulateCache()\n const countAfterCacheClear = exchangeDataApi.callCount\n const newData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n exchangeDataApi.compareCallCountFromBaseline(countAfterCacheClear, {\n createExchangeData: 1,\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 1,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n expect(createdData.exchangeData.id).not.to.equal(\n newData.exchangeData.id,\n 'Exchange data manager should have created new exchange data for encryption'\n )\n expect(ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))).to.not.equal(\n ua2hex(await primitives.AES.exportKey(newData.exchangeKey, 'raw'))\n )\n expect(createdData.accessControlSecret).to.not.equal(newData.accessControlSecret)\n const updatedUnverifiedOldData = (await exchangeData.getDecryptionDataKeyByIds([createdData.exchangeData.id!], true))[\n createdData.exchangeData.id!\n ]\n expect(updatedUnverifiedOldData).to.not.be.undefined\n }\n const extraKeyPair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const extraKeyPairFp = fingerprintV2(ua2hex(await primitives.RSA.exportKey(extraKeyPair.publicKey, 'spki')))\n const fakeKey = primitives.randomBytes(16)\n const tamperByChangingEncryptionKey = async (exchangeData: ExchangeData, selfKeyPair: KeyPair<CryptoKey>, selfKeyFp: string) =>\n new ExchangeData({\n ...exchangeData,\n exchangeKey: {\n ...exchangeData.exchangeKey,\n [selfKeyFp]: ua2b64(await primitives.RSA.encrypt(selfKeyPair.publicKey, fakeKey)),\n },\n })\n const tamperByChangingAccessControlSecret = async (exchangeData: ExchangeData, selfKeyPair: KeyPair<CryptoKey>, selfKeyFp: string) =>\n new ExchangeData({\n ...exchangeData,\n accessControlSecret: {\n ...exchangeData.accessControlSecret,\n [selfKeyFp]: ua2b64(await primitives.RSA.encrypt(selfKeyPair.publicKey, fakeKey)),\n },\n })\n const tamperByChangingBoth = async (exchangeData: ExchangeData, selfKeyPair: KeyPair<CryptoKey>, selfKeyFp: string) =>\n tamperByChangingEncryptionKey(await tamperByChangingAccessControlSecret(exchangeData, selfKeyPair, selfKeyFp), selfKeyPair, selfKeyFp)\n const tamperByAddingEncryptionKey = async (exchangeData: ExchangeData) =>\n new ExchangeData({\n ...exchangeData,\n exchangeKey: {\n ...exchangeData.exchangeKey,\n [extraKeyPairFp]: ua2b64(await primitives.RSA.encrypt(extraKeyPair.publicKey, fakeKey)),\n },\n })\n await doTest(true, tamperByChangingEncryptionKey)\n await doTest(false, tamperByChangingEncryptionKey)\n await doTest(true, tamperByChangingAccessControlSecret)\n await doTest(false, tamperByChangingAccessControlSecret)\n await doTest(true, tamperByChangingBoth)\n await doTest(false, tamperByChangingBoth)\n await doTest(true, tamperByAddingEncryptionKey)\n await doTest(false, tamperByAddingEncryptionKey)\n })\n\n it('should create new exchange data for encryption when the existing data can not be verified due to tampering of the delegate id', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n // Tamper with exchange data\n await exchangeDataApi.modifyExchangeData({\n ...createdData.exchangeData,\n delegate: delegate2Id,\n })\n await exchangeData.clearOrRepopulateCache()\n const countAfterCacheClear = exchangeDataApi.callCount\n const newDataToDelegate = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const newDataToDelegate2 = await exchangeData.getOrCreateEncryptionDataTo(delegate2Id, false)\n exchangeDataApi.compareCallCountFromBaseline(countAfterCacheClear, {\n createExchangeData: 2,\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 2,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n expect(createdData.exchangeData.id).to.not.equal(\n newDataToDelegate.exchangeData.id,\n 'Exchange data manager should have created new exchange data for encryption to delegate'\n )\n expect(createdData.exchangeData.id).to.not.equal(\n newDataToDelegate2.exchangeData.id,\n 'Exchange data manager should have created new exchange data for encryption to delegate 2'\n )\n expect(ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))).to.not.equal(\n ua2hex(await primitives.AES.exportKey(newDataToDelegate.exchangeKey, 'raw'))\n )\n expect(ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))).to.not.equal(\n ua2hex(await primitives.AES.exportKey(newDataToDelegate2.exchangeKey, 'raw'))\n )\n expect(createdData.accessControlSecret).to.not.equal(newDataToDelegate.accessControlSecret)\n expect(createdData.accessControlSecret).to.not.equal(newDataToDelegate2.accessControlSecret)\n const updatedUnverifiedOldData = (await exchangeData.getDecryptionDataKeyByIds([createdData.exchangeData.id!], true))[\n createdData.exchangeData.id!\n ]\n expect(updatedUnverifiedOldData).to.not.be.undefined\n expect(ua2hex(await primitives.AES.exportKey(updatedUnverifiedOldData!.exchangeKey!, 'raw'))).to.equal(\n ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))\n )\n expect(updatedUnverifiedOldData!.accessControlSecret).to.equal(createdData.accessControlSecret)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should return existing exchange data keys for decryption even if the data authenticity could not be verified', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData1 = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const createdData2 = await createDataFromRandomToSelf()\n await encryptionKeysManager.unverifyExistingKeysAndCreateNewVerified(primitives)\n await exchangeData.clearOrRepopulateCache()\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdData1.exchangeData.id!], true)\n )[createdData1.exchangeData.id!],\n createdData1\n )\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdData2.exchangeData.id!], true)\n )[createdData2.exchangeData.id!],\n createdData2\n )\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('newly created data or data retrieved by id should be cached and retrievable by hash', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData1 = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const hashes1 = await accessControlSecretUtils.allSecureDelegationKeysFor(createdData1.accessControlSecret)\n const retrievedKeys1 = await exchangeData.getCachedDecryptionDataKeyByAccessControlHash(hashes1)\n for (const hash of hashes1) {\n await checkDataEqual(retrievedKeys1[hash], createdData1)\n }\n if (!allowFullExchangeDataLoad) {\n const createdData2 = await createDataFromRandomToSelf()\n const hashes2 = await accessControlSecretUtils.allSecureDelegationKeysFor(createdData2.accessControlSecret)\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdData2.exchangeData.id!], true)\n )[createdData2.exchangeData.id!],\n createdData2\n )\n const retrievedKeys2 = await exchangeData.getCachedDecryptionDataKeyByAccessControlHash([...hashes1, ...hashes2])\n for (const hash of hashes2) {\n await checkDataEqual(retrievedKeys2[hash], createdData2)\n }\n }\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('if data can not be decrypted the retrieval method should return undefined', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdBySelf = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n const createdByOther = await createDataFromRandomToSelf()\n const newKey = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n await dataOwnerApi.addPublicKeyForOwner(selfId, newKey)\n // Simulate loss of key\n encryptionKeysManager.deleteKey(selfKeyFpV1)\n await encryptionKeysManager.addOrUpdateKey(primitives, newKey, true)\n await exchangeData.clearOrRepopulateCache()\n await checkDataEqual((await exchangeData.getDecryptionDataKeyByIds([createdBySelf.exchangeData.id!], true))[createdBySelf.exchangeData.id!], {\n exchangeData: createdBySelf.exchangeData,\n exchangeKey: undefined,\n })\n await checkDataEqual((await exchangeData.getDecryptionDataKeyByIds([createdByOther.exchangeData.id!], true))[createdByOther.exchangeData.id!], {\n exchangeData: createdByOther.exchangeData,\n exchangeKey: undefined,\n })\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('unverified keys should still be usable for decryption of data', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdBySelf = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n const createdByOther = await createDataFromRandomToSelf()\n await encryptionKeysManager.addOrUpdateKey(primitives, selfKeypair, false)\n await exchangeData.clearOrRepopulateCache()\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdBySelf.exchangeData.id!], true)\n )[createdBySelf.exchangeData.id!],\n createdBySelf\n )\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdByOther.exchangeData.id!], true)\n )[createdByOther.exchangeData.id!],\n createdByOther\n )\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('implementation with limited cache should trigger eviction of delegate and hash cache on eviction of data by id cache', async function () {\n await initialiseComponents(false, { lruCacheSize: 3 })\n const entityType = EntityWithDelegationTypeName.Contact\n const sfks = [primitives.randomUuid(), primitives.randomUuid(), primitives.randomUuid()]\n\n async function verifyCached(data: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }) {\n const apiCallsBaseline = exchangeDataApi.callCount\n const hashes = await accessControlSecretUtils.allSecureDelegationKeysFor(data.accessControlSecret)\n for (const hash of hashes) {\n await checkDataEqual((await exchangeData.getCachedDecryptionDataKeyByAccessControlHash([hash]))[hash], data)\n }\n if (data.exchangeData.delegator === selfId) {\n await checkDataEqual(await exchangeData.getOrCreateEncryptionDataTo(data.exchangeData.delegate, false), data)\n }\n await checkDataEqual((await exchangeData.getDecryptionDataKeyByIds([data.exchangeData.id!], true))[data.exchangeData.id!], data)\n exchangeDataApi.compareCallCountFromBaseline(apiCallsBaseline, {\n getExchangeDataByIds: 0,\n createExchangeData: 0,\n modifyExchangeData: 0,\n getExchangeDataByParticipant: 0,\n getExchangeDataByDelegatorDelegate: 0,\n })\n }\n\n async function verifyNotCachedThenCache(data: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }) {\n const apiCallsBaseline = exchangeDataApi.callCount\n const hashes = [await accessControlSecretUtils.secureDelegationKeyFor(data.accessControlSecret, entityType)]\n for (const hash of hashes) {\n expect(Object.keys(await exchangeData.getCachedDecryptionDataKeyByAccessControlHash([hash]))).to.have.length(0)\n }\n if (data.exchangeData.delegator === selfId) {\n await checkDataEqual(await exchangeData.getOrCreateEncryptionDataTo(data.exchangeData.delegate, false), data)\n exchangeDataApi.compareCallCountFromBaseline(apiCallsBaseline, {\n getExchangeDataByIds: 0,\n createExchangeData: 0,\n modifyExchangeData: 0,\n getExchangeDataByParticipant: 0,\n getExchangeDataByDelegatorDelegate: 1,\n })\n } else {\n await checkDataEqual((await exchangeData.getDecryptionDataKeyByIds([data.exchangeData.id!], true))[data.exchangeData.id!], data)\n exchangeDataApi.compareCallCountFromBaseline(apiCallsBaseline, {\n getExchangeDataByIds: 1,\n createExchangeData: 0,\n modifyExchangeData: 0,\n getExchangeDataByParticipant: 0,\n getExchangeDataByDelegatorDelegate: 0,\n })\n }\n }\n\n const createdBySelf1 = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n const createdBySelf2 = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const createdByOther1 = await createDataFromRandomToSelf() // Not automatically cached: created by someone else\n const createdByOther2 = await createDataFromRandomToSelf() // Not automatically cached: created by someone else\n // noinspection DuplicatedCode\n await verifyCached(createdBySelf1)\n await verifyCached(createdBySelf2)\n await verifyNotCachedThenCache(createdByOther1)\n await verifyCached(createdBySelf1)\n await verifyCached(createdBySelf2)\n await verifyCached(createdByOther1)\n await verifyNotCachedThenCache(createdByOther2)\n await verifyCached(createdBySelf2)\n await verifyCached(createdByOther1)\n await verifyCached(createdByOther2)\n await verifyNotCachedThenCache(createdBySelf1)\n await verifyCached(createdByOther1)\n await verifyCached(createdByOther2)\n await verifyCached(createdBySelf1)\n await verifyNotCachedThenCache(createdBySelf2)\n await verifyCached(createdByOther2)\n // noinspection DuplicatedCode\n await verifyCached(createdBySelf1)\n await verifyCached(createdBySelf2)\n await verifyNotCachedThenCache(createdByOther1)\n await verifyCached(createdBySelf1)\n await verifyCached(createdBySelf2)\n await verifyCached(createdByOther1)\n await verifyNotCachedThenCache(createdByOther2)\n await verifyCached(createdBySelf2)\n await verifyCached(createdByOther1)\n await verifyCached(createdByOther2)\n })\n\n it('implementation with unlimited cache should preload all existing exchange data on creation', async function () {\n await initialiseComponents(true)\n const createdBySelf = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n const createdByOther = await createDataFromRandomToSelf()\n const recreatedExchangeData = await initialiseExchangeDataManagerForCurrentDataOwner(\n baseExchangeData,\n encryptionKeysManager,\n accessControlSecretUtils,\n new TestCryptoStrategies(),\n dataOwnerApi,\n primitives,\n true\n )\n const apiCallsAfterCreation = exchangeDataApi.callCount\n await checkDataEqual(\n (\n await recreatedExchangeData.getDecryptionDataKeyByIds([createdBySelf.exchangeData.id!], false)\n )[createdBySelf.exchangeData.id!],\n createdBySelf\n )\n await checkDataEqual(\n (\n await recreatedExchangeData.getDecryptionDataKeyByIds([createdByOther.exchangeData.id!], false)\n )[createdByOther.exchangeData.id!],\n createdByOther\n )\n exchangeDataApi.compareCallCountFromBaseline(apiCallsAfterCreation, {\n getExchangeDataByIds: 0,\n createExchangeData: 0,\n modifyExchangeData: 0,\n getExchangeDataByParticipant: 0,\n getExchangeDataByDelegatorDelegate: 0,\n })\n })\n})\n\nlet env: TestVars\n\ndescribe('Exchange data manager - e2e', async function () {\n before(async function () {\n this.timeout(600000)\n const initializer = await getEnvironmentInitializer()\n env = await initializer.execute(getEnvVariables())\n })\n\n it('give access back should not invalidate existing and valid exchange data', async function () {\n const hcp1Details = await createNewHcpApi(env)\n const hcp2Details = await createNewHcpApi(env)\n const ed1to2 = await hcp1Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp2Details.credentials.dataOwnerId, false)\n const ed2to1 = await hcp2Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp1Details.credentials.dataOwnerId, false)\n await hcp1Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n await hcp2Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n const newKeyPair = await hcp1Details.api.cryptoApi.primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const exportedPub = ua2hex(await hcp1Details.api.cryptoApi.primitives.RSA.exportKey(newKeyPair.publicKey, 'spki'))\n const hcp2 = await hcp2Details.api.healthcarePartyApi.getHealthcareParty(hcp2Details.credentials.dataOwnerId)\n await hcp2Details.api.healthcarePartyApi.modifyHealthcareParty({\n ...hcp2,\n publicKeysForOaepWithSha256: [...hcp2.publicKeysForOaepWithSha256, exportedPub],\n })\n await hcp1Details.api.cryptoApi.exchangeData.giveAccessBackTo(hcp2Details.credentials.dataOwnerId, exportedPub)\n await hcp1Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n await hcp2Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n const updatedEd1to2 = await hcp1Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp2Details.credentials.dataOwnerId, false)\n const updatedEd2to1 = await hcp2Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp1Details.credentials.dataOwnerId, false)\n expect(updatedEd1to2.exchangeData.id).to.equal(ed1to2.exchangeData.id)\n expect(Object.keys(updatedEd2to1.exchangeData.exchangeKey).length).to.be.greaterThan(Object.keys(ed2to1.exchangeData.exchangeKey).length)\n expect(Object.keys(updatedEd2to1.exchangeData.exchangeKey).length).to.equal(Object.keys(updatedEd2to1.exchangeData.accessControlSecret).length)\n expect(Object.keys(updatedEd2to1.exchangeData.exchangeKey).length).to.equal(Object.keys(updatedEd2to1.exchangeData.sharedSignatureKey).length)\n expect(updatedEd2to1.exchangeData.id).to.equal(ed2to1.exchangeData.id)\n expect(Object.keys(updatedEd1to2.exchangeData.exchangeKey).length).to.be.greaterThan(Object.keys(ed1to2.exchangeData.exchangeKey).length)\n expect(Object.keys(updatedEd1to2.exchangeData.exchangeKey).length).to.equal(Object.keys(updatedEd1to2.exchangeData.accessControlSecret).length)\n expect(Object.keys(updatedEd1to2.exchangeData.exchangeKey).length).to.equal(Object.keys(updatedEd1to2.exchangeData.sharedSignatureKey).length)\n })\n\n it('invalid exchange data should not be re-validated by give access back', async function () {\n const hcp1Details = await createNewHcpApi(env)\n const hcp2Details = await createNewHcpApi(env)\n const ed1to2 = await hcp1Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp2Details.credentials.dataOwnerId, false)\n const ed2to1 = await hcp2Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp1Details.credentials.dataOwnerId, false)\n await hcp1Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n await hcp2Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n const exchangeDataApi = new IccExchangeDataApi(env.iCureUrl, {}, hcp1Details.api.authApi.authenticationProvider, fetch)\n const extraKeyPair = await hcp1Details.api.cryptoApi.primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const extraKeyPairPub = ua2hex(await hcp1Details.api.cryptoApi.primitives.RSA.exportKey(extraKeyPair.publicKey, 'spki'))\n const extraKeyPairFp = fingerprintV2(extraKeyPairPub)\n const fakeData = await hcp1Details.api.cryptoApi.primitives.randomBytes(16)\n async function tamperWithData(data: ExchangeData) {\n await exchangeDataApi.modifyExchangeData({\n ...data,\n exchangeKey: {\n ...data.exchangeKey,\n [extraKeyPairFp]: ua2b64(await hcp1Details.api.cryptoApi.primitives.RSA.encrypt(extraKeyPair.publicKey, fakeData)),\n },\n accessControlSecret: {\n ...data.accessControlSecret,\n [extraKeyPairFp]: ua2b64(await hcp1Details.api.cryptoApi.primitives.RSA.encrypt(extraKeyPair.publicKey, fakeData)),\n },\n sharedSignatureKey: {\n ...data.sharedSignatureKey,\n [extraKeyPairFp]: ua2b64(await hcp1Details.api.cryptoApi.primitives.RSA.encrypt(extraKeyPair.publicKey, fakeData)),\n },\n })\n }\n await tamperWithData(ed1to2.exchangeData)\n await tamperWithData(ed2to1.exchangeData)\n const newKeyPair = await hcp1Details.api.cryptoApi.primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const exportedPub = ua2hex(await hcp1Details.api.cryptoApi.primitives.RSA.exportKey(newKeyPair.publicKey, 'spki'))\n const hcp2 = await hcp2Details.api.healthcarePartyApi.getHealthcareParty(hcp2Details.credentials.dataOwnerId)\n await hcp2Details.api.healthcarePartyApi.modifyHealthcareParty({\n ...hcp2,\n publicKeysForOaepWithSha256: [...hcp2.publicKeysForOaepWithSha256, exportedPub, extraKeyPairPub],\n })\n await hcp1Details.api.cryptoApi.exchangeData.giveAccessBackTo(hcp2Details.credentials.dataOwnerId, exportedPub)\n await hcp1Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n await hcp2Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n const updatedEd1to2 = await hcp1Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp2Details.credentials.dataOwnerId, false)\n const updatedEd2to1 = await hcp2Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp1Details.credentials.dataOwnerId, false)\n expect(updatedEd1to2.exchangeData.id).to.not.equal(ed1to2.exchangeData.id)\n expect(updatedEd2to1.exchangeData.id).to.not.equal(ed2to1.exchangeData.id)\n const decData1to2 = (await hcp1Details.api.cryptoApi.exchangeData.getDecryptionDataKeyByIds([ed1to2.exchangeData.id!], true))[\n ed1to2.exchangeData.id!\n ]\n expect(decData1to2).to.not.be.undefined\n expect(decData1to2!.exchangeKey).to.not.be.undefined\n expect(decData1to2!.accessControlSecret).to.not.be.undefined\n const decData2to1 = (await hcp2Details.api.cryptoApi.exchangeData.getDecryptionDataKeyByIds([ed2to1.exchangeData.id!], true))[\n ed2to1.exchangeData.id!\n ]\n expect(decData2to1).to.not.be.undefined\n expect(decData2to1!.exchangeKey).to.not.be.undefined\n expect(decData2to1!.accessControlSecret).to.not.be.undefined\n })\n})\n"]}
1
+ {"version":3,"file":"exchange-data-manager-test.js","sourceRoot":"","sources":["../../../../test/icc-x-api/crypto/exchange-data-manager-test.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,iCAAgC;AAChC,uFAIsD;AACtD,iFAAgF;AAChF,mCAAkC;AAClC,+FAA2F;AAC3F,yEAAqE;AACrE,mEAA+D;AAC/D,2EAAuE;AACvE,kDAA6F;AAC7F,qFAAiF;AACjF,iGAA6F;AAC7F,+EAA2E;AAC3E,+BAA6B;AAC7B,gFAAqE;AAErE,4BAA2B;AAC3B,2DAAiG;AACjG,gFAA4E;AAC5E,mDAAmE;AACnE,uDAAoG;AACpG,4BAAyB;AACzB,yFAAqF;AAErF,IAAA,4BAAe,EAAC,KAAK,CAAC,CAAA;AAEtB,IAAA,gBAAQ,EAAC,8BAA8B,EAAE;;QACvC,MAAM,UAAU,GAAG,IAAI,sCAAmB,CAAC,kBAAgB,CAAC,CAAA;QAC5D,MAAM,wBAAwB,GAAG,IAAI,mDAAwB,CAAC,UAAU,CAAC,CAAA;QACzE,IAAI,MAAc,CAAA;QAClB,IAAI,WAAmB,CAAA;QACvB,IAAI,WAAmB,CAAA;QACvB,IAAI,WAA+B,CAAA;QACnC,IAAI,UAAkB,CAAA;QACtB,IAA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AAC,MAAM,CAAC,YAAY,CAAC,EAAG,CAAC,EAAE,IAAI,CAAC,CAAC,CAC3H,MAAM,CAAC,YAAY,CAAC,EAAG,CACxB,CAAA;gBACD,IAAA,aAAM,EAAC,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAA;gBACvC,IAAA,aAAM,EAAC,WAAY,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAA;gBACpD,IAAA,aAAM,EAAC,WAAY,CAAC,mBAAmB,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAA;YAC9D,CAAC;SAAA,CAAC,CAAA;IACJ,CAAC;CAAA,CAAC,CAAA","sourcesContent":["import { describe } from 'mocha'\nimport {\n ExchangeDataManager,\n ExchangeDataManagerOptionalParameters,\n initialiseExchangeDataManagerForCurrentDataOwner,\n} from '../../../icc-x-api/crypto/ExchangeDataManager'\nimport { WebCryptoPrimitives } from '../../../icc-x-api/crypto/CryptoPrimitives'\nimport { webcrypto } from 'crypto'\nimport { BaseExchangeDataManager } from '../../../icc-x-api/crypto/BaseExchangeDataManager'\nimport { FakeExchangeDataApi } from '../../utils/FakeExchangeDataApi'\nimport { FakeDataOwnerApi } from '../../utils/FakeDataOwnerApi'\nimport { TestCryptoStrategies } from '../../utils/TestCryptoStrategies'\nimport { EntityWithDelegationTypeName, ShaVersion, ua2b64, ua2hex } from '../../../icc-x-api'\nimport { FakeEncryptionKeysManager } from '../../utils/FakeEncryptionKeysManager'\nimport { AccessControlSecretUtils } from '../../../icc-x-api/crypto/AccessControlSecretUtils'\nimport { ExchangeData } from '../../../icc-api/model/internal/ExchangeData'\nimport { expect } from 'chai'\nimport { setEquals } from '../../../icc-x-api/utils/collection-utils'\nimport { KeyPair } from '../../../icc-x-api/crypto/RSA'\nimport * as _ from 'lodash'\nimport { fingerprintV1, fingerprintV1toV2, fingerprintV2 } from '../../../icc-x-api/crypto/utils'\nimport { DataOwnerTypeEnum } from '../../../icc-api/model/DataOwnerTypeEnum'\nimport { getEnvVariables, TestVars } from '@icure/test-setup/types'\nimport { createNewHcpApi, getEnvironmentInitializer, setLocalStorage } from '../../utils/test_utils'\nimport 'isomorphic-fetch'\nimport { IccExchangeDataApi } from '../../../icc-api/api/internal/IccExchangeDataApi'\n\nsetLocalStorage(fetch)\n\ndescribe('Exchange data manager - unit', async function () {\n const primitives = new WebCryptoPrimitives(webcrypto as any)\n const accessControlSecretUtils = new AccessControlSecretUtils(primitives)\n let selfId: string\n let selfKeyFpV1: string\n let selfKeyFpV2: string\n let selfKeypair: KeyPair<CryptoKey>\n let delegateId: string\n let delegateKeyFp: string\n let delegateKeypair: KeyPair<CryptoKey>\n let delegate2Id: string\n let delegate2KeyFp: string\n let delegate2Keypair: KeyPair<CryptoKey>\n let dataOwnerApi: FakeDataOwnerApi\n let exchangeDataApi: FakeExchangeDataApi\n let baseExchangeData: BaseExchangeDataManager\n let exchangeData: ExchangeDataManager\n let encryptionKeysManager: FakeEncryptionKeysManager\n\n async function initialiseComponents(\n allowFullExchangeDataLoad: boolean,\n optionalParameters: ExchangeDataManagerOptionalParameters & { verifiedDelegateKeys?: Set<string> } = {}\n ) {\n const dataOwnerType = allowFullExchangeDataLoad ? DataOwnerTypeEnum.Patient : DataOwnerTypeEnum.Hcp\n selfId = primitives.randomUuid()\n selfKeypair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n selfKeyFpV1 = fingerprintV1(ua2hex(await primitives.RSA.exportKey(selfKeypair.publicKey, 'spki')))\n selfKeyFpV2 = fingerprintV1toV2(selfKeyFpV1)\n delegateId = primitives.randomUuid()\n delegateKeypair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n delegateKeyFp = fingerprintV1(ua2hex(await primitives.RSA.exportKey(delegateKeypair.publicKey, 'spki')))\n delegate2Id = primitives.randomUuid()\n delegate2Keypair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n delegate2KeyFp = fingerprintV1(ua2hex(await primitives.RSA.exportKey(delegate2Keypair.publicKey, 'spki')))\n dataOwnerApi = new FakeDataOwnerApi(\n {\n id: selfId,\n type: dataOwnerType,\n publicKeysForOaepWithSha256: [ua2hex(await primitives.RSA.exportKey(selfKeypair.publicKey, 'spki'))],\n },\n [\n {\n id: delegateId,\n type: dataOwnerType,\n publicKeysForOaepWithSha256: [ua2hex(await primitives.RSA.exportKey(delegateKeypair.publicKey, 'spki'))],\n },\n {\n id: delegate2Id,\n type: dataOwnerType,\n publicKeysForOaepWithSha256: [ua2hex(await primitives.RSA.exportKey(delegate2Keypair.publicKey, 'spki'))],\n },\n ]\n )\n const cryptoStrategies = new TestCryptoStrategies(undefined, undefined, optionalParameters.verifiedDelegateKeys)\n exchangeDataApi = new FakeExchangeDataApi()\n baseExchangeData = new BaseExchangeDataManager(exchangeDataApi, dataOwnerApi, primitives, allowFullExchangeDataLoad, false)\n encryptionKeysManager = await FakeEncryptionKeysManager.create(primitives, [selfKeypair])\n exchangeData = await initialiseExchangeDataManagerForCurrentDataOwner(\n baseExchangeData,\n encryptionKeysManager,\n accessControlSecretUtils,\n cryptoStrategies,\n dataOwnerApi,\n primitives,\n true,\n optionalParameters\n )\n }\n\n async function checkDataEqual(\n actual: { exchangeData: ExchangeData; accessControlSecret?: string; exchangeKey: CryptoKey | undefined } | undefined,\n expected: { exchangeData: ExchangeData; accessControlSecret?: string; exchangeKey: CryptoKey | undefined }\n ) {\n expect(actual).to.not.be.undefined\n expect(_.isEqual(_.omit(expected.exchangeData, ['rev']), _.omit(actual!.exchangeData, ['rev']))).to.equal(\n true,\n `Data should be equivalent\\nExpected: ${JSON.stringify(expected.exchangeData, undefined, 2)}\\nActual: ${JSON.stringify(\n actual!.exchangeData,\n undefined,\n 2\n )}\\n`\n )\n expect(expected.accessControlSecret).to.equal(actual!.accessControlSecret)\n await checkAesKeysEquality(actual!.exchangeKey, expected.exchangeKey)\n }\n\n async function checkAesKeysEquality(actual: CryptoKey | undefined, expected: CryptoKey | undefined) {\n if (!actual && !expected) return\n expect(!actual).to.equal(!expected, !expected ? 'Key should not have been decrypted' : 'Key should have been decrypted')\n expect(ua2hex(await primitives.AES.exportKey(expected!, 'raw'))).to.equal(ua2hex(await primitives.AES.exportKey(actual!, 'raw')))\n }\n\n async function createDataFromRandomToSelf(): Promise<{ exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string }> {\n const encryptionKey = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const encryptionFp = ua2hex(await primitives.RSA.exportKey(encryptionKey.publicKey, 'spki')).slice(-32)\n const signatureKey = await primitives.RSA.generateKeyPair(ShaVersion.Sha1)\n const signatureFp = ua2hex(await primitives.RSA.exportKey(signatureKey.publicKey, 'spki')).slice(-32)\n const created = await baseExchangeData.createExchangeData(\n selfId,\n { [signatureFp]: signatureKey.privateKey },\n { [encryptionFp]: encryptionKey.publicKey, [selfKeyFpV1]: selfKeypair.publicKey }\n )\n const modified = await exchangeDataApi.modifyExchangeData(\n new ExchangeData({\n ...created.exchangeData,\n delegator: primitives.randomUuid(),\n })\n )\n return { exchangeData: modified, exchangeKey: created.exchangeKey, accessControlSecret: created.accessControlSecret }\n }\n\n async function generateEncryptionKeys(n: number): Promise<{ pair: KeyPair<CryptoKey>; fingerprintV2: string; hexPub: string }[]> {\n return await Promise.all(\n Array(n)\n .fill(null)\n .map(async () => {\n const pair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const hexPub = ua2hex(await primitives.RSA.exportKey(pair.publicKey, 'spki'))\n const fingerprint = fingerprintV2(hexPub)\n return { pair, fingerprintV2: fingerprint, hexPub }\n })\n )\n }\n\n it('base should be able to retrieve all exchange data for the current data owner if allowed by the crypto strategies', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const expectedData = await Promise.all(\n Array.from(Array(3500), async (_, i) => {\n const data = new ExchangeData({\n id: primitives.randomUuid(),\n delegate: i % 2 === 0 ? selfId : primitives.randomUuid(),\n delegator: i % 2 === 0 ? primitives.randomUuid() : selfId,\n exchangeKey: { not: 'important' },\n accessControlSecret: { not: 'important' },\n sharedSignatureKey: { not: 'important' },\n delegatorSignature: { not: 'important' },\n sharedSignature: 'not important',\n })\n await exchangeDataApi.createExchangeData(data)\n return data\n })\n )\n await Promise.all(\n Array.from(Array(500), async () => {\n // Should not be in result\n const data = new ExchangeData({\n id: primitives.randomUuid(),\n delegate: primitives.randomUuid(),\n delegator: primitives.randomUuid(),\n exchangeKey: { not: 'important' },\n accessControlSecret: { not: 'important' },\n sharedSignatureKey: { not: 'important' },\n delegatorSignature: { not: 'important' },\n sharedSignature: 'not important',\n })\n await exchangeDataApi.createExchangeData(data)\n })\n )\n const retrieved = await baseExchangeData.getAllExchangeDataForCurrentDataOwnerIfAllowed()\n if (allowFullExchangeDataLoad) {\n expect(retrieved).to.not.be.undefined\n expect(retrieved).to.have.length(expectedData.length)\n expect(setEquals(new Set(expectedData.map((x) => x.id)), new Set(retrieved!.map((x) => x.id))), 'Retrieved and expected ids').to.be.true\n } else {\n expect(retrieved).to.be.undefined\n }\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should create new encryption keys when none is available', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const sfk = primitives.randomUuid()\n const initialisedCount = exchangeDataApi.callCount\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const retrievedCachedData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n exchangeDataApi.compareCallCountFromBaseline(initialisedCount, {\n createExchangeData: 1,\n // If we could fully preload we already know whether the exchange key already exists or not, otherwise we have to request from the api\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 1,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n await checkDataEqual(retrievedCachedData, createdData)\n const decryptedKeyByDelegate = await baseExchangeData.tryDecryptExchangeKeys([createdData.exchangeData], { [delegateKeyFp]: delegateKeypair })\n const decryptedAccessControlSecretByDelegate = await baseExchangeData.tryDecryptAccessControlSecret([createdData.exchangeData], {\n [delegateKeyFp]: delegateKeypair,\n })\n await checkAesKeysEquality(decryptedKeyByDelegate.successfulDecryptions[0], createdData.exchangeKey)\n expect(decryptedAccessControlSecretByDelegate.successfulDecryptions[0]).to.equal(createdData.accessControlSecret)\n expect(retrievedCachedData.exchangeData.delegator).to.equal(selfId)\n expect(retrievedCachedData.exchangeData.delegate).to.equal(delegateId)\n expect(Object.keys(retrievedCachedData.exchangeData.delegatorSignature ?? {})).to.have.length(1)\n expect(Object.keys(retrievedCachedData.exchangeData.exchangeKey)).to.have.length(2)\n expect(Object.keys(retrievedCachedData.exchangeData.accessControlSecret)).to.have.length(2)\n expect(Object.keys(retrievedCachedData.exchangeData.sharedSignatureKey)).to.have.length(2)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should create encryption keys to self when none is available', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n expect(createdData.exchangeData.delegator).to.equal(selfId)\n expect(createdData.exchangeData.delegate).to.equal(selfId)\n expect(Object.keys(createdData.exchangeData.delegatorSignature ?? {})).to.have.length(1)\n expect(Object.keys(createdData.exchangeData.sharedSignatureKey)).to.have.length(1)\n expect(Object.keys(createdData.exchangeData.exchangeKey)).to.have.length(1)\n expect(Object.keys(createdData.exchangeData.accessControlSecret)).to.have.length(1)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should ignore unverified keys when creating new exchange data', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n const delegateVerifiedKeys = await generateEncryptionKeys(5)\n const extraDelegateUnverifiedKeys = await generateEncryptionKeys(5)\n const extraDelegatorVerifiedKeys = await generateEncryptionKeys(5)\n const delegatorUnverifiedKeys = await generateEncryptionKeys(5)\n await initialiseComponents(allowFullExchangeDataLoad, { verifiedDelegateKeys: new Set(delegateVerifiedKeys.map((x) => x.hexPub)) })\n for (const keyData of [...delegateVerifiedKeys, ...extraDelegateUnverifiedKeys]) {\n await dataOwnerApi.addPublicKeyForOwner(delegateId, keyData.pair)\n }\n for (const keyData of extraDelegatorVerifiedKeys) {\n await dataOwnerApi.addPublicKeyForOwner(selfId, keyData.pair)\n await encryptionKeysManager.addOrUpdateKey(primitives, keyData.pair, true)\n }\n for (const keyData of delegatorUnverifiedKeys) {\n await dataOwnerApi.addPublicKeyForOwner(selfId, keyData.pair)\n await encryptionKeysManager.addOrUpdateKey(primitives, keyData.pair, false)\n }\n const created = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n expect(\n setEquals(new Set(Object.keys(created.exchangeData.exchangeKey)), new Set(Object.keys(created.exchangeData.accessControlSecret))),\n 'Keys used for encryption of exchange key and access control secret must be the same.'\n ).to.be.true\n expect(\n setEquals(\n new Set(Object.keys(created.exchangeData.exchangeKey)),\n new Set([...delegateVerifiedKeys.map((x) => x.fingerprintV2), ...extraDelegatorVerifiedKeys.map((x) => x.fingerprintV2), selfKeyFpV2])\n ),\n 'Only verified keys of delegate and delegator should be used for encryption of exchange key and access control secret.'\n ).to.be.true\n for (const keyData of [{ pair: selfKeypair, fingerprintV2: selfKeyFpV1 }, ...extraDelegatorVerifiedKeys, ...delegateVerifiedKeys]) {\n await checkAesKeysEquality(\n (\n await baseExchangeData.tryDecryptExchangeKeys([created.exchangeData], { [keyData.fingerprintV2]: keyData.pair })\n ).successfulDecryptions[0],\n created.exchangeKey\n )\n expect(\n (await baseExchangeData.tryDecryptAccessControlSecret([created.exchangeData], { [keyData.fingerprintV2]: keyData.pair }))\n .successfulDecryptions[0]\n ).to.equal(created.accessControlSecret)\n }\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should reuse existing exchange data for encryption when it can be verified', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n await exchangeData.clearOrRepopulateCache()\n const countAfterCacheClear = exchangeDataApi.callCount\n const reloadedData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n exchangeDataApi.compareCallCountFromBaseline(countAfterCacheClear, {\n createExchangeData: 0,\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 1,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n await checkDataEqual(reloadedData, createdData)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should create new exchange data for encryption when the existing data can not be verified due to unavailable verification key', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n await encryptionKeysManager.unverifyExistingKeysAndCreateNewVerified(primitives)\n await exchangeData.clearOrRepopulateCache()\n const countAfterCacheClear = exchangeDataApi.callCount\n const newData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n exchangeDataApi.compareCallCountFromBaseline(countAfterCacheClear, {\n createExchangeData: 1,\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 1,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n expect(_.isEqual(_.omit(createdData.exchangeData, ['rev']), _.omit(newData.exchangeData, ['rev']))).to.equal(\n false,\n 'Exchange data manager should have created new exchange data for encryption'\n )\n expect(ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))).to.not.equal(\n ua2hex(await primitives.AES.exportKey(newData.exchangeKey, 'raw'))\n )\n expect(createdData.accessControlSecret).to.not.equal(newData.accessControlSecret)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should create new exchange data for encryption when the existing data can not be verified due to tampering of the encrypted access control secret and/or encrypted exchange key', async function () {\n async function doTest(\n allowFullExchangeDataLoad: boolean,\n tamper: (exchangeData: ExchangeData, selfKeyPair: KeyPair<CryptoKey>, selfKeyFp: string) => Promise<ExchangeData>\n ) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const sfk = primitives.randomUuid()\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n // Tamper with exchange data\n await exchangeDataApi.modifyExchangeData(await tamper(createdData.exchangeData, selfKeypair, selfKeyFpV2))\n await exchangeData.clearOrRepopulateCache()\n const countAfterCacheClear = exchangeDataApi.callCount\n const newData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n exchangeDataApi.compareCallCountFromBaseline(countAfterCacheClear, {\n createExchangeData: 1,\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 1,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n expect(createdData.exchangeData.id).not.to.equal(\n newData.exchangeData.id,\n 'Exchange data manager should have created new exchange data for encryption'\n )\n expect(ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))).to.not.equal(\n ua2hex(await primitives.AES.exportKey(newData.exchangeKey, 'raw'))\n )\n expect(createdData.accessControlSecret).to.not.equal(newData.accessControlSecret)\n const updatedUnverifiedOldData = (await exchangeData.getDecryptionDataKeyByIds([createdData.exchangeData.id!], true))[\n createdData.exchangeData.id!\n ]\n expect(updatedUnverifiedOldData).to.not.be.undefined\n }\n const extraKeyPair = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const extraKeyPairFp = fingerprintV2(ua2hex(await primitives.RSA.exportKey(extraKeyPair.publicKey, 'spki')))\n const fakeKey = primitives.randomBytes(16)\n const tamperByChangingEncryptionKey = async (exchangeData: ExchangeData, selfKeyPair: KeyPair<CryptoKey>, selfKeyFp: string) =>\n new ExchangeData({\n ...exchangeData,\n exchangeKey: {\n ...exchangeData.exchangeKey,\n [selfKeyFp]: ua2b64(await primitives.RSA.encrypt(selfKeyPair.publicKey, fakeKey)),\n },\n })\n const tamperByChangingAccessControlSecret = async (exchangeData: ExchangeData, selfKeyPair: KeyPair<CryptoKey>, selfKeyFp: string) =>\n new ExchangeData({\n ...exchangeData,\n accessControlSecret: {\n ...exchangeData.accessControlSecret,\n [selfKeyFp]: ua2b64(await primitives.RSA.encrypt(selfKeyPair.publicKey, fakeKey)),\n },\n })\n const tamperByChangingBoth = async (exchangeData: ExchangeData, selfKeyPair: KeyPair<CryptoKey>, selfKeyFp: string) =>\n tamperByChangingEncryptionKey(await tamperByChangingAccessControlSecret(exchangeData, selfKeyPair, selfKeyFp), selfKeyPair, selfKeyFp)\n const tamperByAddingEncryptionKey = async (exchangeData: ExchangeData) =>\n new ExchangeData({\n ...exchangeData,\n exchangeKey: {\n ...exchangeData.exchangeKey,\n [extraKeyPairFp]: ua2b64(await primitives.RSA.encrypt(extraKeyPair.publicKey, fakeKey)),\n },\n })\n await doTest(true, tamperByChangingEncryptionKey)\n await doTest(false, tamperByChangingEncryptionKey)\n await doTest(true, tamperByChangingAccessControlSecret)\n await doTest(false, tamperByChangingAccessControlSecret)\n await doTest(true, tamperByChangingBoth)\n await doTest(false, tamperByChangingBoth)\n await doTest(true, tamperByAddingEncryptionKey)\n await doTest(false, tamperByAddingEncryptionKey)\n })\n\n it('should create new exchange data for encryption when the existing data can not be verified due to tampering of the delegate id', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n // Tamper with exchange data\n await exchangeDataApi.modifyExchangeData({\n ...createdData.exchangeData,\n delegate: delegate2Id,\n })\n await exchangeData.clearOrRepopulateCache()\n const countAfterCacheClear = exchangeDataApi.callCount\n const newDataToDelegate = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const newDataToDelegate2 = await exchangeData.getOrCreateEncryptionDataTo(delegate2Id, false)\n exchangeDataApi.compareCallCountFromBaseline(countAfterCacheClear, {\n createExchangeData: 2,\n getExchangeDataByDelegatorDelegate: allowFullExchangeDataLoad ? 0 : 2,\n modifyExchangeData: 0,\n getExchangeDataByIds: 0,\n getExchangeDataByParticipant: 0,\n })\n expect(createdData.exchangeData.id).to.not.equal(\n newDataToDelegate.exchangeData.id,\n 'Exchange data manager should have created new exchange data for encryption to delegate'\n )\n expect(createdData.exchangeData.id).to.not.equal(\n newDataToDelegate2.exchangeData.id,\n 'Exchange data manager should have created new exchange data for encryption to delegate 2'\n )\n expect(ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))).to.not.equal(\n ua2hex(await primitives.AES.exportKey(newDataToDelegate.exchangeKey, 'raw'))\n )\n expect(ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))).to.not.equal(\n ua2hex(await primitives.AES.exportKey(newDataToDelegate2.exchangeKey, 'raw'))\n )\n expect(createdData.accessControlSecret).to.not.equal(newDataToDelegate.accessControlSecret)\n expect(createdData.accessControlSecret).to.not.equal(newDataToDelegate2.accessControlSecret)\n const updatedUnverifiedOldData = (await exchangeData.getDecryptionDataKeyByIds([createdData.exchangeData.id!], true))[\n createdData.exchangeData.id!\n ]\n expect(updatedUnverifiedOldData).to.not.be.undefined\n expect(ua2hex(await primitives.AES.exportKey(updatedUnverifiedOldData!.exchangeKey!, 'raw'))).to.equal(\n ua2hex(await primitives.AES.exportKey(createdData.exchangeKey, 'raw'))\n )\n expect(updatedUnverifiedOldData!.accessControlSecret).to.equal(createdData.accessControlSecret)\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('should return existing exchange data keys for decryption even if the data authenticity could not be verified', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData1 = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const createdData2 = await createDataFromRandomToSelf()\n await encryptionKeysManager.unverifyExistingKeysAndCreateNewVerified(primitives)\n await exchangeData.clearOrRepopulateCache()\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdData1.exchangeData.id!], true)\n )[createdData1.exchangeData.id!],\n createdData1\n )\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdData2.exchangeData.id!], true)\n )[createdData2.exchangeData.id!],\n createdData2\n )\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('newly created data or data retrieved by id should be cached and retrievable by hash', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdData1 = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const hashes1 = await accessControlSecretUtils.allSecureDelegationKeysFor(createdData1.accessControlSecret)\n const retrievedKeys1 = await exchangeData.getCachedDecryptionDataKeyByAccessControlHash(hashes1)\n for (const hash of hashes1) {\n await checkDataEqual(retrievedKeys1[hash], createdData1)\n }\n if (!allowFullExchangeDataLoad) {\n const createdData2 = await createDataFromRandomToSelf()\n const hashes2 = await accessControlSecretUtils.allSecureDelegationKeysFor(createdData2.accessControlSecret)\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdData2.exchangeData.id!], true)\n )[createdData2.exchangeData.id!],\n createdData2\n )\n const retrievedKeys2 = await exchangeData.getCachedDecryptionDataKeyByAccessControlHash([...hashes1, ...hashes2])\n for (const hash of hashes2) {\n await checkDataEqual(retrievedKeys2[hash], createdData2)\n }\n }\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('if data can not be decrypted the retrieval method should return undefined', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdBySelf = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n const createdByOther = await createDataFromRandomToSelf()\n const newKey = await primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n await dataOwnerApi.addPublicKeyForOwner(selfId, newKey)\n // Simulate loss of key\n encryptionKeysManager.deleteKey(selfKeyFpV1)\n await encryptionKeysManager.addOrUpdateKey(primitives, newKey, true)\n await exchangeData.clearOrRepopulateCache()\n await checkDataEqual((await exchangeData.getDecryptionDataKeyByIds([createdBySelf.exchangeData.id!], true))[createdBySelf.exchangeData.id!], {\n exchangeData: createdBySelf.exchangeData,\n exchangeKey: undefined,\n })\n await checkDataEqual((await exchangeData.getDecryptionDataKeyByIds([createdByOther.exchangeData.id!], true))[createdByOther.exchangeData.id!], {\n exchangeData: createdByOther.exchangeData,\n exchangeKey: undefined,\n })\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('unverified keys should still be usable for decryption of data', async function () {\n async function doTest(allowFullExchangeDataLoad: boolean) {\n await initialiseComponents(allowFullExchangeDataLoad)\n const createdBySelf = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n const createdByOther = await createDataFromRandomToSelf()\n await encryptionKeysManager.addOrUpdateKey(primitives, selfKeypair, false)\n await exchangeData.clearOrRepopulateCache()\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdBySelf.exchangeData.id!], true)\n )[createdBySelf.exchangeData.id!],\n createdBySelf\n )\n await checkDataEqual(\n (\n await exchangeData.getDecryptionDataKeyByIds([createdByOther.exchangeData.id!], true)\n )[createdByOther.exchangeData.id!],\n createdByOther\n )\n }\n await doTest(true)\n await doTest(false)\n })\n\n it('implementation with limited cache should trigger eviction of delegate and hash cache on eviction of data by id cache', async function () {\n await initialiseComponents(false, { lruCacheSize: 3 })\n const entityType = EntityWithDelegationTypeName.Contact\n const sfks = [primitives.randomUuid(), primitives.randomUuid(), primitives.randomUuid()]\n\n async function verifyCached(data: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }) {\n const apiCallsBaseline = exchangeDataApi.callCount\n const hashes = await accessControlSecretUtils.allSecureDelegationKeysFor(data.accessControlSecret)\n for (const hash of hashes) {\n await checkDataEqual((await exchangeData.getCachedDecryptionDataKeyByAccessControlHash([hash]))[hash], data)\n }\n if (data.exchangeData.delegator === selfId) {\n await checkDataEqual(await exchangeData.getOrCreateEncryptionDataTo(data.exchangeData.delegate, false), data)\n }\n await checkDataEqual((await exchangeData.getDecryptionDataKeyByIds([data.exchangeData.id!], true))[data.exchangeData.id!], data)\n exchangeDataApi.compareCallCountFromBaseline(apiCallsBaseline, {\n getExchangeDataByIds: 0,\n createExchangeData: 0,\n modifyExchangeData: 0,\n getExchangeDataByParticipant: 0,\n getExchangeDataByDelegatorDelegate: 0,\n })\n }\n\n async function verifyNotCachedThenCache(data: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }) {\n const apiCallsBaseline = exchangeDataApi.callCount\n const hashes = [await accessControlSecretUtils.secureDelegationKeyFor(data.accessControlSecret, entityType)]\n for (const hash of hashes) {\n expect(Object.keys(await exchangeData.getCachedDecryptionDataKeyByAccessControlHash([hash]))).to.have.length(0)\n }\n if (data.exchangeData.delegator === selfId) {\n await checkDataEqual(await exchangeData.getOrCreateEncryptionDataTo(data.exchangeData.delegate, false), data)\n exchangeDataApi.compareCallCountFromBaseline(apiCallsBaseline, {\n getExchangeDataByIds: 0,\n createExchangeData: 0,\n modifyExchangeData: 0,\n getExchangeDataByParticipant: 0,\n getExchangeDataByDelegatorDelegate: 1,\n })\n } else {\n await checkDataEqual((await exchangeData.getDecryptionDataKeyByIds([data.exchangeData.id!], true))[data.exchangeData.id!], data)\n exchangeDataApi.compareCallCountFromBaseline(apiCallsBaseline, {\n getExchangeDataByIds: 1,\n createExchangeData: 0,\n modifyExchangeData: 0,\n getExchangeDataByParticipant: 0,\n getExchangeDataByDelegatorDelegate: 0,\n })\n }\n }\n\n const createdBySelf1 = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n const createdBySelf2 = await exchangeData.getOrCreateEncryptionDataTo(delegateId, false)\n const createdByOther1 = await createDataFromRandomToSelf() // Not automatically cached: created by someone else\n const createdByOther2 = await createDataFromRandomToSelf() // Not automatically cached: created by someone else\n // noinspection DuplicatedCode\n await verifyCached(createdBySelf1)\n await verifyCached(createdBySelf2)\n await verifyNotCachedThenCache(createdByOther1)\n await verifyCached(createdBySelf1)\n await verifyCached(createdBySelf2)\n await verifyCached(createdByOther1)\n await verifyNotCachedThenCache(createdByOther2)\n await verifyCached(createdBySelf2)\n await verifyCached(createdByOther1)\n await verifyCached(createdByOther2)\n await verifyNotCachedThenCache(createdBySelf1)\n await verifyCached(createdByOther1)\n await verifyCached(createdByOther2)\n await verifyCached(createdBySelf1)\n await verifyNotCachedThenCache(createdBySelf2)\n await verifyCached(createdByOther2)\n // noinspection DuplicatedCode\n await verifyCached(createdBySelf1)\n await verifyCached(createdBySelf2)\n await verifyNotCachedThenCache(createdByOther1)\n await verifyCached(createdBySelf1)\n await verifyCached(createdBySelf2)\n await verifyCached(createdByOther1)\n await verifyNotCachedThenCache(createdByOther2)\n await verifyCached(createdBySelf2)\n await verifyCached(createdByOther1)\n await verifyCached(createdByOther2)\n })\n\n it('implementation with unlimited cache should preload all existing exchange data on creation', async function () {\n await initialiseComponents(true)\n const createdBySelf = await exchangeData.getOrCreateEncryptionDataTo(selfId, false)\n const createdByOther = await createDataFromRandomToSelf()\n const recreatedExchangeData = await initialiseExchangeDataManagerForCurrentDataOwner(\n baseExchangeData,\n encryptionKeysManager,\n accessControlSecretUtils,\n new TestCryptoStrategies(),\n dataOwnerApi,\n primitives,\n true\n )\n const apiCallsAfterCreation = exchangeDataApi.callCount\n await checkDataEqual(\n (\n await recreatedExchangeData.getDecryptionDataKeyByIds([createdBySelf.exchangeData.id!], false)\n )[createdBySelf.exchangeData.id!],\n createdBySelf\n )\n await checkDataEqual(\n (\n await recreatedExchangeData.getDecryptionDataKeyByIds([createdByOther.exchangeData.id!], false)\n )[createdByOther.exchangeData.id!],\n createdByOther\n )\n exchangeDataApi.compareCallCountFromBaseline(apiCallsAfterCreation, {\n getExchangeDataByIds: 0,\n createExchangeData: 0,\n modifyExchangeData: 0,\n getExchangeDataByParticipant: 0,\n getExchangeDataByDelegatorDelegate: 0,\n })\n })\n})\n\nlet env: TestVars\n\ndescribe('Exchange data manager - e2e', async function () {\n before(async function () {\n this.timeout(600000)\n const initializer = await getEnvironmentInitializer()\n env = await initializer.execute(getEnvVariables())\n })\n\n it('give access back should not invalidate existing and valid exchange data', async function () {\n const hcp1Details = await createNewHcpApi(env)\n const hcp2Details = await createNewHcpApi(env)\n const ed1to2 = await hcp1Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp2Details.credentials.dataOwnerId, false)\n const ed2to1 = await hcp2Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp1Details.credentials.dataOwnerId, false)\n await hcp1Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n await hcp2Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n const newKeyPair = await hcp1Details.api.cryptoApi.primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const exportedPub = ua2hex(await hcp1Details.api.cryptoApi.primitives.RSA.exportKey(newKeyPair.publicKey, 'spki'))\n const hcp2 = await hcp2Details.api.healthcarePartyApi.getHealthcareParty(hcp2Details.credentials.dataOwnerId)\n await hcp2Details.api.healthcarePartyApi.modifyHealthcareParty({\n ...hcp2,\n publicKeysForOaepWithSha256: [...hcp2.publicKeysForOaepWithSha256, exportedPub],\n })\n await hcp1Details.api.cryptoApi.exchangeData.giveAccessBackTo(hcp2Details.credentials.dataOwnerId, exportedPub)\n await hcp1Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n await hcp2Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n const updatedEd1to2 = await hcp1Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp2Details.credentials.dataOwnerId, false)\n const updatedEd2to1 = await hcp2Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp1Details.credentials.dataOwnerId, false)\n expect(updatedEd1to2.exchangeData.id).to.equal(ed1to2.exchangeData.id)\n expect(Object.keys(updatedEd2to1.exchangeData.exchangeKey).length).to.be.greaterThan(Object.keys(ed2to1.exchangeData.exchangeKey).length)\n expect(Object.keys(updatedEd2to1.exchangeData.exchangeKey).length).to.equal(Object.keys(updatedEd2to1.exchangeData.accessControlSecret).length)\n expect(Object.keys(updatedEd2to1.exchangeData.exchangeKey).length).to.equal(Object.keys(updatedEd2to1.exchangeData.sharedSignatureKey).length)\n expect(updatedEd2to1.exchangeData.id).to.equal(ed2to1.exchangeData.id)\n expect(Object.keys(updatedEd1to2.exchangeData.exchangeKey).length).to.be.greaterThan(Object.keys(ed1to2.exchangeData.exchangeKey).length)\n expect(Object.keys(updatedEd1to2.exchangeData.exchangeKey).length).to.equal(Object.keys(updatedEd1to2.exchangeData.accessControlSecret).length)\n expect(Object.keys(updatedEd1to2.exchangeData.exchangeKey).length).to.equal(Object.keys(updatedEd1to2.exchangeData.sharedSignatureKey).length)\n })\n\n it('invalid exchange data should not be re-validated by give access back', async function () {\n const hcp1Details = await createNewHcpApi(env)\n const hcp2Details = await createNewHcpApi(env)\n const ed1to2 = await hcp1Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp2Details.credentials.dataOwnerId, false)\n const ed2to1 = await hcp2Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp1Details.credentials.dataOwnerId, false)\n await hcp1Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n await hcp2Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n const exchangeDataApi = new IccExchangeDataApi(env.iCureUrl, {}, hcp1Details.api.authApi.authenticationProvider, fetch)\n const extraKeyPair = await hcp1Details.api.cryptoApi.primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const extraKeyPairPub = ua2hex(await hcp1Details.api.cryptoApi.primitives.RSA.exportKey(extraKeyPair.publicKey, 'spki'))\n const extraKeyPairFp = fingerprintV2(extraKeyPairPub)\n const fakeData = await hcp1Details.api.cryptoApi.primitives.randomBytes(16)\n async function tamperWithData(data: ExchangeData) {\n await exchangeDataApi.modifyExchangeData({\n ...data,\n exchangeKey: {\n ...data.exchangeKey,\n [extraKeyPairFp]: ua2b64(await hcp1Details.api.cryptoApi.primitives.RSA.encrypt(extraKeyPair.publicKey, fakeData)),\n },\n accessControlSecret: {\n ...data.accessControlSecret,\n [extraKeyPairFp]: ua2b64(await hcp1Details.api.cryptoApi.primitives.RSA.encrypt(extraKeyPair.publicKey, fakeData)),\n },\n sharedSignatureKey: {\n ...data.sharedSignatureKey,\n [extraKeyPairFp]: ua2b64(await hcp1Details.api.cryptoApi.primitives.RSA.encrypt(extraKeyPair.publicKey, fakeData)),\n },\n })\n }\n await tamperWithData(ed1to2.exchangeData)\n await tamperWithData(ed2to1.exchangeData)\n const newKeyPair = await hcp1Details.api.cryptoApi.primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const exportedPub = ua2hex(await hcp1Details.api.cryptoApi.primitives.RSA.exportKey(newKeyPair.publicKey, 'spki'))\n const hcp2 = await hcp2Details.api.healthcarePartyApi.getHealthcareParty(hcp2Details.credentials.dataOwnerId)\n await hcp2Details.api.healthcarePartyApi.modifyHealthcareParty({\n ...hcp2,\n publicKeysForOaepWithSha256: [...hcp2.publicKeysForOaepWithSha256, exportedPub, extraKeyPairPub],\n })\n await hcp1Details.api.cryptoApi.exchangeData.giveAccessBackTo(hcp2Details.credentials.dataOwnerId, exportedPub)\n await hcp1Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n await hcp2Details.api.cryptoApi.exchangeData.clearOrRepopulateCache()\n const updatedEd1to2 = await hcp1Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp2Details.credentials.dataOwnerId, false)\n const updatedEd2to1 = await hcp2Details.api.cryptoApi.exchangeData.getOrCreateEncryptionDataTo(hcp1Details.credentials.dataOwnerId, false)\n expect(updatedEd1to2.exchangeData.id).to.not.equal(ed1to2.exchangeData.id)\n expect(updatedEd2to1.exchangeData.id).to.not.equal(ed2to1.exchangeData.id)\n const decData1to2 = (await hcp1Details.api.cryptoApi.exchangeData.getDecryptionDataKeyByIds([ed1to2.exchangeData.id!], true))[\n ed1to2.exchangeData.id!\n ]\n expect(decData1to2).to.not.be.undefined\n expect(decData1to2!.exchangeKey).to.not.be.undefined\n expect(decData1to2!.accessControlSecret).to.not.be.undefined\n const decData2to1 = (await hcp2Details.api.cryptoApi.exchangeData.getDecryptionDataKeyByIds([ed2to1.exchangeData.id!], true))[\n ed2to1.exchangeData.id!\n ]\n expect(decData2to1).to.not.be.undefined\n expect(decData2to1!.exchangeKey).to.not.be.undefined\n expect(decData2to1!.accessControlSecret).to.not.be.undefined\n })\n})\n"]}