@icure/api 6.4.1 → 6.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/icc-api/model/models.d.ts +2 -2
- package/icc-x-api/crypto/AES.js +3 -3
- package/icc-x-api/crypto/AES.js.map +1 -1
- package/icc-x-api/filters/filters.d.ts +1 -1
- package/icc-x-api/icc-bekmehr-x-api.d.ts +1 -1
- package/icc-x-api/icc-crypto-x-api.d.ts +1 -1
- package/icc-x-api/icc-crypto-x-api.js +65 -63
- package/icc-x-api/icc-crypto-x-api.js.map +1 -1
- package/icc-x-api/utils/asn1-packer.d.ts +1 -1
- package/icc-x-api/utils/asn1-parser.d.ts +1 -1
- package/icc-x-api/utils/net-utils.d.ts +2 -2
- package/package.json +1 -1
|
@@ -269,5 +269,5 @@ export * from './VmpStub';
|
|
|
269
269
|
export * from './Vtm';
|
|
270
270
|
export * from './Wada';
|
|
271
271
|
export * from './Weekday';
|
|
272
|
-
export type EncryptedEntity = AccessLog | Article | CalendarItem | Classification | Contact | Document | Form | HealthElement | Invoice | MaintenanceTask | Message | Patient | Receipt;
|
|
273
|
-
export type EncryptedParentEntity = Message | Patient;
|
|
272
|
+
export declare type EncryptedEntity = AccessLog | Article | CalendarItem | Classification | Contact | Document | Form | HealthElement | Invoice | MaintenanceTask | Message | Patient | Receipt;
|
|
273
|
+
export declare type EncryptedParentEntity = Message | Patient;
|
package/icc-x-api/crypto/AES.js
CHANGED
|
@@ -12,9 +12,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
12
12
|
exports.AES = exports.AESUtils = void 0;
|
|
13
13
|
const utils_1 = require("../utils");
|
|
14
14
|
class AESUtils {
|
|
15
|
-
set debug(value) {
|
|
16
|
-
this._debug = value;
|
|
17
|
-
}
|
|
18
15
|
constructor(crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : {}) {
|
|
19
16
|
/********* AES Config **********/
|
|
20
17
|
this.ivLength = 16;
|
|
@@ -27,6 +24,9 @@ class AESUtils {
|
|
|
27
24
|
this._debug = false;
|
|
28
25
|
this.crypto = crypto;
|
|
29
26
|
}
|
|
27
|
+
set debug(value) {
|
|
28
|
+
this._debug = value;
|
|
29
|
+
}
|
|
30
30
|
encrypt(cryptoKey, plainData, rawKey = '<NA>') {
|
|
31
31
|
return new Promise((resolve, reject) => {
|
|
32
32
|
if (plainData instanceof Uint8Array) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AES.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AES.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAAuD;AAEvD,MAAa,QAAQ;IAenB,IAAI,KAAK,CAAC,KAAc;QACtB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,YAAY,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;QAlBvI,iCAAiC;QACjC,aAAQ,GAAG,EAAE,CAAA;QACb,4BAAuB,GAAG,SAAS,CAAA;QAEnC,oBAAe,GAAoB;YACjC,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,GAAG;SACZ,CAAA;QAEO,oBAAe,GAAwB,EAAE,IAAI,EAAE,IAAI,CAAC,uBAAuB,EAAE,CAAA;QAG7E,WAAM,GAAY,KAAK,CAAA;QAO7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAED,OAAO,CAAC,SAAoB,EAAE,SAAmC,EAAE,MAAM,GAAG,MAAM;QAChF,OAAO,IAAI,OAAO,CAAC,CAAC,OAAoC,EAAE,MAA4B,EAAE,EAAE;YACxF,IAAI,SAAS,YAAY,UAAU,EAAE;gBACnC,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,CAAA;gBAC/B,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AS,CAAC,MAAqB,EAAE,MAA6C;QAC5E,OAAO,IAAI,OAAO,CAAC,CAAC,OAAkC,EAAE,MAA4B,EAAE,EAAE;YACtF,MAAM,WAAW,GAAG,IAAI,CAAA;YACxB,MAAM,SAAS,GAAe,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;YACpD,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM;iBACtB,SAAS,CAAC,MAAa,EAAE,MAAa,EAAE,IAAI,CAAC,eAAe,EAAE,WAAW,EAAE,SAAS,CAAC;iBACrF,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACb,IAAI,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE;oBACpF,OAAO,CAAC,IAAI,CAAC,iBAAiB,IAAA,cAAM,EAAC,MAAM,CAAC,SAAS,CAAC,CAAA;iBACvD;gBACD,MAAM,GAAG,CAAA;YACX,CAAC,CAAC;iBACD,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC1B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAnLD,4BAmLC;AAEY,QAAA,GAAG,GAAG,IAAI,QAAQ,EAAE,CAAA","sourcesContent":["import { appendBuffer, hex2ua, ua2hex } from '../utils'\n\nexport class AESUtils {\n /********* AES Config **********/\n ivLength = 16\n aesAlgorithmEncryptName = 'AES-CBC'\n\n aesKeyGenParams: AesKeyGenParams = {\n name: 'AES-CBC',\n length: 256,\n }\n\n private aesImportParams: AlgorithmIdentifier = { name: this.aesAlgorithmEncryptName }\n\n private crypto: Crypto\n private _debug: boolean = false\n\n set debug(value: boolean) {\n this._debug = value\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (plainData instanceof Uint8Array) {\n const buffer = plainData.buffer\n plainData = (buffer.byteLength > plainData.byteLength ? buffer.slice(0, plainData.byteLength) : buffer) as ArrayBuffer\n }\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: this.generateIV(this.ivLength),\n }\n this._debug && console.log(`encrypt ${ua2hex(plainData)} with ${rawKey}`)\n this.crypto.subtle\n .encrypt(\n {\n ...aesAlgorithmEncrypt,\n } /* some ill behaved implementations change the values in place */,\n cryptoKey,\n plainData\n )\n .then(\n (cipherData) => {\n this._debug && console.log(`cipherData: ${ua2hex(cipherData)}`)\n return resolve(appendBuffer(aesAlgorithmEncrypt.iv.buffer as ArrayBuffer, cipherData))\n },\n (err) => reject('AES encryption failed: ' + err)\n )\n })\n }\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (!cryptoKey) {\n return reject('No crypto key provided for decryption')\n }\n const encryptedDataUint8 = encryptedData instanceof ArrayBuffer ? new Uint8Array(encryptedData) : encryptedData\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: encryptedDataUint8.subarray(0, this.ivLength),\n\n /*\n * IF THIS BIT OF CODE PRODUCES A DOMEXCEPTION CODE 0 ERROR, IT MIGHT BE RELATED TO THIS:\n *\n * NOTOK:\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[hcpartyId] && hcparty.hcPartyKeys[hcpartyId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + hcpartyId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[hcpartyId][1];\n *\n * SHOULD BE:\n * var delegatorId = patient.delegations[hcpartyId][0].owner;\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[delegatorId] && hcparty.hcPartyKeys[delegatorId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + delegatorId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[delegatorId][1];\n */\n }\n this._debug && console.log(`decrypt ${ua2hex(encryptedData)} with ${rawKey}`)\n this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length)).then(\n (decipheredData) => {\n this._debug && console.log(`decipheredData: ${ua2hex(decipheredData)}`)\n resolve(decipheredData)\n },\n (err) => {\n reject('AES decryption failed: ' + err)\n }\n )\n })\n }\n\n async decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer> {\n try {\n return this.decrypt(cryptoKeys[0], uint8Array)\n } catch (e) {\n if (cryptoKeys.length > 1) {\n return this.decryptSome(cryptoKeys.slice(1), uint8Array)\n } else {\n throw e\n }\n }\n }\n\n // generate an AES key\n // noinspection JSUnusedGlobalSymbols\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n generateCryptoKey(toHex: true): Promise<string>\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey> {\n return new Promise((resolve: (value: CryptoKey | string) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const cryptoKeyPromise: Promise<CryptoKey> = this.crypto.subtle.generateKey(this.aesKeyGenParams, extractable, keyUsages) as Promise<CryptoKey>\n return toHex === undefined || !toHex\n ? cryptoKeyPromise.then(resolve, reject)\n : cryptoKeyPromise.then((k) => this.exportKey(k, 'raw'), reject).then((raw) => resolve(ua2hex(raw)), reject)\n })\n }\n\n // noinspection JSMethodCanBeStatic\n generateIV(ivByteLength: number): Uint8Array {\n return new Uint8Array(this.crypto.getRandomValues(new Uint8Array(ivByteLength)))\n }\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey> {\n return new Promise((resolve: (value: ArrayBuffer | JsonWebKey) => any, reject: (reason: any) => any) => {\n return this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey> {\n return new Promise((resolve: (value: CryptoKey) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n return this.crypto.subtle\n .importKey(format as any, aesKey as any, this.aesImportParams, extractable, keyUsages)\n .catch((err) => {\n if (format == 'raw' && (aesKey instanceof ArrayBuffer || ArrayBuffer.isView(aesKey))) {\n console.warn(`Import of key ${ua2hex(aesKey)} failed`)\n }\n throw err\n })\n .then(resolve, reject)\n })\n }\n}\n\nexport const AES = new AESUtils()\n"]}
|
|
1
|
+
{"version":3,"file":"AES.js","source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CAAC;iBACrF,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACb,IAAI,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE;oBACpF,OAAO,CAAC,IAAI,CAAC,iBAAiB,IAAA,cAAM,EAAC,MAAM,CAAC,SAAS,CAAC,CAAA;iBACvD;gBACD,MAAM,GAAG,CAAA;YACX,CAAC,CAAC;iBACD,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC1B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAnLD,4BAmLC;AAEY,QAAA,GAAG,GAAG,IAAI,QAAQ,EAAE,CAAA","sourcesContent":["import { appendBuffer, hex2ua, ua2hex } from '../utils'\n\nexport class AESUtils {\n /********* AES Config **********/\n ivLength = 16\n aesAlgorithmEncryptName = 'AES-CBC'\n\n aesKeyGenParams: AesKeyGenParams = {\n name: 'AES-CBC',\n length: 256,\n }\n\n private aesImportParams: AlgorithmIdentifier = { name: this.aesAlgorithmEncryptName }\n\n private crypto: Crypto\n private _debug: boolean = false\n\n set debug(value: boolean) {\n this._debug = value\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (plainData instanceof Uint8Array) {\n const buffer = plainData.buffer\n plainData = (buffer.byteLength > plainData.byteLength ? buffer.slice(0, plainData.byteLength) : buffer) as ArrayBuffer\n }\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: this.generateIV(this.ivLength),\n }\n this._debug && console.log(`encrypt ${ua2hex(plainData)} with ${rawKey}`)\n this.crypto.subtle\n .encrypt(\n {\n ...aesAlgorithmEncrypt,\n } /* some ill behaved implementations change the values in place */,\n cryptoKey,\n plainData\n )\n .then(\n (cipherData) => {\n this._debug && console.log(`cipherData: ${ua2hex(cipherData)}`)\n return resolve(appendBuffer(aesAlgorithmEncrypt.iv.buffer as ArrayBuffer, cipherData))\n },\n (err) => reject('AES encryption failed: ' + err)\n )\n })\n }\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (!cryptoKey) {\n return reject('No crypto key provided for decryption')\n }\n const encryptedDataUint8 = encryptedData instanceof ArrayBuffer ? new Uint8Array(encryptedData) : encryptedData\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: encryptedDataUint8.subarray(0, this.ivLength),\n\n /*\n * IF THIS BIT OF CODE PRODUCES A DOMEXCEPTION CODE 0 ERROR, IT MIGHT BE RELATED TO THIS:\n *\n * NOTOK:\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[hcpartyId] && hcparty.hcPartyKeys[hcpartyId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + hcpartyId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[hcpartyId][1];\n *\n * SHOULD BE:\n * var delegatorId = patient.delegations[hcpartyId][0].owner;\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[delegatorId] && hcparty.hcPartyKeys[delegatorId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + delegatorId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[delegatorId][1];\n */\n }\n this._debug && console.log(`decrypt ${ua2hex(encryptedData)} with ${rawKey}`)\n this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length)).then(\n (decipheredData) => {\n this._debug && console.log(`decipheredData: ${ua2hex(decipheredData)}`)\n resolve(decipheredData)\n },\n (err) => {\n reject('AES decryption failed: ' + err)\n }\n )\n })\n }\n\n async decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer> {\n try {\n return this.decrypt(cryptoKeys[0], uint8Array)\n } catch (e) {\n if (cryptoKeys.length > 1) {\n return this.decryptSome(cryptoKeys.slice(1), uint8Array)\n } else {\n throw e\n }\n }\n }\n\n // generate an AES key\n // noinspection JSUnusedGlobalSymbols\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n generateCryptoKey(toHex: true): Promise<string>\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey> {\n return new Promise((resolve: (value: CryptoKey | string) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const cryptoKeyPromise: Promise<CryptoKey> = this.crypto.subtle.generateKey(this.aesKeyGenParams, extractable, keyUsages) as Promise<CryptoKey>\n return toHex === undefined || !toHex\n ? cryptoKeyPromise.then(resolve, reject)\n : cryptoKeyPromise.then((k) => this.exportKey(k, 'raw'), reject).then((raw) => resolve(ua2hex(raw)), reject)\n })\n }\n\n // noinspection JSMethodCanBeStatic\n generateIV(ivByteLength: number): Uint8Array {\n return new Uint8Array(this.crypto.getRandomValues(new Uint8Array(ivByteLength)))\n }\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey> {\n return new Promise((resolve: (value: ArrayBuffer | JsonWebKey) => any, reject: (reason: any) => any) => {\n return this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey> {\n return new Promise((resolve: (value: CryptoKey) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n return this.crypto.subtle\n .importKey(format as any, aesKey as any, this.aesImportParams, extractable, keyUsages)\n .catch((err) => {\n if (format == 'raw' && (aesKey instanceof ArrayBuffer || ArrayBuffer.isView(aesKey))) {\n console.warn(`Import of key ${ua2hex(aesKey)} failed`)\n }\n throw err\n })\n .then(resolve, reject)\n })\n }\n}\n\nexport const AES = new AESUtils()\n"]}
|
|
@@ -58,7 +58,7 @@ export * from './UserByIdsFilter';
|
|
|
58
58
|
export declare class Filter {
|
|
59
59
|
static patient(): PatientFilterBuilder;
|
|
60
60
|
}
|
|
61
|
-
export type AbstractFilter<T> = T extends Patient ? AbstractFilterPatient | ConstantFilter<Patient> | IntersectionFilter<Patient> | UnionFilter<Patient> | ComplementFilter<Patient> : T extends Contact ? AbstractFilterContact | ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T> : T extends Service ? AbstractFilterService | ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T> : ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T>;
|
|
61
|
+
export declare type AbstractFilter<T> = T extends Patient ? AbstractFilterPatient | ConstantFilter<Patient> | IntersectionFilter<Patient> | UnionFilter<Patient> | ComplementFilter<Patient> : T extends Contact ? AbstractFilterContact | ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T> : T extends Service ? AbstractFilterService | ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T> : ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T>;
|
|
62
62
|
declare abstract class FilterBuilder<T> {
|
|
63
63
|
filterProvider?: () => AbstractFilter<T>;
|
|
64
64
|
composer: (thisFilterBuilder: FilterBuilder<T>, otherFilterBuilder: FilterBuilder<T>) => FilterBuilder<T>;
|
|
@@ -5,7 +5,7 @@ import { IccDocumentXApi } from './icc-document-x-api';
|
|
|
5
5
|
import { IccHelementXApi } from './icc-helement-x-api';
|
|
6
6
|
import { Contact, Document, HealthElement, Service } from '../icc-api/model/models';
|
|
7
7
|
import { AuthenticationProvider } from './auth/AuthenticationProvider';
|
|
8
|
-
export type Patcher = ContactPatcher | HealthElementPatcher | DocumentPatcher | ServicePatcher;
|
|
8
|
+
export declare type Patcher = ContactPatcher | HealthElementPatcher | DocumentPatcher | ServicePatcher;
|
|
9
9
|
export interface ContactPatcher {
|
|
10
10
|
type: 'ContactDto';
|
|
11
11
|
patch: (contacts: Contact[]) => Promise<Contact[]>;
|
|
@@ -18,6 +18,31 @@ const models_1 = require("../icc-api/model/models");
|
|
|
18
18
|
const binary_utils_1 = require("./utils/binary-utils");
|
|
19
19
|
const utils_1 = require("./utils");
|
|
20
20
|
class IccCryptoXApi {
|
|
21
|
+
constructor(host, headers, hcpartyBaseApi, //Init with a hcparty x api for better performances
|
|
22
|
+
patientBaseApi, deviceBaseApi, crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : {}, storage, keyStorage) {
|
|
23
|
+
this.hcPartyKeysCache = {};
|
|
24
|
+
//[delegateId][delegatorId] = delegateEncryptedHcPartyKey
|
|
25
|
+
//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)
|
|
26
|
+
this.hcPartyKeysRequestsCache = {};
|
|
27
|
+
this.cacheLastDeletionTimestamp = undefined;
|
|
28
|
+
this.dataOwnerCache = {};
|
|
29
|
+
this.keychainLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain.';
|
|
30
|
+
this.keychainValidityDateLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain-date.';
|
|
31
|
+
this.hcpPreferenceKeyEhealthCert = 'eHealthCRTCrypt';
|
|
32
|
+
this.hcpPreferenceKeyEhealthCertDate = 'eHealthCRTDate';
|
|
33
|
+
this.rsaLocalStoreIdPrefix = 'org.taktik.icure.rsa.';
|
|
34
|
+
this.rsaKeyPairs = {};
|
|
35
|
+
this.hcpartyBaseApi = hcpartyBaseApi;
|
|
36
|
+
this.patientBaseApi = patientBaseApi;
|
|
37
|
+
this.deviceBaseApi = deviceBaseApi;
|
|
38
|
+
this._crypto = crypto;
|
|
39
|
+
this.generateKeyConcurrencyMap = {};
|
|
40
|
+
this._AES = new AES_1.AESUtils(crypto);
|
|
41
|
+
this._RSA = new RSA_1.RSAUtils(crypto);
|
|
42
|
+
this._shamir = new shamir_1.ShamirClass(crypto);
|
|
43
|
+
this._storage = storage;
|
|
44
|
+
this._keyStorage = keyStorage;
|
|
45
|
+
}
|
|
21
46
|
get crypto() {
|
|
22
47
|
return this._crypto;
|
|
23
48
|
}
|
|
@@ -58,31 +83,6 @@ class IccCryptoXApi {
|
|
|
58
83
|
this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(delegateHcPartyId).catch(() => { }),
|
|
59
84
|
]).then(([a, b, c]) => (Object.assign(Object.assign(Object.assign({}, a), b), c)));
|
|
60
85
|
}
|
|
61
|
-
constructor(host, headers, hcpartyBaseApi, //Init with a hcparty x api for better performances
|
|
62
|
-
patientBaseApi, deviceBaseApi, crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : {}, storage, keyStorage) {
|
|
63
|
-
this.hcPartyKeysCache = {};
|
|
64
|
-
//[delegateId][delegatorId] = delegateEncryptedHcPartyKey
|
|
65
|
-
//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)
|
|
66
|
-
this.hcPartyKeysRequestsCache = {};
|
|
67
|
-
this.cacheLastDeletionTimestamp = undefined;
|
|
68
|
-
this.dataOwnerCache = {};
|
|
69
|
-
this.keychainLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain.';
|
|
70
|
-
this.keychainValidityDateLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain-date.';
|
|
71
|
-
this.hcpPreferenceKeyEhealthCert = 'eHealthCRTCrypt';
|
|
72
|
-
this.hcpPreferenceKeyEhealthCertDate = 'eHealthCRTDate';
|
|
73
|
-
this.rsaLocalStoreIdPrefix = 'org.taktik.icure.rsa.';
|
|
74
|
-
this.rsaKeyPairs = {};
|
|
75
|
-
this.hcpartyBaseApi = hcpartyBaseApi;
|
|
76
|
-
this.patientBaseApi = patientBaseApi;
|
|
77
|
-
this.deviceBaseApi = deviceBaseApi;
|
|
78
|
-
this._crypto = crypto;
|
|
79
|
-
this.generateKeyConcurrencyMap = {};
|
|
80
|
-
this._AES = new AES_1.AESUtils(crypto);
|
|
81
|
-
this._RSA = new RSA_1.RSAUtils(crypto);
|
|
82
|
-
this._shamir = new shamir_1.ShamirClass(crypto);
|
|
83
|
-
this._storage = storage;
|
|
84
|
-
this._keyStorage = keyStorage;
|
|
85
|
-
}
|
|
86
86
|
loadAllKeysFromLocalStorage(dataOwnerId) {
|
|
87
87
|
return __awaiter(this, void 0, void 0, function* () {
|
|
88
88
|
const pubKeys = yield this.getDataOwnerHexPublicKeys((yield this.getDataOwner(dataOwnerId)).dataOwner);
|
|
@@ -1245,32 +1245,36 @@ class IccCryptoXApi {
|
|
|
1245
1245
|
* @returns {Promise} -> {CryptoKey} - imported RSA
|
|
1246
1246
|
*/
|
|
1247
1247
|
loadKeyPairImported(id) {
|
|
1248
|
-
return
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
console.error('Error in RSA.importKeyPair: ' + err);
|
|
1255
|
-
reject(err);
|
|
1256
|
-
});
|
|
1257
|
-
}
|
|
1258
|
-
else {
|
|
1259
|
-
const message = 'Error in RSA.importKeyPair: Invalid key';
|
|
1260
|
-
console.error(message);
|
|
1261
|
-
reject(Error(message));
|
|
1262
|
-
}
|
|
1248
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1249
|
+
let jwkKeyPair = yield this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id);
|
|
1250
|
+
if (!jwkKeyPair) {
|
|
1251
|
+
const { dataOwner } = yield this.getDataOwner(id);
|
|
1252
|
+
if (dataOwner.publicKey) {
|
|
1253
|
+
jwkKeyPair = yield this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id + '.' + dataOwner.publicKey.slice(-32));
|
|
1263
1254
|
}
|
|
1264
1255
|
else {
|
|
1265
|
-
|
|
1256
|
+
console.warn('Attempting to load default public key for data owner without default public key');
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
if (jwkKeyPair !== undefined) {
|
|
1260
|
+
if (jwkKeyPair.publicKey && jwkKeyPair.privateKey) {
|
|
1261
|
+
return yield this._RSA.importKeyPair('jwk', jwkKeyPair.privateKey, 'jwk', jwkKeyPair.publicKey).catch((err) => {
|
|
1262
|
+
console.error('Error in RSA.importKeyPair: ' + err);
|
|
1263
|
+
throw err;
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
else {
|
|
1267
|
+
const message = 'Error in RSA.importKeyPair: Invalid key';
|
|
1266
1268
|
console.error(message);
|
|
1267
|
-
|
|
1269
|
+
throw Error(message);
|
|
1268
1270
|
}
|
|
1269
1271
|
}
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
+
else {
|
|
1273
|
+
const message = 'Error in RSA.importKeyPair: Missing key';
|
|
1274
|
+
console.error(message);
|
|
1275
|
+
throw Error(message);
|
|
1272
1276
|
}
|
|
1273
|
-
})
|
|
1277
|
+
});
|
|
1274
1278
|
}
|
|
1275
1279
|
/**
|
|
1276
1280
|
* When a user lost his keys, people to whom he shared information may call this method to give access back to him, re-encrypting their common
|
|
@@ -1467,29 +1471,27 @@ class IccCryptoXApi {
|
|
|
1467
1471
|
sendMaintenanceTasks(maintenanceTaskApi, user, dataOwner, newPublicKey) {
|
|
1468
1472
|
return __awaiter(this, void 0, void 0, function* () {
|
|
1469
1473
|
const hexNewPubKey = (0, binary_utils_1.ua2hex)(yield this.RSA.exportKey(newPublicKey, 'spki'));
|
|
1470
|
-
const
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
.
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
return Object.keys(aesExchangeKeys).map((delegatePubKey) => {
|
|
1479
|
-
return { delegateId: delegatorId, maintenanceTask: this.createMaintenanceTask(dataOwner, delegatePubKey) };
|
|
1480
|
-
});
|
|
1481
|
-
});
|
|
1482
|
-
});
|
|
1483
|
-
const tasksForDelegator = (yield this._getDelegateIdsOf(dataOwner))
|
|
1474
|
+
const availablePubKeysSet = new Set(yield this.getPublicKeysAsSpki());
|
|
1475
|
+
const hasNonAccessiblePubKeys = Array.from(this.getDataOwnerHexPublicKeys(dataOwner).values()).some((existingPubKey) => existingPubKey != hexNewPubKey && !availablePubKeysSet.has(existingPubKey));
|
|
1476
|
+
if (hasNonAccessiblePubKeys) {
|
|
1477
|
+
const allDelegatesAndDelegator = new Set([
|
|
1478
|
+
...Object.keys(yield this.getEncryptedAesExchangeKeysForDelegate(dataOwner.id)),
|
|
1479
|
+
...(yield this._getDelegateIdsOf(dataOwner)),
|
|
1480
|
+
]);
|
|
1481
|
+
const tasks = [...allDelegatesAndDelegator]
|
|
1484
1482
|
.filter((delegateId) => delegateId != dataOwner.id)
|
|
1485
1483
|
.map((delegateId) => {
|
|
1486
|
-
return { delegateId
|
|
1484
|
+
return { delegateId, maintenanceTask: this.createMaintenanceTask(dataOwner, hexNewPubKey) };
|
|
1487
1485
|
});
|
|
1488
|
-
|
|
1486
|
+
const res = [];
|
|
1487
|
+
for (const task of tasks) {
|
|
1489
1488
|
const taskToCreate = yield (maintenanceTaskApi === null || maintenanceTaskApi === void 0 ? void 0 : maintenanceTaskApi.newInstance(user, task.maintenanceTask, [task.delegateId]));
|
|
1490
1489
|
const createdTask = taskToCreate ? yield (maintenanceTaskApi === null || maintenanceTaskApi === void 0 ? void 0 : maintenanceTaskApi.createMaintenanceTaskWithUser(user, taskToCreate)) : undefined;
|
|
1491
|
-
|
|
1492
|
-
|
|
1490
|
+
if (createdTask) {
|
|
1491
|
+
res.push(createdTask);
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
return res;
|
|
1493
1495
|
}
|
|
1494
1496
|
else {
|
|
1495
1497
|
return [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icc-crypto-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-crypto-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,sCAAuC;AACvC,sCAAuC;AACvC,4CAA6C;AAE7C,4BAA2B;AAC3B,oDAagC;AAChC,uDAA6G;AAC7G,mCAAyF;AAyBzF,MAAa,aAAa;IACxB,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,IAAI,CAAA;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Q,CAAC,CAAA;aAClB;iBAAM;gBACL,OAAO,EAAE,CAAA;aACV;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AA/sED,sCA+sEC","sourcesContent":["/* eslint-disable */\nimport { 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, foldAsync, jwk2spki, notConcurrent, pkcs8ToJwk, spkiToJwk } from './utils'\nimport { IccMaintenanceTaskXApi } from './icc-maintenance-task-x-api'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\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 get keyStorage(): KeyStorageFacade {\n return this._keyStorage\n }\n\n get storage(): StorageFacade<string> {\n return this._storage\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 private readonly _storage: StorageFacade<string>\n private readonly _keyStorage: KeyStorageFacade\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 storage: StorageFacade<string>,\n keyStorage: KeyStorageFacade\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 this._storage = storage\n this._keyStorage = keyStorage\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(await this.loadKeyPairNotImported(dataOwnerId, fingerprint))\n }\n }\n }\n\n async getCachedRsaKeyPairForFingerprint(\n dataOwnerId: string,\n pubKeyOrFingerprint: string\n ): Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }> {\n const fingerprint = pubKeyOrFingerprint.slice(-32)\n return this.rsaKeyPairs[fingerprint] ?? (await this.cacheKeyPair(await 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 async getPublicKeysAsSpki(): Promise<string[]> {\n return await Object.values(this.rsaKeyPairs).reduce(async (p, rsa) => {\n return (await p).concat([ua2hex(await this.RSA.exportKey(rsa.publicKey, 'spki'))])\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 await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${hcp.id!}`, exportedKeyPair)\n } catch (e) {\n console.log('Cannot decrypt shamir RSA key')\n }\n }\n\n /**\n * 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(await this.loadKeyPairNotImported(loggedHcPartyId, fingerprint)))\n if (!keyPair) {\n return\n }\n\n // Due to past bugs the encryptedHcPartyKeys may contain the full key instead of just the fingerprint.\n let encryptedHcPartyKey = encryptedHcPartyKeys[fingerprint] ?? encryptedHcPartyKeys[pk]\n if (!encryptedHcPartyKey) {\n const delegate = await this.getDataOwner(delegateHcPartyId, false) //it is faster to just try to decrypt if not in cache\n if (!delegate?.dataOwner || delegate.dataOwner.publicKey?.endsWith(fingerprint)) {\n encryptedHcPartyKey = encryptedHcPartyKeys['']\n } else {\n return\n }\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\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(undefined as 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 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 }): Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }> {\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 this.getEncryptedAesExchangeKeysForDelegate(delegateHcPartyId).then(\n 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\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 = parentObject\n ? await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(createdObject.id + ':' + parentObject.id).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n )\n : undefined\n\n return {\n owner: modifiedOwner,\n delegations: {\n ...(createdObject.delegations ?? {}),\n [ownerId]: [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedDelegation!),\n },\n ],\n },\n cryptedForeignKeys:\n (encryptedSecretForeignKey\n ? {\n ...(createdObject.cryptedForeignKeys ?? {}),\n [ownerId]: [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedSecretForeignKey!),\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(undefined as 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 // What we need is to find aes exchange keys on the owner ! Even just with whom he shared information, we don't care about aes exchange keys\n private async _getDelegateIdsOf(owner: HealthcareParty | Patient | Device): Promise<string[]> {\n const mapOfAesExchKeysDelegates = Object.entries(owner.aesExchangeKeys ?? {}).reduce(\n (map, [, aesExchKeys]) => map.concat(Object.keys(aesExchKeys).filter((delegateId) => !map.includes(delegateId))),\n [] as string[]\n )\n\n return owner.hcPartyKeys\n ? mapOfAesExchKeysDelegates.concat(Object.keys(owner.hcPartyKeys).filter((delegateId) => !mapOfAesExchKeysDelegates.includes(delegateId)))\n : mapOfAesExchKeysDelegates\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]) //[fingerprint of delegate pub key, key], [fingerprint of owner pub key, key]\n const [publicKeyFingerprint, encryptedAesExchangeKey] = candidates[candidates.findIndex(([k, v]) => publicKeys.some((pk) => pk.endsWith(k)))]\n return { ...map, [e[0]]: { [publicKeyFingerprint]: encryptedAesExchangeKey } }\n }, {} as { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } })\n\n if (!owner.publicKey || mapOfAesExchangeKeys[owner.publicKey] || !owner.hcPartyKeys?.[delegateId]) {\n return mapOfAesExchangeKeys\n }\n const delegate = (await this.getDataOwner(delegateId)).dataOwner\n if (delegate.publicKey && publicKeys.includes(delegate.publicKey)) {\n return {\n ...mapOfAesExchangeKeys,\n [owner.publicKey]: { [(await this.getDataOwner(delegateId)).dataOwner.publicKey?.slice(-32)!]: owner.hcPartyKeys[delegateId][1] },\n }\n } else if (publicKeys.includes(owner.publicKey)) {\n return { ...mapOfAesExchangeKeys, [owner.publicKey]: { [owner.publicKey.slice(-32)]: owner.hcPartyKeys[delegateId][0] } }\n }\n return mapOfAesExchangeKeys\n }\n\n 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 modifiedOwner: Patient | Device | HealthcareParty\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 modifiedOwner,\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<T extends EncryptedEntity>(\n //TODO: suggested name: getExtendedEKwithDelegationFromDelegatorToDelegate\n modifiedObject: T,\n ownerId: string,\n delegateId: string,\n secretEncryptionKeyOfObject: string\n ): Promise<{\n modifiedObject: T\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 const owner = (await this.getDataOwner(ownerId)).dataOwner\n const publicKeys = await this.getPublicKeys()\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, delegateId)\n modifiedObject = modifiedObject?.id === owner.id ? (modifiedOwner as T) : modifiedObject\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, ownerId, delegateId, publicKeys)\n const 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 const encryptedEncryptionKey = await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(modifiedObject.id + ':' + secretEncryptionKeyOfObject)\n )\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 = (\n _.merge(\n ((modifiedObject.encryptionKeys || {})[delegateId] || []).map((d: Delegation) => ({\n d,\n })),\n (previousDecryptedEncryptionKeys || []).map((dd) => (dd ? ua2string(dd) : null)).map((k) => ({ k }))\n ) as { d: Delegation; k: string }[]\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 modifiedObject: modifiedObject,\n encryptionKeys: allEncryptionKeys,\n secretId: secretEncryptionKeyOfObject,\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 async 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\n const extendedChildObjectSPKsAndCFKs = secretDelegationKey\n ? await this.extendedDelegationsAndCryptedForeignKeys(child, parent, ownerId, delegateId, secretDelegationKey)\n : { modifiedObject: child, delegations: {}, cryptedForeignKeys: {}, secretId: null }\n\n const extendedChildObjectEKs = secretEncryptionKey\n ? await this.appendEncryptionKeys(extendedChildObjectSPKsAndCFKs.modifiedObject, ownerId, delegateId, secretEncryptionKey)\n : { encryptionKeys: {}, modifiedObject: extendedChildObjectSPKsAndCFKs.modifiedObject }\n\n const latestObject = extendedChildObjectEKs.modifiedObject\n\n return _.assign(latestObject, {\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(_.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo)))\n ),\n cryptedForeignKeys: _.assignWith(child.cryptedForeignKeys, extendedChildObjectSPKsAndCFKs.cryptedForeignKeys, (dest, src) =>\n (src || []).concat(_.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo)))\n ),\n encryptionKeys: _.assignWith(child.encryptionKeys, extendedChildObjectEKs.encryptionKeys, (dest, src) =>\n (src || []).concat(_.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo)))\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 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(\n (map, k) => ({ ...map, [k.delegatorId]: (map[k.delegatorId] ?? []).concat([k]) }),\n {} as { [key: string]: { key: CryptoKey; rawKey: string }[] }\n )\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)\n .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 )\n .then(async (extractedKeys) => {\n if (extractedKeys.length == 0) {\n return await this._extractDelegationsKeysUsingDataOwnerDelegateAesExchangeKeys(hcp, delegations, objectId)\n }\n return extractedKeys\n })\n .then(async (extractedKeys) => {\n const parentExtractedKeys = (hcp as HealthcareParty).parentId\n ? await this.extractKeysFromDelegationsForHcpHierarchy((hcp as HealthcareParty).parentId!, objectId, delegations)\n : { extractedKeys: [], hcpartyId: undefined }\n return { extractedKeys: extractedKeys.concat(parentExtractedKeys.extractedKeys), hcpartyId: parentExtractedKeys.hcpartyId ?? dataOwnerId }\n })\n )\n .catch((e) => {\n console.error(`DataOwner with id ${dataOwnerId} cannot be resolved`)\n throw e\n })\n }\n\n /**\n * This method covers the use case when a DataOwner found back access to its data, and needs to use the delegations of its delegates instead\n * of its own ones\n *\n * @param dataOwner The current data owner from whom we want to decrypt the aesExchangeKeys\n * @param delegations The object delegations to decrypt\n * @param objectId The object to decrypt id\n * @private\n */\n private async _extractDelegationsKeysUsingDataOwnerDelegateAesExchangeKeys(\n dataOwner: Patient | Device | HealthcareParty,\n delegations: { [p: string]: Array<Delegation> },\n objectId: string\n ) {\n // Find other keys through aesExchangeKeys\n const dataOwnerPubKeys = await this.getPublicKeys()\n const keysToDecrypt = fold(\n Object.entries(dataOwner.aesExchangeKeys!),\n {} as { [delegateId: string]: { [pubKey: string]: { [pubKeyFingerprint: string]: string } } },\n (acc, [pub, aesForPub]) => {\n if (dataOwnerPubKeys.find((pubKey) => pubKey.slice(-32) == pub.slice(-32)) == undefined) {\n // We get AES Keys only from delegates of keys we don't currently have\n // Otherwise, decrypted AES Keys would have previously worked\n Object.entries(aesForPub).forEach(([delegateId, aesKeys]) => {\n if (delegateId != dataOwner.id) {\n const aesAcc = {} as { [pubKeyFingerprint: string]: string }\n Object.entries(aesKeys)\n .filter(([encrPubKey]) => dataOwnerPubKeys.some((pubKey) => pubKey.slice(-32) == encrPubKey))\n .forEach(([pubKeyFingerprint, aesEncr]) => {\n aesAcc[pubKeyFingerprint] = aesEncr\n })\n\n if (acc[delegateId] == undefined) {\n acc[delegateId] = {}\n }\n acc[delegateId][pub] = aesAcc\n }\n })\n }\n return acc\n }\n )\n\n const decryptedAndImportedAesHcPartyKeys = await foldAsync(\n Object.entries(keysToDecrypt),\n [] as DelegatorAndKeys[],\n async (delKeysAcc, [delegateId, keysForDelegate]) => {\n try {\n delKeysAcc.push(await this.decryptAnyAesExchangeKeyForOwner(keysForDelegate, dataOwner.id!, dataOwner.id!, delegateId, dataOwnerPubKeys))\n } catch (e) {\n console.log(`Could not decrypt aesExchangeKeys for delegate ${delegateId}`)\n }\n return delKeysAcc\n }\n )\n\n const collatedAesKeysFromDelegatorToHcpartyId = decryptedAndImportedAesHcPartyKeys.reduce(\n (map, k) => ({ ...map, [k.delegatorId]: (map[k.delegatorId] ?? []).concat([k]) }),\n {} as { [key: string]: { key: CryptoKey; rawKey: string }[] }\n )\n\n const delegateIdsWithNewExtractedAesKeys = Object.keys(keysToDecrypt)\n const delegationsToDecrypt = fold(Object.entries(delegations), [] as Delegation[], (acc, [delegateId, del]) => {\n if (delegateIdsWithNewExtractedAesKeys.find((id) => id == delegateId) != undefined) {\n acc.push(...delegations[delegateId])\n }\n return acc\n })\n\n return this.decryptKeyInDelegationLikes(delegationsToDecrypt, collatedAesKeysFromDelegatorToHcpartyId, objectId!)\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\n return undefined\n }\n }, Promise.resolve(undefined as 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 await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${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[publicKey.slice(-32)] = keyPair\n const exportedKeyPair = await this._RSA.exportKeys(keyPair, 'jwk', 'jwk')\n\n return await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${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 this._storage.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 this._storage.setItem(this.keychainLocalStoreIdPrefix + id, keyChainB64)\n }\n\n // noinspection JSUnusedGlobalSymbols\n async saveKeychainValidityDateInBrowserLocalStorage(id: string, date: string) {\n if (!id) return\n\n if (!date) {\n await this._storage.removeItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n } else {\n await this._storage.setItem(this.keychainValidityDateLocalStoreIdPrefix + id, date)\n }\n }\n\n /**\n * Populate the HCP.options dict with an encrypted eHealth certificate and unencryped expiry date.\n * Any potentially unencrypted certificates will be pruned from the HCP.\n * @param hcpId Id of the hcp to modify\n * @returns modified HCP\n */\n async saveKeyChainInHCPFromLocalStorage(hcpId: string): Promise<HealthcareParty> {\n return await this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let aesKey: CryptoKey | null = null\n try {\n aesKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!aesKey) {\n console.error('No encryption key!')\n }\n\n const opts = hcp.options || {}\n\n const crt = await this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!!)\n if (!!aesKey && !!crt) {\n let crtEncrypted: ArrayBuffer | null = null\n try {\n crtEncrypted = await this.AES.encrypt(aesKey, new Uint8Array(string2ua(atob(crt))))\n } catch (e) {\n console.error('Error while encrypting the certificate', e)\n }\n\n // add the encrypted certificate to the options\n _.set(opts, this.hcpPreferenceKeyEhealthCert, ua2string(new Uint8Array(crtEncrypted!)))\n }\n\n const crtValidityDate = this.getKeychainValidityDateInBrowserLocalStorage(hcp.id!!)\n if (!!crtValidityDate) {\n _.set(opts, this.hcpPreferenceKeyEhealthCertDate, crtValidityDate)\n }\n\n hcp.options = opts\n return hcp\n })\n }\n\n 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 this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n }\n\n getKeychainValidityDateInBrowserLocalStorage(id: string) {\n return this._storage.getItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n }\n\n // noinspection JSUnusedGlobalSymbols\n async loadKeychainFromBrowserLocalStorage(id: string) {\n const lsItem = await this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n return lsItem !== undefined ? b64_2uas(lsItem) : null\n }\n\n /**\n * 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 async loadKeyPairNotImported(id: string, publicKeyFingerPrint?: string): Promise<{ publicKey: JsonWebKey; privateKey: JsonWebKey }> {\n //TODO decryption\n const item = publicKeyFingerPrint\n ? (await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id + '.' + publicKeyFingerPrint.slice(-32))) ??\n (await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id))\n : await this._keyStorage.getKeypair(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 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(async (resolve: (value: { publicKey: CryptoKey; privateKey: CryptoKey }) => any, reject) => {\n try {\n const jwkKeyPair = await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id)\n if (jwkKeyPair !== undefined) {\n if (jwkKeyPair.publicKey && jwkKeyPair.privateKey) {\n this._RSA.importKeyPair('jwk', jwkKeyPair.privateKey, 'jwk', jwkKeyPair.publicKey).then(resolve, (err) => {\n console.error('Error in RSA.importKeyPair: ' + err)\n reject(err)\n })\n } else {\n const message = 'Error in RSA.importKeyPair: Invalid key'\n console.error(message)\n reject(Error(message))\n }\n } else {\n const message = 'Error in RSA.importKeyPair: Missing key'\n console.error(message)\n reject(Error(message))\n }\n } catch (err) {\n reject(err)\n }\n })\n }\n\n /**\n * When a user lost his keys, people to whom he shared information may call this method to give access back to him, re-encrypting their common\n * AES key using the new user public key.\n *\n * @param delegateUser Delegate Data Owner User, in charge of giving access back to the person who previously gave him some access\n * @param ownerId Id of the data owner to which we would like to give access back\n * @param ownerNewPublicKey New Data Owner Public Key we want to use to re-encrypt previously created AES key\n *\n * @return The DataOwner, updated by the delegateUser to add the new encrypted AES Key using the new provided public key\n */\n async giveAccessBackTo(delegateUser: User, ownerId: string, ownerNewPublicKey: string): Promise<CachedDataOwner> {\n const delegateId = delegateUser.healthcarePartyId ?? delegateUser.patientId ?? delegateUser.deviceId\n if (!delegateId) {\n throw new Error(`DelegateUser ${delegateUser.id} must be a data Owner`)\n }\n\n const delegatePublicKeys = await this.getPublicKeys()\n const newPubKeyCryptoKey = await this._RSA.importKey('jwk', spkiToJwk(hex2ua(ownerNewPublicKey)), ['encrypt'])\n const dataOwnerToUpdate = await this.getDataOwner(ownerId)\n\n const newAesExchangeKeys = await foldAsync(\n Object.entries(dataOwnerToUpdate.dataOwner.aesExchangeKeys ?? {}),\n dataOwnerToUpdate.dataOwner.aesExchangeKeys ?? {},\n async (pubAcc, [pubKey, newAesExcKeys]) => {\n const existingKeys = pubAcc[pubKey] ?? {}\n\n pubAcc[pubKey] = await foldAsync(Object.entries(newAesExcKeys), existingKeys, async (delAcc, [delId, delKeys]) => {\n if (delId == delegateId && pubKey != ownerNewPublicKey) {\n // Add the AES Key encrypted with the new public key in the aesExchangeKeys\n try {\n // First, we decrypt it using the delegate RSA Public Key\n const encrAesKeyInfo = await this.decryptHcPartyKey(\n delegateId,\n dataOwnerToUpdate.dataOwner.id!,\n delegateId,\n pubKey,\n delKeys,\n delegatePublicKeys\n ).then(async (delegatorAndKeys) => {\n // Then, we encrypt it using the owner new RSA Public Key (provided in argument)\n return await this.encryptAesKeyOnlyForProvidedKeys(delegatorAndKeys?.rawKey, dataOwnerToUpdate, [newPubKeyCryptoKey])\n .then((encrAes) => Object.values(encrAes)[0])\n .then((encrAesInfo) => {\n return { pubKeyUsedToEncryptAes: Object.keys(encrAesInfo)[0], encryptedAes: Object.values(encrAesInfo)[0] }\n })\n })\n\n delKeys[encrAesKeyInfo.pubKeyUsedToEncryptAes] = encrAesKeyInfo.encryptedAes\n } catch (e) {\n console.log(`${delegateId} could not re-encrypt AES Key of ${dataOwnerToUpdate.dataOwner.id}`)\n } finally {\n delAcc[delId] = delKeys\n }\n } else {\n // Otherwise, we don't transform the aesExchangeKeys for this delegate\n delAcc[delId] = delKeys\n }\n return delAcc\n })\n return pubAcc\n }\n )\n\n // After adding the potential new aesExchangeKeys, we save the updated data owner\n return this._saveDataOwner({\n type: dataOwnerToUpdate.type,\n dataOwner: { ...dataOwnerToUpdate.dataOwner, aesExchangeKeys: newAesExchangeKeys },\n } as CachedDataOwner)\n }\n\n async addNewKeyPairForOwnerId(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n ownerId: string,\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n return this.addNewKeyPairForOwner(maintenanceTasksApi, user, await this.getDataOwner(ownerId), generateTransferKey, sendMaintenanceTasks)\n }\n\n async addNewKeyPairForOwner(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n cdo: CachedDataOwner,\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n const generatedKeypair = await this.RSA.generateKeyPair()\n return this.addKeyPairForOwner(maintenanceTasksApi, user, cdo, generatedKeypair, generateTransferKey, sendMaintenanceTasks)\n }\n\n async addRawKeyPairForOwnerId(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n ownerId: string,\n keypair: { publicKey: string; privateKey: string },\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n return this.addRawKeyPairForOwner(maintenanceTasksApi, user, await this.getDataOwner(ownerId), keypair, generateTransferKey, sendMaintenanceTasks)\n }\n\n async addRawKeyPairForOwner(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n cdo: CachedDataOwner,\n keypair: { publicKey: string; privateKey: string },\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n const importedPrivateKey = await this._RSA.importKey('pkcs8', hex2ua(keypair.privateKey), ['decrypt'])\n const importedPublicKey = await this._RSA.importKey('spki', hex2ua(keypair.publicKey), ['encrypt'])\n\n return this.addKeyPairForOwner(\n maintenanceTasksApi,\n user,\n cdo,\n { publicKey: importedPublicKey, privateKey: importedPrivateKey },\n generateTransferKey,\n sendMaintenanceTasks\n )\n }\n\n async addKeyPairForOwner(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n cdo: CachedDataOwner,\n keypair: { publicKey: CryptoKey; privateKey: CryptoKey },\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n const publicKeyHex = ua2hex(await this.RSA.exportKey(keypair.publicKey!, 'spki'))\n\n const gen = (await this._AES.generateCryptoKey(true)) as string\n\n await this.cacheKeyPair({\n publicKey: await this.RSA.exportKey(keypair.publicKey!, 'jwk'),\n privateKey: await this.RSA.exportKey(keypair.privateKey!, 'jwk'),\n })\n\n const { type: ownerType, dataOwner: ownerToUpdate } = await this.createOrUpdateAesExchangeKeysFor(cdo, gen, {\n pubKey: keypair.publicKey,\n privKey: keypair.privateKey,\n }).then(async (dataOwnerWithUpdatedAesKeys) =>\n generateTransferKey\n ? await this.createOrUpdateTransferKeysFor(dataOwnerWithUpdatedAesKeys, gen, { pubKey: keypair.publicKey, privKey: keypair.privateKey })\n : dataOwnerWithUpdatedAesKeys\n )\n\n const modifiedDataOwnerAndType = await this._saveDataOwner({ type: ownerType, dataOwner: ownerToUpdate })\n const sentMaintenanceTasks = sendMaintenanceTasks\n ? await this.sendMaintenanceTasks(maintenanceTasksApi, user, modifiedDataOwnerAndType.dataOwner, keypair.publicKey)\n : []\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(keypair.privateKey!, 'pkcs8')) as ArrayBuffer),\n }\n }\n\n private async _saveDataOwner(dataOwner: CachedDataOwner): Promise<CachedDataOwner> {\n const ownerType = dataOwner.type\n const ownerToUpdate = dataOwner.dataOwner\n\n return 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\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 return this.encryptAesKeyOnlyForProvidedKeys(aesKey, dataOwner, dataOwnerAllPubKeys)\n }\n\n private async encryptAesKeyOnlyForProvidedKeys(\n aesKey: string,\n dataOwner: HealthcareParty | Patient | Device,\n dataOwnerPubKeys: CryptoKey[]\n ): Promise<{ [delId: string]: { [pk: string]: string } }> {\n const encryptedAesForDataOwner = await foldAsync(dataOwnerPubKeys, {} as { [pubKeyFingerprint: string]: string }, async (encrAes, pubKey) => {\n encrAes[ua2hex(await this.RSA.exportKey(pubKey, 'spki')).slice(-32)] = ua2hex(await this._RSA.encrypt(pubKey, hex2ua(aesKey)))\n return encrAes\n })\n\n return { [dataOwner.id!]: encryptedAesForDataOwner }\n }\n\n private retrieveDataOwnerInfoAfterPotentialUpdate(dataOwnerToUpdate: HealthcareParty | Patient | Device): Promise<CachedDataOwner> {\n this.emptyHcpCache(dataOwnerToUpdate.id!)\n\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(async (existingPubKey) => (await this.getPublicKeysAsSpki()).find((pubKey) => pubKey == existingPubKey) == undefined)\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 = (await this._getDelegateIdsOf(dataOwner))\n .filter((delegateId) => delegateId != dataOwner.id)\n .map((delegateId) => {\n return { delegateId: delegateId, maintenanceTask: this.createMaintenanceTask(dataOwner, hexNewPubKey) }\n })\n\n return await tasksForDelegates.concat(tasksForDelegator).reduce(async (existingTasks, task) => {\n const taskToCreate = await maintenanceTaskApi?.newInstance(user, task.maintenanceTask, [task.delegateId])\n const createdTask: MaintenanceTask = taskToCreate ? await maintenanceTaskApi?.createMaintenanceTaskWithUser(user, taskToCreate) : undefined\n return createdTask ? (await existingTasks).concat(createdTask) : await existingTasks\n }, Promise.resolve([] as MaintenanceTask[]))\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: 'KEY_PAIR_UPDATE',\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 availablePublicKeysFingerprints = Object.keys(this.rsaKeyPairs)\n const ownerLegacyPublicKey = owner.publicKey\n const isOwnerLegacyPublicKeyAvailable = ownerLegacyPublicKey\n ? availablePublicKeysFingerprints.some((fp) => ownerLegacyPublicKey.endsWith(fp))\n : false\n\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.slice(-32)]: 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 && isOwnerLegacyPublicKeyAvailable) {\n owner.hcPartyKeys![delegateId] = [encryptedAesKeys[ownerLegacyPublicKey.slice(-32)], encryptedAesKeys[delegate.publicKey.slice(-32)]]\n }\n owner.aesExchangeKeys = this.fixAesExchangeKeyEntriesToFingerprints({\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, loadIfMissingFromCache: boolean = true) {\n return (\n this.dataOwnerCache[ownerId] ??\n (loadIfMissingFromCache\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 : undefined)\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 = await 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 dataOwnerCanDecryptPatient(dataOwnerId: string, p: Patient): Promise<boolean> {\n if (p.encryptionKeys && p.encryptionKeys[dataOwnerId]?.length) return true\n\n const dataOwner = await this.getDataOwner(dataOwnerId)\n if (dataOwner.type === 'hcp' && p.encryptionKeys && p.encryptionKeys[dataOwner.dataOwner.parentId!]?.length) return true\n\n return false\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 /**\n * Store keypair in storage\n *\n * @param id\n * @param keyPair should be JWK\n *\n * @deprecated use storage.setItem instead\n */\n storeKeyPair(id: string, keyPair: { publicKey: any; privateKey: any }) {\n this._storage.setItem(this.rsaLocalStoreIdPrefix + id, JSON.stringify(keyPair))\n }\n\n fixAesExchangeKeyEntriesToFingerprints(aesExchangeKeys: { [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } } }): {\n [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } }\n } {\n return Object.fromEntries(\n Object.entries(aesExchangeKeys).map(([delegatorPubKey, allDelegates]) => [\n delegatorPubKey,\n Object.fromEntries(\n Object.entries(allDelegates).map(([delegateId, keyEntries]) => [\n delegateId,\n Object.fromEntries(Object.entries(keyEntries).map(([publicKey, encryptedValue]) => [publicKey.slice(-32), encryptedValue])),\n ])\n ),\n ])\n )\n }\n\n /**\n * @internal\n * Keep only strings which match the format of a valid entity encryption key: hex string potentially with dashes.\n * Additionally, this method automatically removes the dashes from the key (from uuid-formatted to standard).\n */\n filterAndFixValidEntityEncryptionKeyStrings(aesKeys: string[]): string[] {\n return aesKeys.flatMap((x) => {\n const undashed = x.length === 36 ? x.replace(/-/g, '') : x\n if ((undashed.length === 32 || undashed.length === 64) && undashed.match(/^[0-9a-fA-F]+$/)) {\n return [undashed]\n } else {\n return []\n }\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":";;;;;;;;;;;;AAEA,sCAAuC;AACvC,sCAAuC;AACvC,4CAA6C;AAE7C,4BAA2B;AAC3B,oDAagC;AAChC,uDAA6G;AAC7G,mCAAyF;AAyBzF,MAAa,aAAa;IA0FxB,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,EAC3H,OAA8B,EAC9B,UAA4B;QAzE9B,qBAAgB,GAEZ,EAAE,CAAA;QAEN,yDAAyD;QACzD,mMAAmM;QACnM,6BAAwB,GAEpB,EAAE,CAAA;QAEN,+BAA0B,GAAuB,SAAS,CAAA;QAE1D,mBAAc,GAAgD,EAAE,CAAA;QAiChE,+BAA0B,GAAG,oCAAoC,CAAA;QACjE,2CAAsC,GAAG,yCAAyC,CAAA;QAClF,gCAA2B,GAAG,iBAAiB,CAAA;QAC/C,oCAA+B,GAAG,gBAAgB,CAAA;QAClD,0BAAqB,GAAG,uBA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AC,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YAC1D,IAAI,CAAC,QAAQ,CAAC,MAAM,KAAK,EAAE,IAAI,QAAQ,CAAC,MAAM,KAAK,EAAE,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,gBAAgB,CAAC,EAAE;gBAC1F,OAAO,CAAC,QAAQ,CAAC,CAAA;aAClB;iBAAM;gBACL,OAAO,EAAE,CAAA;aACV;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AA/sED,sCA+sEC","sourcesContent":["/* eslint-disable */\nimport { 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, foldAsync, jwk2spki, notConcurrent, pkcs8ToJwk, spkiToJwk } from './utils'\nimport { IccMaintenanceTaskXApi } from './icc-maintenance-task-x-api'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\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 get keyStorage(): KeyStorageFacade {\n return this._keyStorage\n }\n\n get storage(): StorageFacade<string> {\n return this._storage\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 private readonly _storage: StorageFacade<string>\n private readonly _keyStorage: KeyStorageFacade\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 storage: StorageFacade<string>,\n keyStorage: KeyStorageFacade\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 this._storage = storage\n this._keyStorage = keyStorage\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(await this.loadKeyPairNotImported(dataOwnerId, fingerprint))\n }\n }\n }\n\n async getCachedRsaKeyPairForFingerprint(\n dataOwnerId: string,\n pubKeyOrFingerprint: string\n ): Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }> {\n const fingerprint = pubKeyOrFingerprint.slice(-32)\n return this.rsaKeyPairs[fingerprint] ?? (await this.cacheKeyPair(await 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 async getPublicKeysAsSpki(): Promise<string[]> {\n return await Object.values(this.rsaKeyPairs).reduce(async (p, rsa) => {\n return (await p).concat([ua2hex(await this.RSA.exportKey(rsa.publicKey, 'spki'))])\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 await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${hcp.id!}`, exportedKeyPair)\n } catch (e) {\n console.log('Cannot decrypt shamir RSA key')\n }\n }\n\n /**\n * 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(await this.loadKeyPairNotImported(loggedHcPartyId, fingerprint)))\n if (!keyPair) {\n return\n }\n\n // Due to past bugs the encryptedHcPartyKeys may contain the full key instead of just the fingerprint.\n let encryptedHcPartyKey = encryptedHcPartyKeys[fingerprint] ?? encryptedHcPartyKeys[pk]\n if (!encryptedHcPartyKey) {\n const delegate = await this.getDataOwner(delegateHcPartyId, false) //it is faster to just try to decrypt if not in cache\n if (!delegate?.dataOwner || delegate.dataOwner.publicKey?.endsWith(fingerprint)) {\n encryptedHcPartyKey = encryptedHcPartyKeys['']\n } else {\n return\n }\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\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(undefined as 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 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 }): Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }> {\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 this.getEncryptedAesExchangeKeysForDelegate(delegateHcPartyId).then(\n 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\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 = parentObject\n ? await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(createdObject.id + ':' + parentObject.id).buffer as ArrayBuffer,\n importedAESHcPartyKey.rawKey\n )\n : undefined\n\n return {\n owner: modifiedOwner,\n delegations: {\n ...(createdObject.delegations ?? {}),\n [ownerId]: [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedDelegation!),\n },\n ],\n },\n cryptedForeignKeys:\n (encryptedSecretForeignKey\n ? {\n ...(createdObject.cryptedForeignKeys ?? {}),\n [ownerId]: [\n {\n owner: ownerId,\n delegatedTo: ownerId,\n key: ua2hex(encryptedSecretForeignKey!),\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(undefined as 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 // What we need is to find aes exchange keys on the owner ! Even just with whom he shared information, we don't care about aes exchange keys\n private async _getDelegateIdsOf(owner: HealthcareParty | Patient | Device): Promise<string[]> {\n const mapOfAesExchKeysDelegates = Object.entries(owner.aesExchangeKeys ?? {}).reduce(\n (map, [, aesExchKeys]) => map.concat(Object.keys(aesExchKeys).filter((delegateId) => !map.includes(delegateId))),\n [] as string[]\n )\n\n return owner.hcPartyKeys\n ? mapOfAesExchKeysDelegates.concat(Object.keys(owner.hcPartyKeys).filter((delegateId) => !mapOfAesExchKeysDelegates.includes(delegateId)))\n : mapOfAesExchKeysDelegates\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]) //[fingerprint of delegate pub key, key], [fingerprint of owner pub key, key]\n const [publicKeyFingerprint, encryptedAesExchangeKey] = candidates[candidates.findIndex(([k, v]) => publicKeys.some((pk) => pk.endsWith(k)))]\n return { ...map, [e[0]]: { [publicKeyFingerprint]: encryptedAesExchangeKey } }\n }, {} as { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } })\n\n if (!owner.publicKey || mapOfAesExchangeKeys[owner.publicKey] || !owner.hcPartyKeys?.[delegateId]) {\n return mapOfAesExchangeKeys\n }\n const delegate = (await this.getDataOwner(delegateId)).dataOwner\n if (delegate.publicKey && publicKeys.includes(delegate.publicKey)) {\n return {\n ...mapOfAesExchangeKeys,\n [owner.publicKey]: { [(await this.getDataOwner(delegateId)).dataOwner.publicKey?.slice(-32)!]: owner.hcPartyKeys[delegateId][1] },\n }\n } else if (publicKeys.includes(owner.publicKey)) {\n return { ...mapOfAesExchangeKeys, [owner.publicKey]: { [owner.publicKey.slice(-32)]: owner.hcPartyKeys[delegateId][0] } }\n }\n return mapOfAesExchangeKeys\n }\n\n 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 modifiedOwner: Patient | Device | HealthcareParty\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 modifiedOwner,\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<T extends EncryptedEntity>(\n //TODO: suggested name: getExtendedEKwithDelegationFromDelegatorToDelegate\n modifiedObject: T,\n ownerId: string,\n delegateId: string,\n secretEncryptionKeyOfObject: string\n ): Promise<{\n modifiedObject: T\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 const owner = (await this.getDataOwner(ownerId)).dataOwner\n const publicKeys = await this.getPublicKeys()\n const { owner: modifiedOwner, aesExchangeKeys } = await this.getOrCreateHcPartyKeys(owner, delegateId)\n modifiedObject = modifiedObject?.id === owner.id ? (modifiedOwner as T) : modifiedObject\n const importedAESHcPartyKey = await this.decryptAnyAesExchangeKeyForOwner(aesExchangeKeys, ownerId, ownerId, delegateId, publicKeys)\n const 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 const encryptedEncryptionKey = await this._AES.encrypt(\n importedAESHcPartyKey.key,\n string2ua(modifiedObject.id + ':' + secretEncryptionKeyOfObject)\n )\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 = (\n _.merge(\n ((modifiedObject.encryptionKeys || {})[delegateId] || []).map((d: Delegation) => ({\n d,\n })),\n (previousDecryptedEncryptionKeys || []).map((dd) => (dd ? ua2string(dd) : null)).map((k) => ({ k }))\n ) as { d: Delegation; k: string }[]\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 modifiedObject: modifiedObject,\n encryptionKeys: allEncryptionKeys,\n secretId: secretEncryptionKeyOfObject,\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 async 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\n const extendedChildObjectSPKsAndCFKs = secretDelegationKey\n ? await this.extendedDelegationsAndCryptedForeignKeys(child, parent, ownerId, delegateId, secretDelegationKey)\n : { modifiedObject: child, delegations: {}, cryptedForeignKeys: {}, secretId: null }\n\n const extendedChildObjectEKs = secretEncryptionKey\n ? await this.appendEncryptionKeys(extendedChildObjectSPKsAndCFKs.modifiedObject, ownerId, delegateId, secretEncryptionKey)\n : { encryptionKeys: {}, modifiedObject: extendedChildObjectSPKsAndCFKs.modifiedObject }\n\n const latestObject = extendedChildObjectEKs.modifiedObject\n\n return _.assign(latestObject, {\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(_.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo)))\n ),\n cryptedForeignKeys: _.assignWith(child.cryptedForeignKeys, extendedChildObjectSPKsAndCFKs.cryptedForeignKeys, (dest, src) =>\n (src || []).concat(_.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo)))\n ),\n encryptionKeys: _.assignWith(child.encryptionKeys, extendedChildObjectEKs.encryptionKeys, (dest, src) =>\n (src || []).concat(_.filter(dest, (d: Delegation) => !src.some((s: Delegation) => s.owner === d.owner && s.delegatedTo === d.delegatedTo)))\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 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(\n (map, k) => ({ ...map, [k.delegatorId]: (map[k.delegatorId] ?? []).concat([k]) }),\n {} as { [key: string]: { key: CryptoKey; rawKey: string }[] }\n )\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)\n .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 )\n .then(async (extractedKeys) => {\n if (extractedKeys.length == 0) {\n return await this._extractDelegationsKeysUsingDataOwnerDelegateAesExchangeKeys(hcp, delegations, objectId)\n }\n return extractedKeys\n })\n .then(async (extractedKeys) => {\n const parentExtractedKeys = (hcp as HealthcareParty).parentId\n ? await this.extractKeysFromDelegationsForHcpHierarchy((hcp as HealthcareParty).parentId!, objectId, delegations)\n : { extractedKeys: [], hcpartyId: undefined }\n return { extractedKeys: extractedKeys.concat(parentExtractedKeys.extractedKeys), hcpartyId: parentExtractedKeys.hcpartyId ?? dataOwnerId }\n })\n )\n .catch((e) => {\n console.error(`DataOwner with id ${dataOwnerId} cannot be resolved`)\n throw e\n })\n }\n\n /**\n * This method covers the use case when a DataOwner found back access to its data, and needs to use the delegations of its delegates instead\n * of its own ones\n *\n * @param dataOwner The current data owner from whom we want to decrypt the aesExchangeKeys\n * @param delegations The object delegations to decrypt\n * @param objectId The object to decrypt id\n * @private\n */\n private async _extractDelegationsKeysUsingDataOwnerDelegateAesExchangeKeys(\n dataOwner: Patient | Device | HealthcareParty,\n delegations: { [p: string]: Array<Delegation> },\n objectId: string\n ) {\n // Find other keys through aesExchangeKeys\n const dataOwnerPubKeys = await this.getPublicKeys()\n const keysToDecrypt = fold(\n Object.entries(dataOwner.aesExchangeKeys!),\n {} as { [delegateId: string]: { [pubKey: string]: { [pubKeyFingerprint: string]: string } } },\n (acc, [pub, aesForPub]) => {\n if (dataOwnerPubKeys.find((pubKey) => pubKey.slice(-32) == pub.slice(-32)) == undefined) {\n // We get AES Keys only from delegates of keys we don't currently have\n // Otherwise, decrypted AES Keys would have previously worked\n Object.entries(aesForPub).forEach(([delegateId, aesKeys]) => {\n if (delegateId != dataOwner.id) {\n const aesAcc = {} as { [pubKeyFingerprint: string]: string }\n Object.entries(aesKeys)\n .filter(([encrPubKey]) => dataOwnerPubKeys.some((pubKey) => pubKey.slice(-32) == encrPubKey))\n .forEach(([pubKeyFingerprint, aesEncr]) => {\n aesAcc[pubKeyFingerprint] = aesEncr\n })\n\n if (acc[delegateId] == undefined) {\n acc[delegateId] = {}\n }\n acc[delegateId][pub] = aesAcc\n }\n })\n }\n return acc\n }\n )\n\n const decryptedAndImportedAesHcPartyKeys = await foldAsync(\n Object.entries(keysToDecrypt),\n [] as DelegatorAndKeys[],\n async (delKeysAcc, [delegateId, keysForDelegate]) => {\n try {\n delKeysAcc.push(await this.decryptAnyAesExchangeKeyForOwner(keysForDelegate, dataOwner.id!, dataOwner.id!, delegateId, dataOwnerPubKeys))\n } catch (e) {\n console.log(`Could not decrypt aesExchangeKeys for delegate ${delegateId}`)\n }\n return delKeysAcc\n }\n )\n\n const collatedAesKeysFromDelegatorToHcpartyId = decryptedAndImportedAesHcPartyKeys.reduce(\n (map, k) => ({ ...map, [k.delegatorId]: (map[k.delegatorId] ?? []).concat([k]) }),\n {} as { [key: string]: { key: CryptoKey; rawKey: string }[] }\n )\n\n const delegateIdsWithNewExtractedAesKeys = Object.keys(keysToDecrypt)\n const delegationsToDecrypt = fold(Object.entries(delegations), [] as Delegation[], (acc, [delegateId, del]) => {\n if (delegateIdsWithNewExtractedAesKeys.find((id) => id == delegateId) != undefined) {\n acc.push(...delegations[delegateId])\n }\n return acc\n })\n\n return this.decryptKeyInDelegationLikes(delegationsToDecrypt, collatedAesKeysFromDelegatorToHcpartyId, objectId!)\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\n return undefined\n }\n }, Promise.resolve(undefined as 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 await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${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[publicKey.slice(-32)] = keyPair\n const exportedKeyPair = await this._RSA.exportKeys(keyPair, 'jwk', 'jwk')\n\n return await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${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 this._storage.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 this._storage.setItem(this.keychainLocalStoreIdPrefix + id, keyChainB64)\n }\n\n // noinspection JSUnusedGlobalSymbols\n async saveKeychainValidityDateInBrowserLocalStorage(id: string, date: string) {\n if (!id) return\n\n if (!date) {\n await this._storage.removeItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n } else {\n await this._storage.setItem(this.keychainValidityDateLocalStoreIdPrefix + id, date)\n }\n }\n\n /**\n * Populate the HCP.options dict with an encrypted eHealth certificate and unencryped expiry date.\n * Any potentially unencrypted certificates will be pruned from the HCP.\n * @param hcpId Id of the hcp to modify\n * @returns modified HCP\n */\n async saveKeyChainInHCPFromLocalStorage(hcpId: string): Promise<HealthcareParty> {\n return await this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let aesKey: CryptoKey | null = null\n try {\n aesKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!aesKey) {\n console.error('No encryption key!')\n }\n\n const opts = hcp.options || {}\n\n const crt = await this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!!)\n if (!!aesKey && !!crt) {\n let crtEncrypted: ArrayBuffer | null = null\n try {\n crtEncrypted = await this.AES.encrypt(aesKey, new Uint8Array(string2ua(atob(crt))))\n } catch (e) {\n console.error('Error while encrypting the certificate', e)\n }\n\n // add the encrypted certificate to the options\n _.set(opts, this.hcpPreferenceKeyEhealthCert, ua2string(new Uint8Array(crtEncrypted!)))\n }\n\n const crtValidityDate = this.getKeychainValidityDateInBrowserLocalStorage(hcp.id!!)\n if (!!crtValidityDate) {\n _.set(opts, this.hcpPreferenceKeyEhealthCertDate, crtValidityDate)\n }\n\n hcp.options = opts\n return hcp\n })\n }\n\n 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 this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n }\n\n getKeychainValidityDateInBrowserLocalStorage(id: string) {\n return this._storage.getItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n }\n\n // noinspection JSUnusedGlobalSymbols\n async loadKeychainFromBrowserLocalStorage(id: string) {\n const lsItem = await this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n return lsItem !== undefined ? b64_2uas(lsItem) : null\n }\n\n /**\n * 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 async loadKeyPairNotImported(id: string, publicKeyFingerPrint?: string): Promise<{ publicKey: JsonWebKey; privateKey: JsonWebKey }> {\n //TODO decryption\n const item = publicKeyFingerPrint\n ? (await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id + '.' + publicKeyFingerPrint.slice(-32))) ??\n (await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id))\n : await this._keyStorage.getKeypair(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 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 async loadKeyPairImported(id: string) {\n let jwkKeyPair = await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id)\n if (!jwkKeyPair) {\n const { dataOwner } = await this.getDataOwner(id)\n if (dataOwner.publicKey) {\n jwkKeyPair = await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id + '.' + dataOwner.publicKey.slice(-32))\n } else {\n console.warn('Attempting to load default public key for data owner without default public key')\n }\n }\n if (jwkKeyPair !== undefined) {\n if (jwkKeyPair.publicKey && jwkKeyPair.privateKey) {\n return await this._RSA.importKeyPair('jwk', jwkKeyPair.privateKey, 'jwk', jwkKeyPair.publicKey).catch((err) => {\n console.error('Error in RSA.importKeyPair: ' + err)\n throw err\n })\n } else {\n const message = 'Error in RSA.importKeyPair: Invalid key'\n console.error(message)\n throw Error(message)\n }\n } else {\n const message = 'Error in RSA.importKeyPair: Missing key'\n console.error(message)\n throw Error(message)\n }\n }\n\n /**\n * When a user lost his keys, people to whom he shared information may call this method to give access back to him, re-encrypting their common\n * AES key using the new user public key.\n *\n * @param delegateUser Delegate Data Owner User, in charge of giving access back to the person who previously gave him some access\n * @param ownerId Id of the data owner to which we would like to give access back\n * @param ownerNewPublicKey New Data Owner Public Key we want to use to re-encrypt previously created AES key\n *\n * @return The DataOwner, updated by the delegateUser to add the new encrypted AES Key using the new provided public key\n */\n async giveAccessBackTo(delegateUser: User, ownerId: string, ownerNewPublicKey: string): Promise<CachedDataOwner> {\n const delegateId = delegateUser.healthcarePartyId ?? delegateUser.patientId ?? delegateUser.deviceId\n if (!delegateId) {\n throw new Error(`DelegateUser ${delegateUser.id} must be a data Owner`)\n }\n\n const delegatePublicKeys = await this.getPublicKeys()\n const newPubKeyCryptoKey = await this._RSA.importKey('jwk', spkiToJwk(hex2ua(ownerNewPublicKey)), ['encrypt'])\n const dataOwnerToUpdate = await this.getDataOwner(ownerId)\n\n const newAesExchangeKeys = await foldAsync(\n Object.entries(dataOwnerToUpdate.dataOwner.aesExchangeKeys ?? {}),\n dataOwnerToUpdate.dataOwner.aesExchangeKeys ?? {},\n async (pubAcc, [pubKey, newAesExcKeys]) => {\n const existingKeys = pubAcc[pubKey] ?? {}\n\n pubAcc[pubKey] = await foldAsync(Object.entries(newAesExcKeys), existingKeys, async (delAcc, [delId, delKeys]) => {\n if (delId == delegateId && pubKey != ownerNewPublicKey) {\n // Add the AES Key encrypted with the new public key in the aesExchangeKeys\n try {\n // First, we decrypt it using the delegate RSA Public Key\n const encrAesKeyInfo = await this.decryptHcPartyKey(\n delegateId,\n dataOwnerToUpdate.dataOwner.id!,\n delegateId,\n pubKey,\n delKeys,\n delegatePublicKeys\n ).then(async (delegatorAndKeys) => {\n // Then, we encrypt it using the owner new RSA Public Key (provided in argument)\n return await this.encryptAesKeyOnlyForProvidedKeys(delegatorAndKeys?.rawKey, dataOwnerToUpdate, [newPubKeyCryptoKey])\n .then((encrAes) => Object.values(encrAes)[0])\n .then((encrAesInfo) => {\n return { pubKeyUsedToEncryptAes: Object.keys(encrAesInfo)[0], encryptedAes: Object.values(encrAesInfo)[0] }\n })\n })\n\n delKeys[encrAesKeyInfo.pubKeyUsedToEncryptAes] = encrAesKeyInfo.encryptedAes\n } catch (e) {\n console.log(`${delegateId} could not re-encrypt AES Key of ${dataOwnerToUpdate.dataOwner.id}`)\n } finally {\n delAcc[delId] = delKeys\n }\n } else {\n // Otherwise, we don't transform the aesExchangeKeys for this delegate\n delAcc[delId] = delKeys\n }\n return delAcc\n })\n return pubAcc\n }\n )\n\n // After adding the potential new aesExchangeKeys, we save the updated data owner\n return this._saveDataOwner({\n type: dataOwnerToUpdate.type,\n dataOwner: { ...dataOwnerToUpdate.dataOwner, aesExchangeKeys: newAesExchangeKeys },\n } as CachedDataOwner)\n }\n\n async addNewKeyPairForOwnerId(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n ownerId: string,\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n return this.addNewKeyPairForOwner(maintenanceTasksApi, user, await this.getDataOwner(ownerId), generateTransferKey, sendMaintenanceTasks)\n }\n\n async addNewKeyPairForOwner(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n cdo: CachedDataOwner,\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n const generatedKeypair = await this.RSA.generateKeyPair()\n return this.addKeyPairForOwner(maintenanceTasksApi, user, cdo, generatedKeypair, generateTransferKey, sendMaintenanceTasks)\n }\n\n async addRawKeyPairForOwnerId(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n ownerId: string,\n keypair: { publicKey: string; privateKey: string },\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n return this.addRawKeyPairForOwner(maintenanceTasksApi, user, await this.getDataOwner(ownerId), keypair, generateTransferKey, sendMaintenanceTasks)\n }\n\n async addRawKeyPairForOwner(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n cdo: CachedDataOwner,\n keypair: { publicKey: string; privateKey: string },\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n const importedPrivateKey = await this._RSA.importKey('pkcs8', hex2ua(keypair.privateKey), ['decrypt'])\n const importedPublicKey = await this._RSA.importKey('spki', hex2ua(keypair.publicKey), ['encrypt'])\n\n return this.addKeyPairForOwner(\n maintenanceTasksApi,\n user,\n cdo,\n { publicKey: importedPublicKey, privateKey: importedPrivateKey },\n generateTransferKey,\n sendMaintenanceTasks\n )\n }\n\n async addKeyPairForOwner(\n maintenanceTasksApi: IccMaintenanceTaskXApi,\n user: User,\n cdo: CachedDataOwner,\n keypair: { publicKey: CryptoKey; privateKey: CryptoKey },\n generateTransferKey: boolean = true,\n sendMaintenanceTasks: boolean = true\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n const publicKeyHex = ua2hex(await this.RSA.exportKey(keypair.publicKey!, 'spki'))\n\n const gen = (await this._AES.generateCryptoKey(true)) as string\n\n await this.cacheKeyPair({\n publicKey: await this.RSA.exportKey(keypair.publicKey!, 'jwk'),\n privateKey: await this.RSA.exportKey(keypair.privateKey!, 'jwk'),\n })\n\n const { type: ownerType, dataOwner: ownerToUpdate } = await this.createOrUpdateAesExchangeKeysFor(cdo, gen, {\n pubKey: keypair.publicKey,\n privKey: keypair.privateKey,\n }).then(async (dataOwnerWithUpdatedAesKeys) =>\n generateTransferKey\n ? await this.createOrUpdateTransferKeysFor(dataOwnerWithUpdatedAesKeys, gen, { pubKey: keypair.publicKey, privKey: keypair.privateKey })\n : dataOwnerWithUpdatedAesKeys\n )\n\n const modifiedDataOwnerAndType = await this._saveDataOwner({ type: ownerType, dataOwner: ownerToUpdate })\n const sentMaintenanceTasks = sendMaintenanceTasks\n ? await this.sendMaintenanceTasks(maintenanceTasksApi, user, modifiedDataOwnerAndType.dataOwner, keypair.publicKey)\n : []\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(keypair.privateKey!, 'pkcs8')) as ArrayBuffer),\n }\n }\n\n private async _saveDataOwner(dataOwner: CachedDataOwner): Promise<CachedDataOwner> {\n const ownerType = dataOwner.type\n const ownerToUpdate = dataOwner.dataOwner\n\n return 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\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 return this.encryptAesKeyOnlyForProvidedKeys(aesKey, dataOwner, dataOwnerAllPubKeys)\n }\n\n private async encryptAesKeyOnlyForProvidedKeys(\n aesKey: string,\n dataOwner: HealthcareParty | Patient | Device,\n dataOwnerPubKeys: CryptoKey[]\n ): Promise<{ [delId: string]: { [pk: string]: string } }> {\n const encryptedAesForDataOwner = await foldAsync(dataOwnerPubKeys, {} as { [pubKeyFingerprint: string]: string }, async (encrAes, pubKey) => {\n encrAes[ua2hex(await this.RSA.exportKey(pubKey, 'spki')).slice(-32)] = ua2hex(await this._RSA.encrypt(pubKey, hex2ua(aesKey)))\n return encrAes\n })\n\n return { [dataOwner.id!]: encryptedAesForDataOwner }\n }\n\n private retrieveDataOwnerInfoAfterPotentialUpdate(dataOwnerToUpdate: HealthcareParty | Patient | Device): Promise<CachedDataOwner> {\n this.emptyHcpCache(dataOwnerToUpdate.id!)\n\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 availablePubKeysSet = new Set(await this.getPublicKeysAsSpki())\n const hasNonAccessiblePubKeys = Array.from(this.getDataOwnerHexPublicKeys(dataOwner).values()).some(\n (existingPubKey) => existingPubKey != hexNewPubKey && !availablePubKeysSet.has(existingPubKey)\n )\n\n if (hasNonAccessiblePubKeys) {\n const allDelegatesAndDelegator = new Set([\n ...Object.keys(await this.getEncryptedAesExchangeKeysForDelegate(dataOwner.id!)),\n ...(await this._getDelegateIdsOf(dataOwner)),\n ])\n const tasks = [...allDelegatesAndDelegator]\n .filter((delegateId) => delegateId != dataOwner.id)\n .map((delegateId) => {\n return { delegateId, maintenanceTask: this.createMaintenanceTask(dataOwner, hexNewPubKey) }\n })\n const res: MaintenanceTask[] = []\n for (const task of tasks) {\n const taskToCreate = await maintenanceTaskApi?.newInstance(user, task.maintenanceTask, [task.delegateId])\n const createdTask: MaintenanceTask = taskToCreate ? await maintenanceTaskApi?.createMaintenanceTaskWithUser(user, taskToCreate) : undefined\n if (createdTask) {\n res.push(createdTask)\n }\n }\n return res\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: 'KEY_PAIR_UPDATE',\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 availablePublicKeysFingerprints = Object.keys(this.rsaKeyPairs)\n const ownerLegacyPublicKey = owner.publicKey\n const isOwnerLegacyPublicKeyAvailable = ownerLegacyPublicKey\n ? availablePublicKeysFingerprints.some((fp) => ownerLegacyPublicKey.endsWith(fp))\n : false\n\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.slice(-32)]: 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 && isOwnerLegacyPublicKeyAvailable) {\n owner.hcPartyKeys![delegateId] = [encryptedAesKeys[ownerLegacyPublicKey.slice(-32)], encryptedAesKeys[delegate.publicKey.slice(-32)]]\n }\n owner.aesExchangeKeys = this.fixAesExchangeKeyEntriesToFingerprints({\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, loadIfMissingFromCache: boolean = true) {\n return (\n this.dataOwnerCache[ownerId] ??\n (loadIfMissingFromCache\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 : undefined)\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 = await 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 dataOwnerCanDecryptPatient(dataOwnerId: string, p: Patient): Promise<boolean> {\n if (p.encryptionKeys && p.encryptionKeys[dataOwnerId]?.length) return true\n\n const dataOwner = await this.getDataOwner(dataOwnerId)\n if (dataOwner.type === 'hcp' && p.encryptionKeys && p.encryptionKeys[dataOwner.dataOwner.parentId!]?.length) return true\n\n return false\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 /**\n * Store keypair in storage\n *\n * @param id\n * @param keyPair should be JWK\n *\n * @deprecated use storage.setItem instead\n */\n storeKeyPair(id: string, keyPair: { publicKey: any; privateKey: any }) {\n this._storage.setItem(this.rsaLocalStoreIdPrefix + id, JSON.stringify(keyPair))\n }\n\n fixAesExchangeKeyEntriesToFingerprints(aesExchangeKeys: { [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } } }): {\n [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } }\n } {\n return Object.fromEntries(\n Object.entries(aesExchangeKeys).map(([delegatorPubKey, allDelegates]) => [\n delegatorPubKey,\n Object.fromEntries(\n Object.entries(allDelegates).map(([delegateId, keyEntries]) => [\n delegateId,\n Object.fromEntries(Object.entries(keyEntries).map(([publicKey, encryptedValue]) => [publicKey.slice(-32), encryptedValue])),\n ])\n ),\n ])\n )\n }\n\n /**\n * @internal\n * Keep only strings which match the format of a valid entity encryption key: hex string potentially with dashes.\n * Additionally, this method automatically removes the dashes from the key (from uuid-formatted to standard).\n */\n filterAndFixValidEntityEncryptionKeyStrings(aesKeys: string[]): string[] {\n return aesKeys.flatMap((x) => {\n const undashed = x.length === 36 ? x.replace(/-/g, '') : x\n if ((undashed.length === 32 || undashed.length === 64) && undashed.match(/^[0-9a-fA-F]+$/)) {\n return [undashed]\n } else {\n return []\n }\n })\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export type PaginatorFunction<X> = (key: any, docId: string | null, limit: number | undefined) => Promise<PaginatorResponse<X>>;
|
|
2
|
-
export type PaginatorExecutor<X> = (latestPaginatorFunctionResult: PaginatorResponse<X>, acc: any[], limit: number | undefined) => Promise<PaginatorResponse<X>>;
|
|
1
|
+
export declare type PaginatorFunction<X> = (key: any, docId: string | null, limit: number | undefined) => Promise<PaginatorResponse<X>>;
|
|
2
|
+
export declare type PaginatorExecutor<X> = (latestPaginatorFunctionResult: PaginatorResponse<X>, acc: any[], limit: number | undefined) => Promise<PaginatorResponse<X>>;
|
|
3
3
|
export interface PaginatorResponse<X> {
|
|
4
4
|
rows: Array<X>;
|
|
5
5
|
nextKey: any | null | undefined;
|