@icure/api 5.0.16 → 5.0.19

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.
@@ -839,7 +839,7 @@ class IccCryptoXApi {
839
839
  const extractedKeys = [];
840
840
  if ((_a = delegations[hcpartyId]) === null || _a === void 0 ? void 0 : _a.length) {
841
841
  const decryptedAndImportedAesHcPartyKeys = yield this.getDecryptedAesExchangeKeysOfDelegateAndParentsFromGenericDelegations(hcpartyId, delegations, false);
842
- const collatedAesKeysFromDelegatorToHcpartyId = decryptedAndImportedAesHcPartyKeys.reduce((map, k) => (Object.assign(Object.assign({}, map), { [k.delegatorId]: k })), {});
842
+ const collatedAesKeysFromDelegatorToHcpartyId = decryptedAndImportedAesHcPartyKeys.reduce((map, k) => { var _a; return (Object.assign(Object.assign({}, map), { [k.delegatorId]: ((_a = map[k.delegatorId]) !== null && _a !== void 0 ? _a : []).concat([k]) })); }, {});
843
843
  extractedKeys.push(...(yield this.decryptKeyInDelegationLikes(delegations[hcpartyId], collatedAesKeysFromDelegatorToHcpartyId, objectId)));
844
844
  }
845
845
  return hcp.parentId
@@ -1156,7 +1156,7 @@ class IccCryptoXApi {
1156
1156
  throw 'Your browser does not support HTML5 Browser Local Storage !';
1157
1157
  }
1158
1158
  //TODO decryption
1159
- const item = (_a = (publicKeyFingerPrint && localStorage.getItem(this.rsaLocalStoreIdPrefix + id + '.' + publicKeyFingerPrint))) !== null && _a !== void 0 ? _a : localStorage.getItem(this.rsaLocalStoreIdPrefix + id);
1159
+ const item = (_a = (publicKeyFingerPrint && localStorage.getItem(this.rsaLocalStoreIdPrefix + id + '.' + publicKeyFingerPrint.slice(-32)))) !== null && _a !== void 0 ? _a : localStorage.getItem(this.rsaLocalStoreIdPrefix + id);
1160
1160
  if (!item) {
1161
1161
  console.warn(`No key can be found in local storage for id ${id} and publicKeyFingerPrint ${publicKeyFingerPrint}`);
1162
1162
  }
@@ -1459,11 +1459,8 @@ class IccCryptoXApi {
1459
1459
  try {
1460
1460
  const k = yield this._RSA.importKey('jwk', (0, utils_1.spkiToJwk)((0, binary_utils_1.hex2ua)(publicKey)), ['encrypt']);
1461
1461
  const cipher = yield this._RSA.encrypt(k, (0, binary_utils_1.utf8_2ua)('shibboleth'));
1462
- const kp = this.loadKeyPairNotImported(dataOwner.id, publicKey.slice(-32));
1463
- const plainText = yield this._RSA
1464
- .importKeyPair('jwk', kp.privateKey, 'jwk', kp.publicKey)
1465
- .then((ikp) => this._RSA.decrypt(ikp.privateKey, new Uint8Array(cipher)))
1466
- .then((x) => (0, binary_utils_1.ua2utf8)(x));
1462
+ const ikp = this.getCachedRsaKeyPairForFingerprint(dataOwner.id, publicKey.slice(-32));
1463
+ const plainText = (0, binary_utils_1.ua2utf8)(yield this._RSA.decrypt(ikp.privateKey, new Uint8Array(cipher)));
1467
1464
  return plainText === 'shibboleth' || res;
1468
1465
  }
1469
1466
  catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"icc-crypto-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-crypto-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,sCAAuC;AACvC,sCAAuC;AACvC,4CAA6C;AAE7C,4BAA2B;AAC3B,oDAagC;AAChC,uDAA6G;AAC7G,mCAA8E;AAuB9E,MAAa,aAAa;IAgFxB,YACE,IAAY,EACZ,OAAkC,EAClC,cAA6B,EAAE,mDAAmD;IAClF,cAA6B,EAC7B,aAA2B,EAC3B,SAAiB,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAE,EAAa;QArE7H,qBAAgB,GAEZ,EAAE,CAAA;QAEN,yDAAyD;QACzD,mMAAmM;QACnM,6BAAwB,GAEpB,EAAE,CAAA;QAEN,+BAA0B,GAAuB,SAAS,CAAA;QAE1D,mBAAc,GAAg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O,CAAA;iBACf;aACF;YAED,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,yCAAyC,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,iBAAkB,EAAE,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,EAAG,EAAE,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,cAAe,CAAC,CAAA;YACjJ,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAA,qBAAM,EAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;YACvG,IAAI;gBACF,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,aAAa,EAAE,OAAO,CAAC,CAAA;aACvD;YAAC,OAAO,CAAC,EAAE;gBACV,OAAO,OAAO,CAAA;aACf;QACH,CAAC;KAAA;CACF;AAn8DD,sCAm8DC","sourcesContent":["import { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../icc-api'\nimport { AESUtils } from './crypto/AES'\nimport { RSAUtils } from './crypto/RSA'\nimport { ShamirClass } from './crypto/shamir'\n\nimport * as _ from 'lodash'\nimport {\n Delegation,\n Device,\n Document,\n EncryptedEntity,\n EncryptedParentEntity,\n HealthcareParty,\n MaintenanceTask,\n Patient,\n PropertyStub,\n PropertyTypeStub,\n TypedValueObject,\n User,\n} from '../icc-api/model/models'\nimport { b2a, b64_2uas, hex2ua, string2ua, ua2hex, ua2string, ua2utf8, utf8_2ua } from './utils/binary-utils'\nimport { fold, jwk2spki, notConcurrent, pkcs8ToJwk, spkiToJwk } from './utils'\nimport { IccMaintenanceTaskXApi } from './icc-maintenance-task-x-api'\n\ninterface DelegatorAndKeys {\n delegatorId: string\n key: CryptoKey\n rawKey: string\n}\n\ntype CachedDataOwner =\n | {\n type: 'patient'\n dataOwner: Patient\n }\n | {\n type: 'device'\n dataOwner: Device\n }\n | {\n type: 'hcp'\n dataOwner: HealthcareParty\n }\n\nexport class IccCryptoXApi {\n get crypto(): Crypto {\n return this._crypto\n }\n\n get shamir(): ShamirClass {\n return this._shamir\n }\n\n get RSA(): RSAUtils {\n return this._RSA\n }\n\n get AES(): AESUtils {\n return this._AES\n }\n\n hcPartyKeysCache: {\n [key: string]: DelegatorAndKeys\n } = {}\n\n //[delegateId][delegatorId] = delegateEncryptedHcPartyKey\n //for each delegate, it stores the list of delegators and the corresponding delegateEncryptedHcPartyKey (shared HcPartyKey, from delegator to delegate, encrypted with the RSA key of the delegate)\n hcPartyKeysRequestsCache: {\n [delegateId: string]: Promise<{ [key: string]: { [key: string]: { [key: string]: string } } }>\n } = {}\n\n cacheLastDeletionTimestamp: number | undefined = undefined\n\n dataOwnerCache: { [key: string]: Promise<CachedDataOwner> } = {}\n\n emptyHcpCache(hcpartyId: string) {\n delete this.hcPartyKeysRequestsCache[hcpartyId]\n delete this.dataOwnerCache[hcpartyId]\n }\n\n /**\n * Gets all delegate encrypted HcParty keys of the delegate with the given `delegateHcPartyId`, and for each key the delegator id\n * If the keys are not cached, they are retrieved from the backend.\n *\n * @param delegateHcPartyId The Health Care Party id\n * @returns \\{delegatorId: delegateEncryptedHcPartyKey\\}\n */\n private getEncryptedAesExchangeKeysForDelegate(\n delegateHcPartyId: string\n ): Promise<{ [key: string]: { [key: string]: { [key: string]: string } } }> {\n return (\n this.hcPartyKeysRequestsCache[delegateHcPartyId] ||\n (this.hcPartyKeysRequestsCache[delegateHcPartyId] = this.forceGetEncryptedAesExchangeKeysForDelegate(delegateHcPartyId))\n )\n }\n\n private forceGetEncryptedAesExchangeKeysForDelegate(\n delegateHcPartyId: string\n ): Promise<{ [key: string]: { [key: string]: { [key: string]: string } } }> {\n return Promise.all([\n this.patientBaseApi.getPatientAesExchangeKeysForDelegate(delegateHcPartyId).catch(() => {}),\n this.hcpartyBaseApi.getAesExchangeKeysForDelegate(delegateHcPartyId).catch(() => {}),\n this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(delegateHcPartyId).catch(() => {}),\n ]).then(([a, b, c]) => ({ ...a, ...b, ...c }))\n }\n\n keychainLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain.'\n keychainValidityDateLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain-date.'\n hcpPreferenceKeyEhealthCert = 'eHealthCRTCrypt'\n hcpPreferenceKeyEhealthCertDate = 'eHealthCRTDate'\n rsaLocalStoreIdPrefix = 'org.taktik.icure.rsa.'\n\n private hcpartyBaseApi: IccHcpartyApi\n private patientBaseApi: IccPatientApi\n private deviceBaseApi: IccDeviceApi\n private readonly _crypto: Crypto\n\n private generateKeyConcurrencyMap: { [key: string]: PromiseLike<HealthcareParty | Patient> }\n private rsaKeyPairs: { [pubKeyFingerprint: string]: { publicKey: CryptoKey; privateKey: CryptoKey } } = {}\n\n private readonly _AES: AESUtils\n private readonly _RSA: RSAUtils\n private readonly _shamir: ShamirClass\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n hcpartyBaseApi: IccHcpartyApi, //Init with a hcparty x api for better performances\n patientBaseApi: IccPatientApi,\n deviceBaseApi: IccDeviceApi,\n crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)\n ) {\n this.hcpartyBaseApi = hcpartyBaseApi\n this.patientBaseApi = patientBaseApi\n this.deviceBaseApi = deviceBaseApi\n this._crypto = crypto\n this.generateKeyConcurrencyMap = {}\n\n this._AES = new AESUtils(crypto)\n this._RSA = new RSAUtils(crypto)\n this._shamir = new ShamirClass(crypto)\n }\n\n async loadAllKeysFromLocalStorage(dataOwnerId: string): Promise<void> {\n const pubKeys = await this.getDataOwnerHexPublicKeys((await this.getDataOwner(dataOwnerId)).dataOwner)\n\n for (const pk of pubKeys) {\n const fingerprint = pk.slice(-32)\n if (!this.rsaKeyPairs[fingerprint]) {\n await this.cacheKeyPair(this.loadKeyPairNotImported(dataOwnerId, fingerprint))\n }\n }\n }\n\n getCachedRsaKeyPairForFingerprint(dataOwnerId: string, pubKeyOrFingerprint: string): { publicKey: CryptoKey; privateKey: CryptoKey } {\n const fingerprint = pubKeyOrFingerprint.slice(-32)\n return this.rsaKeyPairs[fingerprint] ?? this.cacheKeyPair(this.loadKeyPairNotImported(dataOwnerId, fingerprint))\n }\n\n async getPublicKeys() {\n return await Object.values(this.rsaKeyPairs).reduce(async (p, rsa) => {\n return (await p).concat([jwk2spki(await this.RSA.exportKey(rsa.publicKey, 'jwk'))])\n }, Promise.resolve([] as string[]))\n }\n\n randomUuid() {\n return ((1e7).toString() + -1e3 + -4e3 + -8e3 + -1e11).replace(\n /[018]/g,\n (c) => (Number(c) ^ ((this._crypto.getRandomValues(new Uint8Array(1))! as Uint8Array)[0] & (15 >> (Number(c) / 4)))).toString(16) //Keep that inlined or you will loose the random\n )\n }\n\n sha256(data: ArrayBuffer | Uint8Array) {\n return this._crypto.subtle.digest('SHA-256', data)\n }\n\n encryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>, threshold?: number): Promise<HealthcareParty> {\n return this.loadKeyPairImported(hcp.id!).then((keyPair) =>\n this._RSA.exportKey(keyPair.privateKey, 'pkcs8').then(async (exportedKey) => {\n const privateKey = exportedKey as ArrayBuffer\n const nLen = notaries.length\n const shares = nLen == 1 ? [privateKey] : this._shamir.share(ua2hex(privateKey), nLen, threshold || nLen).map((share) => hex2ua(share))\n const publicKeys = await this.getPublicKeys()\n\n return _.reduce(\n notaries,\n (queue, notary, idx) => {\n return queue.then(async (hcp) => {\n const { owner: hcParty, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(hcp, notary.id!)\n const [publicKeyIdentifier, hcPartyKeys] = Object.entries(aesExchangeKeys)[0]\n\n try {\n const importedAESHcPartyKey = await this.decryptHcPartyKey(\n notary.id!,\n hcParty.id!,\n notary.id!,\n publicKeyIdentifier,\n hcPartyKeys,\n publicKeys\n )\n const encryptedShamirPartition = await this.AES.encrypt(importedAESHcPartyKey.key, shares[idx])\n\n hcParty.privateKeyShamirPartitions = hcParty.privateKeyShamirPartitions || {}\n hcParty.privateKeyShamirPartitions[notary.id!] = ua2hex(encryptedShamirPartition)\n } catch (e) {\n console.log('Error during encryptedShamirRSAKey', notary.id, e)\n }\n return hcParty\n })\n },\n Promise.resolve(hcp)\n )\n })\n )\n }\n\n /* Reconstructs the hcp's private key from the notaries' shamir shares and stores it in localstorage.\n The retrieval procedure of the shares is not designed or implemented yet. Therefore, it currently only\n works if the private key of the notaries are stored in local storage (e.g. notaries = [hcp parent]).\n * @param hcp : the hcp whose key we want to reconstruct\n * @param notaries : holders of the shamir shares\n **/\n async decryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>): Promise<void> {\n try {\n const publicKeys = await this.getPublicKeys()\n const nLen = notaries.length\n let decryptedPrivatedKey\n if (nLen == 1) {\n const notaryHcPartyId = notaries[0].id!\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notaryHcPartyId)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notaryHcPartyId, hcp.id!, notaryHcPartyId, idPubKey, keysMap, publicKeys)\n )\n )\n const cryptedPrivatedKey = hcp.privateKeyShamirPartitions![notaryHcPartyId]\n decryptedPrivatedKey = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(cryptedPrivatedKey)\n )\n )\n } else {\n const decryptedShares: string[] = await _.reduce(\n notaries,\n (queue, notary) => {\n return queue.then(async (shares: string[]) => {\n try {\n // TODO: now, we get the encrypted shares in db and decrypt them. This assumes that the\n // the notaries' private keys are in localstorage. We should implement a way for the notaries to\n // give hcp the decrypted shares without having to also share their private keys.\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notary.id!)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notary.id!, hcp.id!, notary.id!, idPubKey, keysMap, publicKeys)\n )\n )\n const encryptedShare = hcp.privateKeyShamirPartitions![notary.id!]\n const decryptedShamirPartition = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(encryptedShare)\n )\n )\n shares.push(decryptedShamirPartition)\n } catch (e) {\n console.log('Error during encryptedShamirRSAKey', notary.id, e)\n }\n return shares\n })\n },\n Promise.resolve([] as string[])\n )\n\n decryptedPrivatedKey = this._shamir.combine(decryptedShares)\n }\n\n const importedPrivateKey = await this._RSA.importKey('pkcs8', hex2ua(decryptedPrivatedKey), ['decrypt'])\n const importedPublicKey = await this._RSA.importKey('spki', hex2ua(hcp.publicKey!), ['encrypt'])\n\n const exportedKeyPair = await this._RSA.exportKeys({ publicKey: importedPublicKey, privateKey: importedPrivateKey }, 'jwk', 'jwk')\n this.storeKeyPair(hcp.id!, exportedKeyPair)\n } catch (e) {\n console.log('Cannot decrypt shamir RSA key')\n }\n }\n\n /**\n * Gets the decryptedHcPartyKey for the given `encryptedHcPartyKey`\n *\n * If the decrypted key exists in the cache, retrieves it from there.\n * Otherwise, decrypts it using the RSA key of the delegator or delegate (depending on the value of `encryptedForDelegator`)\n *\n * @param loggedHcPartyId The logged DataOwner id or the id of his parent\n * @param delegatorId The id of Delegator eg, the DataOwner where this AES exchange key is stored\n * @param delegateHcPartyId The id of the delegate : the data owner for whom this aes exchange key has been created\n * @param publicKey The public key of the delegator : A unique aes exchange key is created for each public key of the delegator. This is the public key corresponding to the encryptedHcPartyKeys\n * @param encryptedHcPartyKeys The encryptedHcPartyKeys to be decrypted\n * @param publicKeys The public keys for which we might have a private key\n *\n * @returns - **delegatorId** the input param `delegatorId`\n * - **key** the decrypted `encryptedHcPartyKey`\n */\n\n async decryptHcPartyKey(\n loggedHcPartyId: string,\n delegatorId: string,\n delegateHcPartyId: string,\n publicKey: string,\n encryptedHcPartyKeys: { [key: string]: string },\n publicKeys: string[]\n ): Promise<DelegatorAndKeys> {\n if (!publicKeys.length) {\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: no public key`\n console.warn(reason)\n throw new Error(reason)\n }\n\n const cacheKey = `${delegateHcPartyId}|${publicKey.slice(-32)}|${delegatorId}`\n const res = this.hcPartyKeysCache[cacheKey]\n\n if (res) {\n return res\n }\n\n const result = await publicKeys.reduce(async (res, pk) => {\n const delegatorAndKeys = await res\n if (delegatorAndKeys) {\n return delegatorAndKeys\n }\n\n const fingerprint = pk.slice(-32)\n const keyPair = this.rsaKeyPairs[fingerprint] ?? (await this.cacheKeyPair(this.loadKeyPairNotImported(loggedHcPartyId, fingerprint)))\n if (!keyPair) {\n return\n }\n\n const encryptedHcPartyKey = encryptedHcPartyKeys[fingerprint]\n if (!encryptedHcPartyKey) {\n return\n }\n\n try {\n const decryptedAesExchangeKey = await this._RSA.decrypt(keyPair.privateKey, hex2ua(encryptedHcPartyKey))\n const importedAesExchangeKey = await this._AES.importKey('raw', decryptedAesExchangeKey)\n return (this.hcPartyKeysCache[cacheKey] = {\n delegatorId: delegatorId,\n key: importedAesExchangeKey,\n rawKey: ua2hex(new Uint8Array(decryptedAesExchangeKey)),\n })\n } catch (e) {\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId} for pubKey ${fingerprint}: impossible to decrypt`\n console.log(reason)\n }\n }, Promise.resolve() as Promise<DelegatorAndKeys | void>)\n\n const availablePublicKeys = publicKeys.filter((pk) => this.rsaKeyPairs[pk.slice(-32)])\n\n if (!result) {\n //Try to find another key from the transfer keys\n const hcp = (await this.getDataOwner(loggedHcPartyId))!\n const candidates = Object.entries(hcp.dataOwner.transferKeys ?? {})\n .filter(([fp, _]) => availablePublicKeys.some((pk) => pk.slice(-32) === fp.slice(-32))) // only keep keys that we will be able to decrypt\n .flatMap(([pk, keys]) => Object.entries(keys).map(([k, v]) => [pk, k, v]))\n .filter(([_, k]) => !publicKeys.some((apk) => apk.slice(-32) === k.slice(-32)))\n if (candidates.length) {\n const newPublicKeys = await candidates.reduce(async (p, [decryptionKeyFingerprint, privateKeyFingerprint, encryptedPrivateKey]) => {\n const newKeys = await p\n const aesExchangeKeys = Object.entries(hcp.dataOwner.aesExchangeKeys!).find(\n ([fp, _]) => fp.slice(-32) === privateKeyFingerprint.slice(-32)\n )?.[1][loggedHcPartyId]\n if (aesExchangeKeys) {\n const encryptedAesExchangeKey = Object.entries(aesExchangeKeys).find(\n ([fp, _]) => fp.slice(-32) === decryptionKeyFingerprint.slice(-32)\n )?.[1]\n if (encryptedAesExchangeKey) {\n const keyPair = this.rsaKeyPairs[decryptionKeyFingerprint.slice(-32)]\n if (!keyPair) {\n return newKeys\n }\n const decryptedAesExchangeKey = await this._RSA.decrypt(keyPair.privateKey, hex2ua(encryptedAesExchangeKey))\n const importedAesExchangeKey = await this._AES.importKey('raw', decryptedAesExchangeKey)\n\n const decryptedPrivateKey = await this._AES.decrypt(importedAesExchangeKey, hex2ua(encryptedPrivateKey))\n\n const newPublicKey = Object.keys(hcp.dataOwner.aesExchangeKeys!).find((fp) => fp.slice(-32) === privateKeyFingerprint.slice(-32))!\n await this.cacheKeyPair({\n publicKey: spkiToJwk(hex2ua(newPublicKey)),\n privateKey: pkcs8ToJwk(decryptedPrivateKey),\n })\n\n return newKeys.concat([newPublicKey])\n }\n }\n return newKeys\n }, Promise.resolve([]) as Promise<string[]>)\n\n if (newPublicKeys.length) {\n return await this.decryptHcPartyKey(loggedHcPartyId, delegatorId, delegateHcPartyId, publicKey, encryptedHcPartyKeys, newPublicKeys)\n }\n }\n\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: impossible to decrypt. No private key was found or could be used to decrypt the aes exchange keys`\n console.log(reason)\n throw new Error(reason)\n }\n\n return result\n }\n\n /**\n * Cache the RSA private/public key pair for the HcP with the given id `hcPartyKeyOwner`\n */\n cacheKeyPair(keyPairInJwk: { publicKey: JsonWebKey; privateKey: JsonWebKey }) {\n return this._RSA.importKeyPair('jwk', keyPairInJwk.privateKey, 'jwk', keyPairInJwk.publicKey).then((importedKeyPair) => {\n const pk = jwk2spki(keyPairInJwk.publicKey)\n return (this.rsaKeyPairs[pk.slice(-32)] = importedKeyPair)\n })\n }\n\n /**\n * Gets the secret ID (SFKs) that should be used in the prescribed context (confidential or not) from decrypted SPKs of the given `parent`, decrypted by the HcP with the given `hcpartyId` AND by its HcP parents\n * @param parent :the object of which delegations (SPKs) to decrypt\n * @param hcpartyId :the id of the delegate HcP\n * @param confidential :weather the key is going to be used for a confidential piece or data or not\n * @returns - **extractedKeys** array containing secret IDs (SFKs) from decrypted SPKs, from both given HcP and its parents ; can contain duplicates\n * - **hcpartyId** the given `hcpartyId` OR, if a parent exist, the HcP id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n async extractPreferredSfk(parent: EncryptedParentEntity, hcpartyId: string, confidential: boolean) {\n const secretForeignKeys = await this.extractSFKsHierarchyFromDelegations(parent, hcpartyId)\n const keys = secretForeignKeys\n .filter(({ extractedKeys }) => extractedKeys.length > 0)\n .filter((x, idx) => (confidential ? x.hcpartyId === hcpartyId : idx === 0))[0]\n\n return (\n (keys &&\n (confidential\n ? keys.extractedKeys.find(\n (k) => !secretForeignKeys.some(({ extractedKeys, hcpartyId: parentHcpId }) => hcpartyId !== parentHcpId && extractedKeys.includes(k))\n )\n : keys.extractedKeys[0])) ||\n undefined\n )\n }\n\n /**\n * Gets an array of decrypted HcPartyKeys, shared between the delegate with ID `delegateHcPartyId` and the delegators in `delegatorsHcPartyIdsSet`\n *\n * 1. Get the keys for the delegateHealthCareParty (cache/backend).\n * 2. For each key in the delegators, decrypt it with the delegate's private key\n * 3. Filter out undefined keys and return them\n *\n * @param delegatorsHcPartyIdsSet array of delegator HcP IDs that could have delegated something to the HcP with ID `delegateHcPartyId`\n * @param delegateHcPartyId the HcP for which the HcPs with IDs in `delegatorsHcPartyIdsSet` could have delegated something\n * @param minCacheDurationInSeconds The minimum cache duration\n * @returns - **delegatorId** : the id of the delegator HcP that shares the **key** with the `delegateHcPartyId`\n * - **key** the decrypted HcPartyKey, shared between **delegatorId** and `delegateHcPartyId`\n */\n async decryptAndImportAesHcPartyKeysForDelegators(\n delegatorsHcPartyIdsSet: Array<string>,\n delegateHcPartyId: string,\n minCacheDurationInSeconds: number = 60\n ): Promise<Array<DelegatorAndKeys>> {\n const aesExchangeKeys = await (\n this.hcPartyKeysRequestsCache[delegateHcPartyId] ||\n (this.hcPartyKeysRequestsCache[delegateHcPartyId] = this.getEncryptedAesExchangeKeysForDelegate(delegateHcPartyId))\n ).then(async (delegatorIdsWithDelegateEncryptedHcPartyKeys: { [key: string]: { [key: string]: { [key: string]: string } } }) => {\n // [key: delegatorId] = delegateEncryptedHcPartyKey\n // For each delegatorId, obtain the AES key (decrypted HcParty Key) shared with the delegate, decrypted by the delegate\n return (\n await Promise.all(\n delegatorsHcPartyIdsSet.map(async (delegatorId: string) => {\n const encryptedHcPartyKeysForPubKeyFingerprint = delegatorIdsWithDelegateEncryptedHcPartyKeys[delegatorId]\n if (!encryptedHcPartyKeysForPubKeyFingerprint) {\n return [] as DelegatorAndKeys[]\n }\n const decryptedKeys = await Promise.all(\n Object.entries(encryptedHcPartyKeysForPubKeyFingerprint).map(async ([delegatorPubKeyFinerprint, encryptedAesExchangeKeys]) => {\n try {\n return await this.decryptHcPartyKey(\n delegateHcPartyId,\n delegatorId,\n delegateHcPartyId,\n delegatorPubKeyFinerprint,\n encryptedAesExchangeKeys,\n Object.keys(this.rsaKeyPairs)\n )\n } catch (e) {\n console.log(`failed to decrypt hcPartyKey from ${delegatorId} to ${delegateHcPartyId}`)\n return\n }\n })\n )\n return decryptedKeys.filter((x) => !!x) as DelegatorAndKeys[]\n })\n )\n ).reduce((acc, x) => [...acc, ...x], [])\n })\n\n if (aesExchangeKeys.length > 0) {\n return aesExchangeKeys\n }\n\n const nowTimestamp = +new Date()\n if (!this.cacheLastDeletionTimestamp || (nowTimestamp - this.cacheLastDeletionTimestamp) / 1000 >= minCacheDurationInSeconds) {\n delete this.hcPartyKeysRequestsCache[delegateHcPartyId]\n this.cacheLastDeletionTimestamp = nowTimestamp\n return this.decryptAndImportAesHcPartyKeysForDelegators(delegatorsHcPartyIdsSet, delegateHcPartyId, minCacheDurationInSeconds)\n }\n\n return []\n }\n\n /**\n * Gets an array of decrypted HcPartyKeys from the given `delegations`, that are shared with / can be decrypted by the HcP with the given `healthcarePartyId` (or by its parents when `fallbackOnParent` is true)\n *\n * 1. Checks whether the delegations' object has a delegation for the\n * given healthCarePartyId.\n * 2. Enumerates all the delegators (delegation.owner) present in\n * the delegations.\n * 3. Decrypt's delegators' keys and returns them.\n *\n * @param dataOwnerId : the id of the delegate HCP\n * @param delegations : delegations (can be SPKs, CFKs, EKs) for all delegates\n * @param fallbackOnParent default true; use parent's healthCarePartyId in case there's no delegation for the `healthcarePartyId`\n * @returns - **delegatorId** : the id of the delegator HcP that shares the **key** with the `healthcarePartyId`\n * - **key** the decrypted HcPartyKey, shared between **delegatorId** and `healthcarePartyId`\n */\n async getDecryptedAesExchangeKeysOfDelegateAndParentsFromGenericDelegations(\n dataOwnerId: string,\n delegations: { [key: string]: Array<Delegation> },\n fallbackOnParent = true\n ): Promise<Array<DelegatorAndKeys>> {\n const delegationsArray = delegations[dataOwnerId] ?? []\n\n if (!delegationsArray.length && fallbackOnParent) {\n const { dataOwner: hcp } = await this.getDataOwner(dataOwnerId)\n return (hcp as any).parentId\n ? await this.getDecryptedAesExchangeKeysOfDelegateAndParentsFromGenericDelegations((hcp as any).parentId, delegations)\n : []\n } else {\n const delegatorIds = new Set<string>()\n delegationsArray.forEach((del) => delegatorIds.add(del.owner!))\n return this.decryptAndImportAesHcPartyKeysForDelegators(Array.from(delegatorIds), dataOwnerId)\n }\n }\n\n /**\n * Retrieve the owner HealthCareParty key and use it to encrypt\n * both the delegations (createdObject.id) and the cryptedForeignKeys\n * (parentObject.id), and returns them in an object.\n */\n async initObjectDelegations(\n createdObject: any,\n parentObject: any,\n ownerId: string,\n secretForeignKeyOfParent: string | null\n ): Promise<{\n owner: HealthcareParty | Device | Patient\n delegations: any\n cryptedForeignKeys: any\n secretForeignKeys: any[]\n secretId: string\n }> {\n const publicKeys = await this.getPublicKeys()\n\n this.throwDetailedExceptionForInvalidParameter('createdObject.id', createdObject.id, 'initObjectDelegations', arguments)\n\n if (parentObject) this.throwDetailedExceptionForInvalidParameter('parentObject.id', parentObject.id, 'initObjectDelegations', arguments)\n\n const secretId = this.randomUuid()\n return this.getDataOwner(ownerId).then(async ({ dataOwner: owner }) => {\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, ownerId)\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, ownerId, ownerId, publicKeys)\n\n const encryptedDelegation = await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(createdObject.id + ':' + secretId).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n )\n const encryptedSecretForeignKey =\n parentObject &&\n this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(createdObject.id + ':' + parentObject.id).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n )\n\n return {\n owner: modifiedOwner,\n delegations: _.fromPairs([\n [\n ownerId,\n [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedDelegation!),\n },\n ],\n ],\n ]),\n cryptedForeignKeys:\n (encryptedSecretForeignKey &&\n _.fromPairs([\n [\n ownerId,\n [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedSecretForeignKey!),\n },\n ],\n ],\n ])) ||\n {},\n secretForeignKeys: (secretForeignKeyOfParent && [secretForeignKeyOfParent]) || [],\n secretId: secretId,\n }\n })\n }\n\n private async decryptAnyAesExchangeKeyForOwner(\n aesExchangeKeys: { [p: string]: { [p: string]: string } },\n loggedHcPartyId: string,\n delegatorId: string,\n delegateHcPartyId: string,\n publicKeys: string[]\n ) {\n const importedAESHcPartyKey = await Object.entries(aesExchangeKeys).reduce(async (acc, [publicKeyIdentifier, hcPartyKeys]) => {\n const accValue = await acc\n if (accValue) {\n return accValue\n }\n try {\n return await this.decryptHcPartyKey(loggedHcPartyId, delegatorId, delegateHcPartyId, publicKeyIdentifier, hcPartyKeys, publicKeys)\n } catch (e) {\n return undefined\n }\n }, Promise.resolve() as Promise<DelegatorAndKeys | undefined>)\n\n if (!importedAESHcPartyKey) {\n throw new Error(`No hcParty key can be decrypted from ${delegatorId} to ${delegateHcPartyId} using currently available private keys`)\n }\n return importedAESHcPartyKey\n }\n\n /**\n * Gets updated instances of SPKs and CKFs for the child object `modifiedObject`.\n * These updated SPKs and CKFs contain new SPKs/CFKs to provide delegation from delegator HcP with id `ownerId` to delegate HcP with id `delegateId`\n *\n * 1. if `secretIdOfModifiedObject` is not provided, the method will throw an exception; this `secretIdOfModifiedObject` is used to generate a new delegation (SPK) in step 3;\n * the `secretIdOfModifiedObject` is returned, unmodified, as `secretId`\n * 2. if the owner (delegator) did not perform a delegation to the delegate, then this HcP delegation (creation of a new HcPKey) is performed now\n * 3. creates a new delegation (Secret Primary Keys) on the `modifiedObject` encrypted with the HcPKey from owner to the delegate;\n * 4. if `parentObject` != null, creates a new CFK on the `modifiedObject` encrypted with the HcPKey from owner to the delegate;\n * 5. this new delegation (from step 3) is added to the list of existing delegations (Secret Primary Keys) on the `modifiedObject` for the delegate given by `delegateId`\n * 6. if the CFK (from step 4) can be created, this new CFK is added to the list of existing CFKs on the `modifiedObject` for the delegate given by `delegateId`\n * 7. then some duplicates delegations (SPKs) and CKFs are removed\n *\n * @param modifiedObject : the object of which SPKs and CFKs will be cloned, the clones will be modified and then used as returned values ; it's a 'child' of `parentObject`; will NOT be mutated\n * @param parentObject : will NOT be mutated\n * @param ownerId : the HcP id of the delegator\n * @param delegateId : the HcP id of the delegate\n * @param secretIdOfModifiedObject : the secret id used in the child object to generate its SPK\n * @returns - **delegations** existing delegations (SPKs) of the `modifiedObject`, appended with results from step 5\n * - **cryptedForeignKeys** existing CFKs of the `modifiedObject`, appended with results from steps 6\n * - **secretId** which is the given input parameter `secretIdOfModifiedObject`\n */\n\n extendedDelegationsAndCryptedForeignKeys<T extends EncryptedEntity, P extends EncryptedParentEntity>(\n //TODO: suggested name: getExtendedChildObjectSPKandCFKwithDelegationFromDelegatorToDelegate\n modifiedObject: T,\n parentObject: P | null,\n ownerId: string,\n delegateId: string,\n secretIdOfModifiedObject: string | null\n ): Promise<{\n modifiedObject: T\n delegations: { [key: string]: Array<Delegation> }\n cryptedForeignKeys: { [key: string]: Array<Delegation> }\n secretId: string | null //TODO: why input parameter secretIdOfModifiedObject is returned?\n }> {\n this.throwDetailedExceptionForInvalidParameter('modifiedObject.id', modifiedObject.id, 'extendedDelegationsAndCryptedForeignKeys', arguments) //modifiedObject should never be null\n\n if (parentObject)\n this.throwDetailedExceptionForInvalidParameter('parentObject.id', parentObject?.id, 'extendedDelegationsAndCryptedForeignKeys', arguments)\n\n this.throwDetailedExceptionForInvalidParameter(\n 'secretIdOfModifiedObject',\n secretIdOfModifiedObject,\n 'extendedDelegationsAndCryptedForeignKeys',\n arguments\n )\n\n return this.getDataOwner(ownerId)\n .then(async ({ dataOwner: owner }) => {\n const publicKeys = await this.getPublicKeys()\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, delegateId)\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, delegateId, ownerId, publicKeys)\n\n modifiedObject = modifiedObject?.id === owner.id ? (modifiedOwner as T) : modifiedObject\n\n return {\n previousDecryptedDelegations: await Promise.all(\n ((modifiedObject.delegations || {})[delegateId] || []).map(\n (d: Delegation) =>\n (d.key &&\n d.owner === ownerId &&\n this._AES.decrypt(importedAESHcPartyKey.key, hex2ua(d.key), importedAESHcPartyKey.rawKey).catch(() => {\n console.log(\n `Cannot decrypt delegation from ${d.owner} to ${d.delegatedTo} for object with id ${modifiedObject.id}:`,\n modifiedObject\n )\n return Promise.resolve()\n })) ||\n Promise.resolve()\n ) as Array<Promise<ArrayBuffer>>\n ),\n\n previousDecryptedCryptedForeignKeys: await Promise.all(\n ((modifiedObject.cryptedForeignKeys || {})[delegateId] || []).map(\n (d: Delegation) =>\n (d.key &&\n d.owner === ownerId &&\n this._AES.decrypt(importedAESHcPartyKey.key, hex2ua(d.key), importedAESHcPartyKey.rawKey).catch(() => {\n console.log(\n `Cannot decrypt cryptedForeignKeys from ${d.owner} to ${d.delegatedTo} for object with id ${modifiedObject.id}:`,\n modifiedObject\n )\n return Promise.resolve()\n })) ||\n Promise.resolve()\n ) as Array<Promise<ArrayBuffer>>\n ),\n\n cryptedDelegation: await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(modifiedObject.id + ':' + secretIdOfModifiedObject!).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n ),\n\n cryptedForeignKey: parentObject\n ? await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(modifiedObject.id + ':' + parentObject.id).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n )\n : undefined,\n }\n })\n .then(({ previousDecryptedDelegations, previousDecryptedCryptedForeignKeys, cryptedDelegation, cryptedForeignKey }) => {\n //try to limit the extent of the modifications to the delegations by preserving the redundant delegation already present and removing duplicates\n //For delegate delegateId, we create:\n // 1. an array of objects { d : {owner,delegatedTo,encrypted(key)}} with one object for each existing delegation and the new key concatenated\n // 2. an array of objects { k : decrypted(key)} with one object for the existing delegations and the new key concatenated\n // We merge them to get one array of objects: { d: {owner,delegatedTo,encrypted(key)}, k: decrypted(key)}\n const delegationCryptedDecrypted = (\n _.merge(\n ((modifiedObject.delegations || {})[delegateId] || []).map((d: Delegation) => ({\n d,\n })),\n (previousDecryptedDelegations || []).map((dd) => (dd ? ua2string(dd) : null)).map((k) => ({ k }))\n ) as { d: Delegation; k: string }[]\n )\n .filter(({ d, k }) => !!k || d.owner !== ownerId) //Only keep the ones created by us that can still be decrypted\n .map(({ d, k }) => ({\n d,\n k: k || this.randomUuid(),\n })) // Use some unique id that ensures the delegation not created by us are going to be held\n .concat([\n {\n d: {\n owner: ownerId,\n delegatedTo: delegateId,\n key: ua2hex(cryptedDelegation!),\n },\n k: modifiedObject.id + ':' + secretIdOfModifiedObject!,\n },\n ])\n\n const allDelegations = _.cloneDeep(modifiedObject.delegations || {})\n\n //Only keep one version of the decrypted key\n allDelegations[delegateId] = _.uniqBy(delegationCryptedDecrypted, (x: any) => x.k).map((x: any) => x.d)\n\n const cryptedForeignKeysCryptedDecrypted = (\n _.merge(\n ((modifiedObject.cryptedForeignKeys || {})[delegateId] || []).map((d: Delegation) => ({\n d,\n })),\n (previousDecryptedCryptedForeignKeys || []).map((dd) => (dd ? ua2string(dd) : null)).map((k) => ({ k }))\n ) as { d: Delegation; k: string }[]\n )\n .filter(({ d, k }) => !!k || d.owner !== ownerId) //Only keep the ones created by us that can still be decrypted\n .map(({ d, k }: { d: Delegation; k: string }) => ({\n d,\n k: k || this.randomUuid(),\n })) // Use some unique id that ensures the delegation not created by us are going to be held\n .concat(\n cryptedForeignKey\n ? [\n {\n d: {\n owner: ownerId,\n delegatedTo: delegateId,\n key: ua2hex(cryptedForeignKey),\n },\n k: modifiedObject.id + ':' + parentObject?.id,\n },\n ]\n : []\n )\n\n const allCryptedForeignKeys = _.cloneDeep(modifiedObject.cryptedForeignKeys || {})\n if (cryptedForeignKeysCryptedDecrypted.length > 0) {\n allCryptedForeignKeys[delegateId] = _.uniqBy(cryptedForeignKeysCryptedDecrypted, (x: any) => x.k).map((x: any) => x.d)\n }\n\n return {\n modifiedObject,\n delegations: allDelegations,\n cryptedForeignKeys: allCryptedForeignKeys,\n secretId: secretIdOfModifiedObject,\n }\n })\n }\n\n async getEncryptedAesExchangeKeys(\n owner: HealthcareParty | Patient | Device,\n delegateId: string\n ): Promise<{ [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } }> {\n const publicKeys = await this.getPublicKeys()\n const mapOfAesExchangeKeys = Object.entries(owner.aesExchangeKeys ?? {})\n .filter((e) => e[1][delegateId] && Object.keys(e[1][delegateId]).some((k1) => publicKeys.some((pk) => pk.endsWith(k1))))\n .reduce((map, e) => {\n const candidates = Object.entries(e[1][delegateId])\n const [publicKeyFingerprint, encryptedAesExchangeKey] = candidates[candidates.findIndex(([k, v]) => publicKeys.some((pk) => pk.endsWith(k)))]\n return { ...map, [e[0]]: { [publicKeyFingerprint]: encryptedAesExchangeKey } }\n }, {} as { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } })\n\n return !owner.publicKey ||\n mapOfAesExchangeKeys[owner.publicKey] ||\n !owner.hcPartyKeys?.[delegateId] ||\n publicKeys.find((p) => p == owner.publicKey!) == undefined\n ? mapOfAesExchangeKeys\n : { ...mapOfAesExchangeKeys, [owner.publicKey]: { [owner.publicKey.slice(-32)]: owner.hcPartyKeys[delegateId][0] } }\n }\n\n async getOrCreateHcPartyKeys(\n owner: HealthcareParty | Patient | Device,\n delegateId: string\n ): Promise<{\n owner: HealthcareParty | Patient | Device\n aesExchangeKeys: { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } }\n }> {\n const aesExchangeKeys = await this.getEncryptedAesExchangeKeys(owner, delegateId)\n if (Object.keys(aesExchangeKeys).length) {\n return { owner, aesExchangeKeys }\n }\n\n const modifiedOwner = await this.generateKeyForDelegate(owner.id!, delegateId)\n return { owner: modifiedOwner, aesExchangeKeys: await this.getEncryptedAesExchangeKeys(modifiedOwner, delegateId) }\n }\n\n /**\n * Retrieve the owners HealthCareParty key, decrypt it, and\n * use it to encrypt & initialize the \"encryptionKeys\" object\n * and return it.\n * @param createdObject\n * @param ownerId\n */\n initEncryptionKeys(\n createdObject: any,\n ownerId: string\n ): Promise<{\n encryptionKeys: any\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('createdObject.id', createdObject.id, 'initEncryptionKeys', arguments)\n\n const secretId = this.randomUuid()\n return this.getDataOwner(ownerId).then(async ({ dataOwner: owner }) => {\n const publicKeys = await this.getPublicKeys()\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, ownerId)\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, ownerId, ownerId, publicKeys)\n const encryptedEncryptionKeys = await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(createdObject.id + ':' + secretId),\n importedAESHcPartyKey.rawKey\n )\n\n return {\n encryptionKeys: _.fromPairs([\n [\n ownerId,\n [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedEncryptionKeys),\n },\n ],\n ],\n ]),\n secretId: secretId,\n }\n })\n }\n\n /**\n * Gets an updated instance of the EKs of `modifiedObject`.\n * The updated EKs contain a new EK to provide delegation from delegator HcP with id `ownerId` to delegate HcP with id `delegateId`.\n * @param modifiedObject : the object of which EKs will be cloned, the clone will be used to append the new EK, and then used as return value; will NOT be mutated\n * @param ownerId : delegator HcP id\n * @param delegateId : delegate HcP id\n * @param secretEncryptionKeyOfObject : secret Id for the EK (Content Encryption Key)\n * @returns\n * - **encryptionKeys** existing EKs of the `modifiedObject`, appended with a new EK item (owner: `ownerId`, delegatedTo: `delegateId`, encrypted key with secretId:\n * `secretEncryptionKeyOfObject` )\n * - **secretId** which is the given input parameter `secretEncryptionKeyOfObject`\n */\n async appendEncryptionKeys(\n //TODO: suggested name: getExtendedEKwithDelegationFromDelegatorToDelegate\n modifiedObject: any,\n ownerId: string,\n delegateId: string,\n secretEncryptionKeyOfObject: string\n ): Promise<{\n encryptionKeys: { [key: string]: Array<Delegation> }\n secretId: string | null //secretEncryptionKeyOfObject is returned to avoid the need for a new decryption when chaining calls\n }> {\n this.throwDetailedExceptionForInvalidParameter('modifiedObject.id', modifiedObject.id, 'appendEncryptionKeys', arguments) //modifiedObject should never be null\n\n this.throwDetailedExceptionForInvalidParameter('secretEncryptionKeyOfObject', secretEncryptionKeyOfObject, 'appendEncryptionKeys', arguments)\n\n return this.getDataOwner(ownerId)\n .then(async ({ dataOwner: owner }) => {\n const publicKeys = await this.getPublicKeys()\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, delegateId)\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, ownerId, delegateId, publicKeys)\n\n return {\n previousDecryptedEncryptionKeys: await Promise.all(\n ((modifiedObject.encryptionKeys || {})[delegateId] || []).map(\n (d: Delegation) =>\n (d.key &&\n d.owner === ownerId &&\n this._AES.decrypt(importedAESHcPartyKey.key, hex2ua(d.key), importedAESHcPartyKey.rawKey).catch(() => {\n console.log(\n `Cannot decrypt encryption key from ${d.owner} to ${d.delegatedTo} for object with id ${modifiedObject.id}:`,\n modifiedObject\n )\n return Promise.resolve()\n })) ||\n Promise.resolve()\n ) as Array<Promise<ArrayBuffer>>\n ),\n encryptedEncryptionKey: await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(modifiedObject.id + ':' + secretEncryptionKeyOfObject)\n ),\n }\n })\n .then(({ previousDecryptedEncryptionKeys, encryptedEncryptionKey }) => {\n //try to limit the extent of the modifications to the delegations by preserving the redundant encryption keys already present and removing duplicates\n //For delegate delegateId, we create:\n // 1. an array of objects { d : {owner,delegatedTo,encrypted(key)}} with one object for the existing encryption keys and the new key concatenated\n // 2. an array of objects { k : decrypted(key)} with one object for the existing delegations and the new key concatenated\n // We merge them to get one array of objects: { d: {owner,delegatedTo,encrypted(key)}, k: decrypted(key)}\n const encryptionKeysCryptedDecrypted = _.merge(\n ((modifiedObject.encryptionKeys || {})[delegateId] || []).map((d: Delegation) => ({\n d,\n })),\n (previousDecryptedEncryptionKeys || []).map((dd) => (dd ? ua2string(dd) : null)).map((k) => ({ k }))\n )\n .filter(({ d, k }: { d: Delegation; k: string }) => !!k || d.owner !== ownerId) //Only keep the ones created by us that can still be decrypted\n .map(({ d, k }: { d: Delegation; k: string }) => ({ d, k: k || this.randomUuid() }))\n .concat([\n {\n d: {\n owner: ownerId,\n delegatedTo: delegateId,\n key: ua2hex(encryptedEncryptionKey),\n },\n k: modifiedObject.id + ':' + secretEncryptionKeyOfObject!,\n },\n ])\n\n const allEncryptionKeys = _.cloneDeep(modifiedObject.encryptionKeys)\n allEncryptionKeys[delegateId] = _.uniqBy(encryptionKeysCryptedDecrypted, (x: any) => x.k).map((x: any) => x.d)\n\n return {\n encryptionKeys: allEncryptionKeys,\n secretId: secretEncryptionKeyOfObject,\n }\n })\n }\n\n /**\n * Gets an updated `child` object that will have its SPKs, CFKs, KSs updated to include delegations from delegator HcP with id `ownerId` to delegate HcP with id `delegateId`\n * The SFKs of `child` are not updated, so this method assumes this is not the initial delegation on the `child` object\n * The method also performs some deduplication of all types of delegations.\n * @param parent : the parent object of `child`; will NOT be mutated\n * @param child : the object that will be mutated and returned\n * @param ownerId delegator HcP id\n * @param delegateId delegate HcP id\n * @param secretDelegationKey the secret Id used in the child object to generate the SPK\n * @param secretEncryptionKey the secret Id used in the child object to generate the EK (Content Encryption Key)\n * @returns - an updated `child` object that will contain updated SPKs, CFKs, EKs\n * */\n\n addDelegationsAndEncryptionKeys<T extends EncryptedEntity>(\n //TODO: suggested name: updateChildGenericDelegationsFromDelegatorToDelegate\n parent: EncryptedParentEntity | null,\n child: T,\n ownerId: string,\n delegateId: string,\n secretDelegationKey: string | null,\n secretEncryptionKey: string | null\n ): Promise<T> {\n if (parent) this.throwDetailedExceptionForInvalidParameter('parent.id', parent.id, 'addDelegationsAndEncryptionKeys', arguments)\n\n this.throwDetailedExceptionForInvalidParameter('child.id', child.id, 'addDelegationsAndEncryptionKeys', arguments)\n return (\n secretDelegationKey\n ? this.extendedDelegationsAndCryptedForeignKeys(child, parent, ownerId, delegateId, secretDelegationKey)\n : Promise.resolve({ modifiedObject: child, delegations: {}, cryptedForeignKeys: {}, secretId: null })\n )\n .then((extendedChildObjectSPKsAndCFKs) =>\n secretEncryptionKey\n ? this.appendEncryptionKeys(extendedChildObjectSPKsAndCFKs.modifiedObject, ownerId, delegateId, secretEncryptionKey).then(\n //TODO: extendedDelegationsAndCryptedForeignKeys and appendEncryptionKeys can be done in parallel\n (extendedChildObjectEKs) => ({\n extendedSPKsAndCFKs: extendedChildObjectSPKsAndCFKs,\n extendedEKs: extendedChildObjectEKs,\n })\n )\n : Promise.resolve({\n extendedSPKsAndCFKs: extendedChildObjectSPKsAndCFKs,\n extendedEKs: { encryptionKeys: {} },\n })\n )\n .then(({ extendedSPKsAndCFKs: extendedChildObjectSPKsAndCFKs, extendedEKs: extendedChildObjectEKs }) => {\n return _.assign(extendedChildObjectSPKsAndCFKs.modifiedObject, {\n // Conservative version ... We might want to be more aggressive with the deduplication of keys\n // For each delegate, we are going to concatenate to the src (the new delegations), the object in dest (the current delegations)\n // for which we do not find an equivalent delegation (same delegator, same delegate)\n delegations: _.assignWith(child.delegations, extendedChildObjectSPKsAndCFKs.delegations, (dest, src) =>\n (src || []).concat(\n _.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo))\n )\n ),\n cryptedForeignKeys: _.assignWith(child.cryptedForeignKeys, extendedChildObjectSPKsAndCFKs.cryptedForeignKeys, (dest, src) =>\n (src || []).concat(\n _.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo))\n )\n ),\n encryptionKeys: _.assignWith(child.encryptionKeys, extendedChildObjectEKs.encryptionKeys, (dest, src) =>\n (src || []).concat(\n _.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo))\n )\n ),\n })\n })\n }\n\n /**\n * Gets the secret IDs (SFKs) inside decrypted SPKs of the given `document`, decrypted by the HcP with the given `hcpartyId` AND by its HcP parents\n * @param document : the object of which delegations (SPKs) to decrypt\n * @param hcpartyId : the id of the delegate HcP\n * @returns - **extractedKeys** array containing secret IDs (SFKs) from decrypted SPKs, from both given HcP and its parents ; can contain duplicates\n * - **hcpartyId** the given `hcpartyId` OR, if a parent exist, the HcP id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n //TODO: even if there are no delegations for parent HCP (but the parent exists), the returned hcpartyId will be the one of the parent; is this ok?\n extractDelegationsSFKs(\n //TODO: suggested name: getSecretIDsSPKofHcpAndParentsFromDocument\n document: EncryptedEntity | null,\n hcpartyId?: string\n ): Promise<{ extractedKeys: Array<string>; hcpartyId?: string }> {\n if (!document || !hcpartyId) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId }) //TODO: thow exception instead?\n }\n const delegationsForAllDelegates = document.delegations\n if (!delegationsForAllDelegates || !Object.keys(delegationsForAllDelegates).length) {\n console.log(`There is no delegation in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return this.extractKeysFromDelegationsForHcpHierarchy(hcpartyId, document.id!, delegationsForAllDelegates)\n }\n\n /**\n * Gets the secret IDs (SFKs) inside decrypted SPKs of the given `document`, decrypted by the HcP with the given `hcpartyId` AND by its HcP parents\n * @param document : the object of which delegations (SPKs) to decrypt\n * @param hcpartyId : the id of the delegate HcP\n * @returns - **extractedKeys** array containing secret IDs (SFKs) from decrypted SPKs, from both given HcP and its parents ; can contain duplicates\n * - **hcpartyId** the given `hcpartyId` OR, if a parent exist, the HcP id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n extractSFKsHierarchyFromDelegations(\n document: EncryptedEntity | null,\n hcpartyId?: string\n ): Promise<Array<{ hcpartyId: string; extractedKeys: Array<string> }>> {\n if (!document || !hcpartyId) {\n return Promise.resolve([])\n }\n const delegationsForAllDelegates = document.delegations\n if (!delegationsForAllDelegates || !Object.keys(delegationsForAllDelegates).length) {\n console.log(`There is no delegation in document (${document.id})`)\n return Promise.resolve([])\n }\n return this.extractKeysHierarchyFromDelegationLikes(hcpartyId, document.id!, delegationsForAllDelegates)\n }\n\n // noinspection JSUnusedGlobalSymbols\n\n extractCryptedFKs(\n //TODO: suggested name: getSecretIDsCFKofHcpAndParentsFromDocument\n document: EncryptedEntity | null,\n hcpartyId: string\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document || !document.cryptedForeignKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const cfksForAllDelegates = document.cryptedForeignKeys\n if (!cfksForAllDelegates || !Object.keys(cfksForAllDelegates).length) {\n console.log(`There is no cryptedForeignKeys in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return this.extractKeysFromDelegationsForHcpHierarchy(hcpartyId, document.id!, cfksForAllDelegates)\n }\n\n extractEncryptionsSKs(\n //TODO: suggested name: getSecretIDsEKofHcpAndParentsFromDocument\n document: EncryptedEntity,\n hcpartyId: string\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document.encryptionKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const eckeysForAllDelegates = document.encryptionKeys\n if (!eckeysForAllDelegates || !Object.keys(eckeysForAllDelegates).length) {\n //console.log(`There is no encryption key in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return this.extractKeysFromDelegationsForHcpHierarchy(hcpartyId, document.id!, eckeysForAllDelegates)\n }\n\n extractDelegationsSFKsAndEncryptionSKs(ety: EncryptedEntity, ownerId: string) {\n const delegationsSfksOwnerPromise = this.extractDelegationsSFKs(ety, ownerId).then((xks) => xks.extractedKeys) //Will climb up hierarchy\n const encryptionKeysOwnerPromise = this.extractEncryptionsSKs(ety, ownerId).then((xks) => xks.extractedKeys) //Will climb up hierarchy\n\n return Promise.all([delegationsSfksOwnerPromise, encryptionKeysOwnerPromise])\n }\n\n /**\n * Get decrypted generic secret IDs (secretIdSPKs, parentIds, secretIdEKs) from generic delegations (SPKs, CFKs, EKs)\n * 1. Get HealthCareParty from it's Id.\n * 2. Decrypt the keys of the given HCP.\n * 3. Decrypt the parent's key if it has parent.\n * 4. Return the decrypted key corresponding to the Health Care Party.\n * @param hcpartyId : the id of the delegate HcP (including its parents) for which to decrypt `extractedKeys`\n * @param objectId : the id of the object/document of which delegations to decrypt ; used just to log to console a message (Cryptographic mistake) in case the object id inside SPK, CFK, EK is different from this one\n * @param delegations : generic delegations (can be SPKs, CFKs, EKs) for all delegates from where to extract `extractedKeys`\n * @returns - **extractedKeys** array containing secret IDs from decrypted generic delegations, from both HCP with given `hcpartyId` and its parents; can contain duplicates\n * - **hcpartyId** the given `hcpartyId` OR, if a parent exist, the HCP id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n //TODO: even if there are no delegations for parent HCP (but the parent exists), the returned hcpartyId will be the one of the parent\n async extractKeysHierarchyFromDelegationLikes(\n //TODO suggested name: getSecretIdsOfHcpAndParentsFromGenericDelegations\n hcpartyId: string,\n objectId: string,\n delegations: { [key: string]: Array<Delegation> }\n ): Promise<Array<{ hcpartyId: string; extractedKeys: Array<string> }>> {\n const { dataOwner: hcp } = await this.getDataOwner(hcpartyId)\n const extractedKeys = []\n if (delegations[hcpartyId]?.length) {\n const decryptedAndImportedAesHcPartyKeys = await this.getDecryptedAesExchangeKeysOfDelegateAndParentsFromGenericDelegations(\n hcpartyId,\n delegations,\n false\n )\n const collatedAesKeysFromDelegatorToHcpartyId = decryptedAndImportedAesHcPartyKeys.reduce((map, k) => ({ ...map, [k.delegatorId]: k }), {})\n extractedKeys.push(...(await this.decryptKeyInDelegationLikes(delegations[hcpartyId], collatedAesKeysFromDelegatorToHcpartyId, objectId)))\n }\n\n return (hcp as HealthcareParty).parentId\n ? [\n ...(await this.extractKeysHierarchyFromDelegationLikes((hcp as HealthcareParty).parentId!, objectId, delegations)),\n { extractedKeys: extractedKeys, hcpartyId: hcpartyId },\n ]\n : [{ extractedKeys: extractedKeys, hcpartyId: hcpartyId }]\n }\n\n /**\n * Get decrypted generic secret IDs (secretIdSPKs, parentIds, secretIdEKs) from generic delegations (SPKs, CFKs, EKs)\n * 1. Get Data Owner (HCP, Patient or Device) from it's Id.\n * 2. Decrypt the keys of the given data owner.\n * 3. Decrypt the parent's key if it has parent.\n * 4. Return the decrypted key corresponding to the Health Care Party.\n * @param dataOwnerId : the id of the delegate data owner (including its parents) for which to decrypt `extractedKeys`\n * @param objectId : the id of the object/document of which delegations to decrypt ; used just to log to console a message (Cryptographic mistake) in case the object id inside SPK, CFK, EK is different from this one\n * @param delegations : generic delegations (can be SPKs, CFKs, EKs) for all delegates from where to extract `extractedKeys`\n * @returns - **extractedKeys** array containing secret IDs from decrypted generic delegations, from both data owner with given `dataOwnerId` and its parents; can contain duplicates\n * - **dataOwnerId** the given `dataOwnerId` OR, if a parent exist, the data owner id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n //TODO: even if there are no delegations for parent HCP (but the parent exists), the returned dataOwnerId will be the one of the parent\n extractKeysFromDelegationsForHcpHierarchy(\n //TODO suggested name: getSecretIdsOfHcpAndParentsFromGenericDelegations\n dataOwnerId: string,\n objectId: string,\n delegations: { [key: string]: Array<Delegation> }\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n return this.getDataOwner(dataOwnerId).then(({ dataOwner: hcp }) =>\n (delegations[dataOwnerId] && delegations[dataOwnerId].length\n ? this.getDecryptedAesExchangeKeysOfDelegateAndParentsFromGenericDelegations(dataOwnerId, delegations, false).then(\n (decryptedAndImportedAesHcPartyKeys) => {\n const collatedAesKeysFromDelegatorToHcpartyId: {\n [key: string]: { key: CryptoKey; rawKey: string }[]\n } = {}\n decryptedAndImportedAesHcPartyKeys.forEach((k) => {\n ;(collatedAesKeysFromDelegatorToHcpartyId[k.delegatorId] ?? (collatedAesKeysFromDelegatorToHcpartyId[k.delegatorId] = [])).push(k)\n })\n return this.decryptKeyInDelegationLikes(delegations[dataOwnerId], collatedAesKeysFromDelegatorToHcpartyId, objectId!)\n }\n )\n : Promise.resolve([])\n ).then((extractedKeys) =>\n (hcp as HealthcareParty).parentId\n ? this.extractKeysFromDelegationsForHcpHierarchy((hcp as HealthcareParty).parentId!, objectId, delegations).then((parentResponse) =>\n _.assign(parentResponse, {\n extractedKeys: parentResponse.extractedKeys.concat(extractedKeys),\n })\n )\n : { extractedKeys: extractedKeys, hcpartyId: dataOwnerId }\n )\n )\n }\n\n /**\n * Gets an array of generic secret IDs decrypted from a list of generic delegations (SPKs, CFKs, EKs) `delegationsArray`\n * If a particular generic delegation thows an exception when decrypted, the return value for it's secret ID will be 'false' and a message is logged to console\n * For each one of the delegations in the `delegationsArray`, it tries to decrypt with the decryptedHcPartyKey of the owner of that delegation;\n *\n * @param delegationsArray : generic delegations array\n * @param aesKeys : **key** HcP ids of delegators/owners in the `delegationsArray`, each with its own decryptedHcPartyKey\n * @param masterId : is the object id to which the generic delegation belongs to\n * - used only to check whether the object.id matches the one stored in the decrypted generic delegation item\n * - even if there's no match, the secret ID is kept as a valid result (and a message logged to console)\n * @returns array of generic secret IDs (secretIdSPK, parentId, secretIdEK)\n */\n async decryptKeyInDelegationLikes(\n //TODO: suggested name: getSecretIdsFromGenericDelegations\n delegationsArray: Array<Delegation>,\n aesKeysForDataOwnerId: { [key: string]: { key: CryptoKey; rawKey: string }[] },\n masterId: string\n ): Promise<Array<string>> {\n const decryptPromises: Array<Promise<string | undefined>> = delegationsArray.map(async (genericDelegationItem) => {\n const aesKeys = aesKeysForDataOwnerId[genericDelegationItem.owner!]\n if (aesKeys?.length) {\n return aesKeys.reduce(async (acc, aesKey) => {\n const accValue = await acc\n if (accValue) {\n return accValue\n }\n try {\n const decryptedGenericDelegationKey = await this._AES.decrypt(aesKey.key, hex2ua(genericDelegationItem.key!), aesKey.rawKey)\n const results = ua2string(decryptedGenericDelegationKey).split(':')\n\n const objectId = results[0] //must be the ID of the object, for checksum\n const genericSecretId = results[1]\n\n const details =\n 'object ID: ' + masterId + '; generic delegation from ' + genericDelegationItem.owner + ' to ' + genericDelegationItem.delegatedTo\n\n if (!objectId) console.warn('Object id is empty; ' + details)\n if (!genericSecretId) console.warn('Secret id is empty; ' + details)\n\n if (objectId !== masterId) {\n /*console.log(\n \"Cryptographic mistake: object ID is not equal to the expected concatenated id within decrypted generic delegation. This may happen when patients have been merged; \" +\n details\n )*/\n }\n return genericSecretId\n } catch (err) {\n console.log(\n `Could not decrypt generic delegation in object with ID: ${masterId} from ${genericDelegationItem.owner} to ${genericDelegationItem.delegatedTo}: ${err}`\n )\n console.log(`AES key is: ${aesKey.rawKey}. Encrypted data is ${genericDelegationItem.key}.`)\n\n return undefined\n }\n }, Promise.resolve() as Promise<string | undefined>)\n } else {\n console.log(`Could not find aes key for object with ID: ${masterId}`)\n }\n })\n return Promise.all(decryptPromises).then((genericSecretId) => genericSecretId.filter((id) => !!id) as string[])\n }\n\n getPublicKeyFromPrivateKey(privateKey: JsonWebKey, dataOwner: Patient | Device | HealthcareParty) {\n if (!privateKey.n || !privateKey.e) {\n throw new Error('No public key can be deduced from incomplete private key')\n }\n\n const publicKeyFromPrivateKey = jwk2spki(privateKey)\n const publicKeys = [dataOwner.publicKey].concat(Object.keys(dataOwner.aesExchangeKeys ?? {})).filter((x) => !!x)\n\n if (!publicKeys.length) {\n throw new Error('No public key has been defined for hcp')\n }\n\n const publicKey = publicKeys.find((it) => it === publicKeyFromPrivateKey)\n if (!publicKey) {\n throw new Error('No public key can be found for this private key')\n }\n\n return publicKey\n }\n\n async loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId: string, privateKey: Uint8Array) {\n const { dataOwner } = await this.getDataOwner(healthcarePartyId)\n\n const privateKeyInJwk = pkcs8ToJwk(privateKey)\n const publicKey = this.getPublicKeyFromPrivateKey(privateKeyInJwk, dataOwner)\n\n const keyPair: { publicKey: CryptoKey; privateKey: CryptoKey } = await this._RSA.importKeyPair(\n 'jwk',\n privateKeyInJwk,\n 'jwk',\n spkiToJwk(hex2ua(publicKey))\n )\n this.rsaKeyPairs[publicKey.slice(-32)] = keyPair\n const exportedKeyPair = await this._RSA.exportKeys(keyPair, 'jwk', 'jwk')\n\n return this.storeKeyPair(`${healthcarePartyId}.${publicKey.slice(-32)}`, exportedKeyPair)\n }\n\n async loadKeyPairsAsJwkInBrowserLocalStorage(healthcarePartyId: string, privateKey: JsonWebKey) {\n const { dataOwner } = await this.getDataOwner(healthcarePartyId)\n\n if ((!privateKey.n || !privateKey.e) && dataOwner.publicKey) {\n //Fallback on default publicKey\n console.warn('An incomplete key has been completed using the default public key of the data owner')\n const publicKeyInJwk = spkiToJwk(hex2ua(dataOwner.publicKey))\n privateKey.n = publicKeyInJwk.n\n privateKey.e = publicKeyInJwk.e\n }\n\n const publicKey = this.getPublicKeyFromPrivateKey(privateKey, dataOwner)\n\n const keyPair = await this._RSA.importKeyPair('jwk', privateKey, 'jwk', spkiToJwk(hex2ua(publicKey)))\n this.rsaKeyPairs[healthcarePartyId] = keyPair\n const exportedKeyPair = await this._RSA.exportKeys(keyPair, 'jwk', 'jwk')\n\n return this.storeKeyPair(`${healthcarePartyId}.${publicKey.slice(-32)}`, exportedKeyPair)\n }\n\n // noinspection JSUnusedGlobalSymbols\n loadKeyPairsInBrowserLocalStorage(healthcarePartyId: string, file: Blob): Promise<void> {\n const fr = new FileReader()\n return new Promise((resolve, reject) => {\n fr.onerror = reject\n fr.onabort = reject\n fr.onload = (e: any) => {\n //TODO remove any\n const privateKey = e.target.result as string\n this.loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId, hex2ua(privateKey))\n .then(() => resolve())\n .catch(reject)\n }\n fr.readAsText(file)\n })\n }\n\n // noinspection JSUnusedGlobalSymbols\n saveKeychainInBrowserLocalStorage(id: string, keychain: number) {\n localStorage.setItem(\n this.keychainLocalStoreIdPrefix + id,\n b2a(new Uint8Array(keychain).reduce((data, byte) => data + String.fromCharCode(byte), ''))\n )\n }\n\n saveKeychainInBrowserLocalStorageAsBase64(id: string, keyChainB64: string) {\n localStorage.setItem(this.keychainLocalStoreIdPrefix + id, keyChainB64)\n }\n\n // noinspection JSUnusedGlobalSymbols\n saveKeychainValidityDateInBrowserLocalStorage(id: string, date: string) {\n if (!id) return\n\n if (!date) {\n localStorage.removeItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n } else {\n localStorage.setItem(this.keychainValidityDateLocalStoreIdPrefix + id, date)\n }\n }\n\n /**\n * Populate the HCP.options dict with an encrypted eHealth certificate and unencryped expiry date.\n * Any potentially unencrypted certificates will be pruned from the HCP.\n * @param hcpId Id of the hcp to modify\n * @returns modified HCP\n */\n async saveKeyChainInHCPFromLocalStorage(hcpId: string): Promise<HealthcareParty> {\n return await this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let aesKey: CryptoKey | null = null\n try {\n aesKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!aesKey) {\n console.error('No encryption key!')\n }\n\n const opts = hcp.options || {}\n\n const crt = this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!!)\n if (!!aesKey && !!crt) {\n let crtEncrypted: ArrayBuffer | null = null\n try {\n crtEncrypted = await this.AES.encrypt(aesKey, new Uint8Array(string2ua(atob(crt))))\n } catch (e) {\n console.error('Error while encrypting the certificate', e)\n }\n\n // add the encrypted certificate to the options\n _.set(opts, this.hcpPreferenceKeyEhealthCert, ua2string(new Uint8Array(crtEncrypted!)))\n }\n\n const crtValidityDate = this.getKeychainValidityDateInBrowserLocalStorage(hcp.id!!)\n if (!!crtValidityDate) {\n _.set(opts, this.hcpPreferenceKeyEhealthCertDate, crtValidityDate)\n }\n\n hcp.options = opts\n return hcp\n })\n }\n\n importKeychainInBrowserFromHCP(hcpId: string): Promise<void> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let crtCryp: Uint8Array | null = null\n if (!!hcp.options && !!hcp.options[this.hcpPreferenceKeyEhealthCert]) {\n crtCryp = string2ua(hcp.options[this.hcpPreferenceKeyEhealthCert])\n }\n\n const crtValidityDate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCertDate)\n\n // store the validity date\n if (!!crtValidityDate) {\n this.saveKeychainValidityDateInBrowserLocalStorage(hcp.id!!, crtValidityDate)\n }\n\n let crt: ArrayBuffer | null = null\n let decryptionKey: CryptoKey | null = null\n try {\n decryptionKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!decryptionKey) {\n throw new Error('No encryption key! eHealth certificate cannot be decrypted.')\n }\n\n if (!!crtCryp && decryptionKey) {\n try {\n crt = await this.AES.decrypt(decryptionKey, crtCryp)\n } catch (e) {\n console.error(e)\n }\n }\n\n if (!crt) {\n throw new Error(`Error while saving certificate in browser local storage! Hcp ${hcp.id} has no certificate.`)\n } else {\n this.saveKeychainInBrowserLocalStorageAsBase64(hcp.id!!, btoa(String.fromCharCode.apply(null, Array.from(new Uint8Array(crt)))))\n }\n\n return\n })\n }\n\n /**\n * Synchronizes the eHealth certificate from the database into the LocalStorage, returning information on the presence\n * of certificate data in either place.\n *\n * @param hcpId The healthcare party id\n * @returns A Promise for an object that represents the existence of a certificate in local storage and in the DB,\n * through the two boolean properties \"local\" and \"remote\".\n */\n syncEhealthCertificateFromDatabase(hcpId: string): Promise<{ remote: boolean; local: boolean }> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then((hcp: HealthcareParty) => {\n const remoteCertificate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCert)\n const localCertificate = this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!)\n\n if (remoteCertificate) {\n return this.importKeychainInBrowserFromHCP(hcp.id!)\n .then(() => ({ local: true, remote: true }))\n .catch(() => ({ local: !!localCertificate, remote: true }))\n } else {\n return { local: !!localCertificate, remote: !!remoteCertificate }\n }\n })\n }\n\n getKeychainInBrowserLocalStorageAsBase64(id: string) {\n return localStorage.getItem(this.keychainLocalStoreIdPrefix + id)\n }\n\n getKeychainValidityDateInBrowserLocalStorage(id: string) {\n return localStorage.getItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n }\n\n // noinspection JSUnusedGlobalSymbols\n loadKeychainFromBrowserLocalStorage(id: string) {\n const lsItem = localStorage.getItem('org.taktik.icure.ehealth.keychain.' + id)\n return lsItem !== null ? b64_2uas(lsItem) : null\n }\n\n /**\n *\n * @param id\n * @param keyPair should be JWK\n */\n storeKeyPair(id: string, keyPair: { publicKey: any; privateKey: any }) {\n if (typeof Storage === 'undefined') {\n console.log('Your browser does not support HTML5 Browser Local Storage !')\n throw 'Your browser does not support HTML5 Browser Local Storage !'\n }\n //TODO encryption\n localStorage.setItem(this.rsaLocalStoreIdPrefix + id, JSON.stringify(keyPair))\n }\n\n /**\n * loads the RSA key pair (hcparty) in JWK from local storage, not imported\n *\n * @param id doc id - hcpartyId\n * @param publicKeyFingerPrint the 32 last characters of public key this private key is associated with\n * @returns {Object} it is in JWK - not imported\n */\n loadKeyPairNotImported(id: string, publicKeyFingerPrint?: string): { publicKey: JsonWebKey; privateKey: JsonWebKey } {\n if (typeof Storage === 'undefined') {\n console.log('Your browser does not support HTML5 Browser Local Storage !')\n throw 'Your browser does not support HTML5 Browser Local Storage !'\n }\n //TODO decryption\n const item =\n (publicKeyFingerPrint && localStorage.getItem(this.rsaLocalStoreIdPrefix + id + '.' + publicKeyFingerPrint)) ??\n localStorage.getItem(this.rsaLocalStoreIdPrefix + id)\n if (!item) {\n console.warn(`No key can be found in local storage for id ${id} and publicKeyFingerPrint ${publicKeyFingerPrint}`)\n }\n return JSON.parse(item!)\n }\n\n /**\n * Loads and imports the RSA key pair (hcparty) from local storage\n *\n * @param id doc id - hcPartyId\n * @returns {Promise} -> {CryptoKey} - imported RSA\n */\n loadKeyPairImported(id: string) {\n return new Promise((resolve: (value: { publicKey: CryptoKey; privateKey: CryptoKey }) => any, reject) => {\n try {\n const jwkKey = localStorage.getItem(this.rsaLocalStoreIdPrefix + id) as string\n if (jwkKey) {\n const jwkKeyPair = JSON.parse(jwkKey)\n if (jwkKeyPair.publicKey && jwkKeyPair.privateKey) {\n this._RSA.importKeyPair('jwk', jwkKeyPair.privateKey, 'jwk', jwkKeyPair.publicKey).then(resolve, (err) => {\n console.log('Error in RSA.importKeyPair: ' + err)\n reject(err)\n })\n } else {\n const message = 'Error in RSA.importKeyPair: Invalid key'\n console.log(message)\n reject(Error(message))\n }\n } else {\n const message = 'Error in RSA.importKeyPair: Missing key'\n console.log(message)\n reject(Error(message))\n }\n } catch (err) {\n reject(err)\n }\n })\n }\n\n async addNewKeyPairForOwnerId(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n ownerId: string,\n generateTransferKey: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n return this.addNewKeyPairForOwner(maintenanceTasksApi, user, await this.getDataOwner(ownerId), generateTransferKey)\n }\n\n async addNewKeyPairForOwner(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n cdo: CachedDataOwner,\n generateTransferKey: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n const { publicKey, privateKey } = await this.RSA.generateKeyPair()\n const publicKeyHex = ua2hex(await this.RSA.exportKey(publicKey!, 'spki'))\n\n const gen = (await this._AES.generateCryptoKey(true)) as string\n\n await this.cacheKeyPair({ publicKey: await this.RSA.exportKey(publicKey!, 'jwk'), privateKey: await this.RSA.exportKey(privateKey!, 'jwk') })\n\n const { type: ownerType, dataOwner: ownerToUpdate } = await this.createOrUpdateAesExchangeKeysFor(cdo, gen, {\n pubKey: publicKey,\n privKey: privateKey,\n }).then((dataOwnerWithUpdatedAesKeys) =>\n generateTransferKey\n ? this.createOrUpdateTransferKeysFor(dataOwnerWithUpdatedAesKeys, gen, { pubKey: publicKey, privKey: privateKey })\n : dataOwnerWithUpdatedAesKeys\n )\n\n const modifiedDataOwnerAndType =\n ownerType === 'hcp'\n ? await (this.dataOwnerCache[ownerToUpdate.id!] = this.hcpartyBaseApi\n .modifyHealthcareParty(ownerToUpdate as HealthcareParty)\n .then((x) => ({ type: 'hcp', dataOwner: x } as CachedDataOwner)))\n : ownerType === 'patient'\n ? await (this.dataOwnerCache[ownerToUpdate.id!] = this.patientBaseApi\n .modifyPatient(ownerToUpdate as Patient)\n .then((x) => ({ type: 'patient', dataOwner: x } as CachedDataOwner)))\n : await (this.dataOwnerCache[ownerToUpdate.id!] = this.deviceBaseApi\n .updateDevice(ownerToUpdate as Device)\n .then((x) => ({ type: 'device', dataOwner: x } as CachedDataOwner)))\n\n const sentMaintenanceTasks = await this.sendMaintenanceTasks(maintenanceTasksApi, user, modifiedDataOwnerAndType.dataOwner, publicKey)\n\n return {\n dataOwner: sentMaintenanceTasks.length\n ? await this.retrieveDataOwnerInfoAfterPotentialUpdate(modifiedDataOwnerAndType.dataOwner)\n : modifiedDataOwnerAndType.dataOwner,\n publicKey: publicKeyHex,\n privateKey: ua2hex((await this.RSA.exportKey(privateKey!, 'pkcs8')) as ArrayBuffer),\n }\n }\n\n private async createOrUpdateAesExchangeKeysFor(\n cdo: CachedDataOwner,\n decryptedAesExchangeKey: string,\n keyToEncrypt: { pubKey: CryptoKey; privKey: CryptoKey }\n ): Promise<CachedDataOwner> {\n const publicKeyHex = ua2hex(await this.RSA.exportKey(keyToEncrypt.pubKey!, 'spki'))\n const existingAesExchangeKeys = cdo.dataOwner.aesExchangeKeys ?? {}\n existingAesExchangeKeys[publicKeyHex] = await this.encryptAesKeyFor(decryptedAesExchangeKey, cdo.dataOwner, keyToEncrypt.pubKey)\n\n return { type: cdo.type, dataOwner: { ...cdo.dataOwner, aesExchangeKeys: existingAesExchangeKeys } } as CachedDataOwner\n }\n\n private async createOrUpdateTransferKeysFor(\n dataOwner: CachedDataOwner,\n decryptedAesExchangeKey: string,\n keyToEncrypt: { pubKey: CryptoKey; privKey: CryptoKey }\n ): Promise<CachedDataOwner> {\n const pubKeyToEncryptHex = ua2hex(await this.RSA.exportKey(keyToEncrypt.pubKey, 'spki'))\n\n const encryptedKey = ua2hex(\n await this._AES.encrypt(\n await this._AES.importKey('raw', hex2ua(decryptedAesExchangeKey)),\n (await this.RSA.exportKey(keyToEncrypt.privKey!, 'pkcs8')) as ArrayBuffer,\n decryptedAesExchangeKey\n )\n )\n\n const dataOwnerExistingPubKeys = Array.from(await this.getDataOwnerHexPublicKeys(dataOwner.dataOwner))\n\n const transferKeys = fold(dataOwnerExistingPubKeys, dataOwner.dataOwner.transferKeys ?? {}, (pubAcc, pubKeyHex) => {\n if (pubKeyHex !== pubKeyToEncryptHex) {\n const existingKeys = pubAcc[pubKeyHex] ?? {}\n existingKeys[pubKeyToEncryptHex] = encryptedKey\n pubAcc[pubKeyHex] = existingKeys\n }\n return pubAcc\n })\n\n return { type: dataOwner.type, dataOwner: { ...dataOwner.dataOwner, transferKeys: transferKeys } } as CachedDataOwner\n }\n\n private async encryptAesKeyFor(\n aesKey: string,\n dataOwner: HealthcareParty | Patient | Device,\n doNewPublicKey: CryptoKey\n ): Promise<{ [delId: string]: { [pk: string]: string } }> {\n const dataOwnerAllPubKeys = [doNewPublicKey].concat(await this.getDataOwnerPublicKeys(dataOwner))\n\n const encrAes: { [pubKeyFingerprint: string]: string } = {}\n for (const pubKey of dataOwnerAllPubKeys) {\n encrAes[ua2hex(await this.RSA.exportKey(pubKey, 'spki')).slice(-32)] = ua2hex(await this._RSA.encrypt(pubKey, hex2ua(aesKey)))\n }\n\n return { [dataOwner.id!]: encrAes }\n }\n\n private retrieveDataOwnerInfoAfterPotentialUpdate(dataOwnerToUpdate: HealthcareParty | Patient | Device): Promise<CachedDataOwner> {\n return this.getDataOwner(dataOwnerToUpdate.id!).then(({ type, dataOwner }) => {\n return {\n type: type,\n dataOwner: {\n ...dataOwner,\n transferKeys: dataOwnerToUpdate.transferKeys,\n hcPartyKeys: fold(Object.entries(dataOwnerToUpdate.hcPartyKeys ?? {}), dataOwner.hcPartyKeys ?? {}, (acc, [delegateId, hcKeys]) => {\n acc[delegateId] = hcKeys\n return acc\n }),\n aesExchangeKeys: fold(\n Object.entries(dataOwnerToUpdate.aesExchangeKeys ?? {}),\n dataOwner.aesExchangeKeys ?? {},\n (pubAcc, [pubKey, newAesExcKeys]) => {\n const existingKeys = pubAcc[pubKey] ?? {}\n pubAcc[pubKey] = fold(Object.entries(newAesExcKeys), existingKeys, (delAcc, [delId, delKeys]) => {\n delAcc[delId] = delKeys\n return delAcc\n })\n return pubAcc\n }\n ),\n },\n } as CachedDataOwner\n })\n }\n\n private async sendMaintenanceTasks(\n maintenanceTaskApi: IccMaintenanceTaskXApi,\n user: User,\n dataOwner: HealthcareParty | Patient | Device,\n newPublicKey: CryptoKey\n ): Promise<MaintenanceTask[]> {\n const hexNewPubKey = ua2hex(await this.RSA.exportKey(newPublicKey, 'spki'))\n const nonAccessiblePubKeys = Array.from(this.getDataOwnerHexPublicKeys(dataOwner).values())\n .filter((existingPubKey) => existingPubKey != hexNewPubKey)\n .filter(\n (existingPubKey) =>\n !Object.values(this.rsaKeyPairs).find(\n async ({ publicKey, privateKey }) => ua2hex(await this.RSA.exportKey(publicKey, 'spki')) == existingPubKey\n )\n )\n\n if (nonAccessiblePubKeys.length) {\n const tasksForDelegates = Object.entries(await this.getEncryptedAesExchangeKeysForDelegate(dataOwner.id!))\n .filter(([delegatorId]) => delegatorId != dataOwner.id)\n .flatMap(([delegatorId, delegatorKeys]) => {\n return Object.entries(delegatorKeys).flatMap(([, aesExchangeKeys]) => {\n return Object.keys(aesExchangeKeys).map((delegatePubKey) => {\n return { delegateId: delegatorId, maintenanceTask: this.createMaintenanceTask(dataOwner, delegatePubKey) }\n })\n })\n })\n\n const tasksForDelegator = Object.entries(await this.getEncryptedAesExchangeKeys(dataOwner, dataOwner.id!)).flatMap(\n ([doPubKey, delegateKeys]) => {\n return Object.keys(delegateKeys)\n .filter((delegateId) => delegateId != dataOwner.id)\n .map((delegateId) => {\n return { delegateId: delegateId, maintenanceTask: this.createMaintenanceTask(dataOwner, doPubKey) }\n })\n }\n )\n\n return Promise.all(\n tasksForDelegates\n .concat(tasksForDelegator)\n .map(async ({ delegateId, maintenanceTask }) => {\n const taskToCreate = await maintenanceTaskApi?.newInstance(user, maintenanceTask, [delegateId])\n return taskToCreate ? maintenanceTaskApi?.createMaintenanceTaskWithUser(user, taskToCreate) : undefined\n })\n .filter((createdTask) => createdTask != undefined)\n )\n } else {\n return []\n }\n }\n\n private createMaintenanceTask(concernedDataOwner: HealthcareParty | Patient | Device, concernedPubKey: string) {\n return new MaintenanceTask({\n id: this.randomUuid(),\n taskType: 'updateAesExchangeKey',\n status: MaintenanceTask.StatusEnum.Pending,\n properties: [\n new PropertyStub({\n id: 'dataOwnerConcernedId',\n type: new PropertyTypeStub({ type: PropertyTypeStub.TypeEnum.STRING }),\n typedValue: new TypedValueObject({\n type: TypedValueObject.TypeEnum.STRING,\n stringValue: concernedDataOwner.id,\n }),\n }),\n new PropertyStub({\n id: 'dataOwnerConcernedPubKey',\n type: new PropertyTypeStub({ type: PropertyTypeStub.TypeEnum.STRING }),\n typedValue: new TypedValueObject({\n type: TypedValueObject.TypeEnum.STRING,\n stringValue: concernedPubKey,\n }),\n }),\n ],\n })\n }\n\n private getDataOwnerHexPublicKeys(dataOwner: HealthcareParty | Patient | Device): Set<string> {\n return new Set(\n (dataOwner.publicKey ? [dataOwner.publicKey] : [])\n .concat(dataOwner.aesExchangeKeys ? Object.keys(dataOwner.aesExchangeKeys) : [])\n .filter((pubKey) => !!pubKey)\n )\n }\n\n private async getDataOwnerPublicKeys(dataOwner: HealthcareParty | Patient | Device): Promise<CryptoKey[]> {\n return await Promise.all(\n Array.from(this.getDataOwnerHexPublicKeys(dataOwner)).map(\n async (pubKey) => await this._RSA.importKey('jwk', spkiToJwk(hex2ua(pubKey)), ['encrypt'])\n )\n )\n }\n\n generateKeyForDelegate(ownerId: string, delegateId: string): PromiseLike<HealthcareParty | Patient> {\n //Preload hcp and patient because we need them and they are going to be invalidated from the caches\n return notConcurrent(this.generateKeyConcurrencyMap, ownerId, async () => {\n const [{ type: ownerType, dataOwner: owner }, { dataOwner: delegate }] = await Promise.all([\n this.getDataOwner(ownerId),\n this.getDataOwner(delegateId),\n ])\n\n const ownerLegacyPublicKey = owner.publicKey\n\n const availablePublicKeysFingerprints = Object.keys(this.rsaKeyPairs)\n const availableOwnerPublicKeys = [\n ownerLegacyPublicKey,\n ...Object.keys(owner.aesExchangeKeys || {}).filter((x) => x !== ownerLegacyPublicKey),\n ].filter((k) => !!k && availablePublicKeysFingerprints.some((fp) => k.endsWith(fp))) as string[]\n const selectedPublicKey = availableOwnerPublicKeys[0]\n\n if (!selectedPublicKey) {\n throw new Error(`Invalid owner, no public key, keypairs have not be set for ${ownerId}`)\n }\n\n if (\n ((owner.hcPartyKeys || {})[delegateId] && owner.publicKey && availablePublicKeysFingerprints.includes(owner.publicKey.slice(-32))) ||\n Object.values(owner.aesExchangeKeys || {}).some(\n (x) => x[delegateId] && Object.keys(x[delegateId]).some((k) => availablePublicKeysFingerprints.includes(k))\n )\n ) {\n return owner\n }\n\n let ownerCombinedAesExchangeKeys = owner.aesExchangeKeys ?? {}\n\n if (ownerLegacyPublicKey && !(owner.aesExchangeKeys ?? {})[ownerLegacyPublicKey]) {\n //Transfer keys from old structure (hcparty keys) to new one (aesExchangeKeys)\n const unknownDataOwnerCounterPartIds = Object.keys(owner.hcPartyKeys ?? {}).filter((x) => x !== ownerId && x !== delegateId)\n const counterParts = [\n owner,\n delegate,\n ...(await Promise.all(unknownDataOwnerCounterPartIds.map((cpid) => this.getDataOwner(cpid).then((dot) => dot.dataOwner)))),\n ]\n ownerCombinedAesExchangeKeys = {\n [ownerLegacyPublicKey]: Object.entries(owner.hcPartyKeys ?? {}).reduce(\n (map, [hcpId, keys]) => ({\n ...map,\n [hcpId]: { [ownerLegacyPublicKey]: keys[0], [counterParts.find((x) => x.id === hcpId)?.publicKey ?? '']: keys[1] },\n ...{},\n }),\n {}\n ),\n ...ownerCombinedAesExchangeKeys,\n }\n }\n\n const delegatePublicKeys = [delegate.publicKey, ...Object.keys(delegate.aesExchangeKeys ?? {}).filter((x) => x !== delegate.publicKey)].filter(\n (x) => !!x\n ) as string[]\n if (!delegatePublicKeys.length) {\n throw new Error(`Invalid delegate, no public key, keypairs have not be set for ${delegateId}`)\n }\n const genProm = this._AES.generateCryptoKey(true).then(async (AESKey) => {\n const allPubKeys = [...availableOwnerPublicKeys, ...delegatePublicKeys]\n const encryptedAesKeys = await allPubKeys.reduce(\n async (map, pubK) => ({\n ...(await map),\n [pubK.slice(-32)]: ua2hex(\n await this._RSA.encrypt(await this._RSA.importKey('jwk', spkiToJwk(hex2ua(pubK)), ['encrypt']), hex2ua(AESKey as string))\n ),\n }),\n Promise.resolve({} as { [pubKey: string]: string })\n )\n\n if (delegate.publicKey && ownerLegacyPublicKey) {\n owner.hcPartyKeys![delegateId] = [encryptedAesKeys[ownerLegacyPublicKey.slice(-32)], encryptedAesKeys[delegate.publicKey.slice(-32)]]\n }\n owner.aesExchangeKeys = {\n ...(ownerCombinedAesExchangeKeys ?? {}),\n [selectedPublicKey]: { ...(owner.aesExchangeKeys?.[selectedPublicKey] ?? {}), [delegateId]: encryptedAesKeys },\n }\n\n return new Promise<['hcp', HealthcareParty] | ['patient', Patient] | ['device', Device]>((resolve, reject) => {\n ownerType === 'hcp'\n ? (this.dataOwnerCache[owner.id!] = this.hcpartyBaseApi\n .modifyHealthcareParty(owner as HealthcareParty)\n .then((x) => ({ type: 'hcp', dataOwner: x } as CachedDataOwner)))\n .then((x) => resolve(['hcp', x.dataOwner]))\n .catch((e) => reject(e))\n : ownerType === 'patient'\n ? (this.dataOwnerCache[owner.id!] = this.patientBaseApi.modifyPatient(owner as Patient).then((x) => ({ type: 'patient', dataOwner: x })))\n .then((x) => resolve(['patient', x.dataOwner]))\n .catch((e) => reject(e))\n : (this.dataOwnerCache[owner.id!] = this.deviceBaseApi.updateDevice(owner as Device).then((x) => ({ type: 'device', dataOwner: x })))\n .then((x) => resolve(['device', x.dataOwner]))\n .catch((e) => reject(e))\n })\n })\n\n this.hcPartyKeysRequestsCache[delegateId] = genProm.then(() => {\n return this.forceGetEncryptedAesExchangeKeysForDelegate(delegateId)\n })\n return genProm.then((res) => {\n return res[1]\n })\n })\n }\n\n getDataOwner(ownerId: string) {\n return (\n this.dataOwnerCache[ownerId] ??\n (this.dataOwnerCache[ownerId] = this.patientBaseApi\n .getPatient(ownerId)\n .then((x) => ({ type: 'patient', dataOwner: x } as CachedDataOwner))\n .catch(() => this.deviceBaseApi.getDevice(ownerId).then((x) => ({ type: 'device', dataOwner: x } as CachedDataOwner)))\n .catch(() => this.hcpartyBaseApi.getHealthcareParty(ownerId).then((x) => ({ type: 'hcp', dataOwner: x } as CachedDataOwner)))\n .catch((e) => {\n delete this.dataOwnerCache[ownerId]\n throw e\n }))\n )\n }\n\n // noinspection JSUnusedGlobalSymbols\n async checkPrivateKeyValidity(dataOwner: HealthcareParty | Patient | Device): Promise<boolean> {\n const publicKeys = Array.from(new Set([dataOwner.publicKey].concat(Object.keys(dataOwner.aesExchangeKeys ?? {})).filter((x) => !!x))) as string[]\n\n return await publicKeys.reduce(async (pres, publicKey) => {\n const res = await pres\n try {\n const k = await this._RSA.importKey('jwk', spkiToJwk(hex2ua(publicKey)), ['encrypt'])\n const cipher = await this._RSA.encrypt(k, utf8_2ua('shibboleth'))\n const kp = this.loadKeyPairNotImported(dataOwner.id!, publicKey.slice(-32))\n const plainText = await this._RSA\n .importKeyPair('jwk', kp.privateKey, 'jwk', kp.publicKey)\n .then((ikp) => this._RSA.decrypt(ikp.privateKey, new Uint8Array(cipher)))\n .then((x) => ua2utf8(x))\n return plainText === 'shibboleth' || res\n } catch (e) {\n return res\n }\n }, Promise.resolve(false))\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: any) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n _.each(argsArray, (arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw '### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details\n }\n\n async getEncryptionDecryptionKeys(dataOwnerId: string, document: EncryptedEntity): Promise<Array<string> | undefined> {\n try {\n return !document.id\n ? undefined\n : _.uniq(\n (\n await this.extractKeysFromDelegationsForHcpHierarchy(\n dataOwnerId,\n document.id,\n (document.encryptionKeys && Object.keys(document.encryptionKeys).length && document.encryptionKeys) || document.delegations!\n )\n ).extractedKeys\n )\n } catch (e) {\n return undefined\n }\n }\n\n async encryptDecrypt(\n method: 'encrypt' | 'decrypt',\n content: Uint8Array | ArrayBuffer,\n edKey?: string,\n user?: User,\n documentObject?: Document\n ): Promise<Uint8Array | Array<any> | any> {\n if (!content || !(edKey || (user?.healthcarePartyId && documentObject))) return content\n\n if (edKey) {\n const importedEdKey = await this._AES.importKey('raw', hex2ua(edKey.replace(/-/g, '')))\n try {\n return await this._AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n const sfks = await this.extractKeysFromDelegationsForHcpHierarchy(user?.healthcarePartyId!, documentObject?.id!, documentObject?.encryptionKeys!)\n const importedEdKey = await this._AES.importKey('raw', hex2ua(sfks.extractedKeys[0].replace(/-/g, '')))\n try {\n return await this._AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n}\n"]}
1
+ {"version":3,"file":"icc-crypto-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-crypto-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,sCAAuC;AACvC,sCAAuC;AACvC,4CAA6C;AAE7C,4BAA2B;AAC3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CAAE,iBAAiB,KAAI,cAAc,CAAC,CAAC;gBAAE,OAAO,OAAO,CAAA;YAEvF,IAAI,KAAK,EAAE;gBACT,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAA,qBAAM,EAAC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;gBACvF,IAAI;oBACF,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,aAAa,EAAE,OAAO,CAAC,CAAA;iBACvD;gBAAC,OAAO,CAAC,EAAE;oBACV,OAAO,OAAO,CAAA;iBACf;aACF;YAED,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,yCAAyC,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,iBAAkB,EAAE,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,EAAG,EAAE,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,cAAe,CAAC,CAAA;YACjJ,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAA,qBAAM,EAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;YACvG,IAAI;gBACF,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,aAAa,EAAE,OAAO,CAAC,CAAA;aACvD;YAAC,OAAO,CAAC,EAAE;gBACV,OAAO,OAAO,CAAA;aACf;QACH,CAAC;KAAA;CACF;AAh8DD,sCAg8DC","sourcesContent":["import { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../icc-api'\nimport { AESUtils } from './crypto/AES'\nimport { RSAUtils } from './crypto/RSA'\nimport { ShamirClass } from './crypto/shamir'\n\nimport * as _ from 'lodash'\nimport {\n Delegation,\n Device,\n Document,\n EncryptedEntity,\n EncryptedParentEntity,\n HealthcareParty,\n MaintenanceTask,\n Patient,\n PropertyStub,\n PropertyTypeStub,\n TypedValueObject,\n User,\n} from '../icc-api/model/models'\nimport { b2a, b64_2uas, hex2ua, string2ua, ua2hex, ua2string, ua2utf8, utf8_2ua } from './utils/binary-utils'\nimport { fold, jwk2spki, notConcurrent, pkcs8ToJwk, spkiToJwk } from './utils'\nimport { IccMaintenanceTaskXApi } from './icc-maintenance-task-x-api'\n\ninterface DelegatorAndKeys {\n delegatorId: string\n key: CryptoKey\n rawKey: string\n}\n\ntype CachedDataOwner =\n | {\n type: 'patient'\n dataOwner: Patient\n }\n | {\n type: 'device'\n dataOwner: Device\n }\n | {\n type: 'hcp'\n dataOwner: HealthcareParty\n }\n\nexport class IccCryptoXApi {\n get crypto(): Crypto {\n return this._crypto\n }\n\n get shamir(): ShamirClass {\n return this._shamir\n }\n\n get RSA(): RSAUtils {\n return this._RSA\n }\n\n get AES(): AESUtils {\n return this._AES\n }\n\n hcPartyKeysCache: {\n [key: string]: DelegatorAndKeys\n } = {}\n\n //[delegateId][delegatorId] = delegateEncryptedHcPartyKey\n //for each delegate, it stores the list of delegators and the corresponding delegateEncryptedHcPartyKey (shared HcPartyKey, from delegator to delegate, encrypted with the RSA key of the delegate)\n hcPartyKeysRequestsCache: {\n [delegateId: string]: Promise<{ [key: string]: { [key: string]: { [key: string]: string } } }>\n } = {}\n\n cacheLastDeletionTimestamp: number | undefined = undefined\n\n dataOwnerCache: { [key: string]: Promise<CachedDataOwner> } = {}\n\n emptyHcpCache(hcpartyId: string) {\n delete this.hcPartyKeysRequestsCache[hcpartyId]\n delete this.dataOwnerCache[hcpartyId]\n }\n\n /**\n * Gets all delegate encrypted HcParty keys of the delegate with the given `delegateHcPartyId`, and for each key the delegator id\n * If the keys are not cached, they are retrieved from the backend.\n *\n * @param delegateHcPartyId The Health Care Party id\n * @returns \\{delegatorId: delegateEncryptedHcPartyKey\\}\n */\n private getEncryptedAesExchangeKeysForDelegate(\n delegateHcPartyId: string\n ): Promise<{ [key: string]: { [key: string]: { [key: string]: string } } }> {\n return (\n this.hcPartyKeysRequestsCache[delegateHcPartyId] ||\n (this.hcPartyKeysRequestsCache[delegateHcPartyId] = this.forceGetEncryptedAesExchangeKeysForDelegate(delegateHcPartyId))\n )\n }\n\n private forceGetEncryptedAesExchangeKeysForDelegate(\n delegateHcPartyId: string\n ): Promise<{ [key: string]: { [key: string]: { [key: string]: string } } }> {\n return Promise.all([\n this.patientBaseApi.getPatientAesExchangeKeysForDelegate(delegateHcPartyId).catch(() => {}),\n this.hcpartyBaseApi.getAesExchangeKeysForDelegate(delegateHcPartyId).catch(() => {}),\n this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(delegateHcPartyId).catch(() => {}),\n ]).then(([a, b, c]) => ({ ...a, ...b, ...c }))\n }\n\n keychainLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain.'\n keychainValidityDateLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain-date.'\n hcpPreferenceKeyEhealthCert = 'eHealthCRTCrypt'\n hcpPreferenceKeyEhealthCertDate = 'eHealthCRTDate'\n rsaLocalStoreIdPrefix = 'org.taktik.icure.rsa.'\n\n private hcpartyBaseApi: IccHcpartyApi\n private patientBaseApi: IccPatientApi\n private deviceBaseApi: IccDeviceApi\n private readonly _crypto: Crypto\n\n private generateKeyConcurrencyMap: { [key: string]: PromiseLike<HealthcareParty | Patient> }\n private rsaKeyPairs: { [pubKeyFingerprint: string]: { publicKey: CryptoKey; privateKey: CryptoKey } } = {}\n\n private readonly _AES: AESUtils\n private readonly _RSA: RSAUtils\n private readonly _shamir: ShamirClass\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n hcpartyBaseApi: IccHcpartyApi, //Init with a hcparty x api for better performances\n patientBaseApi: IccPatientApi,\n deviceBaseApi: IccDeviceApi,\n crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)\n ) {\n this.hcpartyBaseApi = hcpartyBaseApi\n this.patientBaseApi = patientBaseApi\n this.deviceBaseApi = deviceBaseApi\n this._crypto = crypto\n this.generateKeyConcurrencyMap = {}\n\n this._AES = new AESUtils(crypto)\n this._RSA = new RSAUtils(crypto)\n this._shamir = new ShamirClass(crypto)\n }\n\n async loadAllKeysFromLocalStorage(dataOwnerId: string): Promise<void> {\n const pubKeys = await this.getDataOwnerHexPublicKeys((await this.getDataOwner(dataOwnerId)).dataOwner)\n\n for (const pk of pubKeys) {\n const fingerprint = pk.slice(-32)\n if (!this.rsaKeyPairs[fingerprint]) {\n await this.cacheKeyPair(this.loadKeyPairNotImported(dataOwnerId, fingerprint))\n }\n }\n }\n\n getCachedRsaKeyPairForFingerprint(dataOwnerId: string, pubKeyOrFingerprint: string): { publicKey: CryptoKey; privateKey: CryptoKey } {\n const fingerprint = pubKeyOrFingerprint.slice(-32)\n return this.rsaKeyPairs[fingerprint] ?? this.cacheKeyPair(this.loadKeyPairNotImported(dataOwnerId, fingerprint))\n }\n\n async getPublicKeys() {\n return await Object.values(this.rsaKeyPairs).reduce(async (p, rsa) => {\n return (await p).concat([jwk2spki(await this.RSA.exportKey(rsa.publicKey, 'jwk'))])\n }, Promise.resolve([] as string[]))\n }\n\n randomUuid() {\n return ((1e7).toString() + -1e3 + -4e3 + -8e3 + -1e11).replace(\n /[018]/g,\n (c) => (Number(c) ^ ((this._crypto.getRandomValues(new Uint8Array(1))! as Uint8Array)[0] & (15 >> (Number(c) / 4)))).toString(16) //Keep that inlined or you will loose the random\n )\n }\n\n sha256(data: ArrayBuffer | Uint8Array) {\n return this._crypto.subtle.digest('SHA-256', data)\n }\n\n encryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>, threshold?: number): Promise<HealthcareParty> {\n return this.loadKeyPairImported(hcp.id!).then((keyPair) =>\n this._RSA.exportKey(keyPair.privateKey, 'pkcs8').then(async (exportedKey) => {\n const privateKey = exportedKey as ArrayBuffer\n const nLen = notaries.length\n const shares = nLen == 1 ? [privateKey] : this._shamir.share(ua2hex(privateKey), nLen, threshold || nLen).map((share) => hex2ua(share))\n const publicKeys = await this.getPublicKeys()\n\n return _.reduce(\n notaries,\n (queue, notary, idx) => {\n return queue.then(async (hcp) => {\n const { owner: hcParty, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(hcp, notary.id!)\n const [publicKeyIdentifier, hcPartyKeys] = Object.entries(aesExchangeKeys)[0]\n\n try {\n const importedAESHcPartyKey = await this.decryptHcPartyKey(\n notary.id!,\n hcParty.id!,\n notary.id!,\n publicKeyIdentifier,\n hcPartyKeys,\n publicKeys\n )\n const encryptedShamirPartition = await this.AES.encrypt(importedAESHcPartyKey.key, shares[idx])\n\n hcParty.privateKeyShamirPartitions = hcParty.privateKeyShamirPartitions || {}\n hcParty.privateKeyShamirPartitions[notary.id!] = ua2hex(encryptedShamirPartition)\n } catch (e) {\n console.log('Error during encryptedShamirRSAKey', notary.id, e)\n }\n return hcParty\n })\n },\n Promise.resolve(hcp)\n )\n })\n )\n }\n\n /* Reconstructs the hcp's private key from the notaries' shamir shares and stores it in localstorage.\n The retrieval procedure of the shares is not designed or implemented yet. Therefore, it currently only\n works if the private key of the notaries are stored in local storage (e.g. notaries = [hcp parent]).\n * @param hcp : the hcp whose key we want to reconstruct\n * @param notaries : holders of the shamir shares\n **/\n async decryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>): Promise<void> {\n try {\n const publicKeys = await this.getPublicKeys()\n const nLen = notaries.length\n let decryptedPrivatedKey\n if (nLen == 1) {\n const notaryHcPartyId = notaries[0].id!\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notaryHcPartyId)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notaryHcPartyId, hcp.id!, notaryHcPartyId, idPubKey, keysMap, publicKeys)\n )\n )\n const cryptedPrivatedKey = hcp.privateKeyShamirPartitions![notaryHcPartyId]\n decryptedPrivatedKey = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(cryptedPrivatedKey)\n )\n )\n } else {\n const decryptedShares: string[] = await _.reduce(\n notaries,\n (queue, notary) => {\n return queue.then(async (shares: string[]) => {\n try {\n // TODO: now, we get the encrypted shares in db and decrypt them. This assumes that the\n // the notaries' private keys are in localstorage. We should implement a way for the notaries to\n // give hcp the decrypted shares without having to also share their private keys.\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notary.id!)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notary.id!, hcp.id!, notary.id!, idPubKey, keysMap, publicKeys)\n )\n )\n const encryptedShare = hcp.privateKeyShamirPartitions![notary.id!]\n const decryptedShamirPartition = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(encryptedShare)\n )\n )\n shares.push(decryptedShamirPartition)\n } catch (e) {\n console.log('Error during encryptedShamirRSAKey', notary.id, e)\n }\n return shares\n })\n },\n Promise.resolve([] as string[])\n )\n\n decryptedPrivatedKey = this._shamir.combine(decryptedShares)\n }\n\n const importedPrivateKey = await this._RSA.importKey('pkcs8', hex2ua(decryptedPrivatedKey), ['decrypt'])\n const importedPublicKey = await this._RSA.importKey('spki', hex2ua(hcp.publicKey!), ['encrypt'])\n\n const exportedKeyPair = await this._RSA.exportKeys({ publicKey: importedPublicKey, privateKey: importedPrivateKey }, 'jwk', 'jwk')\n this.storeKeyPair(hcp.id!, exportedKeyPair)\n } catch (e) {\n console.log('Cannot decrypt shamir RSA key')\n }\n }\n\n /**\n * Gets the decryptedHcPartyKey for the given `encryptedHcPartyKey`\n *\n * If the decrypted key exists in the cache, retrieves it from there.\n * Otherwise, decrypts it using the RSA key of the delegator or delegate (depending on the value of `encryptedForDelegator`)\n *\n * @param loggedHcPartyId The logged DataOwner id or the id of his parent\n * @param delegatorId The id of Delegator eg, the DataOwner where this AES exchange key is stored\n * @param delegateHcPartyId The id of the delegate : the data owner for whom this aes exchange key has been created\n * @param publicKey The public key of the delegator : A unique aes exchange key is created for each public key of the delegator. This is the public key corresponding to the encryptedHcPartyKeys\n * @param encryptedHcPartyKeys The encryptedHcPartyKeys to be decrypted\n * @param publicKeys The public keys for which we might have a private key\n *\n * @returns - **delegatorId** the input param `delegatorId`\n * - **key** the decrypted `encryptedHcPartyKey`\n */\n\n async decryptHcPartyKey(\n loggedHcPartyId: string,\n delegatorId: string,\n delegateHcPartyId: string,\n publicKey: string,\n encryptedHcPartyKeys: { [key: string]: string },\n publicKeys: string[]\n ): Promise<DelegatorAndKeys> {\n if (!publicKeys.length) {\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: no public key`\n console.warn(reason)\n throw new Error(reason)\n }\n\n const cacheKey = `${delegateHcPartyId}|${publicKey.slice(-32)}|${delegatorId}`\n const res = this.hcPartyKeysCache[cacheKey]\n\n if (res) {\n return res\n }\n\n const result = await publicKeys.reduce(async (res, pk) => {\n const delegatorAndKeys = await res\n if (delegatorAndKeys) {\n return delegatorAndKeys\n }\n\n const fingerprint = pk.slice(-32)\n const keyPair = this.rsaKeyPairs[fingerprint] ?? (await this.cacheKeyPair(this.loadKeyPairNotImported(loggedHcPartyId, fingerprint)))\n if (!keyPair) {\n return\n }\n\n const encryptedHcPartyKey = encryptedHcPartyKeys[fingerprint]\n if (!encryptedHcPartyKey) {\n return\n }\n\n try {\n const decryptedAesExchangeKey = await this._RSA.decrypt(keyPair.privateKey, hex2ua(encryptedHcPartyKey))\n const importedAesExchangeKey = await this._AES.importKey('raw', decryptedAesExchangeKey)\n return (this.hcPartyKeysCache[cacheKey] = {\n delegatorId: delegatorId,\n key: importedAesExchangeKey,\n rawKey: ua2hex(new Uint8Array(decryptedAesExchangeKey)),\n })\n } catch (e) {\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId} for pubKey ${fingerprint}: impossible to decrypt`\n console.log(reason)\n }\n }, Promise.resolve() as Promise<DelegatorAndKeys | void>)\n\n const availablePublicKeys = publicKeys.filter((pk) => this.rsaKeyPairs[pk.slice(-32)])\n\n if (!result) {\n //Try to find another key from the transfer keys\n const hcp = (await this.getDataOwner(loggedHcPartyId))!\n const candidates = Object.entries(hcp.dataOwner.transferKeys ?? {})\n .filter(([fp, _]) => availablePublicKeys.some((pk) => pk.slice(-32) === fp.slice(-32))) // only keep keys that we will be able to decrypt\n .flatMap(([pk, keys]) => Object.entries(keys).map(([k, v]) => [pk, k, v]))\n .filter(([_, k]) => !publicKeys.some((apk) => apk.slice(-32) === k.slice(-32)))\n if (candidates.length) {\n const newPublicKeys = await candidates.reduce(async (p, [decryptionKeyFingerprint, privateKeyFingerprint, encryptedPrivateKey]) => {\n const newKeys = await p\n const aesExchangeKeys = Object.entries(hcp.dataOwner.aesExchangeKeys!).find(\n ([fp, _]) => fp.slice(-32) === privateKeyFingerprint.slice(-32)\n )?.[1][loggedHcPartyId]\n if (aesExchangeKeys) {\n const encryptedAesExchangeKey = Object.entries(aesExchangeKeys).find(\n ([fp, _]) => fp.slice(-32) === decryptionKeyFingerprint.slice(-32)\n )?.[1]\n if (encryptedAesExchangeKey) {\n const keyPair = this.rsaKeyPairs[decryptionKeyFingerprint.slice(-32)]\n if (!keyPair) {\n return newKeys\n }\n const decryptedAesExchangeKey = await this._RSA.decrypt(keyPair.privateKey, hex2ua(encryptedAesExchangeKey))\n const importedAesExchangeKey = await this._AES.importKey('raw', decryptedAesExchangeKey)\n\n const decryptedPrivateKey = await this._AES.decrypt(importedAesExchangeKey, hex2ua(encryptedPrivateKey))\n\n const newPublicKey = Object.keys(hcp.dataOwner.aesExchangeKeys!).find((fp) => fp.slice(-32) === privateKeyFingerprint.slice(-32))!\n await this.cacheKeyPair({\n publicKey: spkiToJwk(hex2ua(newPublicKey)),\n privateKey: pkcs8ToJwk(decryptedPrivateKey),\n })\n\n return newKeys.concat([newPublicKey])\n }\n }\n return newKeys\n }, Promise.resolve([]) as Promise<string[]>)\n\n if (newPublicKeys.length) {\n return await this.decryptHcPartyKey(loggedHcPartyId, delegatorId, delegateHcPartyId, publicKey, encryptedHcPartyKeys, newPublicKeys)\n }\n }\n\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: impossible to decrypt. No private key was found or could be used to decrypt the aes exchange keys`\n console.log(reason)\n throw new Error(reason)\n }\n\n return result\n }\n\n /**\n * Cache the RSA private/public key pair for the HcP with the given id `hcPartyKeyOwner`\n */\n cacheKeyPair(keyPairInJwk: { publicKey: JsonWebKey; privateKey: JsonWebKey }) {\n return this._RSA.importKeyPair('jwk', keyPairInJwk.privateKey, 'jwk', keyPairInJwk.publicKey).then((importedKeyPair) => {\n const pk = jwk2spki(keyPairInJwk.publicKey)\n return (this.rsaKeyPairs[pk.slice(-32)] = importedKeyPair)\n })\n }\n\n /**\n * Gets the secret ID (SFKs) that should be used in the prescribed context (confidential or not) from decrypted SPKs of the given `parent`, decrypted by the HcP with the given `hcpartyId` AND by its HcP parents\n * @param parent :the object of which delegations (SPKs) to decrypt\n * @param hcpartyId :the id of the delegate HcP\n * @param confidential :weather the key is going to be used for a confidential piece or data or not\n * @returns - **extractedKeys** array containing secret IDs (SFKs) from decrypted SPKs, from both given HcP and its parents ; can contain duplicates\n * - **hcpartyId** the given `hcpartyId` OR, if a parent exist, the HcP id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n async extractPreferredSfk(parent: EncryptedParentEntity, hcpartyId: string, confidential: boolean) {\n const secretForeignKeys = await this.extractSFKsHierarchyFromDelegations(parent, hcpartyId)\n const keys = secretForeignKeys\n .filter(({ extractedKeys }) => extractedKeys.length > 0)\n .filter((x, idx) => (confidential ? x.hcpartyId === hcpartyId : idx === 0))[0]\n\n return (\n (keys &&\n (confidential\n ? keys.extractedKeys.find(\n (k) => !secretForeignKeys.some(({ extractedKeys, hcpartyId: parentHcpId }) => hcpartyId !== parentHcpId && extractedKeys.includes(k))\n )\n : keys.extractedKeys[0])) ||\n undefined\n )\n }\n\n /**\n * Gets an array of decrypted HcPartyKeys, shared between the delegate with ID `delegateHcPartyId` and the delegators in `delegatorsHcPartyIdsSet`\n *\n * 1. Get the keys for the delegateHealthCareParty (cache/backend).\n * 2. For each key in the delegators, decrypt it with the delegate's private key\n * 3. Filter out undefined keys and return them\n *\n * @param delegatorsHcPartyIdsSet array of delegator HcP IDs that could have delegated something to the HcP with ID `delegateHcPartyId`\n * @param delegateHcPartyId the HcP for which the HcPs with IDs in `delegatorsHcPartyIdsSet` could have delegated something\n * @param minCacheDurationInSeconds The minimum cache duration\n * @returns - **delegatorId** : the id of the delegator HcP that shares the **key** with the `delegateHcPartyId`\n * - **key** the decrypted HcPartyKey, shared between **delegatorId** and `delegateHcPartyId`\n */\n async decryptAndImportAesHcPartyKeysForDelegators(\n delegatorsHcPartyIdsSet: Array<string>,\n delegateHcPartyId: string,\n minCacheDurationInSeconds: number = 60\n ): Promise<Array<DelegatorAndKeys>> {\n const aesExchangeKeys = await (\n this.hcPartyKeysRequestsCache[delegateHcPartyId] ||\n (this.hcPartyKeysRequestsCache[delegateHcPartyId] = this.getEncryptedAesExchangeKeysForDelegate(delegateHcPartyId))\n ).then(async (delegatorIdsWithDelegateEncryptedHcPartyKeys: { [key: string]: { [key: string]: { [key: string]: string } } }) => {\n // [key: delegatorId] = delegateEncryptedHcPartyKey\n // For each delegatorId, obtain the AES key (decrypted HcParty Key) shared with the delegate, decrypted by the delegate\n return (\n await Promise.all(\n delegatorsHcPartyIdsSet.map(async (delegatorId: string) => {\n const encryptedHcPartyKeysForPubKeyFingerprint = delegatorIdsWithDelegateEncryptedHcPartyKeys[delegatorId]\n if (!encryptedHcPartyKeysForPubKeyFingerprint) {\n return [] as DelegatorAndKeys[]\n }\n const decryptedKeys = await Promise.all(\n Object.entries(encryptedHcPartyKeysForPubKeyFingerprint).map(async ([delegatorPubKeyFinerprint, encryptedAesExchangeKeys]) => {\n try {\n return await this.decryptHcPartyKey(\n delegateHcPartyId,\n delegatorId,\n delegateHcPartyId,\n delegatorPubKeyFinerprint,\n encryptedAesExchangeKeys,\n Object.keys(this.rsaKeyPairs)\n )\n } catch (e) {\n console.log(`failed to decrypt hcPartyKey from ${delegatorId} to ${delegateHcPartyId}`)\n return\n }\n })\n )\n return decryptedKeys.filter((x) => !!x) as DelegatorAndKeys[]\n })\n )\n ).reduce((acc, x) => [...acc, ...x], [])\n })\n\n if (aesExchangeKeys.length > 0) {\n return aesExchangeKeys\n }\n\n const nowTimestamp = +new Date()\n if (!this.cacheLastDeletionTimestamp || (nowTimestamp - this.cacheLastDeletionTimestamp) / 1000 >= minCacheDurationInSeconds) {\n delete this.hcPartyKeysRequestsCache[delegateHcPartyId]\n this.cacheLastDeletionTimestamp = nowTimestamp\n return this.decryptAndImportAesHcPartyKeysForDelegators(delegatorsHcPartyIdsSet, delegateHcPartyId, minCacheDurationInSeconds)\n }\n\n return []\n }\n\n /**\n * Gets an array of decrypted HcPartyKeys from the given `delegations`, that are shared with / can be decrypted by the HcP with the given `healthcarePartyId` (or by its parents when `fallbackOnParent` is true)\n *\n * 1. Checks whether the delegations' object has a delegation for the\n * given healthCarePartyId.\n * 2. Enumerates all the delegators (delegation.owner) present in\n * the delegations.\n * 3. Decrypt's delegators' keys and returns them.\n *\n * @param dataOwnerId : the id of the delegate HCP\n * @param delegations : delegations (can be SPKs, CFKs, EKs) for all delegates\n * @param fallbackOnParent default true; use parent's healthCarePartyId in case there's no delegation for the `healthcarePartyId`\n * @returns - **delegatorId** : the id of the delegator HcP that shares the **key** with the `healthcarePartyId`\n * - **key** the decrypted HcPartyKey, shared between **delegatorId** and `healthcarePartyId`\n */\n async getDecryptedAesExchangeKeysOfDelegateAndParentsFromGenericDelegations(\n dataOwnerId: string,\n delegations: { [key: string]: Array<Delegation> },\n fallbackOnParent = true\n ): Promise<Array<DelegatorAndKeys>> {\n const delegationsArray = delegations[dataOwnerId] ?? []\n\n if (!delegationsArray.length && fallbackOnParent) {\n const { dataOwner: hcp } = await this.getDataOwner(dataOwnerId)\n return (hcp as any).parentId\n ? await this.getDecryptedAesExchangeKeysOfDelegateAndParentsFromGenericDelegations((hcp as any).parentId, delegations)\n : []\n } else {\n const delegatorIds = new Set<string>()\n delegationsArray.forEach((del) => delegatorIds.add(del.owner!))\n return this.decryptAndImportAesHcPartyKeysForDelegators(Array.from(delegatorIds), dataOwnerId)\n }\n }\n\n /**\n * Retrieve the owner HealthCareParty key and use it to encrypt\n * both the delegations (createdObject.id) and the cryptedForeignKeys\n * (parentObject.id), and returns them in an object.\n */\n async initObjectDelegations(\n createdObject: any,\n parentObject: any,\n ownerId: string,\n secretForeignKeyOfParent: string | null\n ): Promise<{\n owner: HealthcareParty | Device | Patient\n delegations: any\n cryptedForeignKeys: any\n secretForeignKeys: any[]\n secretId: string\n }> {\n const publicKeys = await this.getPublicKeys()\n\n this.throwDetailedExceptionForInvalidParameter('createdObject.id', createdObject.id, 'initObjectDelegations', arguments)\n\n if (parentObject) this.throwDetailedExceptionForInvalidParameter('parentObject.id', parentObject.id, 'initObjectDelegations', arguments)\n\n const secretId = this.randomUuid()\n return this.getDataOwner(ownerId).then(async ({ dataOwner: owner }) => {\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, ownerId)\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, ownerId, ownerId, publicKeys)\n\n const encryptedDelegation = await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(createdObject.id + ':' + secretId).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n )\n const encryptedSecretForeignKey =\n parentObject &&\n this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(createdObject.id + ':' + parentObject.id).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n )\n\n return {\n owner: modifiedOwner,\n delegations: _.fromPairs([\n [\n ownerId,\n [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedDelegation!),\n },\n ],\n ],\n ]),\n cryptedForeignKeys:\n (encryptedSecretForeignKey &&\n _.fromPairs([\n [\n ownerId,\n [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedSecretForeignKey!),\n },\n ],\n ],\n ])) ||\n {},\n secretForeignKeys: (secretForeignKeyOfParent && [secretForeignKeyOfParent]) || [],\n secretId: secretId,\n }\n })\n }\n\n private async decryptAnyAesExchangeKeyForOwner(\n aesExchangeKeys: { [p: string]: { [p: string]: string } },\n loggedHcPartyId: string,\n delegatorId: string,\n delegateHcPartyId: string,\n publicKeys: string[]\n ) {\n const importedAESHcPartyKey = await Object.entries(aesExchangeKeys).reduce(async (acc, [publicKeyIdentifier, hcPartyKeys]) => {\n const accValue = await acc\n if (accValue) {\n return accValue\n }\n try {\n return await this.decryptHcPartyKey(loggedHcPartyId, delegatorId, delegateHcPartyId, publicKeyIdentifier, hcPartyKeys, publicKeys)\n } catch (e) {\n return undefined\n }\n }, Promise.resolve() as Promise<DelegatorAndKeys | undefined>)\n\n if (!importedAESHcPartyKey) {\n throw new Error(`No hcParty key can be decrypted from ${delegatorId} to ${delegateHcPartyId} using currently available private keys`)\n }\n return importedAESHcPartyKey\n }\n\n /**\n * Gets updated instances of SPKs and CKFs for the child object `modifiedObject`.\n * These updated SPKs and CKFs contain new SPKs/CFKs to provide delegation from delegator HcP with id `ownerId` to delegate HcP with id `delegateId`\n *\n * 1. if `secretIdOfModifiedObject` is not provided, the method will throw an exception; this `secretIdOfModifiedObject` is used to generate a new delegation (SPK) in step 3;\n * the `secretIdOfModifiedObject` is returned, unmodified, as `secretId`\n * 2. if the owner (delegator) did not perform a delegation to the delegate, then this HcP delegation (creation of a new HcPKey) is performed now\n * 3. creates a new delegation (Secret Primary Keys) on the `modifiedObject` encrypted with the HcPKey from owner to the delegate;\n * 4. if `parentObject` != null, creates a new CFK on the `modifiedObject` encrypted with the HcPKey from owner to the delegate;\n * 5. this new delegation (from step 3) is added to the list of existing delegations (Secret Primary Keys) on the `modifiedObject` for the delegate given by `delegateId`\n * 6. if the CFK (from step 4) can be created, this new CFK is added to the list of existing CFKs on the `modifiedObject` for the delegate given by `delegateId`\n * 7. then some duplicates delegations (SPKs) and CKFs are removed\n *\n * @param modifiedObject : the object of which SPKs and CFKs will be cloned, the clones will be modified and then used as returned values ; it's a 'child' of `parentObject`; will NOT be mutated\n * @param parentObject : will NOT be mutated\n * @param ownerId : the HcP id of the delegator\n * @param delegateId : the HcP id of the delegate\n * @param secretIdOfModifiedObject : the secret id used in the child object to generate its SPK\n * @returns - **delegations** existing delegations (SPKs) of the `modifiedObject`, appended with results from step 5\n * - **cryptedForeignKeys** existing CFKs of the `modifiedObject`, appended with results from steps 6\n * - **secretId** which is the given input parameter `secretIdOfModifiedObject`\n */\n\n extendedDelegationsAndCryptedForeignKeys<T extends EncryptedEntity, P extends EncryptedParentEntity>(\n //TODO: suggested name: getExtendedChildObjectSPKandCFKwithDelegationFromDelegatorToDelegate\n modifiedObject: T,\n parentObject: P | null,\n ownerId: string,\n delegateId: string,\n secretIdOfModifiedObject: string | null\n ): Promise<{\n modifiedObject: T\n delegations: { [key: string]: Array<Delegation> }\n cryptedForeignKeys: { [key: string]: Array<Delegation> }\n secretId: string | null //TODO: why input parameter secretIdOfModifiedObject is returned?\n }> {\n this.throwDetailedExceptionForInvalidParameter('modifiedObject.id', modifiedObject.id, 'extendedDelegationsAndCryptedForeignKeys', arguments) //modifiedObject should never be null\n\n if (parentObject)\n this.throwDetailedExceptionForInvalidParameter('parentObject.id', parentObject?.id, 'extendedDelegationsAndCryptedForeignKeys', arguments)\n\n this.throwDetailedExceptionForInvalidParameter(\n 'secretIdOfModifiedObject',\n secretIdOfModifiedObject,\n 'extendedDelegationsAndCryptedForeignKeys',\n arguments\n )\n\n return this.getDataOwner(ownerId)\n .then(async ({ dataOwner: owner }) => {\n const publicKeys = await this.getPublicKeys()\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, delegateId)\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, delegateId, ownerId, publicKeys)\n\n modifiedObject = modifiedObject?.id === owner.id ? (modifiedOwner as T) : modifiedObject\n\n return {\n previousDecryptedDelegations: await Promise.all(\n ((modifiedObject.delegations || {})[delegateId] || []).map(\n (d: Delegation) =>\n (d.key &&\n d.owner === ownerId &&\n this._AES.decrypt(importedAESHcPartyKey.key, hex2ua(d.key), importedAESHcPartyKey.rawKey).catch(() => {\n console.log(\n `Cannot decrypt delegation from ${d.owner} to ${d.delegatedTo} for object with id ${modifiedObject.id}:`,\n modifiedObject\n )\n return Promise.resolve()\n })) ||\n Promise.resolve()\n ) as Array<Promise<ArrayBuffer>>\n ),\n\n previousDecryptedCryptedForeignKeys: await Promise.all(\n ((modifiedObject.cryptedForeignKeys || {})[delegateId] || []).map(\n (d: Delegation) =>\n (d.key &&\n d.owner === ownerId &&\n this._AES.decrypt(importedAESHcPartyKey.key, hex2ua(d.key), importedAESHcPartyKey.rawKey).catch(() => {\n console.log(\n `Cannot decrypt cryptedForeignKeys from ${d.owner} to ${d.delegatedTo} for object with id ${modifiedObject.id}:`,\n modifiedObject\n )\n return Promise.resolve()\n })) ||\n Promise.resolve()\n ) as Array<Promise<ArrayBuffer>>\n ),\n\n cryptedDelegation: await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(modifiedObject.id + ':' + secretIdOfModifiedObject!).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n ),\n\n cryptedForeignKey: parentObject\n ? await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(modifiedObject.id + ':' + parentObject.id).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n )\n : undefined,\n }\n })\n .then(({ previousDecryptedDelegations, previousDecryptedCryptedForeignKeys, cryptedDelegation, cryptedForeignKey }) => {\n //try to limit the extent of the modifications to the delegations by preserving the redundant delegation already present and removing duplicates\n //For delegate delegateId, we create:\n // 1. an array of objects { d : {owner,delegatedTo,encrypted(key)}} with one object for each existing delegation and the new key concatenated\n // 2. an array of objects { k : decrypted(key)} with one object for the existing delegations and the new key concatenated\n // We merge them to get one array of objects: { d: {owner,delegatedTo,encrypted(key)}, k: decrypted(key)}\n const delegationCryptedDecrypted = (\n _.merge(\n ((modifiedObject.delegations || {})[delegateId] || []).map((d: Delegation) => ({\n d,\n })),\n (previousDecryptedDelegations || []).map((dd) => (dd ? ua2string(dd) : null)).map((k) => ({ k }))\n ) as { d: Delegation; k: string }[]\n )\n .filter(({ d, k }) => !!k || d.owner !== ownerId) //Only keep the ones created by us that can still be decrypted\n .map(({ d, k }) => ({\n d,\n k: k || this.randomUuid(),\n })) // Use some unique id that ensures the delegation not created by us are going to be held\n .concat([\n {\n d: {\n owner: ownerId,\n delegatedTo: delegateId,\n key: ua2hex(cryptedDelegation!),\n },\n k: modifiedObject.id + ':' + secretIdOfModifiedObject!,\n },\n ])\n\n const allDelegations = _.cloneDeep(modifiedObject.delegations || {})\n\n //Only keep one version of the decrypted key\n allDelegations[delegateId] = _.uniqBy(delegationCryptedDecrypted, (x: any) => x.k).map((x: any) => x.d)\n\n const cryptedForeignKeysCryptedDecrypted = (\n _.merge(\n ((modifiedObject.cryptedForeignKeys || {})[delegateId] || []).map((d: Delegation) => ({\n d,\n })),\n (previousDecryptedCryptedForeignKeys || []).map((dd) => (dd ? ua2string(dd) : null)).map((k) => ({ k }))\n ) as { d: Delegation; k: string }[]\n )\n .filter(({ d, k }) => !!k || d.owner !== ownerId) //Only keep the ones created by us that can still be decrypted\n .map(({ d, k }: { d: Delegation; k: string }) => ({\n d,\n k: k || this.randomUuid(),\n })) // Use some unique id that ensures the delegation not created by us are going to be held\n .concat(\n cryptedForeignKey\n ? [\n {\n d: {\n owner: ownerId,\n delegatedTo: delegateId,\n key: ua2hex(cryptedForeignKey),\n },\n k: modifiedObject.id + ':' + parentObject?.id,\n },\n ]\n : []\n )\n\n const allCryptedForeignKeys = _.cloneDeep(modifiedObject.cryptedForeignKeys || {})\n if (cryptedForeignKeysCryptedDecrypted.length > 0) {\n allCryptedForeignKeys[delegateId] = _.uniqBy(cryptedForeignKeysCryptedDecrypted, (x: any) => x.k).map((x: any) => x.d)\n }\n\n return {\n modifiedObject,\n delegations: allDelegations,\n cryptedForeignKeys: allCryptedForeignKeys,\n secretId: secretIdOfModifiedObject,\n }\n })\n }\n\n async getEncryptedAesExchangeKeys(\n owner: HealthcareParty | Patient | Device,\n delegateId: string\n ): Promise<{ [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } }> {\n const publicKeys = await this.getPublicKeys()\n const mapOfAesExchangeKeys = Object.entries(owner.aesExchangeKeys ?? {})\n .filter((e) => e[1][delegateId] && Object.keys(e[1][delegateId]).some((k1) => publicKeys.some((pk) => pk.endsWith(k1))))\n .reduce((map, e) => {\n const candidates = Object.entries(e[1][delegateId])\n const [publicKeyFingerprint, encryptedAesExchangeKey] = candidates[candidates.findIndex(([k, v]) => publicKeys.some((pk) => pk.endsWith(k)))]\n return { ...map, [e[0]]: { [publicKeyFingerprint]: encryptedAesExchangeKey } }\n }, {} as { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } })\n\n return !owner.publicKey ||\n mapOfAesExchangeKeys[owner.publicKey] ||\n !owner.hcPartyKeys?.[delegateId] ||\n publicKeys.find((p) => p == owner.publicKey!) == undefined\n ? mapOfAesExchangeKeys\n : { ...mapOfAesExchangeKeys, [owner.publicKey]: { [owner.publicKey.slice(-32)]: owner.hcPartyKeys[delegateId][0] } }\n }\n\n async getOrCreateHcPartyKeys(\n owner: HealthcareParty | Patient | Device,\n delegateId: string\n ): Promise<{\n owner: HealthcareParty | Patient | Device\n aesExchangeKeys: { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } }\n }> {\n const aesExchangeKeys = await this.getEncryptedAesExchangeKeys(owner, delegateId)\n if (Object.keys(aesExchangeKeys).length) {\n return { owner, aesExchangeKeys }\n }\n\n const modifiedOwner = await this.generateKeyForDelegate(owner.id!, delegateId)\n return { owner: modifiedOwner, aesExchangeKeys: await this.getEncryptedAesExchangeKeys(modifiedOwner, delegateId) }\n }\n\n /**\n * Retrieve the owners HealthCareParty key, decrypt it, and\n * use it to encrypt & initialize the \"encryptionKeys\" object\n * and return it.\n * @param createdObject\n * @param ownerId\n */\n initEncryptionKeys(\n createdObject: any,\n ownerId: string\n ): Promise<{\n encryptionKeys: any\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('createdObject.id', createdObject.id, 'initEncryptionKeys', arguments)\n\n const secretId = this.randomUuid()\n return this.getDataOwner(ownerId).then(async ({ dataOwner: owner }) => {\n const publicKeys = await this.getPublicKeys()\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, ownerId)\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, ownerId, ownerId, publicKeys)\n const encryptedEncryptionKeys = await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(createdObject.id + ':' + secretId),\n importedAESHcPartyKey.rawKey\n )\n\n return {\n encryptionKeys: _.fromPairs([\n [\n ownerId,\n [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedEncryptionKeys),\n },\n ],\n ],\n ]),\n secretId: secretId,\n }\n })\n }\n\n /**\n * Gets an updated instance of the EKs of `modifiedObject`.\n * The updated EKs contain a new EK to provide delegation from delegator HcP with id `ownerId` to delegate HcP with id `delegateId`.\n * @param modifiedObject : the object of which EKs will be cloned, the clone will be used to append the new EK, and then used as return value; will NOT be mutated\n * @param ownerId : delegator HcP id\n * @param delegateId : delegate HcP id\n * @param secretEncryptionKeyOfObject : secret Id for the EK (Content Encryption Key)\n * @returns\n * - **encryptionKeys** existing EKs of the `modifiedObject`, appended with a new EK item (owner: `ownerId`, delegatedTo: `delegateId`, encrypted key with secretId:\n * `secretEncryptionKeyOfObject` )\n * - **secretId** which is the given input parameter `secretEncryptionKeyOfObject`\n */\n async appendEncryptionKeys(\n //TODO: suggested name: getExtendedEKwithDelegationFromDelegatorToDelegate\n modifiedObject: any,\n ownerId: string,\n delegateId: string,\n secretEncryptionKeyOfObject: string\n ): Promise<{\n encryptionKeys: { [key: string]: Array<Delegation> }\n secretId: string | null //secretEncryptionKeyOfObject is returned to avoid the need for a new decryption when chaining calls\n }> {\n this.throwDetailedExceptionForInvalidParameter('modifiedObject.id', modifiedObject.id, 'appendEncryptionKeys', arguments) //modifiedObject should never be null\n\n this.throwDetailedExceptionForInvalidParameter('secretEncryptionKeyOfObject', secretEncryptionKeyOfObject, 'appendEncryptionKeys', arguments)\n\n return this.getDataOwner(ownerId)\n .then(async ({ dataOwner: owner }) => {\n const publicKeys = await this.getPublicKeys()\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, delegateId)\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, ownerId, delegateId, publicKeys)\n\n return {\n previousDecryptedEncryptionKeys: await Promise.all(\n ((modifiedObject.encryptionKeys || {})[delegateId] || []).map(\n (d: Delegation) =>\n (d.key &&\n d.owner === ownerId &&\n this._AES.decrypt(importedAESHcPartyKey.key, hex2ua(d.key), importedAESHcPartyKey.rawKey).catch(() => {\n console.log(\n `Cannot decrypt encryption key from ${d.owner} to ${d.delegatedTo} for object with id ${modifiedObject.id}:`,\n modifiedObject\n )\n return Promise.resolve()\n })) ||\n Promise.resolve()\n ) as Array<Promise<ArrayBuffer>>\n ),\n encryptedEncryptionKey: await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(modifiedObject.id + ':' + secretEncryptionKeyOfObject)\n ),\n }\n })\n .then(({ previousDecryptedEncryptionKeys, encryptedEncryptionKey }) => {\n //try to limit the extent of the modifications to the delegations by preserving the redundant encryption keys already present and removing duplicates\n //For delegate delegateId, we create:\n // 1. an array of objects { d : {owner,delegatedTo,encrypted(key)}} with one object for the existing encryption keys and the new key concatenated\n // 2. an array of objects { k : decrypted(key)} with one object for the existing delegations and the new key concatenated\n // We merge them to get one array of objects: { d: {owner,delegatedTo,encrypted(key)}, k: decrypted(key)}\n const encryptionKeysCryptedDecrypted = _.merge(\n ((modifiedObject.encryptionKeys || {})[delegateId] || []).map((d: Delegation) => ({\n d,\n })),\n (previousDecryptedEncryptionKeys || []).map((dd) => (dd ? ua2string(dd) : null)).map((k) => ({ k }))\n )\n .filter(({ d, k }: { d: Delegation; k: string }) => !!k || d.owner !== ownerId) //Only keep the ones created by us that can still be decrypted\n .map(({ d, k }: { d: Delegation; k: string }) => ({ d, k: k || this.randomUuid() }))\n .concat([\n {\n d: {\n owner: ownerId,\n delegatedTo: delegateId,\n key: ua2hex(encryptedEncryptionKey),\n },\n k: modifiedObject.id + ':' + secretEncryptionKeyOfObject!,\n },\n ])\n\n const allEncryptionKeys = _.cloneDeep(modifiedObject.encryptionKeys)\n allEncryptionKeys[delegateId] = _.uniqBy(encryptionKeysCryptedDecrypted, (x: any) => x.k).map((x: any) => x.d)\n\n return {\n encryptionKeys: allEncryptionKeys,\n secretId: secretEncryptionKeyOfObject,\n }\n })\n }\n\n /**\n * Gets an updated `child` object that will have its SPKs, CFKs, KSs updated to include delegations from delegator HcP with id `ownerId` to delegate HcP with id `delegateId`\n * The SFKs of `child` are not updated, so this method assumes this is not the initial delegation on the `child` object\n * The method also performs some deduplication of all types of delegations.\n * @param parent : the parent object of `child`; will NOT be mutated\n * @param child : the object that will be mutated and returned\n * @param ownerId delegator HcP id\n * @param delegateId delegate HcP id\n * @param secretDelegationKey the secret Id used in the child object to generate the SPK\n * @param secretEncryptionKey the secret Id used in the child object to generate the EK (Content Encryption Key)\n * @returns - an updated `child` object that will contain updated SPKs, CFKs, EKs\n * */\n\n addDelegationsAndEncryptionKeys<T extends EncryptedEntity>(\n //TODO: suggested name: updateChildGenericDelegationsFromDelegatorToDelegate\n parent: EncryptedParentEntity | null,\n child: T,\n ownerId: string,\n delegateId: string,\n secretDelegationKey: string | null,\n secretEncryptionKey: string | null\n ): Promise<T> {\n if (parent) this.throwDetailedExceptionForInvalidParameter('parent.id', parent.id, 'addDelegationsAndEncryptionKeys', arguments)\n\n this.throwDetailedExceptionForInvalidParameter('child.id', child.id, 'addDelegationsAndEncryptionKeys', arguments)\n return (\n secretDelegationKey\n ? this.extendedDelegationsAndCryptedForeignKeys(child, parent, ownerId, delegateId, secretDelegationKey)\n : Promise.resolve({ modifiedObject: child, delegations: {}, cryptedForeignKeys: {}, secretId: null })\n )\n .then((extendedChildObjectSPKsAndCFKs) =>\n secretEncryptionKey\n ? this.appendEncryptionKeys(extendedChildObjectSPKsAndCFKs.modifiedObject, ownerId, delegateId, secretEncryptionKey).then(\n //TODO: extendedDelegationsAndCryptedForeignKeys and appendEncryptionKeys can be done in parallel\n (extendedChildObjectEKs) => ({\n extendedSPKsAndCFKs: extendedChildObjectSPKsAndCFKs,\n extendedEKs: extendedChildObjectEKs,\n })\n )\n : Promise.resolve({\n extendedSPKsAndCFKs: extendedChildObjectSPKsAndCFKs,\n extendedEKs: { encryptionKeys: {} },\n })\n )\n .then(({ extendedSPKsAndCFKs: extendedChildObjectSPKsAndCFKs, extendedEKs: extendedChildObjectEKs }) => {\n return _.assign(extendedChildObjectSPKsAndCFKs.modifiedObject, {\n // Conservative version ... We might want to be more aggressive with the deduplication of keys\n // For each delegate, we are going to concatenate to the src (the new delegations), the object in dest (the current delegations)\n // for which we do not find an equivalent delegation (same delegator, same delegate)\n delegations: _.assignWith(child.delegations, extendedChildObjectSPKsAndCFKs.delegations, (dest, src) =>\n (src || []).concat(\n _.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo))\n )\n ),\n cryptedForeignKeys: _.assignWith(child.cryptedForeignKeys, extendedChildObjectSPKsAndCFKs.cryptedForeignKeys, (dest, src) =>\n (src || []).concat(\n _.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo))\n )\n ),\n encryptionKeys: _.assignWith(child.encryptionKeys, extendedChildObjectEKs.encryptionKeys, (dest, src) =>\n (src || []).concat(\n _.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo))\n )\n ),\n })\n })\n }\n\n /**\n * Gets the secret IDs (SFKs) inside decrypted SPKs of the given `document`, decrypted by the HcP with the given `hcpartyId` AND by its HcP parents\n * @param document : the object of which delegations (SPKs) to decrypt\n * @param hcpartyId : the id of the delegate HcP\n * @returns - **extractedKeys** array containing secret IDs (SFKs) from decrypted SPKs, from both given HcP and its parents ; can contain duplicates\n * - **hcpartyId** the given `hcpartyId` OR, if a parent exist, the HcP id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n //TODO: even if there are no delegations for parent HCP (but the parent exists), the returned hcpartyId will be the one of the parent; is this ok?\n extractDelegationsSFKs(\n //TODO: suggested name: getSecretIDsSPKofHcpAndParentsFromDocument\n document: EncryptedEntity | null,\n hcpartyId?: string\n ): Promise<{ extractedKeys: Array<string>; hcpartyId?: string }> {\n if (!document || !hcpartyId) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId }) //TODO: thow exception instead?\n }\n const delegationsForAllDelegates = document.delegations\n if (!delegationsForAllDelegates || !Object.keys(delegationsForAllDelegates).length) {\n console.log(`There is no delegation in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return this.extractKeysFromDelegationsForHcpHierarchy(hcpartyId, document.id!, delegationsForAllDelegates)\n }\n\n /**\n * Gets the secret IDs (SFKs) inside decrypted SPKs of the given `document`, decrypted by the HcP with the given `hcpartyId` AND by its HcP parents\n * @param document : the object of which delegations (SPKs) to decrypt\n * @param hcpartyId : the id of the delegate HcP\n * @returns - **extractedKeys** array containing secret IDs (SFKs) from decrypted SPKs, from both given HcP and its parents ; can contain duplicates\n * - **hcpartyId** the given `hcpartyId` OR, if a parent exist, the HcP id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n extractSFKsHierarchyFromDelegations(\n document: EncryptedEntity | null,\n hcpartyId?: string\n ): Promise<Array<{ hcpartyId: string; extractedKeys: Array<string> }>> {\n if (!document || !hcpartyId) {\n return Promise.resolve([])\n }\n const delegationsForAllDelegates = document.delegations\n if (!delegationsForAllDelegates || !Object.keys(delegationsForAllDelegates).length) {\n console.log(`There is no delegation in document (${document.id})`)\n return Promise.resolve([])\n }\n return this.extractKeysHierarchyFromDelegationLikes(hcpartyId, document.id!, delegationsForAllDelegates)\n }\n\n // noinspection JSUnusedGlobalSymbols\n\n extractCryptedFKs(\n //TODO: suggested name: getSecretIDsCFKofHcpAndParentsFromDocument\n document: EncryptedEntity | null,\n hcpartyId: string\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document || !document.cryptedForeignKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const cfksForAllDelegates = document.cryptedForeignKeys\n if (!cfksForAllDelegates || !Object.keys(cfksForAllDelegates).length) {\n console.log(`There is no cryptedForeignKeys in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return this.extractKeysFromDelegationsForHcpHierarchy(hcpartyId, document.id!, cfksForAllDelegates)\n }\n\n extractEncryptionsSKs(\n //TODO: suggested name: getSecretIDsEKofHcpAndParentsFromDocument\n document: EncryptedEntity,\n hcpartyId: string\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document.encryptionKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const eckeysForAllDelegates = document.encryptionKeys\n if (!eckeysForAllDelegates || !Object.keys(eckeysForAllDelegates).length) {\n //console.log(`There is no encryption key in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return this.extractKeysFromDelegationsForHcpHierarchy(hcpartyId, document.id!, eckeysForAllDelegates)\n }\n\n extractDelegationsSFKsAndEncryptionSKs(ety: EncryptedEntity, ownerId: string) {\n const delegationsSfksOwnerPromise = this.extractDelegationsSFKs(ety, ownerId).then((xks) => xks.extractedKeys) //Will climb up hierarchy\n const encryptionKeysOwnerPromise = this.extractEncryptionsSKs(ety, ownerId).then((xks) => xks.extractedKeys) //Will climb up hierarchy\n\n return Promise.all([delegationsSfksOwnerPromise, encryptionKeysOwnerPromise])\n }\n\n /**\n * Get decrypted generic secret IDs (secretIdSPKs, parentIds, secretIdEKs) from generic delegations (SPKs, CFKs, EKs)\n * 1. Get HealthCareParty from it's Id.\n * 2. Decrypt the keys of the given HCP.\n * 3. Decrypt the parent's key if it has parent.\n * 4. Return the decrypted key corresponding to the Health Care Party.\n * @param hcpartyId : the id of the delegate HcP (including its parents) for which to decrypt `extractedKeys`\n * @param objectId : the id of the object/document of which delegations to decrypt ; used just to log to console a message (Cryptographic mistake) in case the object id inside SPK, CFK, EK is different from this one\n * @param delegations : generic delegations (can be SPKs, CFKs, EKs) for all delegates from where to extract `extractedKeys`\n * @returns - **extractedKeys** array containing secret IDs from decrypted generic delegations, from both HCP with given `hcpartyId` and its parents; can contain duplicates\n * - **hcpartyId** the given `hcpartyId` OR, if a parent exist, the HCP id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n //TODO: even if there are no delegations for parent HCP (but the parent exists), the returned hcpartyId will be the one of the parent\n async extractKeysHierarchyFromDelegationLikes(\n //TODO suggested name: getSecretIdsOfHcpAndParentsFromGenericDelegations\n hcpartyId: string,\n objectId: string,\n delegations: { [key: string]: Array<Delegation> }\n ): Promise<Array<{ hcpartyId: string; extractedKeys: Array<string> }>> {\n const { dataOwner: hcp } = await this.getDataOwner(hcpartyId)\n const extractedKeys = []\n if (delegations[hcpartyId]?.length) {\n const decryptedAndImportedAesHcPartyKeys = await this.getDecryptedAesExchangeKeysOfDelegateAndParentsFromGenericDelegations(\n hcpartyId,\n delegations,\n false\n )\n const collatedAesKeysFromDelegatorToHcpartyId = decryptedAndImportedAesHcPartyKeys.reduce((map, k) => ({ ...map, [k.delegatorId]: (map[k.delegatorId] ?? []).concat([k]) }), {} as { [key: string]: { key: CryptoKey; rawKey: string }[] })\n extractedKeys.push(...(await this.decryptKeyInDelegationLikes(delegations[hcpartyId], collatedAesKeysFromDelegatorToHcpartyId, objectId)))\n }\n\n return (hcp as HealthcareParty).parentId\n ? [\n ...(await this.extractKeysHierarchyFromDelegationLikes((hcp as HealthcareParty).parentId!, objectId, delegations)),\n { extractedKeys: extractedKeys, hcpartyId: hcpartyId },\n ]\n : [{ extractedKeys: extractedKeys, hcpartyId: hcpartyId }]\n }\n\n /**\n * Get decrypted generic secret IDs (secretIdSPKs, parentIds, secretIdEKs) from generic delegations (SPKs, CFKs, EKs)\n * 1. Get Data Owner (HCP, Patient or Device) from it's Id.\n * 2. Decrypt the keys of the given data owner.\n * 3. Decrypt the parent's key if it has parent.\n * 4. Return the decrypted key corresponding to the Health Care Party.\n * @param dataOwnerId : the id of the delegate data owner (including its parents) for which to decrypt `extractedKeys`\n * @param objectId : the id of the object/document of which delegations to decrypt ; used just to log to console a message (Cryptographic mistake) in case the object id inside SPK, CFK, EK is different from this one\n * @param delegations : generic delegations (can be SPKs, CFKs, EKs) for all delegates from where to extract `extractedKeys`\n * @returns - **extractedKeys** array containing secret IDs from decrypted generic delegations, from both data owner with given `dataOwnerId` and its parents; can contain duplicates\n * - **dataOwnerId** the given `dataOwnerId` OR, if a parent exist, the data owner id of the top parent in the hierarchy (even if that parent has no delegations)\n */\n //TODO: even if there are no delegations for parent HCP (but the parent exists), the returned dataOwnerId will be the one of the parent\n extractKeysFromDelegationsForHcpHierarchy(\n //TODO suggested name: getSecretIdsOfHcpAndParentsFromGenericDelegations\n dataOwnerId: string,\n objectId: string,\n delegations: { [key: string]: Array<Delegation> }\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n return this.getDataOwner(dataOwnerId).then(({ dataOwner: hcp }) =>\n (delegations[dataOwnerId] && delegations[dataOwnerId].length\n ? this.getDecryptedAesExchangeKeysOfDelegateAndParentsFromGenericDelegations(dataOwnerId, delegations, false).then(\n (decryptedAndImportedAesHcPartyKeys) => {\n const collatedAesKeysFromDelegatorToHcpartyId: {\n [key: string]: { key: CryptoKey; rawKey: string }[]\n } = {}\n decryptedAndImportedAesHcPartyKeys.forEach((k) => {\n ;(collatedAesKeysFromDelegatorToHcpartyId[k.delegatorId] ?? (collatedAesKeysFromDelegatorToHcpartyId[k.delegatorId] = [])).push(k)\n })\n return this.decryptKeyInDelegationLikes(delegations[dataOwnerId], collatedAesKeysFromDelegatorToHcpartyId, objectId!)\n }\n )\n : Promise.resolve([])\n ).then((extractedKeys) =>\n (hcp as HealthcareParty).parentId\n ? this.extractKeysFromDelegationsForHcpHierarchy((hcp as HealthcareParty).parentId!, objectId, delegations).then((parentResponse) =>\n _.assign(parentResponse, {\n extractedKeys: parentResponse.extractedKeys.concat(extractedKeys),\n })\n )\n : { extractedKeys: extractedKeys, hcpartyId: dataOwnerId }\n )\n )\n }\n\n /**\n * Gets an array of generic secret IDs decrypted from a list of generic delegations (SPKs, CFKs, EKs) `delegationsArray`\n * If a particular generic delegation thows an exception when decrypted, the return value for it's secret ID will be 'false' and a message is logged to console\n * For each one of the delegations in the `delegationsArray`, it tries to decrypt with the decryptedHcPartyKey of the owner of that delegation;\n *\n * @param delegationsArray : generic delegations array\n * @param aesKeys : **key** HcP ids of delegators/owners in the `delegationsArray`, each with its own decryptedHcPartyKey\n * @param masterId : is the object id to which the generic delegation belongs to\n * - used only to check whether the object.id matches the one stored in the decrypted generic delegation item\n * - even if there's no match, the secret ID is kept as a valid result (and a message logged to console)\n * @returns array of generic secret IDs (secretIdSPK, parentId, secretIdEK)\n */\n async decryptKeyInDelegationLikes(\n //TODO: suggested name: getSecretIdsFromGenericDelegations\n delegationsArray: Array<Delegation>,\n aesKeysForDataOwnerId: { [key: string]: { key: CryptoKey; rawKey: string }[] },\n masterId: string\n ): Promise<Array<string>> {\n const decryptPromises: Array<Promise<string | undefined>> = delegationsArray.map(async (genericDelegationItem) => {\n const aesKeys = aesKeysForDataOwnerId[genericDelegationItem.owner!]\n if (aesKeys?.length) {\n return aesKeys.reduce(async (acc, aesKey) => {\n const accValue = await acc\n if (accValue) {\n return accValue\n }\n try {\n const decryptedGenericDelegationKey = await this._AES.decrypt(aesKey.key, hex2ua(genericDelegationItem.key!), aesKey.rawKey)\n const results = ua2string(decryptedGenericDelegationKey).split(':')\n\n const objectId = results[0] //must be the ID of the object, for checksum\n const genericSecretId = results[1]\n\n const details =\n 'object ID: ' + masterId + '; generic delegation from ' + genericDelegationItem.owner + ' to ' + genericDelegationItem.delegatedTo\n\n if (!objectId) console.warn('Object id is empty; ' + details)\n if (!genericSecretId) console.warn('Secret id is empty; ' + details)\n\n if (objectId !== masterId) {\n /*console.log(\n \"Cryptographic mistake: object ID is not equal to the expected concatenated id within decrypted generic delegation. This may happen when patients have been merged; \" +\n details\n )*/\n }\n return genericSecretId\n } catch (err) {\n console.log(\n `Could not decrypt generic delegation in object with ID: ${masterId} from ${genericDelegationItem.owner} to ${genericDelegationItem.delegatedTo}: ${err}`\n )\n console.log(`AES key is: ${aesKey.rawKey}. Encrypted data is ${genericDelegationItem.key}.`)\n\n return undefined\n }\n }, Promise.resolve() as Promise<string | undefined>)\n } else {\n console.log(`Could not find aes key for object with ID: ${masterId}`)\n }\n })\n return Promise.all(decryptPromises).then((genericSecretId) => genericSecretId.filter((id) => !!id) as string[])\n }\n\n getPublicKeyFromPrivateKey(privateKey: JsonWebKey, dataOwner: Patient | Device | HealthcareParty) {\n if (!privateKey.n || !privateKey.e) {\n throw new Error('No public key can be deduced from incomplete private key')\n }\n\n const publicKeyFromPrivateKey = jwk2spki(privateKey)\n const publicKeys = [dataOwner.publicKey].concat(Object.keys(dataOwner.aesExchangeKeys ?? {})).filter((x) => !!x)\n\n if (!publicKeys.length) {\n throw new Error('No public key has been defined for hcp')\n }\n\n const publicKey = publicKeys.find((it) => it === publicKeyFromPrivateKey)\n if (!publicKey) {\n throw new Error('No public key can be found for this private key')\n }\n\n return publicKey\n }\n\n async loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId: string, privateKey: Uint8Array) {\n const { dataOwner } = await this.getDataOwner(healthcarePartyId)\n\n const privateKeyInJwk = pkcs8ToJwk(privateKey)\n const publicKey = this.getPublicKeyFromPrivateKey(privateKeyInJwk, dataOwner)\n\n const keyPair: { publicKey: CryptoKey; privateKey: CryptoKey } = await this._RSA.importKeyPair(\n 'jwk',\n privateKeyInJwk,\n 'jwk',\n spkiToJwk(hex2ua(publicKey))\n )\n this.rsaKeyPairs[publicKey.slice(-32)] = keyPair\n const exportedKeyPair = await this._RSA.exportKeys(keyPair, 'jwk', 'jwk')\n\n return this.storeKeyPair(`${healthcarePartyId}.${publicKey.slice(-32)}`, exportedKeyPair)\n }\n\n async loadKeyPairsAsJwkInBrowserLocalStorage(healthcarePartyId: string, privateKey: JsonWebKey) {\n const { dataOwner } = await this.getDataOwner(healthcarePartyId)\n\n if ((!privateKey.n || !privateKey.e) && dataOwner.publicKey) {\n //Fallback on default publicKey\n console.warn('An incomplete key has been completed using the default public key of the data owner')\n const publicKeyInJwk = spkiToJwk(hex2ua(dataOwner.publicKey))\n privateKey.n = publicKeyInJwk.n\n privateKey.e = publicKeyInJwk.e\n }\n\n const publicKey = this.getPublicKeyFromPrivateKey(privateKey, dataOwner)\n\n const keyPair = await this._RSA.importKeyPair('jwk', privateKey, 'jwk', spkiToJwk(hex2ua(publicKey)))\n this.rsaKeyPairs[healthcarePartyId] = keyPair\n const exportedKeyPair = await this._RSA.exportKeys(keyPair, 'jwk', 'jwk')\n\n return this.storeKeyPair(`${healthcarePartyId}.${publicKey.slice(-32)}`, exportedKeyPair)\n }\n\n // noinspection JSUnusedGlobalSymbols\n loadKeyPairsInBrowserLocalStorage(healthcarePartyId: string, file: Blob): Promise<void> {\n const fr = new FileReader()\n return new Promise((resolve, reject) => {\n fr.onerror = reject\n fr.onabort = reject\n fr.onload = (e: any) => {\n //TODO remove any\n const privateKey = e.target.result as string\n this.loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId, hex2ua(privateKey))\n .then(() => resolve())\n .catch(reject)\n }\n fr.readAsText(file)\n })\n }\n\n // noinspection JSUnusedGlobalSymbols\n saveKeychainInBrowserLocalStorage(id: string, keychain: number) {\n localStorage.setItem(\n this.keychainLocalStoreIdPrefix + id,\n b2a(new Uint8Array(keychain).reduce((data, byte) => data + String.fromCharCode(byte), ''))\n )\n }\n\n saveKeychainInBrowserLocalStorageAsBase64(id: string, keyChainB64: string) {\n localStorage.setItem(this.keychainLocalStoreIdPrefix + id, keyChainB64)\n }\n\n // noinspection JSUnusedGlobalSymbols\n saveKeychainValidityDateInBrowserLocalStorage(id: string, date: string) {\n if (!id) return\n\n if (!date) {\n localStorage.removeItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n } else {\n localStorage.setItem(this.keychainValidityDateLocalStoreIdPrefix + id, date)\n }\n }\n\n /**\n * Populate the HCP.options dict with an encrypted eHealth certificate and unencryped expiry date.\n * Any potentially unencrypted certificates will be pruned from the HCP.\n * @param hcpId Id of the hcp to modify\n * @returns modified HCP\n */\n async saveKeyChainInHCPFromLocalStorage(hcpId: string): Promise<HealthcareParty> {\n return await this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let aesKey: CryptoKey | null = null\n try {\n aesKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!aesKey) {\n console.error('No encryption key!')\n }\n\n const opts = hcp.options || {}\n\n const crt = this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!!)\n if (!!aesKey && !!crt) {\n let crtEncrypted: ArrayBuffer | null = null\n try {\n crtEncrypted = await this.AES.encrypt(aesKey, new Uint8Array(string2ua(atob(crt))))\n } catch (e) {\n console.error('Error while encrypting the certificate', e)\n }\n\n // add the encrypted certificate to the options\n _.set(opts, this.hcpPreferenceKeyEhealthCert, ua2string(new Uint8Array(crtEncrypted!)))\n }\n\n const crtValidityDate = this.getKeychainValidityDateInBrowserLocalStorage(hcp.id!!)\n if (!!crtValidityDate) {\n _.set(opts, this.hcpPreferenceKeyEhealthCertDate, crtValidityDate)\n }\n\n hcp.options = opts\n return hcp\n })\n }\n\n importKeychainInBrowserFromHCP(hcpId: string): Promise<void> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let crtCryp: Uint8Array | null = null\n if (!!hcp.options && !!hcp.options[this.hcpPreferenceKeyEhealthCert]) {\n crtCryp = string2ua(hcp.options[this.hcpPreferenceKeyEhealthCert])\n }\n\n const crtValidityDate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCertDate)\n\n // store the validity date\n if (!!crtValidityDate) {\n this.saveKeychainValidityDateInBrowserLocalStorage(hcp.id!!, crtValidityDate)\n }\n\n let crt: ArrayBuffer | null = null\n let decryptionKey: CryptoKey | null = null\n try {\n decryptionKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!decryptionKey) {\n throw new Error('No encryption key! eHealth certificate cannot be decrypted.')\n }\n\n if (!!crtCryp && decryptionKey) {\n try {\n crt = await this.AES.decrypt(decryptionKey, crtCryp)\n } catch (e) {\n console.error(e)\n }\n }\n\n if (!crt) {\n throw new Error(`Error while saving certificate in browser local storage! Hcp ${hcp.id} has no certificate.`)\n } else {\n this.saveKeychainInBrowserLocalStorageAsBase64(hcp.id!!, btoa(String.fromCharCode.apply(null, Array.from(new Uint8Array(crt)))))\n }\n\n return\n })\n }\n\n /**\n * Synchronizes the eHealth certificate from the database into the LocalStorage, returning information on the presence\n * of certificate data in either place.\n *\n * @param hcpId The healthcare party id\n * @returns A Promise for an object that represents the existence of a certificate in local storage and in the DB,\n * through the two boolean properties \"local\" and \"remote\".\n */\n syncEhealthCertificateFromDatabase(hcpId: string): Promise<{ remote: boolean; local: boolean }> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then((hcp: HealthcareParty) => {\n const remoteCertificate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCert)\n const localCertificate = this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!)\n\n if (remoteCertificate) {\n return this.importKeychainInBrowserFromHCP(hcp.id!)\n .then(() => ({ local: true, remote: true }))\n .catch(() => ({ local: !!localCertificate, remote: true }))\n } else {\n return { local: !!localCertificate, remote: !!remoteCertificate }\n }\n })\n }\n\n getKeychainInBrowserLocalStorageAsBase64(id: string) {\n return localStorage.getItem(this.keychainLocalStoreIdPrefix + id)\n }\n\n getKeychainValidityDateInBrowserLocalStorage(id: string) {\n return localStorage.getItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n }\n\n // noinspection JSUnusedGlobalSymbols\n loadKeychainFromBrowserLocalStorage(id: string) {\n const lsItem = localStorage.getItem('org.taktik.icure.ehealth.keychain.' + id)\n return lsItem !== null ? b64_2uas(lsItem) : null\n }\n\n /**\n *\n * @param id\n * @param keyPair should be JWK\n */\n storeKeyPair(id: string, keyPair: { publicKey: any; privateKey: any }) {\n if (typeof Storage === 'undefined') {\n console.log('Your browser does not support HTML5 Browser Local Storage !')\n throw 'Your browser does not support HTML5 Browser Local Storage !'\n }\n //TODO encryption\n localStorage.setItem(this.rsaLocalStoreIdPrefix + id, JSON.stringify(keyPair))\n }\n\n /**\n * loads the RSA key pair (hcparty) in JWK from local storage, not imported\n *\n * @param id doc id - hcpartyId\n * @param publicKeyFingerPrint the 32 last characters of public key this private key is associated with\n * @returns {Object} it is in JWK - not imported\n */\n loadKeyPairNotImported(id: string, publicKeyFingerPrint?: string): { publicKey: JsonWebKey; privateKey: JsonWebKey } {\n if (typeof Storage === 'undefined') {\n console.log('Your browser does not support HTML5 Browser Local Storage !')\n throw 'Your browser does not support HTML5 Browser Local Storage !'\n }\n //TODO decryption\n const item =\n (publicKeyFingerPrint && localStorage.getItem(this.rsaLocalStoreIdPrefix + id + '.' + publicKeyFingerPrint.slice(-32))) ??\n localStorage.getItem(this.rsaLocalStoreIdPrefix + id)\n if (!item) {\n console.warn(`No key can be found in local storage for id ${id} and publicKeyFingerPrint ${publicKeyFingerPrint}`)\n }\n return JSON.parse(item!)\n }\n\n /**\n * Loads and imports the RSA key pair (hcparty) from local storage\n *\n * @param id doc id - hcPartyId\n * @returns {Promise} -> {CryptoKey} - imported RSA\n */\n loadKeyPairImported(id: string) {\n return new Promise((resolve: (value: { publicKey: CryptoKey; privateKey: CryptoKey }) => any, reject) => {\n try {\n const jwkKey = localStorage.getItem(this.rsaLocalStoreIdPrefix + id) as string\n if (jwkKey) {\n const jwkKeyPair = JSON.parse(jwkKey)\n if (jwkKeyPair.publicKey && jwkKeyPair.privateKey) {\n this._RSA.importKeyPair('jwk', jwkKeyPair.privateKey, 'jwk', jwkKeyPair.publicKey).then(resolve, (err) => {\n console.log('Error in RSA.importKeyPair: ' + err)\n reject(err)\n })\n } else {\n const message = 'Error in RSA.importKeyPair: Invalid key'\n console.log(message)\n reject(Error(message))\n }\n } else {\n const message = 'Error in RSA.importKeyPair: Missing key'\n console.log(message)\n reject(Error(message))\n }\n } catch (err) {\n reject(err)\n }\n })\n }\n\n async addNewKeyPairForOwnerId(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n ownerId: string,\n generateTransferKey: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n return this.addNewKeyPairForOwner(maintenanceTasksApi, user, await this.getDataOwner(ownerId), generateTransferKey)\n }\n\n async addNewKeyPairForOwner(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n cdo: CachedDataOwner,\n generateTransferKey: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n const { publicKey, privateKey } = await this.RSA.generateKeyPair()\n const publicKeyHex = ua2hex(await this.RSA.exportKey(publicKey!, 'spki'))\n\n const gen = (await this._AES.generateCryptoKey(true)) as string\n\n await this.cacheKeyPair({ publicKey: await this.RSA.exportKey(publicKey!, 'jwk'), privateKey: await this.RSA.exportKey(privateKey!, 'jwk') })\n\n const { type: ownerType, dataOwner: ownerToUpdate } = await this.createOrUpdateAesExchangeKeysFor(cdo, gen, {\n pubKey: publicKey,\n privKey: privateKey,\n }).then((dataOwnerWithUpdatedAesKeys) =>\n generateTransferKey\n ? this.createOrUpdateTransferKeysFor(dataOwnerWithUpdatedAesKeys, gen, { pubKey: publicKey, privKey: privateKey })\n : dataOwnerWithUpdatedAesKeys\n )\n\n const modifiedDataOwnerAndType =\n ownerType === 'hcp'\n ? await (this.dataOwnerCache[ownerToUpdate.id!] = this.hcpartyBaseApi\n .modifyHealthcareParty(ownerToUpdate as HealthcareParty)\n .then((x) => ({ type: 'hcp', dataOwner: x } as CachedDataOwner)))\n : ownerType === 'patient'\n ? await (this.dataOwnerCache[ownerToUpdate.id!] = this.patientBaseApi\n .modifyPatient(ownerToUpdate as Patient)\n .then((x) => ({ type: 'patient', dataOwner: x } as CachedDataOwner)))\n : await (this.dataOwnerCache[ownerToUpdate.id!] = this.deviceBaseApi\n .updateDevice(ownerToUpdate as Device)\n .then((x) => ({ type: 'device', dataOwner: x } as CachedDataOwner)))\n\n const sentMaintenanceTasks = await this.sendMaintenanceTasks(maintenanceTasksApi, user, modifiedDataOwnerAndType.dataOwner, publicKey)\n\n return {\n dataOwner: sentMaintenanceTasks.length\n ? await this.retrieveDataOwnerInfoAfterPotentialUpdate(modifiedDataOwnerAndType.dataOwner)\n : modifiedDataOwnerAndType.dataOwner,\n publicKey: publicKeyHex,\n privateKey: ua2hex((await this.RSA.exportKey(privateKey!, 'pkcs8')) as ArrayBuffer),\n }\n }\n\n private async createOrUpdateAesExchangeKeysFor(\n cdo: CachedDataOwner,\n decryptedAesExchangeKey: string,\n keyToEncrypt: { pubKey: CryptoKey; privKey: CryptoKey }\n ): Promise<CachedDataOwner> {\n const publicKeyHex = ua2hex(await this.RSA.exportKey(keyToEncrypt.pubKey!, 'spki'))\n const existingAesExchangeKeys = cdo.dataOwner.aesExchangeKeys ?? {}\n existingAesExchangeKeys[publicKeyHex] = await this.encryptAesKeyFor(decryptedAesExchangeKey, cdo.dataOwner, keyToEncrypt.pubKey)\n\n return { type: cdo.type, dataOwner: { ...cdo.dataOwner, aesExchangeKeys: existingAesExchangeKeys } } as CachedDataOwner\n }\n\n private async createOrUpdateTransferKeysFor(\n dataOwner: CachedDataOwner,\n decryptedAesExchangeKey: string,\n keyToEncrypt: { pubKey: CryptoKey; privKey: CryptoKey }\n ): Promise<CachedDataOwner> {\n const pubKeyToEncryptHex = ua2hex(await this.RSA.exportKey(keyToEncrypt.pubKey, 'spki'))\n\n const encryptedKey = ua2hex(\n await this._AES.encrypt(\n await this._AES.importKey('raw', hex2ua(decryptedAesExchangeKey)),\n (await this.RSA.exportKey(keyToEncrypt.privKey!, 'pkcs8')) as ArrayBuffer,\n decryptedAesExchangeKey\n )\n )\n\n const dataOwnerExistingPubKeys = Array.from(await this.getDataOwnerHexPublicKeys(dataOwner.dataOwner))\n\n const transferKeys = fold(dataOwnerExistingPubKeys, dataOwner.dataOwner.transferKeys ?? {}, (pubAcc, pubKeyHex) => {\n if (pubKeyHex !== pubKeyToEncryptHex) {\n const existingKeys = pubAcc[pubKeyHex] ?? {}\n existingKeys[pubKeyToEncryptHex] = encryptedKey\n pubAcc[pubKeyHex] = existingKeys\n }\n return pubAcc\n })\n\n return { type: dataOwner.type, dataOwner: { ...dataOwner.dataOwner, transferKeys: transferKeys } } as CachedDataOwner\n }\n\n private async encryptAesKeyFor(\n aesKey: string,\n dataOwner: HealthcareParty | Patient | Device,\n doNewPublicKey: CryptoKey\n ): Promise<{ [delId: string]: { [pk: string]: string } }> {\n const dataOwnerAllPubKeys = [doNewPublicKey].concat(await this.getDataOwnerPublicKeys(dataOwner))\n\n const encrAes: { [pubKeyFingerprint: string]: string } = {}\n for (const pubKey of dataOwnerAllPubKeys) {\n encrAes[ua2hex(await this.RSA.exportKey(pubKey, 'spki')).slice(-32)] = ua2hex(await this._RSA.encrypt(pubKey, hex2ua(aesKey)))\n }\n\n return { [dataOwner.id!]: encrAes }\n }\n\n private retrieveDataOwnerInfoAfterPotentialUpdate(dataOwnerToUpdate: HealthcareParty | Patient | Device): Promise<CachedDataOwner> {\n return this.getDataOwner(dataOwnerToUpdate.id!).then(({ type, dataOwner }) => {\n return {\n type: type,\n dataOwner: {\n ...dataOwner,\n transferKeys: dataOwnerToUpdate.transferKeys,\n hcPartyKeys: fold(Object.entries(dataOwnerToUpdate.hcPartyKeys ?? {}), dataOwner.hcPartyKeys ?? {}, (acc, [delegateId, hcKeys]) => {\n acc[delegateId] = hcKeys\n return acc\n }),\n aesExchangeKeys: fold(\n Object.entries(dataOwnerToUpdate.aesExchangeKeys ?? {}),\n dataOwner.aesExchangeKeys ?? {},\n (pubAcc, [pubKey, newAesExcKeys]) => {\n const existingKeys = pubAcc[pubKey] ?? {}\n pubAcc[pubKey] = fold(Object.entries(newAesExcKeys), existingKeys, (delAcc, [delId, delKeys]) => {\n delAcc[delId] = delKeys\n return delAcc\n })\n return pubAcc\n }\n ),\n },\n } as CachedDataOwner\n })\n }\n\n private async sendMaintenanceTasks(\n maintenanceTaskApi: IccMaintenanceTaskXApi,\n user: User,\n dataOwner: HealthcareParty | Patient | Device,\n newPublicKey: CryptoKey\n ): Promise<MaintenanceTask[]> {\n const hexNewPubKey = ua2hex(await this.RSA.exportKey(newPublicKey, 'spki'))\n const nonAccessiblePubKeys = Array.from(this.getDataOwnerHexPublicKeys(dataOwner).values())\n .filter((existingPubKey) => existingPubKey != hexNewPubKey)\n .filter(\n (existingPubKey) =>\n !Object.values(this.rsaKeyPairs).find(\n async ({ publicKey, privateKey }) => ua2hex(await this.RSA.exportKey(publicKey, 'spki')) == existingPubKey\n )\n )\n\n if (nonAccessiblePubKeys.length) {\n const tasksForDelegates = Object.entries(await this.getEncryptedAesExchangeKeysForDelegate(dataOwner.id!))\n .filter(([delegatorId]) => delegatorId != dataOwner.id)\n .flatMap(([delegatorId, delegatorKeys]) => {\n return Object.entries(delegatorKeys).flatMap(([, aesExchangeKeys]) => {\n return Object.keys(aesExchangeKeys).map((delegatePubKey) => {\n return { delegateId: delegatorId, maintenanceTask: this.createMaintenanceTask(dataOwner, delegatePubKey) }\n })\n })\n })\n\n const tasksForDelegator = Object.entries(await this.getEncryptedAesExchangeKeys(dataOwner, dataOwner.id!)).flatMap(\n ([doPubKey, delegateKeys]) => {\n return Object.keys(delegateKeys)\n .filter((delegateId) => delegateId != dataOwner.id)\n .map((delegateId) => {\n return { delegateId: delegateId, maintenanceTask: this.createMaintenanceTask(dataOwner, doPubKey) }\n })\n }\n )\n\n return Promise.all(\n tasksForDelegates\n .concat(tasksForDelegator)\n .map(async ({ delegateId, maintenanceTask }) => {\n const taskToCreate = await maintenanceTaskApi?.newInstance(user, maintenanceTask, [delegateId])\n return taskToCreate ? maintenanceTaskApi?.createMaintenanceTaskWithUser(user, taskToCreate) : undefined\n })\n .filter((createdTask) => createdTask != undefined)\n )\n } else {\n return []\n }\n }\n\n private createMaintenanceTask(concernedDataOwner: HealthcareParty | Patient | Device, concernedPubKey: string) {\n return new MaintenanceTask({\n id: this.randomUuid(),\n taskType: 'updateAesExchangeKey',\n status: MaintenanceTask.StatusEnum.Pending,\n properties: [\n new PropertyStub({\n id: 'dataOwnerConcernedId',\n type: new PropertyTypeStub({ type: PropertyTypeStub.TypeEnum.STRING }),\n typedValue: new TypedValueObject({\n type: TypedValueObject.TypeEnum.STRING,\n stringValue: concernedDataOwner.id,\n }),\n }),\n new PropertyStub({\n id: 'dataOwnerConcernedPubKey',\n type: new PropertyTypeStub({ type: PropertyTypeStub.TypeEnum.STRING }),\n typedValue: new TypedValueObject({\n type: TypedValueObject.TypeEnum.STRING,\n stringValue: concernedPubKey,\n }),\n }),\n ],\n })\n }\n\n private getDataOwnerHexPublicKeys(dataOwner: HealthcareParty | Patient | Device): Set<string> {\n return new Set(\n (dataOwner.publicKey ? [dataOwner.publicKey] : [])\n .concat(dataOwner.aesExchangeKeys ? Object.keys(dataOwner.aesExchangeKeys) : [])\n .filter((pubKey) => !!pubKey)\n )\n }\n\n private async getDataOwnerPublicKeys(dataOwner: HealthcareParty | Patient | Device): Promise<CryptoKey[]> {\n return await Promise.all(\n Array.from(this.getDataOwnerHexPublicKeys(dataOwner)).map(\n async (pubKey) => await this._RSA.importKey('jwk', spkiToJwk(hex2ua(pubKey)), ['encrypt'])\n )\n )\n }\n\n generateKeyForDelegate(ownerId: string, delegateId: string): PromiseLike<HealthcareParty | Patient> {\n //Preload hcp and patient because we need them and they are going to be invalidated from the caches\n return notConcurrent(this.generateKeyConcurrencyMap, ownerId, async () => {\n const [{ type: ownerType, dataOwner: owner }, { dataOwner: delegate }] = await Promise.all([\n this.getDataOwner(ownerId),\n this.getDataOwner(delegateId),\n ])\n\n const ownerLegacyPublicKey = owner.publicKey\n\n const availablePublicKeysFingerprints = Object.keys(this.rsaKeyPairs)\n const availableOwnerPublicKeys = [\n ownerLegacyPublicKey,\n ...Object.keys(owner.aesExchangeKeys || {}).filter((x) => x !== ownerLegacyPublicKey),\n ].filter((k) => !!k && availablePublicKeysFingerprints.some((fp) => k.endsWith(fp))) as string[]\n const selectedPublicKey = availableOwnerPublicKeys[0]\n\n if (!selectedPublicKey) {\n throw new Error(`Invalid owner, no public key, keypairs have not be set for ${ownerId}`)\n }\n\n if (\n ((owner.hcPartyKeys || {})[delegateId] && owner.publicKey && availablePublicKeysFingerprints.includes(owner.publicKey.slice(-32))) ||\n Object.values(owner.aesExchangeKeys || {}).some(\n (x) => x[delegateId] && Object.keys(x[delegateId]).some((k) => availablePublicKeysFingerprints.includes(k))\n )\n ) {\n return owner\n }\n\n let ownerCombinedAesExchangeKeys = owner.aesExchangeKeys ?? {}\n\n if (ownerLegacyPublicKey && !(owner.aesExchangeKeys ?? {})[ownerLegacyPublicKey]) {\n //Transfer keys from old structure (hcparty keys) to new one (aesExchangeKeys)\n const unknownDataOwnerCounterPartIds = Object.keys(owner.hcPartyKeys ?? {}).filter((x) => x !== ownerId && x !== delegateId)\n const counterParts = [\n owner,\n delegate,\n ...(await Promise.all(unknownDataOwnerCounterPartIds.map((cpid) => this.getDataOwner(cpid).then((dot) => dot.dataOwner)))),\n ]\n ownerCombinedAesExchangeKeys = {\n [ownerLegacyPublicKey]: Object.entries(owner.hcPartyKeys ?? {}).reduce(\n (map, [hcpId, keys]) => ({\n ...map,\n [hcpId]: { [ownerLegacyPublicKey]: keys[0], [counterParts.find((x) => x.id === hcpId)?.publicKey ?? '']: keys[1] },\n ...{},\n }),\n {}\n ),\n ...ownerCombinedAesExchangeKeys,\n }\n }\n\n const delegatePublicKeys = [delegate.publicKey, ...Object.keys(delegate.aesExchangeKeys ?? {}).filter((x) => x !== delegate.publicKey)].filter(\n (x) => !!x\n ) as string[]\n if (!delegatePublicKeys.length) {\n throw new Error(`Invalid delegate, no public key, keypairs have not be set for ${delegateId}`)\n }\n const genProm = this._AES.generateCryptoKey(true).then(async (AESKey) => {\n const allPubKeys = [...availableOwnerPublicKeys, ...delegatePublicKeys]\n const encryptedAesKeys = await allPubKeys.reduce(\n async (map, pubK) => ({\n ...(await map),\n [pubK.slice(-32)]: ua2hex(\n await this._RSA.encrypt(await this._RSA.importKey('jwk', spkiToJwk(hex2ua(pubK)), ['encrypt']), hex2ua(AESKey as string))\n ),\n }),\n Promise.resolve({} as { [pubKey: string]: string })\n )\n\n if (delegate.publicKey && ownerLegacyPublicKey) {\n owner.hcPartyKeys![delegateId] = [encryptedAesKeys[ownerLegacyPublicKey.slice(-32)], encryptedAesKeys[delegate.publicKey.slice(-32)]]\n }\n owner.aesExchangeKeys = {\n ...(ownerCombinedAesExchangeKeys ?? {}),\n [selectedPublicKey]: { ...(owner.aesExchangeKeys?.[selectedPublicKey] ?? {}), [delegateId]: encryptedAesKeys },\n }\n\n return new Promise<['hcp', HealthcareParty] | ['patient', Patient] | ['device', Device]>((resolve, reject) => {\n ownerType === 'hcp'\n ? (this.dataOwnerCache[owner.id!] = this.hcpartyBaseApi\n .modifyHealthcareParty(owner as HealthcareParty)\n .then((x) => ({ type: 'hcp', dataOwner: x } as CachedDataOwner)))\n .then((x) => resolve(['hcp', x.dataOwner]))\n .catch((e) => reject(e))\n : ownerType === 'patient'\n ? (this.dataOwnerCache[owner.id!] = this.patientBaseApi.modifyPatient(owner as Patient).then((x) => ({ type: 'patient', dataOwner: x })))\n .then((x) => resolve(['patient', x.dataOwner]))\n .catch((e) => reject(e))\n : (this.dataOwnerCache[owner.id!] = this.deviceBaseApi.updateDevice(owner as Device).then((x) => ({ type: 'device', dataOwner: x })))\n .then((x) => resolve(['device', x.dataOwner]))\n .catch((e) => reject(e))\n })\n })\n\n this.hcPartyKeysRequestsCache[delegateId] = genProm.then(() => {\n return this.forceGetEncryptedAesExchangeKeysForDelegate(delegateId)\n })\n return genProm.then((res) => {\n return res[1]\n })\n })\n }\n\n getDataOwner(ownerId: string) {\n return (\n this.dataOwnerCache[ownerId] ??\n (this.dataOwnerCache[ownerId] = this.patientBaseApi\n .getPatient(ownerId)\n .then((x) => ({ type: 'patient', dataOwner: x } as CachedDataOwner))\n .catch(() => this.deviceBaseApi.getDevice(ownerId).then((x) => ({ type: 'device', dataOwner: x } as CachedDataOwner)))\n .catch(() => this.hcpartyBaseApi.getHealthcareParty(ownerId).then((x) => ({ type: 'hcp', dataOwner: x } as CachedDataOwner)))\n .catch((e) => {\n delete this.dataOwnerCache[ownerId]\n throw e\n }))\n )\n }\n\n // noinspection JSUnusedGlobalSymbols\n async checkPrivateKeyValidity(dataOwner: HealthcareParty | Patient | Device): Promise<boolean> {\n const publicKeys = Array.from(new Set([dataOwner.publicKey].concat(Object.keys(dataOwner.aesExchangeKeys ?? {})).filter((x) => !!x))) as string[]\n\n return await publicKeys.reduce(async (pres, publicKey) => {\n const res = await pres\n try {\n const k = await this._RSA.importKey('jwk', spkiToJwk(hex2ua(publicKey)), ['encrypt'])\n const cipher = await this._RSA.encrypt(k, utf8_2ua('shibboleth'))\n const ikp = this.getCachedRsaKeyPairForFingerprint(dataOwner.id!, publicKey.slice(-32))\n const plainText = ua2utf8(await this._RSA.decrypt(ikp.privateKey, new Uint8Array(cipher)))\n return plainText === 'shibboleth' || res\n } catch (e) {\n return res\n }\n }, Promise.resolve(false))\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: any) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n _.each(argsArray, (arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw '### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details\n }\n\n async getEncryptionDecryptionKeys(dataOwnerId: string, document: EncryptedEntity): Promise<Array<string> | undefined> {\n try {\n return !document.id\n ? undefined\n : _.uniq(\n (\n await this.extractKeysFromDelegationsForHcpHierarchy(\n dataOwnerId,\n document.id,\n (document.encryptionKeys && Object.keys(document.encryptionKeys).length && document.encryptionKeys) || document.delegations!\n )\n ).extractedKeys\n )\n } catch (e) {\n return undefined\n }\n }\n\n async encryptDecrypt(\n method: 'encrypt' | 'decrypt',\n content: Uint8Array | ArrayBuffer,\n edKey?: string,\n user?: User,\n documentObject?: Document\n ): Promise<Uint8Array | Array<any> | any> {\n if (!content || !(edKey || (user?.healthcarePartyId && documentObject))) return content\n\n if (edKey) {\n const importedEdKey = await this._AES.importKey('raw', hex2ua(edKey.replace(/-/g, '')))\n try {\n return await this._AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n const sfks = await this.extractKeysFromDelegationsForHcpHierarchy(user?.healthcarePartyId!, documentObject?.id!, documentObject?.encryptionKeys!)\n const importedEdKey = await this._AES.importKey('raw', hex2ua(sfks.extractedKeys[0].replace(/-/g, '')))\n try {\n return await this._AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icure/api",
3
- "version": "5.0.16",
3
+ "version": "5.0.19",
4
4
  "description": "Typescript version of iCure standalone API client",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",