@icure/api 7.1.11 → 7.1.12

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.
@@ -40,7 +40,7 @@ class BaseExchangeKeysManager {
40
40
  return __awaiter(this, void 0, void 0, function* () {
41
41
  const delegatorId = yield this.dataOwnerApi.getCurrentDataOwnerId();
42
42
  return yield (0, utils_1.notConcurrent)(this.generateKeyConcurrencyMap, delegatorId, () => __awaiter(this, void 0, void 0, function* () {
43
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
43
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
44
44
  const delegator = CryptoActorStub_1.CryptoActorStubWithType.fromDataOwner(yield this.dataOwnerApi.getCurrentDataOwner());
45
45
  const delegate = delegatorId === delegateId ? delegator : yield this.dataOwnerApi.getCryptoActorStub(delegateId);
46
46
  const mainDelegatorKeyPairPubHex = (0, utils_1.ua2hex)(yield this.primitives.RSA.exportKey(delegatorMainKeyPair.publicKey, 'spki'));
@@ -62,7 +62,16 @@ class BaseExchangeKeysManager {
62
62
  }
63
63
  const allPublicKeys = Object.assign(Object.assign({}, additionalPublicKeys), { [mainDelegatorKeyPairPubHex.slice(-32)]: delegatorMainKeyPair.publicKey });
64
64
  const encryptedKeyInfo = yield this.encryptExchangeKey(exchangeKey, allPublicKeys);
65
- const updatedStub = Object.assign(Object.assign({}, delegator.stub), { aesExchangeKeys: yield this.updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyInfo.encryptedExchangeKey), publicKey: (_j = delegator.stub.publicKey) !== null && _j !== void 0 ? _j : mainDelegatorKeyPairPubHex });
65
+ let updatedDelegatorPublicKey;
66
+ if (delegator.stub.publicKey == '') {
67
+ if (Object.entries((_j = delegator.stub.hcPartyKeys) !== null && _j !== void 0 ? _j : {}).length > 0)
68
+ throw new Error(`Data owner ${delegator.stub.id} has "" as public key but has non-empty hcPartyKeys`);
69
+ updatedDelegatorPublicKey = mainDelegatorKeyPairPubHex;
70
+ }
71
+ else {
72
+ updatedDelegatorPublicKey = (_k = delegator.stub.publicKey) !== null && _k !== void 0 ? _k : mainDelegatorKeyPairPubHex;
73
+ }
74
+ const updatedStub = Object.assign(Object.assign({}, delegator.stub), { aesExchangeKeys: yield this.updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyInfo.encryptedExchangeKey), publicKey: updatedDelegatorPublicKey });
66
75
  if (delegator.stub.publicKey === mainDelegatorKeyPairPubHex) {
67
76
  updatedStub.hcPartyKeys = this.updateLegacyExchangeKeys(delegator, delegate, encryptedKeyInfo.encryptedExchangeKey);
68
77
  }
@@ -1 +1 @@
1
- {"version":3,"file":"BaseExchangeKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,oCAAwD;AAIxD,yEAA8F;AAC9F,6EAAyE;AAEzE;;;;GAIG;AACH,MAAa,uBAAuB;IAQlC,YACE,UAA4B,EAC5B,YAA8B,EAC9B,cAA6B,EAC7B,cAA6B,EAC7B,aAA2B;QAZZ,8BAAyB,GAAwC,EAAE,CAAA;QAclF,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,cAAc,GAAG,cAAc,CAAA;QACpC,IAAI,CAAC,cAAc,GAAG,cAAc,CAAA;QACpC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAA;IACpC,CAAC;IAED;;;;;;;;OAQG;IACG,oCAAoC,CACxC,UAAkB,EAClB,oBAAwC,EACxC,oBAA6D;;YAK7D,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAA;YACnE,OAAO,MAAM,IAAA,qBAAa,EAAC,IAAI,CAAC,yBAAyB,EAAE,WAAW,EAAE,GAAS,EAAE;;gBACjF,MAAM,SAAS,GAAG,yCAAuB,CAAC,aAAa,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AAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC;aAC5H,CAAC,CACH;SACF,CAAC,CACH,CAAA;IACH,CAAC;CACF;AAlaD,0DAkaC","sourcesContent":["import { KeyPair } from './RSA'\nimport { hex2ua, notConcurrent, ua2hex } from '../utils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../../icc-api'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * Functions to create and get exchange keys.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeKeysManager {\n private readonly generateKeyConcurrencyMap: { [key: string]: PromiseLike<any> } = {}\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly hcpartyBaseApi: IccHcpartyApi\n private readonly patientBaseApi: IccPatientApi\n private readonly deviceBaseApi: IccDeviceApi\n\n constructor(\n primitives: CryptoPrimitives,\n dataOwnerApi: IccDataOwnerXApi,\n hcpartyBaseApi: IccHcpartyApi,\n patientBaseApi: IccPatientApi,\n deviceBaseApi: IccDeviceApi\n ) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.hcpartyBaseApi = hcpartyBaseApi\n this.patientBaseApi = patientBaseApi\n this.deviceBaseApi = deviceBaseApi\n }\n\n /**\n * Creates a new exchange key from the current data owner to a delegate, or updates an existing one allowing additional public keys to access it.\n * @param delegateId the delegate data owner id.\n * @param delegatorMainKeyPair main key pair for the delegator. The private key will be used for the decryption of the existing key in case of\n * update, and the public key will be used as entry key of the aesExchangeKey map\n * @param additionalPublicKeys all public keys of key pairs other than {@link delegatorMainKeyPair} that need to have access to the exchange key.\n * Can be a mix of crypto keys and full hex-encoded spki format (no fingerprints).\n * @return the exchange key for the delegator-delegate-delegatorKey triple (new or existing) and the updated delegator.\n */\n async createOrUpdateEncryptedExchangeKeyTo(\n delegateId: string,\n delegatorMainKeyPair: KeyPair<CryptoKey>,\n additionalPublicKeys: { [keyFingerprint: string]: CryptoKey }\n ): Promise<{\n updatedDelegator: CryptoActorStubWithType\n key: CryptoKey\n }> {\n const delegatorId = await this.dataOwnerApi.getCurrentDataOwnerId()\n return await notConcurrent(this.generateKeyConcurrencyMap, delegatorId, async () => {\n const delegator = CryptoActorStubWithType.fromDataOwner(await this.dataOwnerApi.getCurrentDataOwner())\n const delegate = delegatorId === delegateId ? delegator : await this.dataOwnerApi.getCryptoActorStub(delegateId)\n const mainDelegatorKeyPairPubHex = ua2hex(await this.primitives.RSA.exportKey(delegatorMainKeyPair.publicKey, 'spki'))\n let exchangeKey: { raw: string; key: CryptoKey } | undefined = undefined\n const existingExchangeKey =\n delegator.stub.aesExchangeKeys?.[mainDelegatorKeyPairPubHex]?.[delegateId]?.[mainDelegatorKeyPairPubHex.slice(-32)] ??\n (mainDelegatorKeyPairPubHex === delegator.stub.publicKey ? delegator.stub.hcPartyKeys?.[delegateId]?.[0] : undefined)\n if (existingExchangeKey) {\n exchangeKey = await this.tryDecryptExchangeKeyWith(existingExchangeKey, delegatorMainKeyPair, undefined)\n if (!exchangeKey)\n throw new Error(\n `Failed to decrypt existing exchange key for update of ${mainDelegatorKeyPairPubHex.slice(-32)}@${delegatorId}->${delegateId}`\n )\n const existingAesExchangeKey = delegator.stub.aesExchangeKeys?.[mainDelegatorKeyPairPubHex]?.[delegateId]\n if (existingAesExchangeKey) {\n const existingPublicKeysSet = new Set(existingExchangeKey)\n if (Object.keys(additionalPublicKeys).every((fp) => existingPublicKeysSet.has(fp)))\n return {\n updatedDelegator: delegator,\n key: exchangeKey.key,\n }\n }\n }\n const allPublicKeys = {\n ...additionalPublicKeys,\n [mainDelegatorKeyPairPubHex.slice(-32)]: delegatorMainKeyPair.publicKey,\n }\n const encryptedKeyInfo = await this.encryptExchangeKey(exchangeKey, allPublicKeys)\n const updatedStub: CryptoActorStub = {\n ...delegator.stub,\n aesExchangeKeys: await this.updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyInfo.encryptedExchangeKey),\n publicKey: delegator.stub.publicKey ?? mainDelegatorKeyPairPubHex,\n }\n if (delegator.stub.publicKey === mainDelegatorKeyPairPubHex) {\n updatedStub.hcPartyKeys = this.updateLegacyExchangeKeys(delegator, delegate, encryptedKeyInfo.encryptedExchangeKey)\n }\n const updatedDelegator = await this.dataOwnerApi.modifyCryptoActorStub({\n type: delegator.type,\n stub: updatedStub,\n })\n return {\n key: encryptedKeyInfo.exchangeKey,\n updatedDelegator,\n }\n })\n }\n\n /**\n * Updates the aes exchange keys between the current data owner and another data owner to allow the other data owner to access the exchange key\n * using his new public key. Note that this will make existing exchange keys from the other data owner to the current data owner invalid for\n * encryption.\n * @param otherDataOwner the other data owner.\n * @param newDataOwnerPublicKey a new public key of the other data owner.\n * @param keyPairsByFingerprint all available key pairs to use for the decryption of existing aes exchange keys.\n */\n async giveAccessBackTo(\n otherDataOwner: string,\n newDataOwnerPublicKey: string,\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const newPublicKey = await this.primitives.RSA.importKey('spki', hex2ua(newDataOwnerPublicKey), ['encrypt'])\n await this.extendForGiveAccessBackTo(selfId, otherDataOwner, newDataOwnerPublicKey.slice(-32), newPublicKey, keyPairsByFingerprint)\n await this.extendForGiveAccessBackTo(otherDataOwner, selfId, newDataOwnerPublicKey.slice(-32), newPublicKey, keyPairsByFingerprint)\n }\n\n /**\n * Get the encrypted exchange keys for a delegator-delegate pair.\n * @param delegatorId id of the delegator data owner.\n * @param delegateId id of the delegate data owner.\n * @return an array of exchange keys from the delegator to delegate where each key is encrypted with one or more public keys.\n */\n async getEncryptedExchangeKeysFor(delegatorId: string, delegateId: string): Promise<{ [publicKeyFingerprint: string]: string }[]> {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const res: { [publicKeyFingerprint: string]: string }[] = Object.values(delegator.stub.aesExchangeKeys ?? {}).flatMap((delegateToKey) => {\n const encryptedKeyForDelegate = delegateToKey[delegateId]\n if (encryptedKeyForDelegate) {\n return [encryptedKeyForDelegate]\n } else {\n return []\n }\n })\n const legacyDelegation = delegator.stub.hcPartyKeys?.[delegateId]?.[1]\n if (legacyDelegation) res.push({ '': legacyDelegation })\n return res\n }\n\n /**\n * Get all exchange keys where the provided data owner is involved either as the delegator or as the delegate.\n * @param dataOwnerId id of a data owner.\n * @param otherOwnerTypes only exchange keys between the current data owner and data owners of this type will be included in the result.\n * @return all exchange keys involving the provided data owner. Note that there may be an overlap between some keys to and from the data owner.\n */\n async getAllExchangeKeysWith(\n dataOwnerId: string,\n otherOwnerTypes: DataOwnerTypeEnum[]\n ): Promise<{\n keysToOwner: { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }\n keysFromOwner: { [delegatorFp: string]: { [delegateId: string]: { [entryFp: string]: string } } }\n }> {\n if (otherOwnerTypes.length === 0) throw new Error('otherOwnerTypes must not be empty!')\n const keysToOwner = await Promise.all([\n otherOwnerTypes.find((x) => x === DataOwnerTypeEnum.Hcp)\n ? this.hcpartyBaseApi.getAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes.find((x) => x === DataOwnerTypeEnum.Patient)\n ? this.patientBaseApi.getPatientAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes.find((x) => x === DataOwnerTypeEnum.Device)\n ? this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n ]).then(([a, b, c]) => ({ ...a, ...b, ...c } as { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }))\n const dataOwner = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n const allOwnerKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(dataOwner.stub, undefined)\n const filteredDelegates = new Set(\n await Array.from(new Set(Object.values(allOwnerKeys).flatMap((x) => Object.keys(x)))).reduce(async (acc, ownerId) => {\n const awaitedAcc = await acc\n if (ownerId === dataOwnerId) {\n return [...awaitedAcc, ownerId]\n } else {\n const dataOwnerType: DataOwnerTypeEnum = (await this.dataOwnerApi.getCryptoActorStub(ownerId)).type\n if (otherOwnerTypes.some((x) => x === dataOwnerType)) {\n return [...awaitedAcc, ownerId]\n } else return awaitedAcc\n }\n }, Promise.resolve([] as string[]))\n )\n const keysFromOwner = Object.fromEntries(\n Object.entries(allOwnerKeys)\n .map(([delegatorPubKey, delegateToKeys]) => [\n delegatorPubKey,\n Object.fromEntries(\n Object.entries(delegateToKeys).filter(([delegateId]) => filteredDelegates.has(delegateId)) as [string, { [k: string]: string }][]\n ),\n ])\n .filter(([, x]) => Object.keys(x).length > 0) as [string, { [k: string]: { [k: string]: string } }][]\n )\n return { keysToOwner, keysFromOwner }\n }\n\n /**\n * Attempts to decrypt many exchange keys using any of the provided key pairs.\n * @param encryptedExchangeKeys an array of exchange keys where each key is encrypted with one or more public keys.\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return an array all successfully decrypted exchange keys and an array containing all exchange keys which could not be decrypted.\n */\n async tryDecryptExchangeKeys(\n encryptedExchangeKeys: { [publicKeyFingerprint: string]: string }[],\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n }> {\n const raws = new Set<string>()\n const res: {\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n } = { successfulDecryptions: [], failedDecryptions: [] }\n for (const encryptedExchangeKey of encryptedExchangeKeys) {\n const decrypted = await this.tryDecryptExchangeKey(encryptedExchangeKey, keyPairsByFingerprint)\n if (decrypted !== undefined && !raws.has(decrypted.raw)) {\n raws.add(decrypted.raw)\n res.successfulDecryptions.push(decrypted.key)\n } else {\n res.failedDecryptions.push(encryptedExchangeKey)\n }\n }\n return res\n }\n\n private async extendForGiveAccessBackTo(\n delegatorId: string,\n delegateId: string,\n newPublicKeyFp: string,\n newPublicKey: CryptoKey,\n decryptionKeyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n await notConcurrent(this.generateKeyConcurrencyMap, delegatorId, async () => {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n let didUpdateSomeKey = false\n const combinedKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub)\n const updatedExchangeKeys: { [delegatorKey: string]: { [delegateId: string]: { [keyFp: string]: string } } } = {}\n const newEncryptionKeys = { [newPublicKeyFp]: newPublicKey }\n for (const [currDelegatorKey, currDelegatesToKeys] of Object.entries(combinedKeys)) {\n const updatedDelegatesToKeys: { [delegateId: string]: { [keyFp: string]: string } } = {}\n for (const [currDelegateId, currEncryptedKey] of Object.entries(currDelegatesToKeys)) {\n if (delegateId !== currDelegateId || newPublicKeyFp in currEncryptedKey) {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n } else {\n const decrypted = await this.tryDecryptExchangeKey(currEncryptedKey, decryptionKeyPairsByFingerprint)\n if (decrypted) {\n didUpdateSomeKey = true\n updatedDelegatesToKeys[currDelegateId] = {\n ...currEncryptedKey,\n ...(await this.encryptExchangeKey(decrypted, newEncryptionKeys)).encryptedExchangeKey,\n }\n } else {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n }\n }\n }\n updatedExchangeKeys[currDelegatorKey] = updatedDelegatesToKeys\n }\n if (didUpdateSomeKey) {\n await this.dataOwnerApi.modifyCryptoActorStub({\n type: delegator.type,\n stub: {\n ...delegator.stub,\n aesExchangeKeys: updatedExchangeKeys,\n },\n })\n }\n })\n }\n\n /**\n * Attempts to decrypt an exchange key using any of the provided key pairs.\n * @param encryptedExchangeKey an encrypted exchange key, in the form publicKeyXyzFingerprint -> hex(exchangeKeyEncryptedByPrivateKeyXyz).\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided keys.\n */\n private async tryDecryptExchangeKey(\n encryptedExchangeKey: { [publicKeyFingerprint: string]: string },\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n for (const [entryKey, encrypted] of Object.entries(encryptedExchangeKey)) {\n // Due to bugs in past version the entry may actually contain the full public key instead of just the fingerprint.\n const fp = entryKey.slice(-32)\n const keyPair = keyPairsByFingerprint[fp]\n if (keyPair !== undefined) {\n const res = await this.tryDecryptExchangeKeyWith(encrypted, keyPair, fp)\n if (res !== undefined) return res\n }\n }\n const defaultEncryptedKey = encryptedExchangeKey['']\n if (defaultEncryptedKey !== undefined) {\n for (const keyPair of Object.values(keyPairsByFingerprint)) {\n // disable error logging, we are not sure keyPair is the correct key\n const res = await this.tryDecryptExchangeKeyWith(defaultEncryptedKey, keyPair, undefined)\n if (res !== undefined) return res\n }\n }\n return undefined\n }\n\n /**\n * Creates an encrypted exchange key for the provided public keys.\n * @param exchangeKey the exchange key in raw and imported format. If undefined a new key will be automatically created.\n * @param publicKeys additional public keys that will have access to the exchange key in spki format, hex-encoded.\n * @return the exchangeKey and an object with the exchange key encrypted with each of the provided public keys, hex-encoded, by fingerprint.\n */\n private async encryptExchangeKey(\n exchangeKey: { raw: string; key: CryptoKey } | undefined,\n publicKeys: { [keyFingerprint: string]: CryptoKey }\n ): Promise<{\n exchangeKey: CryptoKey\n encryptedExchangeKey: { [pubKeyFp: string]: string }\n }> {\n const exchangeKeyCrypto = exchangeKey?.key ?? (await this.primitives.AES.generateCryptoKey(false))\n const exchangeKeyBytes = exchangeKey !== undefined ? hex2ua(exchangeKey.raw) : await this.primitives.AES.exportKey(exchangeKeyCrypto, 'raw')\n const encryptedExchangeKey = await Object.entries(publicKeys).reduce(\n async (acc, [currKeyFp, currKey]) => ({\n ...(await acc),\n [currKeyFp]: ua2hex(await this.primitives.RSA.encrypt(currKey, new Uint8Array(exchangeKeyBytes))),\n }),\n Promise.resolve({} as { [pubKeyFp: string]: string })\n )\n return { exchangeKey: exchangeKeyCrypto, encryptedExchangeKey }\n }\n\n /**\n * Attempts to decrypt an exchange key using the provided key pairs.\n * If you are confident that the provided {@link keyPair} was used to encrypt {@link encryptedByOneKey} you should also provide {@link keyPairFp},\n * so that if the decryption fail an error will be logged to console before returning undefined.\n * @param encryptedByOneKey an exchange key which may be encrypted with {@link keyPair}.\n * @param keyPair an rsa key pair.\n * @param keyPairFp the fingerprint of the provided key pair or undefined to disable logging of error if the decryption failed.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided key.\n */\n private async tryDecryptExchangeKeyWith(\n encryptedByOneKey: string,\n keyPair: KeyPair<CryptoKey>,\n keyPairFp: string | undefined // if undefined will not log errors, when we are not sure the key to be used is the provided key.\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n try {\n const decrypted = await this.primitives.RSA.decrypt(keyPair.privateKey, hex2ua(encryptedByOneKey))\n return { raw: ua2hex(decrypted), key: await this.primitives.AES.importKey('raw', decrypted) }\n } catch (e) {\n if (keyPairFp) {\n console.error(`Failed to decrypt or import exchange key ${encryptedByOneKey} using key with fingerprint ${keyPairFp}.`, e)\n }\n }\n }\n\n private updateLegacyExchangeKeys(\n delegator: CryptoActorStubWithType,\n delegate: CryptoActorStubWithType,\n encryptedKeyMap: { [fp: string]: string }\n ): { [delegateId: string]: string[] } | undefined {\n const legacyEncryptedKeyDelegator = delegator.stub.publicKey ? encryptedKeyMap[delegator.stub.publicKey] : undefined\n const legacyEncryptedKeyDelegate = delegate.stub.publicKey ? encryptedKeyMap[delegate.stub.publicKey] : undefined\n if (legacyEncryptedKeyDelegator && legacyEncryptedKeyDelegate) {\n return {\n ...(delegator.stub.hcPartyKeys ?? {}),\n [delegate.stub.id!]: [legacyEncryptedKeyDelegator, legacyEncryptedKeyDelegate],\n }\n } else return delegator.stub.hcPartyKeys\n }\n\n private async updateExchangeKeys(\n delegator: CryptoActorStubWithType,\n delegate: CryptoActorStubWithType,\n mainDelegatorKeyPairPubHex: string,\n encryptedKeyMap: { [fp: string]: string }\n ): Promise<{ [ownerPublicKey: string]: { [delegateId: string]: { [fingerprint: string]: string } } }> {\n const combinedAesExchangeKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub)\n return this.fixAesExchangeKeyEntriesToFingerprints({\n ...combinedAesExchangeKeys,\n [mainDelegatorKeyPairPubHex]: {\n ...(combinedAesExchangeKeys[mainDelegatorKeyPairPubHex] ?? {}),\n [delegate.stub.id!]: {\n ...(combinedAesExchangeKeys[mainDelegatorKeyPairPubHex]?.[delegate.stub.id!] ?? {}),\n ...encryptedKeyMap,\n },\n },\n })\n }\n\n // Copy all legacy hcp exchange keys into the new aes exchange keys\n private async combineLegacyHcpKeysWithAesExchangeKeys(\n owner: CryptoActorStub,\n delegate: CryptoActorStub | undefined\n ): Promise<{ [ownerPublicKey: string]: { [delegateId: string]: { [fingerprint: string]: string } } }> {\n const ownerLegacyPublicKey = owner.publicKey\n if (ownerLegacyPublicKey && !(owner.aesExchangeKeys ?? {})[ownerLegacyPublicKey]) {\n /*\n * This condition would technically prevent new updates to the hcPartyKeys to be migrated to the aes exchange keys, but since I can only update\n * data for self data owner and parent entities this is not an issue, because I will always be using the new api from now on and I won't have\n * a situation where the legacy keys are updated but the aes exchange keys are not.\n */\n const unknownDataOwnerCounterPartIds = Object.keys(owner.hcPartyKeys ?? {}).filter((x) => x !== owner.id && x !== delegate?.id)\n const counterPartsById = [\n owner,\n ...(delegate ? [delegate] : []),\n ...(await Promise.all(unknownDataOwnerCounterPartIds.map(async (cpid) => (await this.dataOwnerApi.getCryptoActorStub(cpid)).stub))),\n ].reduce((acc, dataOwner) => {\n acc[dataOwner.id!] = dataOwner\n return acc\n }, {} as { [id: string]: CryptoActorStub })\n return {\n [ownerLegacyPublicKey]: Object.entries(owner.hcPartyKeys ?? {}).reduce((acc, [hcpId, keys]) => {\n acc[hcpId] = { [ownerLegacyPublicKey.slice(-32)]: keys[0], [counterPartsById[hcpId]?.publicKey?.slice(-32) ?? '']: keys[1] }\n return acc\n }, {} as { [delegateId: string]: { [fingerprint: string]: string } }),\n ...(owner.aesExchangeKeys ?? {}),\n }\n } else return owner.aesExchangeKeys ?? {}\n }\n\n private fixAesExchangeKeyEntriesToFingerprints(aesExchangeKeys: {\n [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } }\n }): { [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } } } {\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"]}
1
+ {"version":3,"file":"BaseExchangeKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,oCAAwD;AAIxD,yEAA8F;AAC9F,6EAAyE;AAEzE;;;;GAIG;AACH,MAAa,uBAAuB;IAQlC,YACE,UAA4B,EAC5B,YAA8B,EAC9B,cAA6B,EAC7B,cAA6B,EAC7B,aAA2B;QAZZ,8BAAyB,GAAwC,EAAE,CAAA;QAclF,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,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,CAAC,CAAC,EAAE,CAAC,MAAA,MAAA,MAAA,gBAAgB,CAAC,KAAK,CAAC,0CAAE,SAAS,0CAAE,KAAK,CAAC,CAAC,EAAE,CAAC,mCAAI,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;wBAC5H,OAAO,GAAG,CAAA;oBACZ,CAAC,EAAE,EAAiE,CAAC,IAClE,CAAC,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAC,EACjC;aACF;;gBAAM,OAAO,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAA;;KAC1C;IAEO,sCAAsC,CAAC,eAE9C;QACC,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,eAAe,EAAE,YAAY,CAAC,EAAE,EAAE,CAAC;YACvE,eAAe;YACf,MAAM,CAAC,WAAW,CAChB,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,UAAU,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC;gBAC7D,UAAU;gBACV,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,EAAE,cAAc,CAAC,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC;aAC5H,CAAC,CACH;SACF,CAAC,CACH,CAAA;IACH,CAAC;CACF;AA1aD,0DA0aC","sourcesContent":["import { KeyPair } from './RSA'\nimport { hex2ua, notConcurrent, ua2hex } from '../utils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../../icc-api'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * Functions to create and get exchange keys.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeKeysManager {\n private readonly generateKeyConcurrencyMap: { [key: string]: PromiseLike<any> } = {}\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly hcpartyBaseApi: IccHcpartyApi\n private readonly patientBaseApi: IccPatientApi\n private readonly deviceBaseApi: IccDeviceApi\n\n constructor(\n primitives: CryptoPrimitives,\n dataOwnerApi: IccDataOwnerXApi,\n hcpartyBaseApi: IccHcpartyApi,\n patientBaseApi: IccPatientApi,\n deviceBaseApi: IccDeviceApi\n ) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.hcpartyBaseApi = hcpartyBaseApi\n this.patientBaseApi = patientBaseApi\n this.deviceBaseApi = deviceBaseApi\n }\n\n /**\n * Creates a new exchange key from the current data owner to a delegate, or updates an existing one allowing additional public keys to access it.\n * @param delegateId the delegate data owner id.\n * @param delegatorMainKeyPair main key pair for the delegator. The private key will be used for the decryption of the existing key in case of\n * update, and the public key will be used as entry key of the aesExchangeKey map\n * @param additionalPublicKeys all public keys of key pairs other than {@link delegatorMainKeyPair} that need to have access to the exchange key.\n * Can be a mix of crypto keys and full hex-encoded spki format (no fingerprints).\n * @return the exchange key for the delegator-delegate-delegatorKey triple (new or existing) and the updated delegator.\n */\n async createOrUpdateEncryptedExchangeKeyTo(\n delegateId: string,\n delegatorMainKeyPair: KeyPair<CryptoKey>,\n additionalPublicKeys: { [keyFingerprint: string]: CryptoKey }\n ): Promise<{\n updatedDelegator: CryptoActorStubWithType\n key: CryptoKey\n }> {\n const delegatorId = await this.dataOwnerApi.getCurrentDataOwnerId()\n return await notConcurrent(this.generateKeyConcurrencyMap, delegatorId, async () => {\n const delegator = CryptoActorStubWithType.fromDataOwner(await this.dataOwnerApi.getCurrentDataOwner())\n const delegate = delegatorId === delegateId ? delegator : await this.dataOwnerApi.getCryptoActorStub(delegateId)\n const mainDelegatorKeyPairPubHex = ua2hex(await this.primitives.RSA.exportKey(delegatorMainKeyPair.publicKey, 'spki'))\n let exchangeKey: { raw: string; key: CryptoKey } | undefined = undefined\n const existingExchangeKey =\n delegator.stub.aesExchangeKeys?.[mainDelegatorKeyPairPubHex]?.[delegateId]?.[mainDelegatorKeyPairPubHex.slice(-32)] ??\n (mainDelegatorKeyPairPubHex === delegator.stub.publicKey ? delegator.stub.hcPartyKeys?.[delegateId]?.[0] : undefined)\n if (existingExchangeKey) {\n exchangeKey = await this.tryDecryptExchangeKeyWith(existingExchangeKey, delegatorMainKeyPair, undefined)\n if (!exchangeKey)\n throw new Error(\n `Failed to decrypt existing exchange key for update of ${mainDelegatorKeyPairPubHex.slice(-32)}@${delegatorId}->${delegateId}`\n )\n const existingAesExchangeKey = delegator.stub.aesExchangeKeys?.[mainDelegatorKeyPairPubHex]?.[delegateId]\n if (existingAesExchangeKey) {\n const existingPublicKeysSet = new Set(existingExchangeKey)\n if (Object.keys(additionalPublicKeys).every((fp) => existingPublicKeysSet.has(fp)))\n return {\n updatedDelegator: delegator,\n key: exchangeKey.key,\n }\n }\n }\n const allPublicKeys = {\n ...additionalPublicKeys,\n [mainDelegatorKeyPairPubHex.slice(-32)]: delegatorMainKeyPair.publicKey,\n }\n const encryptedKeyInfo = await this.encryptExchangeKey(exchangeKey, allPublicKeys)\n let updatedDelegatorPublicKey: string\n if (delegator.stub.publicKey == '') {\n if (Object.entries(delegator.stub.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${delegator.stub.id} has \"\" as public key but has non-empty hcPartyKeys`)\n updatedDelegatorPublicKey = mainDelegatorKeyPairPubHex\n } else {\n updatedDelegatorPublicKey = delegator.stub.publicKey ?? mainDelegatorKeyPairPubHex\n }\n const updatedStub: CryptoActorStub = {\n ...delegator.stub,\n aesExchangeKeys: await this.updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyInfo.encryptedExchangeKey),\n publicKey: updatedDelegatorPublicKey,\n }\n if (delegator.stub.publicKey === mainDelegatorKeyPairPubHex) {\n updatedStub.hcPartyKeys = this.updateLegacyExchangeKeys(delegator, delegate, encryptedKeyInfo.encryptedExchangeKey)\n }\n const updatedDelegator = await this.dataOwnerApi.modifyCryptoActorStub({\n type: delegator.type,\n stub: updatedStub,\n })\n return {\n key: encryptedKeyInfo.exchangeKey,\n updatedDelegator,\n }\n })\n }\n\n /**\n * Updates the aes exchange keys between the current data owner and another data owner to allow the other data owner to access the exchange key\n * using his new public key. Note that this will make existing exchange keys from the other data owner to the current data owner invalid for\n * encryption.\n * @param otherDataOwner the other data owner.\n * @param newDataOwnerPublicKey a new public key of the other data owner.\n * @param keyPairsByFingerprint all available key pairs to use for the decryption of existing aes exchange keys.\n */\n async giveAccessBackTo(\n otherDataOwner: string,\n newDataOwnerPublicKey: string,\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const newPublicKey = await this.primitives.RSA.importKey('spki', hex2ua(newDataOwnerPublicKey), ['encrypt'])\n await this.extendForGiveAccessBackTo(selfId, otherDataOwner, newDataOwnerPublicKey.slice(-32), newPublicKey, keyPairsByFingerprint)\n await this.extendForGiveAccessBackTo(otherDataOwner, selfId, newDataOwnerPublicKey.slice(-32), newPublicKey, keyPairsByFingerprint)\n }\n\n /**\n * Get the encrypted exchange keys for a delegator-delegate pair.\n * @param delegatorId id of the delegator data owner.\n * @param delegateId id of the delegate data owner.\n * @return an array of exchange keys from the delegator to delegate where each key is encrypted with one or more public keys.\n */\n async getEncryptedExchangeKeysFor(delegatorId: string, delegateId: string): Promise<{ [publicKeyFingerprint: string]: string }[]> {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const res: { [publicKeyFingerprint: string]: string }[] = Object.values(delegator.stub.aesExchangeKeys ?? {}).flatMap((delegateToKey) => {\n const encryptedKeyForDelegate = delegateToKey[delegateId]\n if (encryptedKeyForDelegate) {\n return [encryptedKeyForDelegate]\n } else {\n return []\n }\n })\n const legacyDelegation = delegator.stub.hcPartyKeys?.[delegateId]?.[1]\n if (legacyDelegation) res.push({ '': legacyDelegation })\n return res\n }\n\n /**\n * Get all exchange keys where the provided data owner is involved either as the delegator or as the delegate.\n * @param dataOwnerId id of a data owner.\n * @param otherOwnerTypes only exchange keys between the current data owner and data owners of this type will be included in the result.\n * @return all exchange keys involving the provided data owner. Note that there may be an overlap between some keys to and from the data owner.\n */\n async getAllExchangeKeysWith(\n dataOwnerId: string,\n otherOwnerTypes: DataOwnerTypeEnum[]\n ): Promise<{\n keysToOwner: { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }\n keysFromOwner: { [delegatorFp: string]: { [delegateId: string]: { [entryFp: string]: string } } }\n }> {\n if (otherOwnerTypes.length === 0) throw new Error('otherOwnerTypes must not be empty!')\n const keysToOwner = await Promise.all([\n otherOwnerTypes.find((x) => x === DataOwnerTypeEnum.Hcp)\n ? this.hcpartyBaseApi.getAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes.find((x) => x === DataOwnerTypeEnum.Patient)\n ? this.patientBaseApi.getPatientAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes.find((x) => x === DataOwnerTypeEnum.Device)\n ? this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n ]).then(([a, b, c]) => ({ ...a, ...b, ...c } as { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }))\n const dataOwner = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n const allOwnerKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(dataOwner.stub, undefined)\n const filteredDelegates = new Set(\n await Array.from(new Set(Object.values(allOwnerKeys).flatMap((x) => Object.keys(x)))).reduce(async (acc, ownerId) => {\n const awaitedAcc = await acc\n if (ownerId === dataOwnerId) {\n return [...awaitedAcc, ownerId]\n } else {\n const dataOwnerType: DataOwnerTypeEnum = (await this.dataOwnerApi.getCryptoActorStub(ownerId)).type\n if (otherOwnerTypes.some((x) => x === dataOwnerType)) {\n return [...awaitedAcc, ownerId]\n } else return awaitedAcc\n }\n }, Promise.resolve([] as string[]))\n )\n const keysFromOwner = Object.fromEntries(\n Object.entries(allOwnerKeys)\n .map(([delegatorPubKey, delegateToKeys]) => [\n delegatorPubKey,\n Object.fromEntries(\n Object.entries(delegateToKeys).filter(([delegateId]) => filteredDelegates.has(delegateId)) as [string, { [k: string]: string }][]\n ),\n ])\n .filter(([, x]) => Object.keys(x).length > 0) as [string, { [k: string]: { [k: string]: string } }][]\n )\n return { keysToOwner, keysFromOwner }\n }\n\n /**\n * Attempts to decrypt many exchange keys using any of the provided key pairs.\n * @param encryptedExchangeKeys an array of exchange keys where each key is encrypted with one or more public keys.\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return an array all successfully decrypted exchange keys and an array containing all exchange keys which could not be decrypted.\n */\n async tryDecryptExchangeKeys(\n encryptedExchangeKeys: { [publicKeyFingerprint: string]: string }[],\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n }> {\n const raws = new Set<string>()\n const res: {\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n } = { successfulDecryptions: [], failedDecryptions: [] }\n for (const encryptedExchangeKey of encryptedExchangeKeys) {\n const decrypted = await this.tryDecryptExchangeKey(encryptedExchangeKey, keyPairsByFingerprint)\n if (decrypted !== undefined && !raws.has(decrypted.raw)) {\n raws.add(decrypted.raw)\n res.successfulDecryptions.push(decrypted.key)\n } else {\n res.failedDecryptions.push(encryptedExchangeKey)\n }\n }\n return res\n }\n\n private async extendForGiveAccessBackTo(\n delegatorId: string,\n delegateId: string,\n newPublicKeyFp: string,\n newPublicKey: CryptoKey,\n decryptionKeyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n await notConcurrent(this.generateKeyConcurrencyMap, delegatorId, async () => {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n let didUpdateSomeKey = false\n const combinedKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub)\n const updatedExchangeKeys: { [delegatorKey: string]: { [delegateId: string]: { [keyFp: string]: string } } } = {}\n const newEncryptionKeys = { [newPublicKeyFp]: newPublicKey }\n for (const [currDelegatorKey, currDelegatesToKeys] of Object.entries(combinedKeys)) {\n const updatedDelegatesToKeys: { [delegateId: string]: { [keyFp: string]: string } } = {}\n for (const [currDelegateId, currEncryptedKey] of Object.entries(currDelegatesToKeys)) {\n if (delegateId !== currDelegateId || newPublicKeyFp in currEncryptedKey) {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n } else {\n const decrypted = await this.tryDecryptExchangeKey(currEncryptedKey, decryptionKeyPairsByFingerprint)\n if (decrypted) {\n didUpdateSomeKey = true\n updatedDelegatesToKeys[currDelegateId] = {\n ...currEncryptedKey,\n ...(await this.encryptExchangeKey(decrypted, newEncryptionKeys)).encryptedExchangeKey,\n }\n } else {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n }\n }\n }\n updatedExchangeKeys[currDelegatorKey] = updatedDelegatesToKeys\n }\n if (didUpdateSomeKey) {\n await this.dataOwnerApi.modifyCryptoActorStub({\n type: delegator.type,\n stub: {\n ...delegator.stub,\n aesExchangeKeys: updatedExchangeKeys,\n },\n })\n }\n })\n }\n\n /**\n * Attempts to decrypt an exchange key using any of the provided key pairs.\n * @param encryptedExchangeKey an encrypted exchange key, in the form publicKeyXyzFingerprint -> hex(exchangeKeyEncryptedByPrivateKeyXyz).\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided keys.\n */\n private async tryDecryptExchangeKey(\n encryptedExchangeKey: { [publicKeyFingerprint: string]: string },\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n for (const [entryKey, encrypted] of Object.entries(encryptedExchangeKey)) {\n // Due to bugs in past version the entry may actually contain the full public key instead of just the fingerprint.\n const fp = entryKey.slice(-32)\n const keyPair = keyPairsByFingerprint[fp]\n if (keyPair !== undefined) {\n const res = await this.tryDecryptExchangeKeyWith(encrypted, keyPair, fp)\n if (res !== undefined) return res\n }\n }\n const defaultEncryptedKey = encryptedExchangeKey['']\n if (defaultEncryptedKey !== undefined) {\n for (const keyPair of Object.values(keyPairsByFingerprint)) {\n // disable error logging, we are not sure keyPair is the correct key\n const res = await this.tryDecryptExchangeKeyWith(defaultEncryptedKey, keyPair, undefined)\n if (res !== undefined) return res\n }\n }\n return undefined\n }\n\n /**\n * Creates an encrypted exchange key for the provided public keys.\n * @param exchangeKey the exchange key in raw and imported format. If undefined a new key will be automatically created.\n * @param publicKeys additional public keys that will have access to the exchange key in spki format, hex-encoded.\n * @return the exchangeKey and an object with the exchange key encrypted with each of the provided public keys, hex-encoded, by fingerprint.\n */\n private async encryptExchangeKey(\n exchangeKey: { raw: string; key: CryptoKey } | undefined,\n publicKeys: { [keyFingerprint: string]: CryptoKey }\n ): Promise<{\n exchangeKey: CryptoKey\n encryptedExchangeKey: { [pubKeyFp: string]: string }\n }> {\n const exchangeKeyCrypto = exchangeKey?.key ?? (await this.primitives.AES.generateCryptoKey(false))\n const exchangeKeyBytes = exchangeKey !== undefined ? hex2ua(exchangeKey.raw) : await this.primitives.AES.exportKey(exchangeKeyCrypto, 'raw')\n const encryptedExchangeKey = await Object.entries(publicKeys).reduce(\n async (acc, [currKeyFp, currKey]) => ({\n ...(await acc),\n [currKeyFp]: ua2hex(await this.primitives.RSA.encrypt(currKey, new Uint8Array(exchangeKeyBytes))),\n }),\n Promise.resolve({} as { [pubKeyFp: string]: string })\n )\n return { exchangeKey: exchangeKeyCrypto, encryptedExchangeKey }\n }\n\n /**\n * Attempts to decrypt an exchange key using the provided key pairs.\n * If you are confident that the provided {@link keyPair} was used to encrypt {@link encryptedByOneKey} you should also provide {@link keyPairFp},\n * so that if the decryption fail an error will be logged to console before returning undefined.\n * @param encryptedByOneKey an exchange key which may be encrypted with {@link keyPair}.\n * @param keyPair an rsa key pair.\n * @param keyPairFp the fingerprint of the provided key pair or undefined to disable logging of error if the decryption failed.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided key.\n */\n private async tryDecryptExchangeKeyWith(\n encryptedByOneKey: string,\n keyPair: KeyPair<CryptoKey>,\n keyPairFp: string | undefined // if undefined will not log errors, when we are not sure the key to be used is the provided key.\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n try {\n const decrypted = await this.primitives.RSA.decrypt(keyPair.privateKey, hex2ua(encryptedByOneKey))\n return { raw: ua2hex(decrypted), key: await this.primitives.AES.importKey('raw', decrypted) }\n } catch (e) {\n if (keyPairFp) {\n console.error(`Failed to decrypt or import exchange key ${encryptedByOneKey} using key with fingerprint ${keyPairFp}.`, e)\n }\n }\n }\n\n private updateLegacyExchangeKeys(\n delegator: CryptoActorStubWithType,\n delegate: CryptoActorStubWithType,\n encryptedKeyMap: { [fp: string]: string }\n ): { [delegateId: string]: string[] } | undefined {\n const legacyEncryptedKeyDelegator = delegator.stub.publicKey ? encryptedKeyMap[delegator.stub.publicKey] : undefined\n const legacyEncryptedKeyDelegate = delegate.stub.publicKey ? encryptedKeyMap[delegate.stub.publicKey] : undefined\n if (legacyEncryptedKeyDelegator && legacyEncryptedKeyDelegate) {\n return {\n ...(delegator.stub.hcPartyKeys ?? {}),\n [delegate.stub.id!]: [legacyEncryptedKeyDelegator, legacyEncryptedKeyDelegate],\n }\n } else return delegator.stub.hcPartyKeys\n }\n\n private async updateExchangeKeys(\n delegator: CryptoActorStubWithType,\n delegate: CryptoActorStubWithType,\n mainDelegatorKeyPairPubHex: string,\n encryptedKeyMap: { [fp: string]: string }\n ): Promise<{ [ownerPublicKey: string]: { [delegateId: string]: { [fingerprint: string]: string } } }> {\n const combinedAesExchangeKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub)\n return this.fixAesExchangeKeyEntriesToFingerprints({\n ...combinedAesExchangeKeys,\n [mainDelegatorKeyPairPubHex]: {\n ...(combinedAesExchangeKeys[mainDelegatorKeyPairPubHex] ?? {}),\n [delegate.stub.id!]: {\n ...(combinedAesExchangeKeys[mainDelegatorKeyPairPubHex]?.[delegate.stub.id!] ?? {}),\n ...encryptedKeyMap,\n },\n },\n })\n }\n\n // Copy all legacy hcp exchange keys into the new aes exchange keys\n private async combineLegacyHcpKeysWithAesExchangeKeys(\n owner: CryptoActorStub,\n delegate: CryptoActorStub | undefined\n ): Promise<{ [ownerPublicKey: string]: { [delegateId: string]: { [fingerprint: string]: string } } }> {\n const ownerLegacyPublicKey = owner.publicKey\n if (ownerLegacyPublicKey && !(owner.aesExchangeKeys ?? {})[ownerLegacyPublicKey]) {\n /*\n * This condition would technically prevent new updates to the hcPartyKeys to be migrated to the aes exchange keys, but since I can only update\n * data for self data owner and parent entities this is not an issue, because I will always be using the new api from now on and I won't have\n * a situation where the legacy keys are updated but the aes exchange keys are not.\n */\n const unknownDataOwnerCounterPartIds = Object.keys(owner.hcPartyKeys ?? {}).filter((x) => x !== owner.id && x !== delegate?.id)\n const counterPartsById = [\n owner,\n ...(delegate ? [delegate] : []),\n ...(await Promise.all(unknownDataOwnerCounterPartIds.map(async (cpid) => (await this.dataOwnerApi.getCryptoActorStub(cpid)).stub))),\n ].reduce((acc, dataOwner) => {\n acc[dataOwner.id!] = dataOwner\n return acc\n }, {} as { [id: string]: CryptoActorStub })\n return {\n [ownerLegacyPublicKey]: Object.entries(owner.hcPartyKeys ?? {}).reduce((acc, [hcpId, keys]) => {\n acc[hcpId] = { [ownerLegacyPublicKey.slice(-32)]: keys[0], [counterPartsById[hcpId]?.publicKey?.slice(-32) ?? '']: keys[1] }\n return acc\n }, {} as { [delegateId: string]: { [fingerprint: string]: string } }),\n ...(owner.aesExchangeKeys ?? {}),\n }\n } else return owner.aesExchangeKeys ?? {}\n }\n\n private fixAesExchangeKeyEntriesToFingerprints(aesExchangeKeys: {\n [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } }\n }): { [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } } } {\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"]}
@@ -187,7 +187,18 @@ class KeyManager {
187
187
  doLoadKeys(keyRecovererAndVerifier, currentOwnerKeyGenerator) {
188
188
  return __awaiter(this, void 0, void 0, function* () {
189
189
  // Load all keys for self from key store
190
- const hierarchy = yield this.dataOwnerApi.getCurrentDataOwnerHierarchy();
190
+ const hierarchy = (yield this.dataOwnerApi.getCurrentDataOwnerHierarchy()).map(({ dataOwner, type }) => {
191
+ var _a;
192
+ if (dataOwner.publicKey == '') {
193
+ if (Object.entries((_a = dataOwner.hcPartyKeys) !== null && _a !== void 0 ? _a : {}).length > 0)
194
+ throw new Error(`Data owner ${dataOwner.id} has "" as public key but has non-empty hcPartyKeys`);
195
+ delete dataOwner.publicKey;
196
+ }
197
+ return {
198
+ dataOwner,
199
+ type,
200
+ };
201
+ });
191
202
  const self = hierarchy[hierarchy.length - 1];
192
203
  this.selfId = self.dataOwner.id;
193
204
  const keysData = [];
@@ -196,7 +207,6 @@ class KeyManager {
196
207
  const availableKeysFpSet = new Set(Object.keys(availableKeys));
197
208
  const verifiedKeysMap = yield this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id);
198
209
  const allPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dowt.dataOwner);
199
- const fpToFullMap = (0, utils_2.fingerprintToPublicKeysMapOf)(dowt.dataOwner);
200
210
  const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {
201
211
  return availableKeysFpSet.has(key.slice(-32)) ? [] : [key];
202
212
  });
@@ -1 +1 @@
1
- {"version":3,"file":"KeyManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/KeyManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAiC;AAGjC,mCAAsE;AAoBtE,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAAC,CAAC,MAAM,CACN,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAG,CAAC,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE,eAAe,EAAE,EAAE,EAAE,IAAG,EAC3G,EAKC,CACF,CACF,CAAA;AAGH;;GAEG;AACH,MAAa,UAAU;IAKrB,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,YAAgC,EAChC,WAAwB,EACxB,sBAA+C,EAC/C,UAA4B,EAC5B,oBAA6B;QAN7B,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,iBAAY,GAAZ,YAAY,CAAoB;QAChC,gBAAW,GAAX,WAAW,CAAa;QACxB,2BAAsB,GAAtB,sBAAsB,CAAyB;QAC/C,eAAU,GAAV,UAAU,CAAkB;QAC5B,yBAAoB,GAApB,oBAAoB,CAAS;QATxC,cAAS,GAA2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,CAAC,SAAS,EAAE,IAAI,CAAC,sBAAsB,CAAC,UAAU,CAAC,CAAC,CAAA;gBACxG,KAAK,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;oBACtD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAA;iBAC3C;aACF;YACD,OAAO,UAAU,CAAA;QACnB,CAAC;KAAA;IAEO,qBAAqB,CAAI,GAAyC;QACxE,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IACnF,CAAC;IAEO,cAAc,CAAC,QAAuC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AAnXD,gCAmXC","sourcesContent":["import { DataOwner, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { fingerprintToPublicKeysMapOf, loadPublicKeys } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class KeyManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly baseExchangeKeyManager: BaseExchangeKeysManager,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey> }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair }) => ({ pair })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey?.slice(-32)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwner): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from(this.dataOwnerApi.getHexPublicKeysOf(dataOwner)).filter((key) => {\n const fp = key.slice(-32)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchy()\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {\n const availableKeys = await this.loadAndRecoverKeysFor(dowt)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dowt.dataOwner)\n const fpToFullMap = fingerprintToPublicKeysMapOf(dowt.dataOwner)\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(key.slice(-32)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(x.slice(-32) in verifiedKeysMap) && !(availableKeys?.[x.slice(-32)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (const keyData of keysData) {\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp],\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(keyData.dowt, this.plainKeysByFingerprint(keysWithExternallyRecovered))\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair())\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const publicKeyFingerprint = publicKeyHex.slice(-32)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n const verifiedPublicKeysMap = await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const { updatedDelegator } = await this.baseExchangeKeyManager.createOrUpdateEncryptedExchangeKeyTo(\n selfDataOwner.dataOwner.id!,\n keyPair,\n await loadPublicKeys(\n this.primitives.RSA,\n Array.from(this.dataOwnerApi.getHexPublicKeysOf(selfDataOwner.dataOwner)).filter((x) => verifiedPublicKeysMap[x.slice(-32)])\n )\n )\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf: updatedDelegator }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: string[]\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n return await pubKeysFingerprints.reduce(async (acc, currentFingerprint) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair('jwk', storedKeypair.pair.privateKey, 'jwk', storedKeypair.pair.publicKey)\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(dataOwner: DataOwnerWithType): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const selfPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dataOwner.dataOwner)\n const pubKeysFingerprints = Array.from(selfPublicKeys).map((x) => x.slice(-32))\n const loadedKeys = pubKeysFingerprints.length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (loadedKeysFingerprints.length !== pubKeysFingerprints.length && loadedKeysFingerprints.length > 0) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint(loadedKeys))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k.slice(-32), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}
1
+ {"version":3,"file":"KeyManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/KeyManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAiC;AAGjC,mCAAsE;AAoBtE,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAAC,CAAC,MAAM,CACN,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAG,CAAC,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE,eAAe,EAAE,EAAE,EAAE,IAAG,EAC3G,EAKC,CACF,CACF,CAAA;AAGH;;GAEG;AACH,MAAa,UAAU;IAKrB,YACmB,UAA4B,EAC5B,YAA8B,EA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AAA;IACnF,CAAC;IAEO,cAAc,CAAC,QAAuC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AA5XD,gCA4XC","sourcesContent":["import { DataOwner, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { fingerprintToPublicKeysMapOf, loadPublicKeys } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class KeyManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly baseExchangeKeyManager: BaseExchangeKeysManager,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey> }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair }) => ({ pair })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey?.slice(-32)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwner): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from(this.dataOwnerApi.getHexPublicKeysOf(dataOwner)).filter((key) => {\n const fp = key.slice(-32)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = (await this.dataOwnerApi.getCurrentDataOwnerHierarchy()).map(({ dataOwner, type }) => {\n if (dataOwner.publicKey == '') {\n if (Object.entries(dataOwner.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${dataOwner.id} has \"\" as public key but has non-empty hcPartyKeys`)\n delete dataOwner.publicKey\n }\n return {\n dataOwner,\n type,\n } as DataOwnerWithType\n })\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {\n const availableKeys = await this.loadAndRecoverKeysFor(dowt)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dowt.dataOwner)\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(key.slice(-32)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(x.slice(-32) in verifiedKeysMap) && !(availableKeys?.[x.slice(-32)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (const keyData of keysData) {\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp],\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(keyData.dowt, this.plainKeysByFingerprint(keysWithExternallyRecovered))\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair())\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const publicKeyFingerprint = publicKeyHex.slice(-32)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n const verifiedPublicKeysMap = await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const { updatedDelegator } = await this.baseExchangeKeyManager.createOrUpdateEncryptedExchangeKeyTo(\n selfDataOwner.dataOwner.id!,\n keyPair,\n await loadPublicKeys(\n this.primitives.RSA,\n Array.from(this.dataOwnerApi.getHexPublicKeysOf(selfDataOwner.dataOwner)).filter((x) => verifiedPublicKeysMap[x.slice(-32)])\n )\n )\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf: updatedDelegator }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: string[]\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n return await pubKeysFingerprints.reduce(async (acc, currentFingerprint) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair('jwk', storedKeypair.pair.privateKey, 'jwk', storedKeypair.pair.publicKey)\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(dataOwner: DataOwnerWithType): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const selfPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dataOwner.dataOwner)\n const pubKeysFingerprints = Array.from(selfPublicKeys).map((x) => x.slice(-32))\n const loadedKeys = pubKeysFingerprints.length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (loadedKeysFingerprints.length !== pubKeysFingerprints.length && loadedKeysFingerprints.length > 0) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint(loadedKeys))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k.slice(-32), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { AESUtils } from './crypto/AES';
2
2
  import { KeyPair, RSAUtils } from './crypto/RSA';
3
3
  import { ShamirClass } from './crypto/shamir';
4
- import { Delegation, Document, EncryptedEntity, EncryptedParentEntity, HealthcareParty, User } from '../icc-api/model/models';
4
+ import { Delegation, Device, Document, EncryptedEntity, EncryptedParentEntity, HealthcareParty, Patient, User } from '../icc-api/model/models';
5
5
  import { StorageFacade } from './storage/StorageFacade';
6
6
  import { KeyStorageFacade } from './storage/KeyStorageFacade';
7
7
  import { ExchangeKeysManager } from './crypto/ExchangeKeysManager';
@@ -11,7 +11,7 @@ import { DataOwner, IccDataOwnerXApi } from './icc-data-owner-x-api';
11
11
  import { EntitiesEncryption } from './crypto/EntitiesEncryption';
12
12
  import { IcureStorageFacade } from './storage/IcureStorageFacade';
13
13
  import { ShamirKeysManager } from './crypto/ShamirKeysManager';
14
- import { IccHcpartyApi } from '../icc-api';
14
+ import { IccHcpartyApi, IccPatientApi } from '../icc-api';
15
15
  import { ConfidentialEntities } from './crypto/ConfidentialEntities';
16
16
  interface DelegatorAndKeys {
17
17
  delegatorId: string;
@@ -19,6 +19,7 @@ interface DelegatorAndKeys {
19
19
  rawKey: string;
20
20
  }
21
21
  export declare class IccCryptoXApi {
22
+ private readonly basePatientApi;
22
23
  keychainLocalStoreIdPrefix: string;
23
24
  keychainValidityDateLocalStoreIdPrefix: string;
24
25
  hcpPreferenceKeyEhealthCert: string;
@@ -83,7 +84,7 @@ export declare class IccCryptoXApi {
83
84
  /**
84
85
  * @internal
85
86
  */
86
- constructor(exchangeKeysManager: ExchangeKeysManager, cryptoPrimitives: CryptoPrimitives, keyManager: KeyManager, dataOwnerApi: IccDataOwnerXApi, entitiesEncrypiton: EntitiesEncryption, shamirManager: ShamirKeysManager, storage: StorageFacade<string>, keyStorage: KeyStorageFacade, icureStorageFacade: IcureStorageFacade, hcPartyBaseApi: IccHcpartyApi, confidentialEntities: ConfidentialEntities);
87
+ constructor(exchangeKeysManager: ExchangeKeysManager, cryptoPrimitives: CryptoPrimitives, keyManager: KeyManager, dataOwnerApi: IccDataOwnerXApi, entitiesEncrypiton: EntitiesEncryption, shamirManager: ShamirKeysManager, storage: StorageFacade<string>, keyStorage: KeyStorageFacade, icureStorageFacade: IcureStorageFacade, hcPartyBaseApi: IccHcpartyApi, confidentialEntities: ConfidentialEntities, basePatientApi: IccPatientApi);
87
88
  /**
88
89
  * Deletes values cached by the crypto api, to allow to detect changes in stored key pairs, exchange keys and/or current data owner details.
89
90
  * This method may be useful in cases where a user is logged in from multiple devices or in cases where other users have just shared some data with
@@ -414,5 +415,15 @@ export declare class IccCryptoXApi {
414
415
  publicKey: any;
415
416
  privateKey: any;
416
417
  }): void;
418
+ /**
419
+ * @deprecated This method is not safe as it allows any data owner to add a public key to other data owners. The method will be removed in future,
420
+ * additionally the user calling this method will require a special permission when calling it for another data owner.
421
+ * @param ownerId the id of the data owner which will have a new key.
422
+ */
423
+ generateAndAddNewKeyPairForOwner(ownerId: string): Promise<{
424
+ dataOwner: HealthcareParty | Patient | Device;
425
+ publicKey: string;
426
+ privateKey: string;
427
+ }>;
417
428
  }
418
429
  export {};
@@ -86,7 +86,8 @@ class IccCryptoXApi {
86
86
  /**
87
87
  * @internal
88
88
  */
89
- constructor(exchangeKeysManager, cryptoPrimitives, keyManager, dataOwnerApi, entitiesEncrypiton, shamirManager, storage, keyStorage, icureStorageFacade, hcPartyBaseApi, confidentialEntities) {
89
+ constructor(exchangeKeysManager, cryptoPrimitives, keyManager, dataOwnerApi, entitiesEncrypiton, shamirManager, storage, keyStorage, icureStorageFacade, hcPartyBaseApi, confidentialEntities, basePatientApi) {
90
+ this.basePatientApi = basePatientApi;
90
91
  this.keychainLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain.';
91
92
  this.keychainValidityDateLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain-date.';
92
93
  this.hcpPreferenceKeyEhealthCert = 'eHealthCRTCrypt';
@@ -826,6 +827,46 @@ class IccCryptoXApi {
826
827
  storeKeyPair(id, keyPair) {
827
828
  this._storage.setItem(this.rsaLocalStoreIdPrefix + id, JSON.stringify(keyPair));
828
829
  }
830
+ /**
831
+ * @deprecated This method is not safe as it allows any data owner to add a public key to other data owners. The method will be removed in future,
832
+ * additionally the user calling this method will require a special permission when calling it for another data owner.
833
+ * @param ownerId the id of the data owner which will have a new key.
834
+ */
835
+ generateAndAddNewKeyPairForOwner(ownerId) {
836
+ var _a, _b;
837
+ return __awaiter(this, void 0, void 0, function* () {
838
+ const { dataOwner, type } = yield this.dataOwnerApi.getDataOwner(ownerId);
839
+ if (type === 'device')
840
+ throw new Error('Cannot add a key pair to a device');
841
+ const newPair = yield this.primitives.RSA.generateKeyPair();
842
+ const exportedPub = (0, binary_utils_1.ua2hex)(yield this.primitives.RSA.exportKey(newPair.publicKey, 'spki'));
843
+ const exportedPriv = (0, binary_utils_1.ua2hex)(yield this.primitives.RSA.exportKey(newPair.privateKey, 'pkcs8'));
844
+ let updatedPub;
845
+ if (dataOwner.publicKey == '') {
846
+ if (Object.keys((_a = dataOwner.hcPartyKeys) !== null && _a !== void 0 ? _a : {}).length > 0)
847
+ throw new Error(`Data owner ${ownerId} has empty public key but non-empty hcPartyKeys`);
848
+ updatedPub = exportedPub;
849
+ }
850
+ else {
851
+ updatedPub = (_b = dataOwner.publicKey) !== null && _b !== void 0 ? _b : exportedPub;
852
+ }
853
+ const updatedDataOwner = Object.assign(Object.assign({}, dataOwner), { publicKey: updatedPub, aesExchangeKeys: Object.assign(Object.assign({}, dataOwner.aesExchangeKeys), { [exportedPub]: {} }) });
854
+ let savedDataOwner;
855
+ if (type === 'patient') {
856
+ savedDataOwner = yield this.basePatientApi.modifyPatient(updatedDataOwner);
857
+ }
858
+ else if (type === 'hcp') {
859
+ savedDataOwner = yield this.hcpartyBaseApi.modifyHealthcareParty(updatedDataOwner);
860
+ }
861
+ else
862
+ throw new Error(`Unknown data owner type ${type}`);
863
+ return {
864
+ dataOwner: savedDataOwner,
865
+ publicKey: exportedPub,
866
+ privateKey: exportedPriv,
867
+ };
868
+ });
869
+ }
829
870
  }
830
871
  exports.IccCryptoXApi = IccCryptoXApi;
831
872
  //# sourceMappingURL=icc-crypto-x-api.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"icc-crypto-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-crypto-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,4BAA2B;AAE3B,uDAA6G;AAC7G,mCAAyE;AAoBzE,MAAa,aAAa;IAmBxB,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,gBAAgB,CAAA;IAC9B,CAAC;IAED;;OAEG;IACH,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,mBAAmB,CAAA;IACjC,CAAC;IAED;;OAEG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAA;IACrC,CAAC;IAED;;OAEG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAA;IACrC,CAAC;IAED;;OAEG;IACH,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAA;IAClC,CAAC;IAED;;OAEG;IACH,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAA;IAClC,CAAC;IAED;;OAEG;IACH,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,WAAW,CAAA;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,KAAK,EAAE,IAAA,qBAAM,EAAC,cAAc,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;YAC7G,IAAI;gBACF,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,aAAa,EAAE,OAAO,CAAC,CAAA;aACjE;YAAC,OAAO,CAAC,EAAE;gBACV,OAAO,OAAO,CAAA;aACf;QACH,CAAC;KAAA;IAED;;OAEG;IACH,YAAY,CAAC,EAAU,EAAE,OAA4C;QACnE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,qBAAqB,GAAG,EAAE,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAA;IACjF,CAAC;CACF;AAj6BD,sCAi6BC","sourcesContent":["/* eslint-disable */\nimport { AESUtils } from './crypto/AES'\nimport { KeyPair, RSAUtils } from './crypto/RSA'\nimport { ShamirClass } from './crypto/shamir'\nimport * as _ from 'lodash'\nimport { Delegation, Device, Document, EncryptedEntity, EncryptedParentEntity, HealthcareParty, Patient, User } from '../icc-api/model/models'\nimport { b2a, b64_2uas, hex2ua, string2ua, ua2hex, ua2string, ua2utf8, utf8_2ua } from './utils/binary-utils'\nimport { keyPairFromPrivateKeyJwk, pkcs8ToJwk, spkiToJwk } from './utils'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\nimport { ExchangeKeysManager } from './crypto/ExchangeKeysManager'\nimport { CryptoPrimitives } from './crypto/CryptoPrimitives'\nimport { KeyManager } from './crypto/KeyManager'\nimport { DataOwner, IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { EntitiesEncryption } from './crypto/EntitiesEncryption'\nimport { IcureStorageFacade } from './storage/IcureStorageFacade'\nimport { ShamirKeysManager } from './crypto/ShamirKeysManager'\nimport { IccHcpartyApi } from '../icc-api'\nimport { StorageEntryKeysFactory } from './storage/StorageEntryKeysFactory'\nimport { ConfidentialEntities } from './crypto/ConfidentialEntities'\n\ninterface DelegatorAndKeys {\n delegatorId: string\n key: CryptoKey\n rawKey: string\n}\n\nexport class IccCryptoXApi {\n keychainLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain.'\n keychainValidityDateLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain-date.'\n hcpPreferenceKeyEhealthCert = 'eHealthCRTCrypt'\n hcpPreferenceKeyEhealthCertDate = 'eHealthCRTDate'\n rsaLocalStoreIdPrefix = 'org.taktik.icure.rsa.'\n private readonly exchangeKeysManager: ExchangeKeysManager\n private readonly cryptoPrimitives: CryptoPrimitives\n private readonly keyManager: KeyManager\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly entitiesEncrypiton: EntitiesEncryption\n private readonly confidentialEntities: ConfidentialEntities\n private readonly icureStorage: IcureStorageFacade\n private readonly shamirManager: ShamirKeysManager\n private readonly _storage: StorageFacade<string>\n private readonly _keyStorage: KeyStorageFacade\n\n private readonly hcpartyBaseApi: IccHcpartyApi\n\n get primitives(): CryptoPrimitives {\n return this.cryptoPrimitives\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n get exchangeKeys(): ExchangeKeysManager {\n return this.exchangeKeysManager\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.crypto} at {@link primitives}.\n */\n get crypto(): Crypto {\n return this.cryptoPrimitives.crypto\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.shamir} at {@link primitives}.\n */\n get shamir(): ShamirClass {\n return this.cryptoPrimitives.shamir\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.RSA} at {@link primitives}.\n */\n get RSA(): RSAUtils {\n return this.cryptoPrimitives.RSA\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.AES} at {@link primitives}.\n */\n get AES(): AESUtils {\n return this.cryptoPrimitives.AES\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get keyStorage(): KeyStorageFacade {\n return this._keyStorage\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get storage(): StorageFacade<string> {\n return this._storage\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get entities(): EntitiesEncryption {\n return this.entitiesEncrypiton\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get confidential(): ConfidentialEntities {\n return this.confidentialEntities\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get userKeysManager(): KeyManager {\n return this.keyManager\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get shamirKeysManager(): ShamirKeysManager {\n return this.shamirManager\n }\n\n /**\n * @internal\n */\n constructor(\n exchangeKeysManager: ExchangeKeysManager,\n cryptoPrimitives: CryptoPrimitives,\n keyManager: KeyManager,\n dataOwnerApi: IccDataOwnerXApi,\n entitiesEncrypiton: EntitiesEncryption,\n shamirManager: ShamirKeysManager,\n storage: StorageFacade<string>,\n keyStorage: KeyStorageFacade,\n icureStorageFacade: IcureStorageFacade,\n hcPartyBaseApi: IccHcpartyApi,\n confidentialEntities: ConfidentialEntities\n ) {\n this.exchangeKeysManager = exchangeKeysManager\n this.cryptoPrimitives = cryptoPrimitives\n this.keyManager = keyManager\n this.dataOwnerApi = dataOwnerApi\n this.entitiesEncrypiton = entitiesEncrypiton\n this.shamirManager = shamirManager\n this._storage = storage\n this._keyStorage = keyStorage\n this.icureStorage = icureStorageFacade\n this.hcpartyBaseApi = hcPartyBaseApi\n this.confidentialEntities = confidentialEntities\n }\n\n /**\n * Deletes values cached by the crypto api, to allow to detect changes in stored key pairs, exchange keys and/or current data owner details.\n * This method may be useful in cases where a user is logged in from multiple devices or in cases where other users have just shared some data with\n * the current user for the first time.\n */\n async forceReload() {\n this.exchangeKeysManager.clearCache(true)\n this.dataOwnerApi.clearCurrentDataOwnerIdsCache()\n await this.keyManager.reloadKeys()\n }\n\n /**\n * Get all key pairs available for the decrpytion and encryption of data to the current data owner. These include the key pairs from the data owner\n * and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n getEncryptionDecryptionKeypairsForDataOwnerHierarchy(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey> }[]\n }[]\n }> {\n return this.keyManager.getCurrentUserHierarchyAvailableKeypairs()\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n return this.keyManager.getKeyPairForFingerprint(fingerprint)\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return this.keyManager.getCurrentUserHierarchyAvailablePublicKeysHex()\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n return this.keyManager.getCurrentUserAvailablePublicKeysHex(verifiedOnly)\n }\n\n /**\n * @deprecated depending on your use case you should delete the calls to this method or call {@link forceReload}:\n * - Replace with `forceReload()` if one of the following parts of the current data owner may have been modified from a different api instance:\n * - Hcp hierarchy\n * - Key recovery data (transfer keys or shamir)\n * - Exchange keys (formerly hcp keys)\n * - Remove the call if the main goal was to force reload the data owner: data owner are not cached anymore.\n */\n emptyHcpCache(hcpartyId: string) {\n this.exchangeKeysManager.clearCache(false)\n }\n\n /**\n * @deprecated you should not need this method anymore to deal with the encryption of iCure entities because everything related to entities\n * encryption should be done either through the entity-specific extended api or through the extended apis.\n * Note that keys returned by the current implementation of this method may not be safe for encryption/sharing.\n * If instead you are using this method to retrieve key pairs for other purposes, for example because you want to reuse the user keys in iCure for\n * other services consider the following alternatives:\n * - If you want to use all iCure facilities including key recovery and key verification you can use {@link getKeyPairForFingerprint}.\n * Note that this solution can only give access to keys for the data owner of the instantiated api and his parents.\n * - Alternatively you can use directly your choice of {@link KeyStorageFacade} and {@link StorageEntryKeysFactory}: if these are the same you use\n * for the iCure API client the keys will be shared with it. Note however that the iCure api client uses\n * {@link StorageEntryKeysFactory.cachedRecoveredKeypairOfDataOwner} to cache recovered keys of a data owner which may not have originated from\n * this device, so you should only use {@link StorageEntryKeysFactory.deviceKeypairOfDataOwner} if you want to make sure the keys you use are safe\n * for encryption.\n */\n async getCachedRsaKeyPairForFingerprint(\n dataOwnerId: string,\n pubKeyOrFingerprint: string\n ): Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }> {\n const fingerprint = pubKeyOrFingerprint.slice(-32)\n const res = this.keyManager.getDecryptionKeys()[fingerprint]\n if (!res) console.warn(`Could not find any keypair for fingerprint ${fingerprint}`)\n return res\n }\n\n /**\n * @deprecated You do not need this method to encrypt/decrypt data of iCure, but if you want to reuse the iCure keys for the user for other purposes\n * you have different options to replace this method, depending on what you actually need. All options return the hex-encoded spki representation of\n * the public keys.\n * - If you want only the public keys for which we have a private key available\n * - you can replicate the current behaviour using {@link getCurrentUserHierarchyAvailablePublicKeysHex}. This includes keys for the current user\n * and his parents.\n * - use {@link getCurrentUserAvailablePublicKeysHex} to get public keys only for the current data owner, ignoring any keys of the\n * parent hierarchy. In this case you can also apply a filter to only get verified keys (safe for encryption).\n * - If you need all public keys for the data owner, including those for which there is no corresponding private key available on the device use\n * {@link IccDataOwnerXApi.getHexPublicKeysOf} with the current data owner. If you don't have it available you may get it from\n * {@link IccDataOwnerXApi.getCurrentDataOwner}, but this will require to do a request to the iCure server (other options use only cached data).\n */\n async getPublicKeys(): Promise<string[]> {\n return this.userKeysManager.getCurrentUserHierarchyAvailablePublicKeysHex()\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.randomUuid} at {@link primitives}.\n */\n randomUuid() {\n return this.primitives.randomUuid()\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.sha256} at {@link primitives}.\n */\n sha256(data: ArrayBuffer | Uint8Array) {\n return this.primitives.sha256(data)\n }\n\n /**\n * @deprecated Use {@link ShamirKeysManager.updateSelfSplits} from {@link shamirKeysManager} instead. Note that the new method completely replaces\n * all current values if a split for the provided key already exists.\n */\n async encryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>, threshold?: number): Promise<HealthcareParty> {\n const legacyKeyFp = hcp.publicKey?.slice(-32)\n if (!legacyKeyFp) throw new Error(`No legacy/default key for hcp ${hcp.id}`)\n await this.shamirKeysManager.updateSelfSplits(\n { [legacyKeyFp]: { notariesIds: notaries.map((x) => x.id!), minShares: threshold ?? notaries.length } },\n []\n )\n return (await this.dataOwnerApi.getDataOwner(hcp.id!)).dataOwner as HealthcareParty\n }\n\n /**\n * @deprecated You should not need this method anymore because the api will automatically try to recover the available shamir keys on startup.\n */\n async decryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>): Promise<void> {\n try {\n const publicKeys = await this.getPublicKeys()\n const nLen = notaries.length\n let decryptedPrivatedKey\n if (nLen == 1) {\n const notaryHcPartyId = notaries[0].id!\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notaryHcPartyId)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notaryHcPartyId, hcp.id!, notaryHcPartyId, idPubKey, keysMap, publicKeys)\n )\n )\n const cryptedPrivatedKey = hcp.privateKeyShamirPartitions![notaryHcPartyId]\n decryptedPrivatedKey = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(cryptedPrivatedKey)\n )\n )\n } else {\n const decryptedShares: string[] = await _.reduce(\n notaries,\n (queue, notary) => {\n return queue.then(async (shares: string[]) => {\n try {\n // now, we get the encrypted shares in db and decrypt them. This assumes that the\n // the notaries' private keys are in localstorage. We should implement a way for the notaries to\n // give hcp the decrypted shares without having to also share their private keys.\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notary.id!)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notary.id!, hcp.id!, notary.id!, idPubKey, keysMap, publicKeys)\n )\n )\n const encryptedShare = hcp.privateKeyShamirPartitions![notary.id!]\n const decryptedShamirPartition = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(encryptedShare)\n )\n )\n shares.push(decryptedShamirPartition)\n } catch (e) {\n console.log('Error during encryptedShamirRSAKey', notary.id, e)\n }\n return shares\n })\n },\n Promise.resolve([] as string[])\n )\n\n decryptedPrivatedKey = this.primitives.shamir.combine(decryptedShares)\n }\n\n const importedPrivateKey = await this.primitives.RSA.importKey('pkcs8', hex2ua(decryptedPrivatedKey), ['decrypt'])\n const importedPublicKey = await this.primitives.RSA.importKey('spki', hex2ua(hcp.publicKey!), ['encrypt'])\n\n const exportedKeyPair = await this.primitives.RSA.exportKeys({ publicKey: importedPublicKey, privateKey: importedPrivateKey }, 'jwk', 'jwk')\n await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${hcp.id!}`, exportedKeyPair)\n } catch (e) {\n console.log('Cannot decrypt shamir RSA key')\n }\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n * Note that currently this method does not cache results anymore (but the updated methods do).\n */\n async decryptHcPartyKey(\n loggedHcPartyId: string,\n delegatorId: string,\n delegateHcPartyId: string,\n publicKey: string,\n encryptedHcPartyKeys: { [key: string]: string },\n publicKeys: string[]\n ): Promise<DelegatorAndKeys> {\n if (!publicKeys.length) {\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: no public key`\n console.warn(reason)\n throw new Error(reason)\n }\n const keysFpSet = new Set(publicKeys.map((x) => x.slice(-32)))\n const filteredKeys = Object.fromEntries(Object.entries(this.keyManager.getDecryptionKeys()).filter(([fp]) => keysFpSet.has(fp)))\n const decrypted = await this.exchangeKeysManager.base.tryDecryptExchangeKeys([encryptedHcPartyKeys], filteredKeys)\n const res = decrypted.successfulDecryptions[0]\n if (!res) {\n const error =\n `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: impossible to decrypt. ` +\n 'No private key was found or could be used to decrypt the aes exchange keys`'\n console.warn(error)\n throw new Error(error)\n }\n return {\n delegatorId,\n key: res,\n rawKey: ua2hex(await this.primitives.AES.exportKey(res, 'raw')),\n }\n }\n\n /**\n * @deprecated you should not need this method anymore. The new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If no verified key (safe for encryption) can be found during the instantiation\n * of the API, depending on the parameters passed to the factory one of two scenarios will happen:\n * - A new key will be automatically created on the device and stored using the key storage facade.\n * - The api instantiation fails with an exception. This is ideal if you want to try to recover an existing key pair before creating a new one.\n *\n * If you were using this method to allow the user to recover an existing key that is not available in the storage facade nor recoverable through\n * transfer keys or shamir split (for example by scanning a qr code, or by loading a file from the computer to the web browser's local storage)\n * you will have to move that logic in your implementation of CryptoStrategies.\n * It is currently not allowed to create new key pairs if a verified key pair is already available on the device, as this would be wasteful.\n * If you want to convert a `JsonWebKey` pair to a `CryptoKey` pair you should use directly the method in `primitives.RSA`.\n */\n async cacheKeyPair(keyPairInJwk: KeyPair<JsonWebKey>): Promise<KeyPair<CryptoKey>> {\n const cryptoKeyPair = await this.primitives.RSA.importKeyPair('jwk', keyPairInJwk.privateKey, 'jwk', keyPairInJwk.publicKey)\n const pubHex = ua2hex(await this.primitives.RSA.exportKey(cryptoKeyPair.publicKey, 'spki'))\n const fingerprint = pubHex.slice(-32)\n if (!this.keyManager.getDecryptionKeys()[fingerprint]) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const selfKeys = this.dataOwnerApi.getHexPublicKeysOf((await this.dataOwnerApi.getCurrentDataOwner()).dataOwner)\n if (!selfKeys.has(pubHex))\n throw new Error(\n `Impossible to add key pair with fingerprint ${fingerprint} to data owner ${selfId}: the data owner has no matching public key`\n )\n await this.icureStorage.saveKey(selfId, fingerprint, keyPairInJwk, true)\n // Force reload to check if more private keys can be recovered or more exchange keys become available.\n await this.forceReload()\n }\n return cryptoKeyPair\n }\n\n /**\n * @deprecated Usually you should not need this method, since the preferred sfk is automatically chosen by the extended entity apis when creating a\n * new instance of the entity.\n */\n async extractPreferredSfk(parent: EncryptedParentEntity, hcpartyId: string, confidential: boolean) {\n return confidential ? this.confidential.getConfidentialSecretId(parent, hcpartyId) : this.confidential.getAnySecretIdSharedWithParents(parent)\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n */\n async decryptAndImportAesHcPartyKeysForDelegators(\n delegatorsHcPartyIdsSet: Array<string>,\n delegateHcPartyId: string,\n minCacheDurationInSeconds: number = 60\n ): Promise<Array<DelegatorAndKeys>> {\n return await delegatorsHcPartyIdsSet.reduce(async (acc, delegator) => {\n const awaitedAcc = await acc\n const keys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegator, delegateHcPartyId)\n const keysForDelegator = await keys.reduce(async (accForKey, cryptoKey) => {\n const awaitedAccForKey = await accForKey\n const rawKey = ua2hex(await this.primitives.RSA.exportKey(cryptoKey, 'spki'))\n return [\n ...awaitedAccForKey,\n {\n key: cryptoKey,\n delegatorId: delegator,\n rawKey: rawKey,\n },\n ]\n }, Promise.resolve([] as DelegatorAndKeys[]))\n return [...awaitedAcc, ...keysForDelegator]\n }, Promise.resolve([] as DelegatorAndKeys[]))\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n * Note that currently this method does not cache results anymore (but the updated methods do).\n */\n async getEncryptedAesExchangeKeys(\n owner: DataOwner,\n delegateId: string\n ): Promise<{ [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } }> {\n const publicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(owner))\n const mapOfAesExchangeKeys = Object.entries(owner.aesExchangeKeys ?? {})\n .filter((e) => e[1][delegateId] && Object.keys(e[1][delegateId]).some((k1) => publicKeys.some((pk) => pk.endsWith(k1))))\n .reduce((map, e) => {\n const candidates = Object.entries(e[1][delegateId]) //[fingerprint of delegate pub key, key], [fingerprint of owner pub key, key]\n const [publicKeyFingerprint, encryptedAesExchangeKey] = candidates[candidates.findIndex(([k, v]) => publicKeys.some((pk) => pk.endsWith(k)))]\n return { ...map, [e[0]]: { [publicKeyFingerprint]: encryptedAesExchangeKey } }\n }, {} as { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } })\n\n if (!owner.publicKey || mapOfAesExchangeKeys[owner.publicKey] || !owner.hcPartyKeys?.[delegateId]) {\n return mapOfAesExchangeKeys\n }\n const delegate = (await this.dataOwnerApi.getDataOwner(delegateId)).dataOwner\n if (delegate.publicKey && publicKeys.includes(delegate.publicKey)) {\n return {\n ...mapOfAesExchangeKeys,\n [owner.publicKey]: { [delegate.publicKey!.slice(-32)]: owner.hcPartyKeys[delegateId][1] },\n }\n } else if (publicKeys.includes(owner.publicKey)) {\n return { ...mapOfAesExchangeKeys, [owner.publicKey]: { [owner.publicKey.slice(-32)]: owner.hcPartyKeys[delegateId][0] } }\n }\n return mapOfAesExchangeKeys\n }\n\n /**\n * @deprecated you should not use this method because initialisation of encrypted entities keys is done automatically by the entity-specific\n * extended api. Also note that it is now forbidden to initialise an entity as a data owner which is not the current data owner: you should instead\n * create the entity as the current data owner then create a delegation to the other data owner.\n */\n async initEncryptionKeys(\n createdObject: any,\n ownerId: string\n ): Promise<{\n encryptionKeys: any\n secretId: string\n }> {\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n throw new Error('Impossible to initialise keys as a data owner which is not the current data owner')\n }\n const { updatedEntity, rawEncryptionKey } = await this.entities.entityWithInitialisedEncryptedMetadata(\n {\n ...createdObject,\n delegations: undefined,\n encryptionKeys: undefined,\n cryptedForeignKeys: undefined,\n secretForeignKeys: undefined,\n } as EncryptedEntity,\n undefined,\n undefined,\n true\n )\n return {\n encryptionKeys: updatedEntity.encryptionKeys,\n secretId: rawEncryptionKey!,\n }\n }\n\n /**\n * @deprecated You should use:\n * - {@link IccPatientXApi.decryptSecretIdsOf} or {@link IccMessageXApi.decryptSecretIdsOf} to get the delegation sfks (now caleld secret ids).\n * - {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds} to get the full hierarchy for the current data owner (cached). The first element is\n * the id of the topmost parent, while the last is the current data owner.\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractDelegationsSFKs(document: EncryptedEntity | null, hcpartyId?: string): Promise<{ extractedKeys: Array<string>; hcpartyId?: string }> {\n if (!document || !hcpartyId) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const delegationsForAllDelegates = document.delegations\n if (!delegationsForAllDelegates || !Object.keys(delegationsForAllDelegates).length) {\n console.log(`There is no delegation in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.secretIdsOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated (light) You should use:\n * - {@link IccHelementXApi.decryptPatientIdOf}, {@link IccDocumentXApi.decryptMessageIdOf}, ... to get the crypted foreign keys.\n * - {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds} to get the full hierarchy for the current data owner (cached). The first element is\n * the id of the topmost parent, while the last is the current data owner.\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractCryptedFKs(document: EncryptedEntity | null, hcpartyId: string): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document || !document.cryptedForeignKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const cfksForAllDelegates = document.cryptedForeignKeys\n if (!cfksForAllDelegates || !Object.keys(cfksForAllDelegates).length) {\n console.log(`There is no cryptedForeignKeys in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.owningEntityIdsOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated You should use the extended apis methods to encrypt/decrypt entities or their attachments\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractEncryptionsSKs(document: EncryptedEntity, hcpartyId: string): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document.encryptionKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const eckeysForAllDelegates = document.encryptionKeys\n if (!eckeysForAllDelegates || !Object.keys(eckeysForAllDelegates).length) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.encryptionKeysOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated You should not use this method anymore, depending on what you were passing as {@link delegations} you should replace this method as\n * explained in {@link extractEncryptionsSKs} (if you were passing encryptionKeys), {@link extractCryptedFKs} (cryptedForeignKeys), or\n * {@link extractDelegationsSFKs} (delegations).\n */\n async extractKeysFromDelegationsForHcpHierarchy(\n dataOwnerId: string,\n objectId: string,\n delegations: { [key: string]: Array<Delegation> }\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n return {\n extractedKeys: await this.entities.extractMergedHierarchyFromDelegationAndOwner(\n delegations,\n dataOwnerId,\n (x) => !!x,\n () => Promise.resolve(true)\n ),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n * You can convert the private key pkcs8 array to a jwk key using {@link pkcs8ToJwk} then you can extract the full key pair using\n * {@link keyPairFromPrivateKeyJwk}.\n */\n async loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId: string, privateKey: Uint8Array) {\n await this.cacheKeyPair(keyPairFromPrivateKeyJwk(pkcs8ToJwk(privateKey)))\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n * You can extract the full key pair using {@link keyPairFromPrivateKeyJwk}.\n */\n async loadKeyPairsAsJwkInBrowserLocalStorage(healthcarePartyId: string, privateKey: JsonWebKey) {\n await this.cacheKeyPair(keyPairFromPrivateKeyJwk(privateKey))\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n */\n loadKeyPairsInBrowserLocalStorage(healthcarePartyId: string, file: Blob): Promise<void> {\n const fr = new FileReader()\n return new Promise((resolve, reject) => {\n fr.onerror = reject\n fr.onabort = reject\n fr.onload = (e: any) => {\n const privateKey = e.target.result as string\n this.loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId, hex2ua(privateKey))\n .then(() => resolve())\n .catch(reject)\n }\n fr.readAsText(file)\n })\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n saveKeychainInBrowserLocalStorage(id: string, keychain: number) {\n this._storage.setItem(\n this.keychainLocalStoreIdPrefix + id,\n b2a(new Uint8Array(keychain).reduce((data, byte) => data + String.fromCharCode(byte), ''))\n )\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n saveKeychainInBrowserLocalStorageAsBase64(id: string, keyChainB64: string) {\n this._storage.setItem(this.keychainLocalStoreIdPrefix + id, keyChainB64)\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n async saveKeychainValidityDateInBrowserLocalStorage(id: string, date: string) {\n if (!id) return\n\n if (!date) {\n await this._storage.removeItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n } else {\n await this._storage.setItem(this.keychainValidityDateLocalStoreIdPrefix + id, date)\n }\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n *\n * Populate the HCP.options dict with an encrypted eHealth certificate and unencryped expiry date.\n * Any potentially unencrypted certificates will be pruned from the HCP.\n * @param hcpId Id of the hcp to modify\n * @returns modified HCP\n */\n async saveKeyChainInHCPFromLocalStorage(hcpId: string): Promise<HealthcareParty> {\n return await this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let aesKey: CryptoKey | null = null\n try {\n aesKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!aesKey) {\n console.error('No encryption key!')\n }\n\n const opts = hcp.options || {}\n\n const crt = await this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!!)\n if (!!aesKey && !!crt) {\n let crtEncrypted: ArrayBuffer | null = null\n try {\n crtEncrypted = await this.AES.encrypt(aesKey, new Uint8Array(string2ua(atob(crt))))\n } catch (e) {\n console.error('Error while encrypting the certificate', e)\n }\n\n // add the encrypted certificate to the options\n _.set(opts, this.hcpPreferenceKeyEhealthCert, ua2string(new Uint8Array(crtEncrypted!)))\n }\n\n const crtValidityDate = this.getKeychainValidityDateInBrowserLocalStorage(hcp.id!!)\n if (!!crtValidityDate) {\n _.set(opts, this.hcpPreferenceKeyEhealthCertDate, crtValidityDate)\n }\n\n hcp.options = opts\n return hcp\n })\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n importKeychainInBrowserFromHCP(hcpId: string): Promise<void> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let crtCryp: Uint8Array | null = null\n if (!!hcp.options && !!hcp.options[this.hcpPreferenceKeyEhealthCert]) {\n crtCryp = string2ua(hcp.options[this.hcpPreferenceKeyEhealthCert])\n }\n\n const crtValidityDate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCertDate)\n\n // store the validity date\n if (!!crtValidityDate) {\n this.saveKeychainValidityDateInBrowserLocalStorage(hcp.id!!, crtValidityDate)\n }\n\n let crt: ArrayBuffer | null = null\n let decryptionKey: CryptoKey | null = null\n try {\n decryptionKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!decryptionKey) {\n throw new Error('No encryption key! eHealth certificate cannot be decrypted.')\n }\n\n if (!!crtCryp && decryptionKey) {\n try {\n crt = await this.AES.decrypt(decryptionKey, crtCryp)\n } catch (e) {\n console.error(e)\n }\n }\n\n if (!crt) {\n throw new Error(`Error while saving certificate in browser local storage! Hcp ${hcp.id} has no certificate.`)\n } else {\n this.saveKeychainInBrowserLocalStorageAsBase64(hcp.id!!, btoa(String.fromCharCode.apply(null, Array.from(new Uint8Array(crt)))))\n }\n\n return\n })\n }\n\n /**\n * @deprecated e-health certificates and keychains are not part of iCure's api: this method will be removed.\n *\n * Synchronizes the eHealth certificate from the database into the LocalStorage, returning information on the presence\n * of certificate data in either place.\n *\n * @param hcpId The healthcare party id\n * @returns A Promise for an object that represents the existence of a certificate in local storage and in the DB,\n * through the two boolean properties \"local\" and \"remote\".\n */\n syncEhealthCertificateFromDatabase(hcpId: string): Promise<{ remote: boolean; local: boolean }> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then((hcp: HealthcareParty) => {\n const remoteCertificate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCert)\n const localCertificate = this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!)\n\n if (remoteCertificate) {\n return this.importKeychainInBrowserFromHCP(hcp.id!)\n .then(() => ({ local: true, remote: true }))\n .catch(() => ({ local: !!localCertificate, remote: true }))\n } else {\n return { local: !!localCertificate, remote: !!remoteCertificate }\n }\n })\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n getKeychainInBrowserLocalStorageAsBase64(id: string) {\n return this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n getKeychainValidityDateInBrowserLocalStorage(id: string) {\n return this._storage.getItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n async loadKeychainFromBrowserLocalStorage(id: string) {\n const lsItem = await this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n return lsItem !== undefined ? b64_2uas(lsItem) : null\n }\n\n /**\n * @deprecated you should not need this method anymore to deal with the encryption of iCure entities because everything related to entities\n * encryption should be done through the entity-specific extended api.\n * If instead you were using the method for other reasons check {@link getCachedRsaKeyPairForFingerprint} to get an idea of possible replacements.\n */\n async loadKeyPairNotImported(id: string, publicKeyFingerPrint?: string): Promise<{ publicKey: JsonWebKey; privateKey: JsonWebKey } | undefined> {\n if (publicKeyFingerPrint) {\n const cached = this.keyManager.getKeyPairForFingerprint(publicKeyFingerPrint)?.pair\n if (cached) {\n return this.primitives.RSA.exportKeys(cached, 'jwk', 'jwk')\n }\n } else {\n const defaultKey = await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id)\n if (defaultKey) return defaultKey\n }\n console.warn(`No key can be found in local storage for id ${id} and publicKeyFingerPrint ${publicKeyFingerPrint}`)\n }\n\n /**\n * @deprecated use {@link IccIcureMaintenanceXApi.applyKeyPairUpdate} instead.\n */\n async giveAccessBackTo(delegateUser: User, ownerId: string, ownerNewPublicKey: string): Promise<DataOwner> {\n await this.exchangeKeys.base.giveAccessBackTo(ownerId, ownerNewPublicKey, this.userKeysManager.getDecryptionKeys())\n return this.dataOwnerApi.getDataOwner(ownerId).then((x) => x.dataOwner)\n }\n /**\n * @deprecated You don't need to manually generate exchange keys as they will be automatically created by the api when needed.\n * Note that this method has some changes compared to previous version:\n * - The method may return any data owner (including devices)\n * - The method will throw an exception if the provided ownerId does not match the current data owner\n */\n async generateKeyForDelegate(ownerId: string, delegateId: string): Promise<DataOwner> {\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n throw new Error('You can only create delegation where the delegator is the current data owner')\n }\n return (await this.dataOwnerApi.getDataOwner(ownerId)).dataOwner\n }\n\n /**\n * @deprecated replace with {@link IccDataOwnerXApi.getDataOwner}. Note that data owners are not cached anymore.\n */\n getDataOwner(ownerId: string, loadIfMissingFromCache: boolean = true) {\n return this.dataOwnerApi.getDataOwner(ownerId)\n }\n\n /**\n * @deprecated the crypto api will automatically verify on startup the validity of private keys, but in some cases you may want to verify the\n * validity of keys recovered in your implementation of {@link CryptoStrategies}: in this case the method has been replaced with\n * {@link RSA.checkKeyPairValidity}\n */\n async checkPrivateKeyValidity(dataOwner: DataOwner): Promise<boolean> {\n const publicKeys = Array.from(new Set([dataOwner.publicKey].concat(Object.keys(dataOwner.aesExchangeKeys ?? {})).filter((x) => !!x))) as string[]\n\n return await publicKeys.reduce(async (pres, publicKey) => {\n const res = await pres\n try {\n const k = await this.primitives.RSA.importKey('jwk', spkiToJwk(hex2ua(publicKey)), ['encrypt'])\n const cipher = await this.primitives.RSA.encrypt(k, utf8_2ua('shibboleth'))\n const ikp = await this.getCachedRsaKeyPairForFingerprint(dataOwner.id!, publicKey.slice(-32))\n const plainText = ua2utf8(await this.primitives.RSA.decrypt(ikp.privateKey, new Uint8Array(cipher)))\n return plainText === 'shibboleth' || res\n } catch (e) {\n return res\n }\n }, Promise.resolve(false))\n }\n\n /**\n * @deprecated (See {@link extractEncryptionsSKs} for a detailed explanation).\n */\n async getEncryptionDecryptionKeys(dataOwnerId: string, document: EncryptedEntity): Promise<Array<string> | undefined> {\n return this.entities.encryptionKeysOf(document, dataOwnerId)\n }\n\n /**\n * @deprecated For the encryption/decryption of iCure entities and attachments you should rely solely on the extended apis methods.\n */\n async encryptDecrypt(\n method: 'encrypt' | 'decrypt',\n content: Uint8Array | ArrayBuffer,\n edKey?: string,\n user?: User,\n documentObject?: Document\n ): Promise<Uint8Array | Array<any> | any> {\n if (!content || !(edKey || (user?.healthcarePartyId && documentObject))) return content\n\n if (edKey) {\n const importedEdKey = await this.primitives.AES.importKey('raw', hex2ua(edKey.replace(/-/g, '')))\n try {\n return await this.primitives.AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n const encryptionKeys = await this.entities.encryptionKeysOf(documentObject!, user?.healthcarePartyId!)\n const importedEdKey = await this.primitives.AES.importKey('raw', hex2ua(encryptionKeys[0].replace(/-/g, '')))\n try {\n return await this.primitives.AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n /**\n * @deprecated you should not need to interact directly with the storage instance used by the iCure sdk.\n */\n storeKeyPair(id: string, keyPair: { publicKey: any; privateKey: any }) {\n this._storage.setItem(this.rsaLocalStoreIdPrefix + id, JSON.stringify(keyPair))\n }\n}\n"]}
1
+ {"version":3,"file":"icc-crypto-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-crypto-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,4BAA2B;AAE3B,uDAA6G;AAC7G,mCAAyE;AAoBzE,MAAa,aAAa;IAmBxB,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,gBAAgB,CAAA;IAC9B,CAAC;IAED;;OAEG;IACH,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,mBAAmB,CAAA;IACjC,CAAC;IAED;;OAEG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAA;IACrC,CAAC;IAED;;OAEG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAA;IACrC,CAAC;IAED;;OAEG;IACH,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAA;IAClC,CAAC;IAED;;OAEG;IACH,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAA;IAClC,CAAC;IAED;;OAEG;IACH,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,WAAW,CAAA;IACzB,CAAC;IAED;;OAEG;IACH,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAA;IACtB,CAAC;IAED;;OAEG;IACH,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,kBAAkB,CAAA;IAChC,CAAC;IAED;;OAEG;IACH,IAAI,YAAY;QACd,OAAO,I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M;gBACL,UAAU,GAAG,MAAA,SAAS,CAAC,SAAS,mCAAI,WAAW,CAAA;aAChD;YACD,MAAM,gBAAgB,mCACjB,SAAS,KACZ,SAAS,EAAE,UAAU,EACrB,eAAe,kCACV,SAAS,CAAC,eAAe,KAC5B,CAAC,WAAW,CAAC,EAAE,EAAE,MAEpB,CAAA;YACD,IAAI,cAAyC,CAAA;YAC7C,IAAI,IAAI,KAAK,SAAS,EAAE;gBACtB,cAAc,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,aAAa,CAAC,gBAA2B,CAAC,CAAA;aACtF;iBAAM,IAAI,IAAI,KAAK,KAAK,EAAE;gBACzB,cAAc,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,qBAAqB,CAAC,gBAAmC,CAAC,CAAA;aACtG;;gBAAM,MAAM,IAAI,KAAK,CAAC,2BAA2B,IAAI,EAAE,CAAC,CAAA;YACzD,OAAO;gBACL,SAAS,EAAE,cAAc;gBACzB,SAAS,EAAE,WAAW;gBACtB,UAAU,EAAE,YAAY;aACzB,CAAA;;KACF;CACF;AA38BD,sCA28BC","sourcesContent":["/* eslint-disable */\nimport { AESUtils } from './crypto/AES'\nimport { KeyPair, RSAUtils } from './crypto/RSA'\nimport { ShamirClass } from './crypto/shamir'\nimport * as _ from 'lodash'\nimport { Delegation, Device, Document, EncryptedEntity, EncryptedParentEntity, HealthcareParty, Patient, User } from '../icc-api/model/models'\nimport { b2a, b64_2uas, hex2ua, string2ua, ua2hex, ua2string, ua2utf8, utf8_2ua } from './utils/binary-utils'\nimport { keyPairFromPrivateKeyJwk, pkcs8ToJwk, spkiToJwk } from './utils'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\nimport { ExchangeKeysManager } from './crypto/ExchangeKeysManager'\nimport { CryptoPrimitives } from './crypto/CryptoPrimitives'\nimport { KeyManager } from './crypto/KeyManager'\nimport { DataOwner, IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { EntitiesEncryption } from './crypto/EntitiesEncryption'\nimport { IcureStorageFacade } from './storage/IcureStorageFacade'\nimport { ShamirKeysManager } from './crypto/ShamirKeysManager'\nimport { IccHcpartyApi, IccPatientApi } from '../icc-api'\nimport { StorageEntryKeysFactory } from './storage/StorageEntryKeysFactory'\nimport { ConfidentialEntities } from './crypto/ConfidentialEntities'\n\ninterface DelegatorAndKeys {\n delegatorId: string\n key: CryptoKey\n rawKey: string\n}\n\nexport class IccCryptoXApi {\n keychainLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain.'\n keychainValidityDateLocalStoreIdPrefix = 'org.taktik.icure.ehealth.keychain-date.'\n hcpPreferenceKeyEhealthCert = 'eHealthCRTCrypt'\n hcpPreferenceKeyEhealthCertDate = 'eHealthCRTDate'\n rsaLocalStoreIdPrefix = 'org.taktik.icure.rsa.'\n private readonly exchangeKeysManager: ExchangeKeysManager\n private readonly cryptoPrimitives: CryptoPrimitives\n private readonly keyManager: KeyManager\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly entitiesEncrypiton: EntitiesEncryption\n private readonly confidentialEntities: ConfidentialEntities\n private readonly icureStorage: IcureStorageFacade\n private readonly shamirManager: ShamirKeysManager\n private readonly _storage: StorageFacade<string>\n private readonly _keyStorage: KeyStorageFacade\n\n private readonly hcpartyBaseApi: IccHcpartyApi\n\n get primitives(): CryptoPrimitives {\n return this.cryptoPrimitives\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n get exchangeKeys(): ExchangeKeysManager {\n return this.exchangeKeysManager\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.crypto} at {@link primitives}.\n */\n get crypto(): Crypto {\n return this.cryptoPrimitives.crypto\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.shamir} at {@link primitives}.\n */\n get shamir(): ShamirClass {\n return this.cryptoPrimitives.shamir\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.RSA} at {@link primitives}.\n */\n get RSA(): RSAUtils {\n return this.cryptoPrimitives.RSA\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.AES} at {@link primitives}.\n */\n get AES(): AESUtils {\n return this.cryptoPrimitives.AES\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get keyStorage(): KeyStorageFacade {\n return this._keyStorage\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get storage(): StorageFacade<string> {\n return this._storage\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get entities(): EntitiesEncryption {\n return this.entitiesEncrypiton\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get confidential(): ConfidentialEntities {\n return this.confidentialEntities\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get userKeysManager(): KeyManager {\n return this.keyManager\n }\n\n /**\n * @internal this is for internal use only and may be changed without notice.\n */\n get shamirKeysManager(): ShamirKeysManager {\n return this.shamirManager\n }\n\n /**\n * @internal\n */\n constructor(\n exchangeKeysManager: ExchangeKeysManager,\n cryptoPrimitives: CryptoPrimitives,\n keyManager: KeyManager,\n dataOwnerApi: IccDataOwnerXApi,\n entitiesEncrypiton: EntitiesEncryption,\n shamirManager: ShamirKeysManager,\n storage: StorageFacade<string>,\n keyStorage: KeyStorageFacade,\n icureStorageFacade: IcureStorageFacade,\n hcPartyBaseApi: IccHcpartyApi,\n confidentialEntities: ConfidentialEntities,\n private readonly basePatientApi: IccPatientApi\n ) {\n this.exchangeKeysManager = exchangeKeysManager\n this.cryptoPrimitives = cryptoPrimitives\n this.keyManager = keyManager\n this.dataOwnerApi = dataOwnerApi\n this.entitiesEncrypiton = entitiesEncrypiton\n this.shamirManager = shamirManager\n this._storage = storage\n this._keyStorage = keyStorage\n this.icureStorage = icureStorageFacade\n this.hcpartyBaseApi = hcPartyBaseApi\n this.confidentialEntities = confidentialEntities\n }\n\n /**\n * Deletes values cached by the crypto api, to allow to detect changes in stored key pairs, exchange keys and/or current data owner details.\n * This method may be useful in cases where a user is logged in from multiple devices or in cases where other users have just shared some data with\n * the current user for the first time.\n */\n async forceReload() {\n this.exchangeKeysManager.clearCache(true)\n this.dataOwnerApi.clearCurrentDataOwnerIdsCache()\n await this.keyManager.reloadKeys()\n }\n\n /**\n * Get all key pairs available for the decrpytion and encryption of data to the current data owner. These include the key pairs from the data owner\n * and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n getEncryptionDecryptionKeypairsForDataOwnerHierarchy(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey> }[]\n }[]\n }> {\n return this.keyManager.getCurrentUserHierarchyAvailableKeypairs()\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n return this.keyManager.getKeyPairForFingerprint(fingerprint)\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return this.keyManager.getCurrentUserHierarchyAvailablePublicKeysHex()\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n return this.keyManager.getCurrentUserAvailablePublicKeysHex(verifiedOnly)\n }\n\n /**\n * @deprecated depending on your use case you should delete the calls to this method or call {@link forceReload}:\n * - Replace with `forceReload()` if one of the following parts of the current data owner may have been modified from a different api instance:\n * - Hcp hierarchy\n * - Key recovery data (transfer keys or shamir)\n * - Exchange keys (formerly hcp keys)\n * - Remove the call if the main goal was to force reload the data owner: data owner are not cached anymore.\n */\n emptyHcpCache(hcpartyId: string) {\n this.exchangeKeysManager.clearCache(false)\n }\n\n /**\n * @deprecated you should not need this method anymore to deal with the encryption of iCure entities because everything related to entities\n * encryption should be done either through the entity-specific extended api or through the extended apis.\n * Note that keys returned by the current implementation of this method may not be safe for encryption/sharing.\n * If instead you are using this method to retrieve key pairs for other purposes, for example because you want to reuse the user keys in iCure for\n * other services consider the following alternatives:\n * - If you want to use all iCure facilities including key recovery and key verification you can use {@link getKeyPairForFingerprint}.\n * Note that this solution can only give access to keys for the data owner of the instantiated api and his parents.\n * - Alternatively you can use directly your choice of {@link KeyStorageFacade} and {@link StorageEntryKeysFactory}: if these are the same you use\n * for the iCure API client the keys will be shared with it. Note however that the iCure api client uses\n * {@link StorageEntryKeysFactory.cachedRecoveredKeypairOfDataOwner} to cache recovered keys of a data owner which may not have originated from\n * this device, so you should only use {@link StorageEntryKeysFactory.deviceKeypairOfDataOwner} if you want to make sure the keys you use are safe\n * for encryption.\n */\n async getCachedRsaKeyPairForFingerprint(\n dataOwnerId: string,\n pubKeyOrFingerprint: string\n ): Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }> {\n const fingerprint = pubKeyOrFingerprint.slice(-32)\n const res = this.keyManager.getDecryptionKeys()[fingerprint]\n if (!res) console.warn(`Could not find any keypair for fingerprint ${fingerprint}`)\n return res\n }\n\n /**\n * @deprecated You do not need this method to encrypt/decrypt data of iCure, but if you want to reuse the iCure keys for the user for other purposes\n * you have different options to replace this method, depending on what you actually need. All options return the hex-encoded spki representation of\n * the public keys.\n * - If you want only the public keys for which we have a private key available\n * - you can replicate the current behaviour using {@link getCurrentUserHierarchyAvailablePublicKeysHex}. This includes keys for the current user\n * and his parents.\n * - use {@link getCurrentUserAvailablePublicKeysHex} to get public keys only for the current data owner, ignoring any keys of the\n * parent hierarchy. In this case you can also apply a filter to only get verified keys (safe for encryption).\n * - If you need all public keys for the data owner, including those for which there is no corresponding private key available on the device use\n * {@link IccDataOwnerXApi.getHexPublicKeysOf} with the current data owner. If you don't have it available you may get it from\n * {@link IccDataOwnerXApi.getCurrentDataOwner}, but this will require to do a request to the iCure server (other options use only cached data).\n */\n async getPublicKeys(): Promise<string[]> {\n return this.userKeysManager.getCurrentUserHierarchyAvailablePublicKeysHex()\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.randomUuid} at {@link primitives}.\n */\n randomUuid() {\n return this.primitives.randomUuid()\n }\n\n /**\n * @deprecated replace with {@link CryptoPrimitives.sha256} at {@link primitives}.\n */\n sha256(data: ArrayBuffer | Uint8Array) {\n return this.primitives.sha256(data)\n }\n\n /**\n * @deprecated Use {@link ShamirKeysManager.updateSelfSplits} from {@link shamirKeysManager} instead. Note that the new method completely replaces\n * all current values if a split for the provided key already exists.\n */\n async encryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>, threshold?: number): Promise<HealthcareParty> {\n const legacyKeyFp = hcp.publicKey?.slice(-32)\n if (!legacyKeyFp) throw new Error(`No legacy/default key for hcp ${hcp.id}`)\n await this.shamirKeysManager.updateSelfSplits(\n { [legacyKeyFp]: { notariesIds: notaries.map((x) => x.id!), minShares: threshold ?? notaries.length } },\n []\n )\n return (await this.dataOwnerApi.getDataOwner(hcp.id!)).dataOwner as HealthcareParty\n }\n\n /**\n * @deprecated You should not need this method anymore because the api will automatically try to recover the available shamir keys on startup.\n */\n async decryptShamirRSAKey(hcp: HealthcareParty, notaries: Array<HealthcareParty>): Promise<void> {\n try {\n const publicKeys = await this.getPublicKeys()\n const nLen = notaries.length\n let decryptedPrivatedKey\n if (nLen == 1) {\n const notaryHcPartyId = notaries[0].id!\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notaryHcPartyId)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notaryHcPartyId, hcp.id!, notaryHcPartyId, idPubKey, keysMap, publicKeys)\n )\n )\n const cryptedPrivatedKey = hcp.privateKeyShamirPartitions![notaryHcPartyId]\n decryptedPrivatedKey = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(cryptedPrivatedKey)\n )\n )\n } else {\n const decryptedShares: string[] = await _.reduce(\n notaries,\n (queue, notary) => {\n return queue.then(async (shares: string[]) => {\n try {\n // now, we get the encrypted shares in db and decrypt them. This assumes that the\n // the notaries' private keys are in localstorage. We should implement a way for the notaries to\n // give hcp the decrypted shares without having to also share their private keys.\n const encryptedAesKeyMap = await this.getEncryptedAesExchangeKeys(hcp, notary.id!)\n const importedAESHcPartyKey = await Promise.all(\n Object.entries(encryptedAesKeyMap).map(\n async ([idPubKey, keysMap]) => await this.decryptHcPartyKey(notary.id!, hcp.id!, notary.id!, idPubKey, keysMap, publicKeys)\n )\n )\n const encryptedShare = hcp.privateKeyShamirPartitions![notary.id!]\n const decryptedShamirPartition = ua2hex(\n await this.AES.decryptSome(\n importedAESHcPartyKey.map((k) => k.key),\n hex2ua(encryptedShare)\n )\n )\n shares.push(decryptedShamirPartition)\n } catch (e) {\n console.log('Error during encryptedShamirRSAKey', notary.id, e)\n }\n return shares\n })\n },\n Promise.resolve([] as string[])\n )\n\n decryptedPrivatedKey = this.primitives.shamir.combine(decryptedShares)\n }\n\n const importedPrivateKey = await this.primitives.RSA.importKey('pkcs8', hex2ua(decryptedPrivatedKey), ['decrypt'])\n const importedPublicKey = await this.primitives.RSA.importKey('spki', hex2ua(hcp.publicKey!), ['encrypt'])\n\n const exportedKeyPair = await this.primitives.RSA.exportKeys({ publicKey: importedPublicKey, privateKey: importedPrivateKey }, 'jwk', 'jwk')\n await this._keyStorage.storeKeyPair(`${this.rsaLocalStoreIdPrefix}${hcp.id!}`, exportedKeyPair)\n } catch (e) {\n console.log('Cannot decrypt shamir RSA key')\n }\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n * Note that currently this method does not cache results anymore (but the updated methods do).\n */\n async decryptHcPartyKey(\n loggedHcPartyId: string,\n delegatorId: string,\n delegateHcPartyId: string,\n publicKey: string,\n encryptedHcPartyKeys: { [key: string]: string },\n publicKeys: string[]\n ): Promise<DelegatorAndKeys> {\n if (!publicKeys.length) {\n const reason = `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: no public key`\n console.warn(reason)\n throw new Error(reason)\n }\n const keysFpSet = new Set(publicKeys.map((x) => x.slice(-32)))\n const filteredKeys = Object.fromEntries(Object.entries(this.keyManager.getDecryptionKeys()).filter(([fp]) => keysFpSet.has(fp)))\n const decrypted = await this.exchangeKeysManager.base.tryDecryptExchangeKeys([encryptedHcPartyKeys], filteredKeys)\n const res = decrypted.successfulDecryptions[0]\n if (!res) {\n const error =\n `Cannot decrypt RSA encrypted AES HcPartyKey from ${delegatorId} to ${delegateHcPartyId}: impossible to decrypt. ` +\n 'No private key was found or could be used to decrypt the aes exchange keys`'\n console.warn(error)\n throw new Error(error)\n }\n return {\n delegatorId,\n key: res,\n rawKey: ua2hex(await this.primitives.AES.exportKey(res, 'raw')),\n }\n }\n\n /**\n * @deprecated you should not need this method anymore. The new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If no verified key (safe for encryption) can be found during the instantiation\n * of the API, depending on the parameters passed to the factory one of two scenarios will happen:\n * - A new key will be automatically created on the device and stored using the key storage facade.\n * - The api instantiation fails with an exception. This is ideal if you want to try to recover an existing key pair before creating a new one.\n *\n * If you were using this method to allow the user to recover an existing key that is not available in the storage facade nor recoverable through\n * transfer keys or shamir split (for example by scanning a qr code, or by loading a file from the computer to the web browser's local storage)\n * you will have to move that logic in your implementation of CryptoStrategies.\n * It is currently not allowed to create new key pairs if a verified key pair is already available on the device, as this would be wasteful.\n * If you want to convert a `JsonWebKey` pair to a `CryptoKey` pair you should use directly the method in `primitives.RSA`.\n */\n async cacheKeyPair(keyPairInJwk: KeyPair<JsonWebKey>): Promise<KeyPair<CryptoKey>> {\n const cryptoKeyPair = await this.primitives.RSA.importKeyPair('jwk', keyPairInJwk.privateKey, 'jwk', keyPairInJwk.publicKey)\n const pubHex = ua2hex(await this.primitives.RSA.exportKey(cryptoKeyPair.publicKey, 'spki'))\n const fingerprint = pubHex.slice(-32)\n if (!this.keyManager.getDecryptionKeys()[fingerprint]) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const selfKeys = this.dataOwnerApi.getHexPublicKeysOf((await this.dataOwnerApi.getCurrentDataOwner()).dataOwner)\n if (!selfKeys.has(pubHex))\n throw new Error(\n `Impossible to add key pair with fingerprint ${fingerprint} to data owner ${selfId}: the data owner has no matching public key`\n )\n await this.icureStorage.saveKey(selfId, fingerprint, keyPairInJwk, true)\n // Force reload to check if more private keys can be recovered or more exchange keys become available.\n await this.forceReload()\n }\n return cryptoKeyPair\n }\n\n /**\n * @deprecated Usually you should not need this method, since the preferred sfk is automatically chosen by the extended entity apis when creating a\n * new instance of the entity.\n */\n async extractPreferredSfk(parent: EncryptedParentEntity, hcpartyId: string, confidential: boolean) {\n return confidential ? this.confidential.getConfidentialSecretId(parent, hcpartyId) : this.confidential.getAnySecretIdSharedWithParents(parent)\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n */\n async decryptAndImportAesHcPartyKeysForDelegators(\n delegatorsHcPartyIdsSet: Array<string>,\n delegateHcPartyId: string,\n minCacheDurationInSeconds: number = 60\n ): Promise<Array<DelegatorAndKeys>> {\n return await delegatorsHcPartyIdsSet.reduce(async (acc, delegator) => {\n const awaitedAcc = await acc\n const keys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegator, delegateHcPartyId)\n const keysForDelegator = await keys.reduce(async (accForKey, cryptoKey) => {\n const awaitedAccForKey = await accForKey\n const rawKey = ua2hex(await this.primitives.RSA.exportKey(cryptoKey, 'spki'))\n return [\n ...awaitedAccForKey,\n {\n key: cryptoKey,\n delegatorId: delegator,\n rawKey: rawKey,\n },\n ]\n }, Promise.resolve([] as DelegatorAndKeys[]))\n return [...awaitedAcc, ...keysForDelegator]\n }, Promise.resolve([] as DelegatorAndKeys[]))\n }\n\n /**\n * @deprecated you should not need this method anymore because everything related to entities encryption should be done either through the\n * entity-specific extended api.\n * Note that currently this method does not cache results anymore (but the updated methods do).\n */\n async getEncryptedAesExchangeKeys(\n owner: DataOwner,\n delegateId: string\n ): Promise<{ [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } }> {\n const publicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(owner))\n const mapOfAesExchangeKeys = Object.entries(owner.aesExchangeKeys ?? {})\n .filter((e) => e[1][delegateId] && Object.keys(e[1][delegateId]).some((k1) => publicKeys.some((pk) => pk.endsWith(k1))))\n .reduce((map, e) => {\n const candidates = Object.entries(e[1][delegateId]) //[fingerprint of delegate pub key, key], [fingerprint of owner pub key, key]\n const [publicKeyFingerprint, encryptedAesExchangeKey] = candidates[candidates.findIndex(([k, v]) => publicKeys.some((pk) => pk.endsWith(k)))]\n return { ...map, [e[0]]: { [publicKeyFingerprint]: encryptedAesExchangeKey } }\n }, {} as { [pubKeyIdentifier: string]: { [pubKeyFingerprint: string]: string } })\n\n if (!owner.publicKey || mapOfAesExchangeKeys[owner.publicKey] || !owner.hcPartyKeys?.[delegateId]) {\n return mapOfAesExchangeKeys\n }\n const delegate = (await this.dataOwnerApi.getDataOwner(delegateId)).dataOwner\n if (delegate.publicKey && publicKeys.includes(delegate.publicKey)) {\n return {\n ...mapOfAesExchangeKeys,\n [owner.publicKey]: { [delegate.publicKey!.slice(-32)]: owner.hcPartyKeys[delegateId][1] },\n }\n } else if (publicKeys.includes(owner.publicKey)) {\n return { ...mapOfAesExchangeKeys, [owner.publicKey]: { [owner.publicKey.slice(-32)]: owner.hcPartyKeys[delegateId][0] } }\n }\n return mapOfAesExchangeKeys\n }\n\n /**\n * @deprecated you should not use this method because initialisation of encrypted entities keys is done automatically by the entity-specific\n * extended api. Also note that it is now forbidden to initialise an entity as a data owner which is not the current data owner: you should instead\n * create the entity as the current data owner then create a delegation to the other data owner.\n */\n async initEncryptionKeys(\n createdObject: any,\n ownerId: string\n ): Promise<{\n encryptionKeys: any\n secretId: string\n }> {\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n throw new Error('Impossible to initialise keys as a data owner which is not the current data owner')\n }\n const { updatedEntity, rawEncryptionKey } = await this.entities.entityWithInitialisedEncryptedMetadata(\n {\n ...createdObject,\n delegations: undefined,\n encryptionKeys: undefined,\n cryptedForeignKeys: undefined,\n secretForeignKeys: undefined,\n } as EncryptedEntity,\n undefined,\n undefined,\n true\n )\n return {\n encryptionKeys: updatedEntity.encryptionKeys,\n secretId: rawEncryptionKey!,\n }\n }\n\n /**\n * @deprecated You should use:\n * - {@link IccPatientXApi.decryptSecretIdsOf} or {@link IccMessageXApi.decryptSecretIdsOf} to get the delegation sfks (now caleld secret ids).\n * - {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds} to get the full hierarchy for the current data owner (cached). The first element is\n * the id of the topmost parent, while the last is the current data owner.\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractDelegationsSFKs(document: EncryptedEntity | null, hcpartyId?: string): Promise<{ extractedKeys: Array<string>; hcpartyId?: string }> {\n if (!document || !hcpartyId) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const delegationsForAllDelegates = document.delegations\n if (!delegationsForAllDelegates || !Object.keys(delegationsForAllDelegates).length) {\n console.log(`There is no delegation in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.secretIdsOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated (light) You should use:\n * - {@link IccHelementXApi.decryptPatientIdOf}, {@link IccDocumentXApi.decryptMessageIdOf}, ... to get the crypted foreign keys.\n * - {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds} to get the full hierarchy for the current data owner (cached). The first element is\n * the id of the topmost parent, while the last is the current data owner.\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractCryptedFKs(document: EncryptedEntity | null, hcpartyId: string): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document || !document.cryptedForeignKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const cfksForAllDelegates = document.cryptedForeignKeys\n if (!cfksForAllDelegates || !Object.keys(cfksForAllDelegates).length) {\n console.log(`There is no cryptedForeignKeys in document (${document.id})`)\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.owningEntityIdsOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated You should use the extended apis methods to encrypt/decrypt entities or their attachments\n * Note that the behaviour of this method has some subtle changes compared to the past:\n * - throws an error if the provided hcpartyId is not part of the current data owner hierarchy.\n * - does not provide any guarantees on the ordering of the extracted keys\n * - deduplicates extracted keys\n */\n async extractEncryptionsSKs(document: EncryptedEntity, hcpartyId: string): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n if (!document.encryptionKeys) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n const eckeysForAllDelegates = document.encryptionKeys\n if (!eckeysForAllDelegates || !Object.keys(eckeysForAllDelegates).length) {\n return Promise.resolve({ extractedKeys: [], hcpartyId: hcpartyId })\n }\n return {\n extractedKeys: await this.entities.encryptionKeysOf(document, hcpartyId),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated You should not use this method anymore, depending on what you were passing as {@link delegations} you should replace this method as\n * explained in {@link extractEncryptionsSKs} (if you were passing encryptionKeys), {@link extractCryptedFKs} (cryptedForeignKeys), or\n * {@link extractDelegationsSFKs} (delegations).\n */\n async extractKeysFromDelegationsForHcpHierarchy(\n dataOwnerId: string,\n objectId: string,\n delegations: { [key: string]: Array<Delegation> }\n ): Promise<{ extractedKeys: Array<string>; hcpartyId: string }> {\n return {\n extractedKeys: await this.entities.extractMergedHierarchyFromDelegationAndOwner(\n delegations,\n dataOwnerId,\n (x) => !!x,\n () => Promise.resolve(true)\n ),\n hcpartyId: (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0],\n }\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n * You can convert the private key pkcs8 array to a jwk key using {@link pkcs8ToJwk} then you can extract the full key pair using\n * {@link keyPairFromPrivateKeyJwk}.\n */\n async loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId: string, privateKey: Uint8Array) {\n await this.cacheKeyPair(keyPairFromPrivateKeyJwk(pkcs8ToJwk(privateKey)))\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n * You can extract the full key pair using {@link keyPairFromPrivateKeyJwk}.\n */\n async loadKeyPairsAsJwkInBrowserLocalStorage(healthcarePartyId: string, privateKey: JsonWebKey) {\n await this.cacheKeyPair(keyPairFromPrivateKeyJwk(privateKey))\n }\n\n /**\n * @deprecated you should not need this method anymore: the new API will automatically load on startup all keys available through the key storage\n * facade and/or recoverable through transfer keys or shamir split. If you were using this method to load a key recovered through other means you\n * will have to do so in your implementation of CryptoStrategies.\n */\n loadKeyPairsInBrowserLocalStorage(healthcarePartyId: string, file: Blob): Promise<void> {\n const fr = new FileReader()\n return new Promise((resolve, reject) => {\n fr.onerror = reject\n fr.onabort = reject\n fr.onload = (e: any) => {\n const privateKey = e.target.result as string\n this.loadKeyPairsAsTextInBrowserLocalStorage(healthcarePartyId, hex2ua(privateKey))\n .then(() => resolve())\n .catch(reject)\n }\n fr.readAsText(file)\n })\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n saveKeychainInBrowserLocalStorage(id: string, keychain: number) {\n this._storage.setItem(\n this.keychainLocalStoreIdPrefix + id,\n b2a(new Uint8Array(keychain).reduce((data, byte) => data + String.fromCharCode(byte), ''))\n )\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n saveKeychainInBrowserLocalStorageAsBase64(id: string, keyChainB64: string) {\n this._storage.setItem(this.keychainLocalStoreIdPrefix + id, keyChainB64)\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n async saveKeychainValidityDateInBrowserLocalStorage(id: string, date: string) {\n if (!id) return\n\n if (!date) {\n await this._storage.removeItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n } else {\n await this._storage.setItem(this.keychainValidityDateLocalStoreIdPrefix + id, date)\n }\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n *\n * Populate the HCP.options dict with an encrypted eHealth certificate and unencryped expiry date.\n * Any potentially unencrypted certificates will be pruned from the HCP.\n * @param hcpId Id of the hcp to modify\n * @returns modified HCP\n */\n async saveKeyChainInHCPFromLocalStorage(hcpId: string): Promise<HealthcareParty> {\n return await this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let aesKey: CryptoKey | null = null\n try {\n aesKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!aesKey) {\n console.error('No encryption key!')\n }\n\n const opts = hcp.options || {}\n\n const crt = await this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!!)\n if (!!aesKey && !!crt) {\n let crtEncrypted: ArrayBuffer | null = null\n try {\n crtEncrypted = await this.AES.encrypt(aesKey, new Uint8Array(string2ua(atob(crt))))\n } catch (e) {\n console.error('Error while encrypting the certificate', e)\n }\n\n // add the encrypted certificate to the options\n _.set(opts, this.hcpPreferenceKeyEhealthCert, ua2string(new Uint8Array(crtEncrypted!)))\n }\n\n const crtValidityDate = this.getKeychainValidityDateInBrowserLocalStorage(hcp.id!!)\n if (!!crtValidityDate) {\n _.set(opts, this.hcpPreferenceKeyEhealthCertDate, crtValidityDate)\n }\n\n hcp.options = opts\n return hcp\n })\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n importKeychainInBrowserFromHCP(hcpId: string): Promise<void> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then(async (hcp: HealthcareParty) => {\n let crtCryp: Uint8Array | null = null\n if (!!hcp.options && !!hcp.options[this.hcpPreferenceKeyEhealthCert]) {\n crtCryp = string2ua(hcp.options[this.hcpPreferenceKeyEhealthCert])\n }\n\n const crtValidityDate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCertDate)\n\n // store the validity date\n if (!!crtValidityDate) {\n this.saveKeychainValidityDateInBrowserLocalStorage(hcp.id!!, crtValidityDate)\n }\n\n let crt: ArrayBuffer | null = null\n let decryptionKey: CryptoKey | null = null\n try {\n decryptionKey = _.find(\n await this.decryptAndImportAesHcPartyKeysForDelegators([hcp.id!], hcp.id!),\n (delegator: DelegatorAndKeys) => delegator.delegatorId === hcp.id\n )!.key\n } catch (e) {\n console.error('Error while importing the AES key.')\n }\n if (!decryptionKey) {\n throw new Error('No encryption key! eHealth certificate cannot be decrypted.')\n }\n\n if (!!crtCryp && decryptionKey) {\n try {\n crt = await this.AES.decrypt(decryptionKey, crtCryp)\n } catch (e) {\n console.error(e)\n }\n }\n\n if (!crt) {\n throw new Error(`Error while saving certificate in browser local storage! Hcp ${hcp.id} has no certificate.`)\n } else {\n this.saveKeychainInBrowserLocalStorageAsBase64(hcp.id!!, btoa(String.fromCharCode.apply(null, Array.from(new Uint8Array(crt)))))\n }\n\n return\n })\n }\n\n /**\n * @deprecated e-health certificates and keychains are not part of iCure's api: this method will be removed.\n *\n * Synchronizes the eHealth certificate from the database into the LocalStorage, returning information on the presence\n * of certificate data in either place.\n *\n * @param hcpId The healthcare party id\n * @returns A Promise for an object that represents the existence of a certificate in local storage and in the DB,\n * through the two boolean properties \"local\" and \"remote\".\n */\n syncEhealthCertificateFromDatabase(hcpId: string): Promise<{ remote: boolean; local: boolean }> {\n return this.hcpartyBaseApi.getHealthcareParty(hcpId).then((hcp: HealthcareParty) => {\n const remoteCertificate = _.get(hcp.options, this.hcpPreferenceKeyEhealthCert)\n const localCertificate = this.getKeychainInBrowserLocalStorageAsBase64(hcp.id!)\n\n if (remoteCertificate) {\n return this.importKeychainInBrowserFromHCP(hcp.id!)\n .then(() => ({ local: true, remote: true }))\n .catch(() => ({ local: !!localCertificate, remote: true }))\n } else {\n return { local: !!localCertificate, remote: !!remoteCertificate }\n }\n })\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n getKeychainInBrowserLocalStorageAsBase64(id: string) {\n return this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n getKeychainValidityDateInBrowserLocalStorage(id: string) {\n return this._storage.getItem(this.keychainValidityDateLocalStoreIdPrefix + id)\n }\n\n /**\n * @deprecated keychains are not part of iCure's api: this method will be removed.\n */\n async loadKeychainFromBrowserLocalStorage(id: string) {\n const lsItem = await this._storage.getItem(this.keychainLocalStoreIdPrefix + id)\n return lsItem !== undefined ? b64_2uas(lsItem) : null\n }\n\n /**\n * @deprecated you should not need this method anymore to deal with the encryption of iCure entities because everything related to entities\n * encryption should be done through the entity-specific extended api.\n * If instead you were using the method for other reasons check {@link getCachedRsaKeyPairForFingerprint} to get an idea of possible replacements.\n */\n async loadKeyPairNotImported(id: string, publicKeyFingerPrint?: string): Promise<{ publicKey: JsonWebKey; privateKey: JsonWebKey } | undefined> {\n if (publicKeyFingerPrint) {\n const cached = this.keyManager.getKeyPairForFingerprint(publicKeyFingerPrint)?.pair\n if (cached) {\n return this.primitives.RSA.exportKeys(cached, 'jwk', 'jwk')\n }\n } else {\n const defaultKey = await this._keyStorage.getKeypair(this.rsaLocalStoreIdPrefix + id)\n if (defaultKey) return defaultKey\n }\n console.warn(`No key can be found in local storage for id ${id} and publicKeyFingerPrint ${publicKeyFingerPrint}`)\n }\n\n /**\n * @deprecated use {@link IccIcureMaintenanceXApi.applyKeyPairUpdate} instead.\n */\n async giveAccessBackTo(delegateUser: User, ownerId: string, ownerNewPublicKey: string): Promise<DataOwner> {\n await this.exchangeKeys.base.giveAccessBackTo(ownerId, ownerNewPublicKey, this.userKeysManager.getDecryptionKeys())\n return this.dataOwnerApi.getDataOwner(ownerId).then((x) => x.dataOwner)\n }\n /**\n * @deprecated You don't need to manually generate exchange keys as they will be automatically created by the api when needed.\n * Note that this method has some changes compared to previous version:\n * - The method may return any data owner (including devices)\n * - The method will throw an exception if the provided ownerId does not match the current data owner\n */\n async generateKeyForDelegate(ownerId: string, delegateId: string): Promise<DataOwner> {\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n throw new Error('You can only create delegation where the delegator is the current data owner')\n }\n return (await this.dataOwnerApi.getDataOwner(ownerId)).dataOwner\n }\n\n /**\n * @deprecated replace with {@link IccDataOwnerXApi.getDataOwner}. Note that data owners are not cached anymore.\n */\n getDataOwner(ownerId: string, loadIfMissingFromCache: boolean = true) {\n return this.dataOwnerApi.getDataOwner(ownerId)\n }\n\n /**\n * @deprecated the crypto api will automatically verify on startup the validity of private keys, but in some cases you may want to verify the\n * validity of keys recovered in your implementation of {@link CryptoStrategies}: in this case the method has been replaced with\n * {@link RSA.checkKeyPairValidity}\n */\n async checkPrivateKeyValidity(dataOwner: DataOwner): Promise<boolean> {\n const publicKeys = Array.from(new Set([dataOwner.publicKey].concat(Object.keys(dataOwner.aesExchangeKeys ?? {})).filter((x) => !!x))) as string[]\n\n return await publicKeys.reduce(async (pres, publicKey) => {\n const res = await pres\n try {\n const k = await this.primitives.RSA.importKey('jwk', spkiToJwk(hex2ua(publicKey)), ['encrypt'])\n const cipher = await this.primitives.RSA.encrypt(k, utf8_2ua('shibboleth'))\n const ikp = await this.getCachedRsaKeyPairForFingerprint(dataOwner.id!, publicKey.slice(-32))\n const plainText = ua2utf8(await this.primitives.RSA.decrypt(ikp.privateKey, new Uint8Array(cipher)))\n return plainText === 'shibboleth' || res\n } catch (e) {\n return res\n }\n }, Promise.resolve(false))\n }\n\n /**\n * @deprecated (See {@link extractEncryptionsSKs} for a detailed explanation).\n */\n async getEncryptionDecryptionKeys(dataOwnerId: string, document: EncryptedEntity): Promise<Array<string> | undefined> {\n return this.entities.encryptionKeysOf(document, dataOwnerId)\n }\n\n /**\n * @deprecated For the encryption/decryption of iCure entities and attachments you should rely solely on the extended apis methods.\n */\n async encryptDecrypt(\n method: 'encrypt' | 'decrypt',\n content: Uint8Array | ArrayBuffer,\n edKey?: string,\n user?: User,\n documentObject?: Document\n ): Promise<Uint8Array | Array<any> | any> {\n if (!content || !(edKey || (user?.healthcarePartyId && documentObject))) return content\n\n if (edKey) {\n const importedEdKey = await this.primitives.AES.importKey('raw', hex2ua(edKey.replace(/-/g, '')))\n try {\n return await this.primitives.AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n const encryptionKeys = await this.entities.encryptionKeysOf(documentObject!, user?.healthcarePartyId!)\n const importedEdKey = await this.primitives.AES.importKey('raw', hex2ua(encryptionKeys[0].replace(/-/g, '')))\n try {\n return await this.primitives.AES[method](importedEdKey, content)\n } catch (e) {\n return content\n }\n }\n\n /**\n * @deprecated you should not need to interact directly with the storage instance used by the iCure sdk.\n */\n storeKeyPair(id: string, keyPair: { publicKey: any; privateKey: any }) {\n this._storage.setItem(this.rsaLocalStoreIdPrefix + id, JSON.stringify(keyPair))\n }\n\n /**\n * @deprecated This method is not safe as it allows any data owner to add a public key to other data owners. The method will be removed in future,\n * additionally the user calling this method will require a special permission when calling it for another data owner.\n * @param ownerId the id of the data owner which will have a new key.\n */\n async generateAndAddNewKeyPairForOwner(\n ownerId: string\n ): Promise<{ dataOwner: HealthcareParty | Patient | Device; publicKey: string; privateKey: string }> {\n const { dataOwner, type } = await this.dataOwnerApi.getDataOwner(ownerId)\n if (type === 'device') throw new Error('Cannot add a key pair to a device')\n const newPair = await this.primitives.RSA.generateKeyPair()\n const exportedPub: string = ua2hex(await this.primitives.RSA.exportKey(newPair.publicKey, 'spki'))\n const exportedPriv: string = ua2hex(await this.primitives.RSA.exportKey(newPair.privateKey, 'pkcs8'))\n let updatedPub: string\n if (dataOwner.publicKey == '') {\n if (Object.keys(dataOwner.hcPartyKeys ?? {}).length > 0) throw new Error(`Data owner ${ownerId} has empty public key but non-empty hcPartyKeys`)\n updatedPub = exportedPub\n } else {\n updatedPub = dataOwner.publicKey ?? exportedPub\n }\n const updatedDataOwner = {\n ...dataOwner,\n publicKey: updatedPub,\n aesExchangeKeys: {\n ...dataOwner.aesExchangeKeys,\n [exportedPub]: {},\n },\n }\n let savedDataOwner: HealthcareParty | Patient\n if (type === 'patient') {\n savedDataOwner = await this.basePatientApi.modifyPatient(updatedDataOwner as Patient)\n } else if (type === 'hcp') {\n savedDataOwner = await this.hcpartyBaseApi.modifyHealthcareParty(updatedDataOwner as HealthcareParty)\n } else throw new Error(`Unknown data owner type ${type}`)\n return {\n dataOwner: savedDataOwner,\n publicKey: exportedPub,\n privateKey: exportedPriv,\n }\n }\n}\n"]}
@@ -195,7 +195,7 @@ function initialiseCryptoWithProvider(host, fetchImpl, groupSpecificAuthenticati
195
195
  const shamirManager = new ShamirKeysManager_1.ShamirKeysManager(cryptoPrimitives, dataOwnerApi, keyManager, exchangeKeysManager);
196
196
  const confidentialEntitites = new ConfidentialEntities_1.ConfidentialEntities(entitiesEncryption, cryptoPrimitives, dataOwnerApi);
197
197
  yield (0, utils_1.ensureDelegationForSelf)(dataOwnerApi, entitiesEncryption, cryptoPrimitives, basePatientApi);
198
- const cryptoApi = new icc_crypto_x_api_1.IccCryptoXApi(exchangeKeysManager, cryptoPrimitives, keyManager, dataOwnerApi, entitiesEncryption, shamirManager, params.storage, params.keyStorage, icureStorage, healthcarePartyApi, confidentialEntitites);
198
+ const cryptoApi = new icc_crypto_x_api_1.IccCryptoXApi(exchangeKeysManager, cryptoPrimitives, keyManager, dataOwnerApi, entitiesEncryption, shamirManager, params.storage, params.keyStorage, icureStorage, healthcarePartyApi, confidentialEntitites, basePatientApi);
199
199
  const maintenanceTaskApi = new icc_maintenance_task_x_api_1.IccMaintenanceTaskXApi(host, params.headers, cryptoApi, healthcarePartyApi, dataOwnerApi, userApi, authApi, (_b = (_a = params.encryptedFieldsConfig) === null || _a === void 0 ? void 0 : _a.maintenanceTask) !== null && _b !== void 0 ? _b : EncryptedFieldsConfig.Defaults.maintenanceTask, groupSpecificAuthenticationProvider, fetchImpl);
200
200
  const icureMaintenanceTaskApi = new icc_icure_maintenance_x_api_1.IccIcureMaintenanceXApi(cryptoApi, maintenanceTaskApi, dataOwnerApi);
201
201
  if (newKey && params.createMaintenanceTasksOnNewKey) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../icc-x-api/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wCA8BmB;AACnB,qDAA8C;AAC9C,yDAAkD;AAClD,2DAAoD;AACpD,2DAAoD;AACpD,6DAAsD;AACtD,2DAAoD;AACpD,qDAA8C;AAC9C,6DAAsD;AACtD,yEAAkE;AAClE,uEAA+D;AAC/D,2DAAoD;AACpD,2DAAoD;AACpD,2DAAoD;AACpD,+DAAwD;AACxD,iEAAyD;AAEzD,qDAA8C;AAC9C,6EAAqE;AACrE,iEAAyD;AAGzD,iEAA6D;AAC7D,6DAAyD;AACzD,0EAMsC;AACtC,gEAA4D;AAC5D,oDAAgD;AAChD,qEAAiE;AACjE,6FAAyF;AACzF,sDAAkD;AAClD,8EAA0E;AAG1E,sEAAkE;AAClE,kEAA8D;AAC9D,sEAAkE;AAClE,+EAAuE;AACvE,oEAAgE;AAChE,wEAAoE;AACpE,0CAAwD;AACxD,sEAA0E;AAC1E,2DAAoD;AACpD,mEAA4D;AAE5D,yDAAkD;AAElD,wDAAqC;AACrC,sDAAmC;AACnC,4DAAyC;AACzC,6DAA0C;AAC1C,mDAAgC;AAChC,sDAAmC;AACnC,qDAAkC;AAClC,0DAAuC;AACvC,uDAAoC;AACpC,mDAAgC;AAChC,sDAAmC;AACnC,uDAAoC;AACpC,sDAAmC;AACnC,sDAAmC;AACnC,sDAAmC;AACnC,mDAAgC;AAChC,yDAAsC;AACtC,sDAAmC;AACnC,yDAAsC;AACtC,gEAA6C;AAC7C,+DAA4C;AAC5C,0CAAuB;AAEvB,+CAA4B;AAC5B,4DAAyC;AACzC,gEAA6C;AAG7C,+DAA6D;AAApD,oHAAA,gBAAgB,OAAA;AAEzB,2DAAyD;AAAhD,gHAAA,cAAc,OAAA;AA8GvB,IAAU,eAAe,CA2BxB;AA3BD,WAAU,eAAe;IACvB,IAAiB,QAAQ,CAIxB;IAJD,WAAiB,QAAQ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IccApplicationsettingsApi,\n IccArticleApi,\n IccAuthApi,\n IccBeefactApi,\n IccBeresultexportApi,\n IccBeresultimportApi,\n IccBesamv2Api,\n IccCalendarItemTypeApi,\n IccClassificationTemplateApi,\n IccEntityrefApi,\n IccEntitytemplateApi,\n IccFrontendmigrationApi,\n IccGroupApi,\n IccIcureApi,\n IccInsuranceApi,\n IccKeywordApi,\n IccMedexApi,\n IccMedicallocationApi,\n IccPatientApi,\n IccPermissionApi,\n IccPlaceApi,\n IccPubsubApi,\n IccReplicationApi,\n IccTarificationApi,\n IccTmpApi,\n IccUserApi,\n OAuthThirdParty,\n} from '../icc-api'\nimport { IccUserXApi } from './icc-user-x-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccInvoiceXApi } from './icc-invoice-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHcpartyXApi } from './icc-hcparty-x-api'\nimport { IccFormXApi } from './icc-form-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { IccClassificationXApi } from './icc-classification-x-api'\nimport { IccCalendarItemXApi } from './icc-calendar-item-x-api'\nimport { IccPatientXApi } from './icc-patient-x-api'\nimport { IccMessageXApi } from './icc-message-x-api'\nimport { IccReceiptXApi } from './icc-receipt-x-api'\nimport { IccAccesslogXApi } from './icc-accesslog-x-api'\nimport { IccTimeTableXApi } from './icc-time-table-x-api'\nimport { IccDeviceApi } from '../icc-api'\nimport { IccCodeXApi } from './icc-code-x-api'\nimport { IccMaintenanceTaskXApi } from './icc-maintenance-task-x-api'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\nimport { LocalStorageImpl } from './storage/LocalStorageImpl'\nimport { KeyStorageImpl } from './storage/KeyStorageImpl'\nimport {\n AuthenticationProvider,\n BasicAuthenticationProvider,\n EnsembleAuthenticationProvider,\n JwtAuthenticationProvider,\n NoAuthenticationProvider,\n} from './auth/AuthenticationProvider'\nimport { CryptoPrimitives } from './crypto/CryptoPrimitives'\nimport { KeyManager } from './crypto/KeyManager'\nimport { IcureStorageFacade } from './storage/IcureStorageFacade'\nimport { DefaultStorageEntryKeysFactory } from './storage/DefaultStorageEntryKeysFactory'\nimport { KeyRecovery } from './crypto/KeyRecovery'\nimport { BaseExchangeKeysManager } from './crypto/BaseExchangeKeysManager'\nimport { StorageEntryKeysFactory } from './storage/StorageEntryKeysFactory'\nimport { CryptoStrategies } from './crypto/CryptoStrategies'\nimport { ExchangeKeysManager } from './crypto/ExchangeKeysManager'\nimport { ShamirKeysManager } from './crypto/ShamirKeysManager'\nimport { TransferKeysManager } from './crypto/TransferKeysManager'\nimport { IccIcureMaintenanceXApi } from './icc-icure-maintenance-x-api'\nimport { EntitiesEncryption } from './crypto/EntitiesEncryption'\nimport { ConfidentialEntities } from './crypto/ConfidentialEntities'\nimport { ensureDelegationForSelf } from './crypto/utils'\nimport { CryptoActorStubWithType } from '../icc-api/model/CryptoActorStub'\nimport { IccBekmehrXApi } from './icc-bekmehr-x-api'\nimport { IccDoctemplateXApi } from './icc-doctemplate-x-api'\nimport { UserGroup } from '../icc-api/model/UserGroup'\nimport { IccDeviceXApi } from './icc-device-x-api'\n\nexport * from './icc-accesslog-x-api'\nexport * from './icc-bekmehr-x-api'\nexport * from './icc-calendar-item-x-api'\nexport * from './icc-classification-x-api'\nexport * from './icc-code-x-api'\nexport * from './icc-contact-x-api'\nexport * from './icc-crypto-x-api'\nexport * from './icc-doctemplate-x-api'\nexport * from './icc-document-x-api'\nexport * from './icc-form-x-api'\nexport * from './icc-hcparty-x-api'\nexport * from './icc-helement-x-api'\nexport * from './icc-invoice-x-api'\nexport * from './icc-message-x-api'\nexport * from './icc-patient-x-api'\nexport * from './icc-user-x-api'\nexport * from './icc-time-table-x-api'\nexport * from './icc-receipt-x-api'\nexport * from './icc-data-owner-x-api'\nexport * from './icc-icure-maintenance-x-api'\nexport * from './icc-maintenance-task-x-api'\nexport * from './utils'\n\nexport * from './crypto/RSA'\nexport * from './crypto/CryptoPrimitives'\nexport * from './auth/AuthenticationProvider'\n\nexport { KeyStorageFacade } from './storage/KeyStorageFacade'\nexport { LocalStorageImpl } from './storage/LocalStorageImpl'\nexport { StorageFacade } from './storage/StorageFacade'\nexport { KeyStorageImpl } from './storage/KeyStorageImpl'\nexport { CryptoStrategies } from './crypto/CryptoStrategies'\n\nexport interface Apis {\n readonly authApi: IccAuthApi\n readonly codeApi: IccCodeXApi\n readonly calendarItemTypeApi: IccCalendarItemTypeApi\n readonly medicalLocationApi: IccMedicallocationApi\n readonly entityReferenceApi: IccEntityrefApi\n readonly userApi: IccUserXApi\n readonly permissionApi: IccPermissionApi\n readonly healthcarePartyApi: IccHcpartyXApi\n readonly deviceApi: IccDeviceXApi\n readonly cryptoApi: IccCryptoXApi\n readonly accessLogApi: IccAccesslogXApi\n readonly agendaApi: IccAgendaApi\n readonly contactApi: IccContactXApi\n readonly formApi: IccFormXApi\n readonly groupApi: IccGroupApi\n readonly invoiceApi: IccInvoiceXApi\n readonly insuranceApi: IccInsuranceApi\n readonly documentApi: IccDocumentXApi\n readonly healthcareElementApi: IccHelementXApi\n readonly classificationApi: IccClassificationXApi\n readonly calendarItemApi: IccCalendarItemXApi\n readonly receiptApi: IccReceiptXApi\n readonly timetableApi: IccTimeTableXApi\n readonly patientApi: IccPatientXApi\n readonly messageApi: IccMessageXApi\n readonly maintenanceTaskApi: IccMaintenanceTaskXApi\n readonly dataOwnerApi: IccDataOwnerXApi\n readonly icureMaintenanceTaskApi: IccIcureMaintenanceXApi\n readonly anonymousAccessApi: IccAnonymousAccessApi\n readonly applicationSettingsApi: IccApplicationsettingsApi\n readonly articleApi: IccArticleApi\n readonly bekmehrApi: IccBekmehrXApi\n readonly beefactApi: IccBeefactApi\n readonly beresultexportApi: IccBeresultexportApi\n readonly beresultimportApi: IccBeresultimportApi\n readonly besamv2Api: IccBesamv2Api\n readonly classificationTemplateApi: IccClassificationTemplateApi\n readonly doctemplateApi: IccDoctemplateXApi\n readonly entitytemplateApi: IccEntitytemplateApi\n readonly frontendmigrationApi: IccFrontendmigrationApi\n readonly icureApi: IccIcureApi\n readonly keywordApi: IccKeywordApi\n readonly medexApi: IccMedexApi\n readonly placeApi: IccPlaceApi\n readonly pubsubApi: IccPubsubApi\n readonly replicationApi: IccReplicationApi\n readonly tarificationApi: IccTarificationApi\n readonly tmpApi: IccTmpApi\n}\n\n/**\n * Allows to customise the behaviour of the iCure API by providing various optional parameters.\n */\nexport interface IcureApiOptions {\n /**\n * Specifies how iCure can store string values (e.g. json). In production this should be persistent storage.\n * @default the browser's localStorage.\n */\n readonly storage?: StorageFacade<string>\n /**\n * Specifies how iCure can store cryptographic keys. Preferably this should be some ad-hoc storage key storage.\n * @default stores the json of the jwk representation of the key in {@link storage}.\n */\n readonly keyStorage?: KeyStorageFacade\n /**\n * Specifies where iCure should store his data within the {@link storage} and {@link keyStorage}.\n * @default {@link DefaultStorageEntryKeysFactory}\n */\n readonly entryKeysFactory?: StorageEntryKeysFactory\n /**\n * Specifies if iCure should create maintenance tasks for requesting access back when a new key is generated at initialisation time.\n * @default true\n */\n readonly createMaintenanceTasksOnNewKey?: boolean\n /**\n * Additional headers to use on each request made by the iCure api.\n * @default no additional headers\n */\n readonly headers?: { [headerName: string]: string }\n /**\n * Specifies which fields should be encrypted for each kind of encryptable entity. You should make sure that every application in your environment\n * specifies the same values for this configuration.\n * @default see documentation for {@link EncryptedFieldsConfig}\n */\n readonly encryptedFieldsConfig?: EncryptedFieldsConfig\n /**\n * Each user may exist in multiple groups, but an instance of {@link IcureApi} is specialised for a single group. This function allows you to decide\n * the group to use for a given user. This functions will be called only if a user exists in at least 2 groups, takes in input the information on\n * the groups the user can access (in no specific order) and must return the id of one of these groups.\n * @default takes the first group provided. The group chosen by this method may vary between different instantiations of the {@link IcureApi} even\n * if for the same user and if the groups available for the user do not change.\n */\n readonly groupSelector?: (availableGroupsInfo: UserGroup[]) => Promise<string>\n /**\n * Temporary value to support EHR Lite and MedTech api implementations.\n *\n * Currently, all hcps are able to access encrypted data shared with any of their parents, and on initialisation the api will verify that there is a\n * key pair available for the current user and for every parent of the user. If this option is set to true, the api will not load keys for the\n * parent users.\n *\n * This \"implicit data-sharing scheme\" (each parent HCP is essentially sharing data with all its children HCPs), however, may not be ideal for all\n * use cases, and it will be changed in future to be configurable in order to make it more general.\n * @default false, equivalent to previous behaviour.\n */\n readonly disableParentKeysInitialisation?: boolean\n}\nnamespace IcureApiOptions {\n export namespace Defaults {\n export const entryKeysFactory = new DefaultStorageEntryKeysFactory()\n export const createMaintenanceTasksOnNewKey = true\n export const headers = {}\n }\n export class WithDefaults implements IcureApiOptions {\n constructor(custom: IcureApiOptions) {\n this.entryKeysFactory = custom.entryKeysFactory ?? Defaults.entryKeysFactory\n this.createMaintenanceTasksOnNewKey = custom.createMaintenanceTasksOnNewKey ?? Defaults.createMaintenanceTasksOnNewKey\n this.storage = custom.storage ?? new LocalStorageImpl()\n this.keyStorage = custom.keyStorage ?? new KeyStorageImpl(this.storage)\n this.headers = custom.headers ?? Defaults.headers\n this.encryptedFieldsConfig = custom.encryptedFieldsConfig ?? EncryptedFieldsConfig.Defaults\n this.groupSelector = custom.groupSelector ?? ((groups) => Promise.resolve(groups[0].groupId!))\n this.disableParentKeysInitialisation = custom.disableParentKeysInitialisation ?? false\n }\n\n readonly entryKeysFactory: StorageEntryKeysFactory\n readonly createMaintenanceTasksOnNewKey: boolean\n readonly storage: StorageFacade<string>\n readonly keyStorage: KeyStorageFacade\n readonly headers: { [headerName: string]: string }\n readonly encryptedFieldsConfig: EncryptedFieldsConfig\n readonly groupSelector: (availableGroupsInfo: UserGroup[]) => Promise<string>\n readonly disableParentKeysInitialisation: boolean\n }\n}\n\n/**\n * Specifies which fields should be encrypted for each kind of encryptable entity.\n *\n * Note that any value you specify here overrides the default values. For example if you specify `['medicalLocationId']` for `healthElement` the\n * fields `['descr', 'note']` which are usually encrypted by default will no longer be encrypted. If you want to add fields to the default values\n * you can use {@link EncryptedFieldsConfig.Defaults}, for example `[...EncryptedFieldsConfig.Defaults.healthElement, 'medicalLocationId'].\n *\n * # Encrypted fields syntax\n *\n * ## Grammar\n *\n * The grammar for each encrypted field is the following:\n * ```\n * fieldName :=\n * regex([a-zA-Z_][a-zA-Z0-9_]+)\n * encryptedField :=\n * fieldName\n * | fieldName + (\".\" | \".*.\" | \"[].\") + encryptedField\n * ```\n *\n * This grammar allows you to specify the fields to encrypt for the object and recursively for nested objects.\n * - A string containing only a single `fieldName` will encrypt the field with the given name.\n * - A string starting with `fieldName.` allows to specify the encrypted fields of a nested object. The encrypted values of the\n * fields in the nested object will be saved in the nested object.\n * - A string starting with `fieldName.*.` treats `fieldName` as a map/dictionary data structure and allows to specify the encrypted fields of the\n * values of the map. Note that the values of the map must be objects as well. The encrypted content of each map value is stored in that value.\n * - A string starting with `fieldName[].` treats `fieldName` as an array and allows to specify the encrypted fields of the values of the array.\n * Note that the values of the array must be objects as well. The encrypted content of each array element is stored in that element.\n *\n * ## Example\n *\n * Consider the following object and encryption keys:\n * ```javascript\n * const obj = {\n * a: { x: 0, y: 1 },\n * b: \"hello\",\n * c: [ { public: \"a\", secret: \"b\" }, { public: \"c\", secret: \"d\" } ],\n * d: \"ok\",\n * e: {\n * info: \"something\",\n * private: \"secret\",\n * dataMap: {\n * \"en\": {\n * a: 1,\n * b: 2\n * },\n * \"fr\": {\n * a: 3,\n * b: 4\n * }\n * }\n * }\n * }\n * const encryptedFields = [\n * \"a\",\n * \"c[].secret\",\n * \"d\",\n * \"e.private\",\n * \"e.datamap.*.a\"\n * ]\n * ```\n * If you use them with the crypt method you will get the following result:\n * ```json\n * {\n * b: \"hello\",\n * c: [\n * { public: \"a\", encryptedSelf: 'encrypted+encoded { secret: \"b\" }' },\n * { public: \"c\", encryptedSelf: 'encrypted+encoded { secret: \"d\" }' }\n * ],\n * e: {\n * info: \"something\",\n * dataMap: {\n * \"en\": { b: 2, encryptedSelf: 'encrypted+encoded { a: 1 }' },\n * \"fr\": { b: 4, encryptedSelf: 'encrypted+encoded { a: 3 }' }\n * },\n * encryptedSelf: 'encrypted+encoded { private: \"secret\" }'\n * },\n * encryptedSelf: 'encrypted+encoded { a: { x: 0, y: 1 }, d: \"ok\" }'\n * }\n * ```\n *\n * ## Shortened representation\n *\n * You can also group encrypted fields having the same prefix by concatenating to the prefix the JSON representation of an array of all the postfixes.\n * For example the following encrypted fields:\n * ```javascript\n * const encryptedFields = [\"a.b.c.d.e.f1\", \"a.b.c.d.e.f2\", \"a.b.c.d.e.f3\", \"a.b.c.d.e.f4\"]\n * ```\n * can be shortened to\n * ```javascript\n * const encryptedFields = ['a.b.c.d.e.[\"f1\",\"f2\",\"f3\",\"f4\"]'] // Note the use of single quotes to avoid escaping the double quotes\n * ```\n * If you use the shortened representation you may need to escape nested json representations. In that case the use of `JSON.stringify` is\n * recommended.\n */\nexport interface EncryptedFieldsConfig {\n /**\n * Fields to encrypt for entities of type {@link AccessLog}\n * @default ['detail', 'objectId']\n */\n readonly accessLog?: string[]\n /**\n * Fields to encrypt for entities of type {@link CalendarItem}\n * @default ['details', 'title', 'patientId']\n */\n readonly calendarItem?: string[]\n /**\n * Fields to encrypt for entities of type {@link Contact}, excluding `services`. You can specify which fields of `services` should be encrypted\n * using {@link service}.\n * @default ['descr'] // encryption of `services` is managed through {@link service}\n */\n readonly contact?: string[]\n /**\n * Fields to encrypt for entities of type {@link Service}. Note that encryption of the `content` field and recursively contained `Services` through\n * `content.compoundValue` is automatically managed by the sdk, and you are not allowed to modify it.\n *\n * Note: any non-empty values for this field will break bi-directional data compatibility between v7 and previous: Contacts created with\n * v7 will not be read properly by previous versions. If you want\n * @default ['notes[].markdown'] // encryption of `content` is managed in a special way\n */\n readonly service?: string[]\n /**\n * Fields to encrypt for entities of type {@link HealthElement}\n * @default ['descr', 'note', 'notes[].markdown']\n */\n readonly healthElement?: string[]\n /**\n * Fields to encrypt for entities of type {@link MaintenanceTask}\n * @default ['properties']\n */\n readonly maintenanceTask?: string[]\n /**\n * Fields to encrypt for entities of type {@link Patient}\n * @default ['note', 'notes[].markdown']\n */\n readonly patient?: string[]\n}\nexport namespace EncryptedFieldsConfig {\n export const Defaults = {\n accessLog: ['detail', 'objectId'],\n calendarItem: ['details', 'title', 'patientId'],\n contact: ['descr'],\n service: ['notes[].markdown'],\n healthElement: ['descr', 'note', 'notes[].markdown'],\n maintenanceTask: ['properties'],\n patient: ['note', 'notes[].markdown'],\n }\n}\n\n/**\n * Details for the authentication of a user\n */\nexport type AuthenticationDetails = {\n username: string\n password: string\n forceBasic?: boolean // default false\n icureTokens?: { token: string; refreshToken: string }\n thirdPartyTokens?: { [thirdParty: string]: string }\n}\n\n/**\n * Main entry point for the iCure API. Provides entity-specific sub-apis and some general methods which are not related to a specific entity.\n */\nexport interface IcureApi extends Apis {\n /**\n * Get the information on groups that the current user can access and the current group that this api instance is working on.\n * Note that the values you will get for `availableGroups` may differ from the values you would get if you call {@link IccUserApi.getMatchingUsers}\n * on {@link Apis.userApi}, since the latter is specialised on the specific instance of the user in `currentGroup`.\n */\n getGroupsInfo(): Promise<{ currentGroup: UserGroup; availableGroups: UserGroup[] }>\n\n /**\n * Switches the api to allow the user to work on a different group.\n * @param newGroupId the id of the group to switch to.\n * @return a new api for the specified group.\n */\n switchGroup(newGroupId: string): Promise<IcureApi>\n}\nexport namespace IcureApi {\n /**\n * Initialises a new instance of the iCure API.\n */\n export async function initialise(\n host: string,\n authenticationOptions: AuthenticationDetails | AuthenticationProvider,\n cryptoStrategies: CryptoStrategies,\n crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n options: IcureApiOptions = {}\n ): Promise<IcureApi> {\n const params = new IcureApiOptions.WithDefaults(options)\n let grouplessAuthenticationProvider: AuthenticationProvider\n if ('getIcureTokens' in authenticationOptions && 'switchGroup' in authenticationOptions && 'getAuthService' in authenticationOptions) {\n const tokens = await authenticationOptions.getIcureTokens()\n if (!!tokens && !!tokens.token && !!tokens.refreshToken) {\n grouplessAuthenticationProvider = new JwtAuthenticationProvider(\n new IccAuthApi(host, params.headers, new NoAuthenticationProvider(), fetchImpl),\n undefined,\n undefined,\n undefined,\n tokens\n )\n } else {\n grouplessAuthenticationProvider = authenticationOptions\n }\n } else if (\n 'username' in authenticationOptions &&\n 'password' in authenticationOptions &&\n !!authenticationOptions.username &&\n !!authenticationOptions.password\n ) {\n grouplessAuthenticationProvider = new EnsembleAuthenticationProvider(\n new IccAuthApi(host, params.headers, new NoAuthenticationProvider(), fetchImpl),\n authenticationOptions.username,\n authenticationOptions.password,\n 3600,\n undefined,\n undefined,\n authenticationOptions.thirdPartyTokens\n )\n } else {\n throw new Error('Invalid authentication options provided')\n }\n const grouplessUserApi = new IccUserApi(host, params.headers, grouplessAuthenticationProvider, fetchImpl)\n const matches = await grouplessUserApi.getMatchingUsers()\n const chosenGroupId = matches.length > 1 ? await params.groupSelector(matches) : matches[0].groupId!\n /*TODO\n * On new very new users switching the authentication provider to a specific group may fail and block the user for too many requests. This is\n * probably linked to replication of the user in the fallback database.\n */\n const groupSpecificAuthenticationProvider =\n matches.length > 1 ? await grouplessAuthenticationProvider.switchGroup(chosenGroupId, matches) : grouplessAuthenticationProvider\n const cryptoApis = await initialiseCryptoWithProvider(host, fetchImpl, groupSpecificAuthenticationProvider, params, cryptoStrategies, crypto)\n return new IcureApiImpl(\n cryptoApis,\n host,\n groupSpecificAuthenticationProvider,\n fetch,\n grouplessUserApi,\n matches,\n matches.find((match) => match.groupId === chosenGroupId)!,\n params,\n cryptoStrategies\n )\n }\n}\n\n// Apis which are used during crypto api initialisation, to avoid re-instantiating them later\ntype CryptoInitialisationApis = {\n cryptoApi: IccCryptoXApi\n healthcarePartyApi: IccHcpartyXApi\n deviceApi: IccDeviceXApi\n // no patient api since it is base\n dataOwnerApi: IccDataOwnerXApi\n userApi: IccUserXApi\n icureMaintenanceTaskApi: IccIcureMaintenanceXApi\n maintenanceTaskApi: IccMaintenanceTaskXApi\n}\n\nasync function initialiseCryptoWithProvider(\n host: string,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n groupSpecificAuthenticationProvider: AuthenticationProvider,\n params: IcureApiOptions.WithDefaults,\n cryptoStrategies: CryptoStrategies,\n crypto: Crypto\n): Promise<CryptoInitialisationApis> {\n const authApi = new IccAuthApi(host, params.headers, groupSpecificAuthenticationProvider, fetchImpl)\n const userApi = new IccUserXApi(host, params.headers, groupSpecificAuthenticationProvider, authApi, fetchImpl)\n const healthcarePartyApi = new IccHcpartyXApi(host, params.headers, groupSpecificAuthenticationProvider, authApi, fetchImpl)\n const deviceApi = new IccDeviceXApi(host, params.headers, groupSpecificAuthenticationProvider, userApi, authApi, fetchImpl)\n const basePatientApi = new IccPatientApi(host, params.headers, groupSpecificAuthenticationProvider, fetchImpl)\n const dataOwnerApi = new IccDataOwnerXApi(host, params.headers, groupSpecificAuthenticationProvider, fetchImpl)\n // Crypto initialisation\n const icureStorage = new IcureStorageFacade(params.keyStorage, params.storage, params.entryKeysFactory)\n const cryptoPrimitives = new CryptoPrimitives(crypto)\n const baseExchangeKeysManager = new BaseExchangeKeysManager(cryptoPrimitives, dataOwnerApi, healthcarePartyApi, basePatientApi, deviceApi)\n const keyRecovery = new KeyRecovery(cryptoPrimitives, baseExchangeKeysManager, dataOwnerApi)\n const keyManager = new KeyManager(\n cryptoPrimitives,\n dataOwnerApi,\n icureStorage,\n keyRecovery,\n baseExchangeKeysManager,\n cryptoStrategies,\n !params.disableParentKeysInitialisation\n )\n const newKey = await keyManager.initialiseKeys()\n await new TransferKeysManager(cryptoPrimitives, baseExchangeKeysManager, dataOwnerApi, keyManager, icureStorage).updateTransferKeys(\n CryptoActorStubWithType.fromDataOwner(await dataOwnerApi.getCurrentDataOwner())\n )\n // TODO customise cache size?\n const exchangeKeysManager = new ExchangeKeysManager(\n 100,\n 500,\n 60000,\n 600000,\n cryptoStrategies,\n cryptoPrimitives,\n keyManager,\n baseExchangeKeysManager,\n dataOwnerApi,\n !params.disableParentKeysInitialisation\n )\n const entitiesEncryption = new EntitiesEncryption(cryptoPrimitives, dataOwnerApi, exchangeKeysManager, !params.disableParentKeysInitialisation)\n const shamirManager = new ShamirKeysManager(cryptoPrimitives, dataOwnerApi, keyManager, exchangeKeysManager)\n const confidentialEntitites = new ConfidentialEntities(entitiesEncryption, cryptoPrimitives, dataOwnerApi)\n await ensureDelegationForSelf(dataOwnerApi, entitiesEncryption, cryptoPrimitives, basePatientApi)\n const cryptoApi = new IccCryptoXApi(\n exchangeKeysManager,\n cryptoPrimitives,\n keyManager,\n dataOwnerApi,\n entitiesEncryption,\n shamirManager,\n params.storage,\n params.keyStorage,\n icureStorage,\n healthcarePartyApi,\n confidentialEntitites\n )\n const maintenanceTaskApi = new IccMaintenanceTaskXApi(\n host,\n params.headers,\n cryptoApi,\n healthcarePartyApi,\n dataOwnerApi,\n userApi,\n authApi,\n params.encryptedFieldsConfig?.maintenanceTask ?? EncryptedFieldsConfig.Defaults.maintenanceTask,\n groupSpecificAuthenticationProvider,\n fetchImpl\n )\n const icureMaintenanceTaskApi = new IccIcureMaintenanceXApi(cryptoApi, maintenanceTaskApi, dataOwnerApi)\n if (newKey && params.createMaintenanceTasksOnNewKey) {\n await icureMaintenanceTaskApi.createMaintenanceTasksForNewKeypair(await userApi.getCurrentUser(), newKey.newKeyPair)\n }\n return {\n cryptoApi,\n healthcarePartyApi,\n deviceApi,\n dataOwnerApi,\n userApi,\n icureMaintenanceTaskApi,\n maintenanceTaskApi,\n }\n}\n\nclass IcureApiImpl implements IcureApi {\n private latestGroupsRequest: Promise<UserGroup[]>\n private _authApi: IccAuthApi | undefined\n private _codeApi: IccCodeXApi | undefined\n private _calendarItemTypeApi: IccCalendarItemTypeApi | undefined\n private _medicalLocationApi: IccMedicallocationApi | undefined\n private _entityReferenceApi: IccEntityrefApi | undefined\n private _permissionApi: IccPermissionApi | undefined\n private _accessLogApi: IccAccesslogXApi | undefined\n private _agendaApi: IccAgendaApi | undefined\n private _contactApi: IccContactXApi | undefined\n private _formApi: IccFormXApi | undefined\n private _groupApi: IccGroupApi | undefined\n private _invoiceApi: IccInvoiceXApi | undefined\n private _insuranceApi: IccInsuranceApi | undefined\n private _documentApi: IccDocumentXApi | undefined\n private _healthcareElementApi: IccHelementXApi | undefined\n private _classificationApi: IccClassificationXApi | undefined\n private _calendarItemApi: IccCalendarItemXApi | undefined\n private _receiptApi: IccReceiptXApi | undefined\n private _timetableApi: IccTimeTableXApi | undefined\n private _patientApi: IccPatientXApi | undefined\n private _messageApi: IccMessageXApi | undefined\n private _anonymousAccessApi: IccAnonymousAccessApi | undefined\n private _applicationSettingsApi: IccApplicationsettingsApi | undefined\n private _articleApi: IccArticleApi | undefined\n private _bekmehrApi: IccBekmehrXApi | undefined\n private _beefactApi: IccBeefactApi | undefined\n private _beresultexportApi: IccBeresultexportApi | undefined\n private _beresultimportApi: IccBeresultimportApi | undefined\n private _besamv2Api: IccBesamv2Api | undefined\n private _classificationTemplateApi: IccClassificationTemplateApi | undefined\n private _doctemplateApi: IccDoctemplateXApi | undefined\n private _entitytemplateApi: IccEntitytemplateApi | undefined\n private _frontendmigrationApi: IccFrontendmigrationApi | undefined\n private _icureApi: IccIcureApi | undefined\n private _keywordApi: IccKeywordApi | undefined\n private _medexApi: IccMedexApi | undefined\n private _placeApi: IccPlaceApi | undefined\n private _pubsubApi: IccPubsubApi | undefined\n private _replicationApi: IccReplicationApi | undefined\n private _tarificationApi: IccTarificationApi | undefined\n private _tmpApi: IccTmpApi | undefined\n\n get cryptoApi(): IccCryptoXApi {\n return this.cryptoInitApis.cryptoApi\n }\n\n get dataOwnerApi(): IccDataOwnerXApi {\n return this.cryptoInitApis.dataOwnerApi\n }\n\n get accessLogApi(): IccAccesslogXApi {\n return (\n this._accessLogApi ??\n (this._accessLogApi = new IccAccesslogXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.params.encryptedFieldsConfig.accessLog ?? EncryptedFieldsConfig.Defaults.accessLog,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get agendaApi(): IccAgendaApi {\n return (\n this._agendaApi ?? (this._agendaApi = new IccAgendaApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get anonymousAccessApi(): IccAnonymousAccessApi {\n return (\n this._anonymousAccessApi ??\n (this._anonymousAccessApi = new IccAnonymousAccessApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get applicationSettingsApi(): IccApplicationsettingsApi {\n return (\n this._applicationSettingsApi ??\n (this._applicationSettingsApi = new IccApplicationsettingsApi(\n this.host,\n this.params.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get articleApi(): IccArticleApi {\n return (\n this._articleApi ?? (this._articleApi = new IccArticleApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get authApi(): IccAuthApi {\n return this._authApi ?? (this._authApi = new IccAuthApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get beefactApi(): IccBeefactApi {\n return (\n this._beefactApi ?? (this._beefactApi = new IccBeefactApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get bekmehrApi(): IccBekmehrXApi {\n return (\n this._bekmehrApi ??\n (this._bekmehrApi = new IccBekmehrXApi(\n this.host,\n this.params.headers,\n this.authApi,\n this.contactApi,\n this.healthcareElementApi,\n this.documentApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get beresultexportApi(): IccBeresultexportApi {\n return (\n this._beresultexportApi ??\n (this._beresultexportApi = new IccBeresultexportApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get beresultimportApi(): IccBeresultimportApi {\n return (\n this._beresultimportApi ??\n (this._beresultimportApi = new IccBeresultimportApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get besamv2Api(): IccBesamv2Api {\n return (\n this._besamv2Api ?? (this._besamv2Api = new IccBesamv2Api(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get calendarItemApi(): IccCalendarItemXApi {\n return (\n this._calendarItemApi ??\n (this._calendarItemApi = new IccCalendarItemXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.params.encryptedFieldsConfig.calendarItem ?? EncryptedFieldsConfig.Defaults.calendarItem,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get calendarItemTypeApi(): IccCalendarItemTypeApi {\n return (\n this._calendarItemTypeApi ??\n (this._calendarItemTypeApi = new IccCalendarItemTypeApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get classificationApi(): IccClassificationXApi {\n return (\n this._classificationApi ??\n (this._classificationApi = new IccClassificationXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get classificationTemplateApi(): IccClassificationTemplateApi {\n return (\n this._classificationTemplateApi ??\n (this._classificationTemplateApi = new IccClassificationTemplateApi(\n this.host,\n this.params.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get codeApi(): IccCodeXApi {\n return this._codeApi ?? (this._codeApi = new IccCodeXApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get contactApi(): IccContactXApi {\n return (\n this._contactApi ??\n (this._contactApi = new IccContactXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.userApi,\n this.authApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch,\n this.params.encryptedFieldsConfig.contact ?? EncryptedFieldsConfig.Defaults.contact,\n this.params.encryptedFieldsConfig.service ?? EncryptedFieldsConfig.Defaults.service\n ))\n )\n }\n get deviceApi(): IccDeviceXApi {\n return this.cryptoInitApis.deviceApi\n }\n get doctemplateApi(): IccDoctemplateXApi {\n return (\n this._doctemplateApi ??\n (this._doctemplateApi = new IccDoctemplateXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get documentApi(): IccDocumentXApi {\n return (\n this._documentApi ??\n (this._documentApi = new IccDocumentXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.authApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get entityReferenceApi(): IccEntityrefApi {\n return (\n this._entityReferenceApi ??\n (this._entityReferenceApi = new IccEntityrefApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get entitytemplateApi(): IccEntitytemplateApi {\n return (\n this._entitytemplateApi ??\n (this._entitytemplateApi = new IccEntitytemplateApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get formApi(): IccFormXApi {\n return (\n this._formApi ??\n (this._formApi = new IccFormXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get frontendmigrationApi(): IccFrontendmigrationApi {\n return (\n this._frontendmigrationApi ??\n (this._frontendmigrationApi = new IccFrontendmigrationApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get groupApi(): IccGroupApi {\n return this._groupApi ?? (this._groupApi = new IccGroupApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get healthcareElementApi(): IccHelementXApi {\n return (\n this._healthcareElementApi ??\n (this._healthcareElementApi = new IccHelementXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.userApi,\n this.authApi,\n this.params.encryptedFieldsConfig.healthElement ?? EncryptedFieldsConfig.Defaults.healthElement,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get healthcarePartyApi(): IccHcpartyXApi {\n return this.cryptoInitApis.healthcarePartyApi\n }\n get icureApi(): IccIcureApi {\n return this._icureApi ?? (this._icureApi = new IccIcureApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get icureMaintenanceTaskApi(): IccIcureMaintenanceXApi {\n return this.cryptoInitApis.icureMaintenanceTaskApi\n }\n get insuranceApi(): IccInsuranceApi {\n return (\n this._insuranceApi ??\n (this._insuranceApi = new IccInsuranceApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get invoiceApi(): IccInvoiceXApi {\n return (\n this._invoiceApi ??\n (this._invoiceApi = new IccInvoiceXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.entityReferenceApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get keywordApi(): IccKeywordApi {\n return (\n this._keywordApi ?? (this._keywordApi = new IccKeywordApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get maintenanceTaskApi(): IccMaintenanceTaskXApi {\n return this.cryptoInitApis.maintenanceTaskApi\n }\n get medexApi(): IccMedexApi {\n return this._medexApi ?? (this._medexApi = new IccMedexApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get medicalLocationApi(): IccMedicallocationApi {\n return (\n this._medicalLocationApi ??\n (this._medicalLocationApi = new IccMedicallocationApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get messageApi(): IccMessageXApi {\n return (\n this._messageApi ??\n (this._messageApi = new IccMessageXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get patientApi(): IccPatientXApi {\n return (\n this._patientApi ??\n (this._patientApi = new IccPatientXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.contactApi,\n this.formApi,\n this.healthcareElementApi,\n this.invoiceApi,\n this.documentApi,\n this.healthcarePartyApi,\n this.classificationApi,\n this.dataOwnerApi,\n this.calendarItemApi,\n this.userApi,\n this.authApi,\n this.params.encryptedFieldsConfig.patient ?? EncryptedFieldsConfig.Defaults.patient,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get permissionApi(): IccPermissionApi {\n return (\n this._permissionApi ??\n (this._permissionApi = new IccPermissionApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get placeApi(): IccPlaceApi {\n return this._placeApi ?? (this._placeApi = new IccPlaceApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get pubsubApi(): IccPubsubApi {\n return (\n this._pubsubApi ?? (this._pubsubApi = new IccPubsubApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get receiptApi(): IccReceiptXApi {\n return (\n this._receiptApi ??\n (this._receiptApi = new IccReceiptXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get replicationApi(): IccReplicationApi {\n return (\n this._replicationApi ??\n (this._replicationApi = new IccReplicationApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get tarificationApi(): IccTarificationApi {\n return (\n this._tarificationApi ??\n (this._tarificationApi = new IccTarificationApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get timetableApi(): IccTimeTableXApi {\n return (\n this._timetableApi ??\n (this._timetableApi = new IccTimeTableXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get tmpApi(): IccTmpApi {\n return this._tmpApi ?? (this._tmpApi = new IccTmpApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get userApi(): IccUserXApi {\n return this.cryptoInitApis.userApi\n }\n\n constructor(\n private readonly cryptoInitApis: CryptoInitialisationApis,\n private readonly host: string,\n private readonly groupSpecificAuthenticationProvider: AuthenticationProvider,\n private readonly fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n private readonly grouplessUserApi: IccUserApi,\n private readonly latestMatches: UserGroup[],\n private readonly currentGroupInfo: UserGroup,\n private readonly params: IcureApiOptions.WithDefaults,\n private readonly cryptoStrategies: CryptoStrategies\n ) {\n this.latestGroupsRequest = Promise.resolve(latestMatches)\n }\n\n async getGroupsInfo(): Promise<{ currentGroup: UserGroup; availableGroups: UserGroup[] }> {\n this.latestGroupsRequest = this.grouplessUserApi.getMatchingUsers()\n return { currentGroup: this.currentGroupInfo, availableGroups: await this.latestGroupsRequest }\n }\n\n async switchGroup(newGroupId: string): Promise<IcureApi> {\n const availableGroups = await this.latestGroupsRequest\n const switchedProvider = await this.groupSpecificAuthenticationProvider.switchGroup(newGroupId, availableGroups)\n const cryptoInitApis = await initialiseCryptoWithProvider(\n this.host,\n this.fetch,\n switchedProvider,\n this.params,\n this.cryptoStrategies,\n this.cryptoApi.primitives.crypto\n )\n return new IcureApiImpl(\n cryptoInitApis,\n this.host,\n switchedProvider,\n this.fetch,\n this.grouplessUserApi,\n availableGroups,\n availableGroups.find((x) => x.groupId === newGroupId)!,\n this.params,\n this.cryptoStrategies\n )\n }\n}\n\n/**\n * @experimental This function still needs development and will be changed\n * Build apis which do not need crypto and can be used by non-data-owner users\n */\nexport const BasicApis = async function (\n host: string,\n username: string,\n password: string,\n crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n forceBasic: boolean = false\n) {\n const headers = {}\n const authenticationProvider = forceBasic\n ? new BasicAuthenticationProvider(username, password)\n : new EnsembleAuthenticationProvider(new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl), username, password)\n const authApi = new IccAuthApi(host, headers, authenticationProvider, fetchImpl)\n\n const codeApi = new IccCodeXApi(host, headers, authenticationProvider, fetchImpl)\n const entityReferenceApi = new IccEntityrefApi(host, headers, authenticationProvider, fetchImpl)\n const userApi = new IccUserXApi(host, headers, authenticationProvider, authApi, fetchImpl)\n const permissionApi = new IccPermissionApi(host, headers, authenticationProvider, fetchImpl)\n const agendaApi = new IccAgendaApi(host, headers, authenticationProvider, fetchImpl)\n const groupApi = new IccGroupApi(host, headers, authenticationProvider)\n const insuranceApi = new IccInsuranceApi(host, headers, authenticationProvider, fetchImpl)\n const healthcarePartyApi = new IccHcpartyXApi(host, headers, authenticationProvider, authApi, fetchImpl)\n\n return {\n authApi,\n codeApi,\n userApi,\n permissionApi,\n insuranceApi,\n entityReferenceApi,\n agendaApi,\n groupApi,\n healthcarePartyApi,\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../icc-x-api/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wCA8BmB;AACnB,qDAA8C;AAC9C,yDAAkD;AAClD,2DAAoD;AACpD,2DAAoD;AACpD,6DAAsD;AACtD,2DAAoD;AACpD,qDAA8C;AAC9C,6DAAsD;AACtD,yEAAkE;AAClE,uEAA+D;AAC/D,2DAAoD;AACpD,2DAAoD;AACpD,2DAAoD;AACpD,+DAAwD;AACxD,iEAAyD;AAEzD,qDAA8C;AAC9C,6EAAqE;AACrE,iEAAyD;AAGzD,iEAA6D;AAC7D,6DAAyD;AACzD,0EAMsC;AACtC,gEAA4D;AAC5D,oDAAgD;AAChD,qEAAiE;AACjE,6FAAyF;AACzF,sDAAkD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AA;QAC1F,MAAM,aAAa,GAAG,IAAI,0BAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QAC5F,MAAM,SAAS,GAAG,IAAI,sBAAY,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QACpF,MAAM,QAAQ,GAAG,IAAI,qBAAW,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,CAAC,CAAA;QACvE,MAAM,YAAY,GAAG,IAAI,yBAAe,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QAC1F,MAAM,kBAAkB,GAAG,IAAI,kCAAc,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,SAAS,CAAC,CAAA;QAExG,OAAO;YACL,OAAO;YACP,OAAO;YACP,OAAO;YACP,aAAa;YACb,YAAY;YACZ,kBAAkB;YAClB,SAAS;YACT,QAAQ;YACR,kBAAkB;SACnB,CAAA;IACH,CAAC;CAAA,CAAA;AAtCY,QAAA,SAAS,aAsCrB","sourcesContent":["import {\n IccAgendaApi,\n IccAnonymousAccessApi,\n IccApplicationsettingsApi,\n IccArticleApi,\n IccAuthApi,\n IccBeefactApi,\n IccBeresultexportApi,\n IccBeresultimportApi,\n IccBesamv2Api,\n IccCalendarItemTypeApi,\n IccClassificationTemplateApi,\n IccEntityrefApi,\n IccEntitytemplateApi,\n IccFrontendmigrationApi,\n IccGroupApi,\n IccIcureApi,\n IccInsuranceApi,\n IccKeywordApi,\n IccMedexApi,\n IccMedicallocationApi,\n IccPatientApi,\n IccPermissionApi,\n IccPlaceApi,\n IccPubsubApi,\n IccReplicationApi,\n IccTarificationApi,\n IccTmpApi,\n IccUserApi,\n OAuthThirdParty,\n} from '../icc-api'\nimport { IccUserXApi } from './icc-user-x-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccInvoiceXApi } from './icc-invoice-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHcpartyXApi } from './icc-hcparty-x-api'\nimport { IccFormXApi } from './icc-form-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { IccClassificationXApi } from './icc-classification-x-api'\nimport { IccCalendarItemXApi } from './icc-calendar-item-x-api'\nimport { IccPatientXApi } from './icc-patient-x-api'\nimport { IccMessageXApi } from './icc-message-x-api'\nimport { IccReceiptXApi } from './icc-receipt-x-api'\nimport { IccAccesslogXApi } from './icc-accesslog-x-api'\nimport { IccTimeTableXApi } from './icc-time-table-x-api'\nimport { IccDeviceApi } from '../icc-api'\nimport { IccCodeXApi } from './icc-code-x-api'\nimport { IccMaintenanceTaskXApi } from './icc-maintenance-task-x-api'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\nimport { LocalStorageImpl } from './storage/LocalStorageImpl'\nimport { KeyStorageImpl } from './storage/KeyStorageImpl'\nimport {\n AuthenticationProvider,\n BasicAuthenticationProvider,\n EnsembleAuthenticationProvider,\n JwtAuthenticationProvider,\n NoAuthenticationProvider,\n} from './auth/AuthenticationProvider'\nimport { CryptoPrimitives } from './crypto/CryptoPrimitives'\nimport { KeyManager } from './crypto/KeyManager'\nimport { IcureStorageFacade } from './storage/IcureStorageFacade'\nimport { DefaultStorageEntryKeysFactory } from './storage/DefaultStorageEntryKeysFactory'\nimport { KeyRecovery } from './crypto/KeyRecovery'\nimport { BaseExchangeKeysManager } from './crypto/BaseExchangeKeysManager'\nimport { StorageEntryKeysFactory } from './storage/StorageEntryKeysFactory'\nimport { CryptoStrategies } from './crypto/CryptoStrategies'\nimport { ExchangeKeysManager } from './crypto/ExchangeKeysManager'\nimport { ShamirKeysManager } from './crypto/ShamirKeysManager'\nimport { TransferKeysManager } from './crypto/TransferKeysManager'\nimport { IccIcureMaintenanceXApi } from './icc-icure-maintenance-x-api'\nimport { EntitiesEncryption } from './crypto/EntitiesEncryption'\nimport { ConfidentialEntities } from './crypto/ConfidentialEntities'\nimport { ensureDelegationForSelf } from './crypto/utils'\nimport { CryptoActorStubWithType } from '../icc-api/model/CryptoActorStub'\nimport { IccBekmehrXApi } from './icc-bekmehr-x-api'\nimport { IccDoctemplateXApi } from './icc-doctemplate-x-api'\nimport { UserGroup } from '../icc-api/model/UserGroup'\nimport { IccDeviceXApi } from './icc-device-x-api'\n\nexport * from './icc-accesslog-x-api'\nexport * from './icc-bekmehr-x-api'\nexport * from './icc-calendar-item-x-api'\nexport * from './icc-classification-x-api'\nexport * from './icc-code-x-api'\nexport * from './icc-contact-x-api'\nexport * from './icc-crypto-x-api'\nexport * from './icc-doctemplate-x-api'\nexport * from './icc-document-x-api'\nexport * from './icc-form-x-api'\nexport * from './icc-hcparty-x-api'\nexport * from './icc-helement-x-api'\nexport * from './icc-invoice-x-api'\nexport * from './icc-message-x-api'\nexport * from './icc-patient-x-api'\nexport * from './icc-user-x-api'\nexport * from './icc-time-table-x-api'\nexport * from './icc-receipt-x-api'\nexport * from './icc-data-owner-x-api'\nexport * from './icc-icure-maintenance-x-api'\nexport * from './icc-maintenance-task-x-api'\nexport * from './utils'\n\nexport * from './crypto/RSA'\nexport * from './crypto/CryptoPrimitives'\nexport * from './auth/AuthenticationProvider'\n\nexport { KeyStorageFacade } from './storage/KeyStorageFacade'\nexport { LocalStorageImpl } from './storage/LocalStorageImpl'\nexport { StorageFacade } from './storage/StorageFacade'\nexport { KeyStorageImpl } from './storage/KeyStorageImpl'\nexport { CryptoStrategies } from './crypto/CryptoStrategies'\n\nexport interface Apis {\n readonly authApi: IccAuthApi\n readonly codeApi: IccCodeXApi\n readonly calendarItemTypeApi: IccCalendarItemTypeApi\n readonly medicalLocationApi: IccMedicallocationApi\n readonly entityReferenceApi: IccEntityrefApi\n readonly userApi: IccUserXApi\n readonly permissionApi: IccPermissionApi\n readonly healthcarePartyApi: IccHcpartyXApi\n readonly deviceApi: IccDeviceXApi\n readonly cryptoApi: IccCryptoXApi\n readonly accessLogApi: IccAccesslogXApi\n readonly agendaApi: IccAgendaApi\n readonly contactApi: IccContactXApi\n readonly formApi: IccFormXApi\n readonly groupApi: IccGroupApi\n readonly invoiceApi: IccInvoiceXApi\n readonly insuranceApi: IccInsuranceApi\n readonly documentApi: IccDocumentXApi\n readonly healthcareElementApi: IccHelementXApi\n readonly classificationApi: IccClassificationXApi\n readonly calendarItemApi: IccCalendarItemXApi\n readonly receiptApi: IccReceiptXApi\n readonly timetableApi: IccTimeTableXApi\n readonly patientApi: IccPatientXApi\n readonly messageApi: IccMessageXApi\n readonly maintenanceTaskApi: IccMaintenanceTaskXApi\n readonly dataOwnerApi: IccDataOwnerXApi\n readonly icureMaintenanceTaskApi: IccIcureMaintenanceXApi\n readonly anonymousAccessApi: IccAnonymousAccessApi\n readonly applicationSettingsApi: IccApplicationsettingsApi\n readonly articleApi: IccArticleApi\n readonly bekmehrApi: IccBekmehrXApi\n readonly beefactApi: IccBeefactApi\n readonly beresultexportApi: IccBeresultexportApi\n readonly beresultimportApi: IccBeresultimportApi\n readonly besamv2Api: IccBesamv2Api\n readonly classificationTemplateApi: IccClassificationTemplateApi\n readonly doctemplateApi: IccDoctemplateXApi\n readonly entitytemplateApi: IccEntitytemplateApi\n readonly frontendmigrationApi: IccFrontendmigrationApi\n readonly icureApi: IccIcureApi\n readonly keywordApi: IccKeywordApi\n readonly medexApi: IccMedexApi\n readonly placeApi: IccPlaceApi\n readonly pubsubApi: IccPubsubApi\n readonly replicationApi: IccReplicationApi\n readonly tarificationApi: IccTarificationApi\n readonly tmpApi: IccTmpApi\n}\n\n/**\n * Allows to customise the behaviour of the iCure API by providing various optional parameters.\n */\nexport interface IcureApiOptions {\n /**\n * Specifies how iCure can store string values (e.g. json). In production this should be persistent storage.\n * @default the browser's localStorage.\n */\n readonly storage?: StorageFacade<string>\n /**\n * Specifies how iCure can store cryptographic keys. Preferably this should be some ad-hoc storage key storage.\n * @default stores the json of the jwk representation of the key in {@link storage}.\n */\n readonly keyStorage?: KeyStorageFacade\n /**\n * Specifies where iCure should store his data within the {@link storage} and {@link keyStorage}.\n * @default {@link DefaultStorageEntryKeysFactory}\n */\n readonly entryKeysFactory?: StorageEntryKeysFactory\n /**\n * Specifies if iCure should create maintenance tasks for requesting access back when a new key is generated at initialisation time.\n * @default true\n */\n readonly createMaintenanceTasksOnNewKey?: boolean\n /**\n * Additional headers to use on each request made by the iCure api.\n * @default no additional headers\n */\n readonly headers?: { [headerName: string]: string }\n /**\n * Specifies which fields should be encrypted for each kind of encryptable entity. You should make sure that every application in your environment\n * specifies the same values for this configuration.\n * @default see documentation for {@link EncryptedFieldsConfig}\n */\n readonly encryptedFieldsConfig?: EncryptedFieldsConfig\n /**\n * Each user may exist in multiple groups, but an instance of {@link IcureApi} is specialised for a single group. This function allows you to decide\n * the group to use for a given user. This functions will be called only if a user exists in at least 2 groups, takes in input the information on\n * the groups the user can access (in no specific order) and must return the id of one of these groups.\n * @default takes the first group provided. The group chosen by this method may vary between different instantiations of the {@link IcureApi} even\n * if for the same user and if the groups available for the user do not change.\n */\n readonly groupSelector?: (availableGroupsInfo: UserGroup[]) => Promise<string>\n /**\n * Temporary value to support EHR Lite and MedTech api implementations.\n *\n * Currently, all hcps are able to access encrypted data shared with any of their parents, and on initialisation the api will verify that there is a\n * key pair available for the current user and for every parent of the user. If this option is set to true, the api will not load keys for the\n * parent users.\n *\n * This \"implicit data-sharing scheme\" (each parent HCP is essentially sharing data with all its children HCPs), however, may not be ideal for all\n * use cases, and it will be changed in future to be configurable in order to make it more general.\n * @default false, equivalent to previous behaviour.\n */\n readonly disableParentKeysInitialisation?: boolean\n}\nnamespace IcureApiOptions {\n export namespace Defaults {\n export const entryKeysFactory = new DefaultStorageEntryKeysFactory()\n export const createMaintenanceTasksOnNewKey = true\n export const headers = {}\n }\n export class WithDefaults implements IcureApiOptions {\n constructor(custom: IcureApiOptions) {\n this.entryKeysFactory = custom.entryKeysFactory ?? Defaults.entryKeysFactory\n this.createMaintenanceTasksOnNewKey = custom.createMaintenanceTasksOnNewKey ?? Defaults.createMaintenanceTasksOnNewKey\n this.storage = custom.storage ?? new LocalStorageImpl()\n this.keyStorage = custom.keyStorage ?? new KeyStorageImpl(this.storage)\n this.headers = custom.headers ?? Defaults.headers\n this.encryptedFieldsConfig = custom.encryptedFieldsConfig ?? EncryptedFieldsConfig.Defaults\n this.groupSelector = custom.groupSelector ?? ((groups) => Promise.resolve(groups[0].groupId!))\n this.disableParentKeysInitialisation = custom.disableParentKeysInitialisation ?? false\n }\n\n readonly entryKeysFactory: StorageEntryKeysFactory\n readonly createMaintenanceTasksOnNewKey: boolean\n readonly storage: StorageFacade<string>\n readonly keyStorage: KeyStorageFacade\n readonly headers: { [headerName: string]: string }\n readonly encryptedFieldsConfig: EncryptedFieldsConfig\n readonly groupSelector: (availableGroupsInfo: UserGroup[]) => Promise<string>\n readonly disableParentKeysInitialisation: boolean\n }\n}\n\n/**\n * Specifies which fields should be encrypted for each kind of encryptable entity.\n *\n * Note that any value you specify here overrides the default values. For example if you specify `['medicalLocationId']` for `healthElement` the\n * fields `['descr', 'note']` which are usually encrypted by default will no longer be encrypted. If you want to add fields to the default values\n * you can use {@link EncryptedFieldsConfig.Defaults}, for example `[...EncryptedFieldsConfig.Defaults.healthElement, 'medicalLocationId'].\n *\n * # Encrypted fields syntax\n *\n * ## Grammar\n *\n * The grammar for each encrypted field is the following:\n * ```\n * fieldName :=\n * regex([a-zA-Z_][a-zA-Z0-9_]+)\n * encryptedField :=\n * fieldName\n * | fieldName + (\".\" | \".*.\" | \"[].\") + encryptedField\n * ```\n *\n * This grammar allows you to specify the fields to encrypt for the object and recursively for nested objects.\n * - A string containing only a single `fieldName` will encrypt the field with the given name.\n * - A string starting with `fieldName.` allows to specify the encrypted fields of a nested object. The encrypted values of the\n * fields in the nested object will be saved in the nested object.\n * - A string starting with `fieldName.*.` treats `fieldName` as a map/dictionary data structure and allows to specify the encrypted fields of the\n * values of the map. Note that the values of the map must be objects as well. The encrypted content of each map value is stored in that value.\n * - A string starting with `fieldName[].` treats `fieldName` as an array and allows to specify the encrypted fields of the values of the array.\n * Note that the values of the array must be objects as well. The encrypted content of each array element is stored in that element.\n *\n * ## Example\n *\n * Consider the following object and encryption keys:\n * ```javascript\n * const obj = {\n * a: { x: 0, y: 1 },\n * b: \"hello\",\n * c: [ { public: \"a\", secret: \"b\" }, { public: \"c\", secret: \"d\" } ],\n * d: \"ok\",\n * e: {\n * info: \"something\",\n * private: \"secret\",\n * dataMap: {\n * \"en\": {\n * a: 1,\n * b: 2\n * },\n * \"fr\": {\n * a: 3,\n * b: 4\n * }\n * }\n * }\n * }\n * const encryptedFields = [\n * \"a\",\n * \"c[].secret\",\n * \"d\",\n * \"e.private\",\n * \"e.datamap.*.a\"\n * ]\n * ```\n * If you use them with the crypt method you will get the following result:\n * ```json\n * {\n * b: \"hello\",\n * c: [\n * { public: \"a\", encryptedSelf: 'encrypted+encoded { secret: \"b\" }' },\n * { public: \"c\", encryptedSelf: 'encrypted+encoded { secret: \"d\" }' }\n * ],\n * e: {\n * info: \"something\",\n * dataMap: {\n * \"en\": { b: 2, encryptedSelf: 'encrypted+encoded { a: 1 }' },\n * \"fr\": { b: 4, encryptedSelf: 'encrypted+encoded { a: 3 }' }\n * },\n * encryptedSelf: 'encrypted+encoded { private: \"secret\" }'\n * },\n * encryptedSelf: 'encrypted+encoded { a: { x: 0, y: 1 }, d: \"ok\" }'\n * }\n * ```\n *\n * ## Shortened representation\n *\n * You can also group encrypted fields having the same prefix by concatenating to the prefix the JSON representation of an array of all the postfixes.\n * For example the following encrypted fields:\n * ```javascript\n * const encryptedFields = [\"a.b.c.d.e.f1\", \"a.b.c.d.e.f2\", \"a.b.c.d.e.f3\", \"a.b.c.d.e.f4\"]\n * ```\n * can be shortened to\n * ```javascript\n * const encryptedFields = ['a.b.c.d.e.[\"f1\",\"f2\",\"f3\",\"f4\"]'] // Note the use of single quotes to avoid escaping the double quotes\n * ```\n * If you use the shortened representation you may need to escape nested json representations. In that case the use of `JSON.stringify` is\n * recommended.\n */\nexport interface EncryptedFieldsConfig {\n /**\n * Fields to encrypt for entities of type {@link AccessLog}\n * @default ['detail', 'objectId']\n */\n readonly accessLog?: string[]\n /**\n * Fields to encrypt for entities of type {@link CalendarItem}\n * @default ['details', 'title', 'patientId']\n */\n readonly calendarItem?: string[]\n /**\n * Fields to encrypt for entities of type {@link Contact}, excluding `services`. You can specify which fields of `services` should be encrypted\n * using {@link service}.\n * @default ['descr'] // encryption of `services` is managed through {@link service}\n */\n readonly contact?: string[]\n /**\n * Fields to encrypt for entities of type {@link Service}. Note that encryption of the `content` field and recursively contained `Services` through\n * `content.compoundValue` is automatically managed by the sdk, and you are not allowed to modify it.\n *\n * Note: any non-empty values for this field will break bi-directional data compatibility between v7 and previous: Contacts created with\n * v7 will not be read properly by previous versions. If you want\n * @default ['notes[].markdown'] // encryption of `content` is managed in a special way\n */\n readonly service?: string[]\n /**\n * Fields to encrypt for entities of type {@link HealthElement}\n * @default ['descr', 'note', 'notes[].markdown']\n */\n readonly healthElement?: string[]\n /**\n * Fields to encrypt for entities of type {@link MaintenanceTask}\n * @default ['properties']\n */\n readonly maintenanceTask?: string[]\n /**\n * Fields to encrypt for entities of type {@link Patient}\n * @default ['note', 'notes[].markdown']\n */\n readonly patient?: string[]\n}\nexport namespace EncryptedFieldsConfig {\n export const Defaults = {\n accessLog: ['detail', 'objectId'],\n calendarItem: ['details', 'title', 'patientId'],\n contact: ['descr'],\n service: ['notes[].markdown'],\n healthElement: ['descr', 'note', 'notes[].markdown'],\n maintenanceTask: ['properties'],\n patient: ['note', 'notes[].markdown'],\n }\n}\n\n/**\n * Details for the authentication of a user\n */\nexport type AuthenticationDetails = {\n username: string\n password: string\n forceBasic?: boolean // default false\n icureTokens?: { token: string; refreshToken: string }\n thirdPartyTokens?: { [thirdParty: string]: string }\n}\n\n/**\n * Main entry point for the iCure API. Provides entity-specific sub-apis and some general methods which are not related to a specific entity.\n */\nexport interface IcureApi extends Apis {\n /**\n * Get the information on groups that the current user can access and the current group that this api instance is working on.\n * Note that the values you will get for `availableGroups` may differ from the values you would get if you call {@link IccUserApi.getMatchingUsers}\n * on {@link Apis.userApi}, since the latter is specialised on the specific instance of the user in `currentGroup`.\n */\n getGroupsInfo(): Promise<{ currentGroup: UserGroup; availableGroups: UserGroup[] }>\n\n /**\n * Switches the api to allow the user to work on a different group.\n * @param newGroupId the id of the group to switch to.\n * @return a new api for the specified group.\n */\n switchGroup(newGroupId: string): Promise<IcureApi>\n}\nexport namespace IcureApi {\n /**\n * Initialises a new instance of the iCure API.\n */\n export async function initialise(\n host: string,\n authenticationOptions: AuthenticationDetails | AuthenticationProvider,\n cryptoStrategies: CryptoStrategies,\n crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n options: IcureApiOptions = {}\n ): Promise<IcureApi> {\n const params = new IcureApiOptions.WithDefaults(options)\n let grouplessAuthenticationProvider: AuthenticationProvider\n if ('getIcureTokens' in authenticationOptions && 'switchGroup' in authenticationOptions && 'getAuthService' in authenticationOptions) {\n const tokens = await authenticationOptions.getIcureTokens()\n if (!!tokens && !!tokens.token && !!tokens.refreshToken) {\n grouplessAuthenticationProvider = new JwtAuthenticationProvider(\n new IccAuthApi(host, params.headers, new NoAuthenticationProvider(), fetchImpl),\n undefined,\n undefined,\n undefined,\n tokens\n )\n } else {\n grouplessAuthenticationProvider = authenticationOptions\n }\n } else if (\n 'username' in authenticationOptions &&\n 'password' in authenticationOptions &&\n !!authenticationOptions.username &&\n !!authenticationOptions.password\n ) {\n grouplessAuthenticationProvider = new EnsembleAuthenticationProvider(\n new IccAuthApi(host, params.headers, new NoAuthenticationProvider(), fetchImpl),\n authenticationOptions.username,\n authenticationOptions.password,\n 3600,\n undefined,\n undefined,\n authenticationOptions.thirdPartyTokens\n )\n } else {\n throw new Error('Invalid authentication options provided')\n }\n const grouplessUserApi = new IccUserApi(host, params.headers, grouplessAuthenticationProvider, fetchImpl)\n const matches = await grouplessUserApi.getMatchingUsers()\n const chosenGroupId = matches.length > 1 ? await params.groupSelector(matches) : matches[0].groupId!\n /*TODO\n * On new very new users switching the authentication provider to a specific group may fail and block the user for too many requests. This is\n * probably linked to replication of the user in the fallback database.\n */\n const groupSpecificAuthenticationProvider =\n matches.length > 1 ? await grouplessAuthenticationProvider.switchGroup(chosenGroupId, matches) : grouplessAuthenticationProvider\n const cryptoApis = await initialiseCryptoWithProvider(host, fetchImpl, groupSpecificAuthenticationProvider, params, cryptoStrategies, crypto)\n return new IcureApiImpl(\n cryptoApis,\n host,\n groupSpecificAuthenticationProvider,\n fetch,\n grouplessUserApi,\n matches,\n matches.find((match) => match.groupId === chosenGroupId)!,\n params,\n cryptoStrategies\n )\n }\n}\n\n// Apis which are used during crypto api initialisation, to avoid re-instantiating them later\ntype CryptoInitialisationApis = {\n cryptoApi: IccCryptoXApi\n healthcarePartyApi: IccHcpartyXApi\n deviceApi: IccDeviceXApi\n // no patient api since it is base\n dataOwnerApi: IccDataOwnerXApi\n userApi: IccUserXApi\n icureMaintenanceTaskApi: IccIcureMaintenanceXApi\n maintenanceTaskApi: IccMaintenanceTaskXApi\n}\n\nasync function initialiseCryptoWithProvider(\n host: string,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n groupSpecificAuthenticationProvider: AuthenticationProvider,\n params: IcureApiOptions.WithDefaults,\n cryptoStrategies: CryptoStrategies,\n crypto: Crypto\n): Promise<CryptoInitialisationApis> {\n const authApi = new IccAuthApi(host, params.headers, groupSpecificAuthenticationProvider, fetchImpl)\n const userApi = new IccUserXApi(host, params.headers, groupSpecificAuthenticationProvider, authApi, fetchImpl)\n const healthcarePartyApi = new IccHcpartyXApi(host, params.headers, groupSpecificAuthenticationProvider, authApi, fetchImpl)\n const deviceApi = new IccDeviceXApi(host, params.headers, groupSpecificAuthenticationProvider, userApi, authApi, fetchImpl)\n const basePatientApi = new IccPatientApi(host, params.headers, groupSpecificAuthenticationProvider, fetchImpl)\n const dataOwnerApi = new IccDataOwnerXApi(host, params.headers, groupSpecificAuthenticationProvider, fetchImpl)\n // Crypto initialisation\n const icureStorage = new IcureStorageFacade(params.keyStorage, params.storage, params.entryKeysFactory)\n const cryptoPrimitives = new CryptoPrimitives(crypto)\n const baseExchangeKeysManager = new BaseExchangeKeysManager(cryptoPrimitives, dataOwnerApi, healthcarePartyApi, basePatientApi, deviceApi)\n const keyRecovery = new KeyRecovery(cryptoPrimitives, baseExchangeKeysManager, dataOwnerApi)\n const keyManager = new KeyManager(\n cryptoPrimitives,\n dataOwnerApi,\n icureStorage,\n keyRecovery,\n baseExchangeKeysManager,\n cryptoStrategies,\n !params.disableParentKeysInitialisation\n )\n const newKey = await keyManager.initialiseKeys()\n await new TransferKeysManager(cryptoPrimitives, baseExchangeKeysManager, dataOwnerApi, keyManager, icureStorage).updateTransferKeys(\n CryptoActorStubWithType.fromDataOwner(await dataOwnerApi.getCurrentDataOwner())\n )\n // TODO customise cache size?\n const exchangeKeysManager = new ExchangeKeysManager(\n 100,\n 500,\n 60000,\n 600000,\n cryptoStrategies,\n cryptoPrimitives,\n keyManager,\n baseExchangeKeysManager,\n dataOwnerApi,\n !params.disableParentKeysInitialisation\n )\n const entitiesEncryption = new EntitiesEncryption(cryptoPrimitives, dataOwnerApi, exchangeKeysManager, !params.disableParentKeysInitialisation)\n const shamirManager = new ShamirKeysManager(cryptoPrimitives, dataOwnerApi, keyManager, exchangeKeysManager)\n const confidentialEntitites = new ConfidentialEntities(entitiesEncryption, cryptoPrimitives, dataOwnerApi)\n await ensureDelegationForSelf(dataOwnerApi, entitiesEncryption, cryptoPrimitives, basePatientApi)\n const cryptoApi = new IccCryptoXApi(\n exchangeKeysManager,\n cryptoPrimitives,\n keyManager,\n dataOwnerApi,\n entitiesEncryption,\n shamirManager,\n params.storage,\n params.keyStorage,\n icureStorage,\n healthcarePartyApi,\n confidentialEntitites,\n basePatientApi\n )\n const maintenanceTaskApi = new IccMaintenanceTaskXApi(\n host,\n params.headers,\n cryptoApi,\n healthcarePartyApi,\n dataOwnerApi,\n userApi,\n authApi,\n params.encryptedFieldsConfig?.maintenanceTask ?? EncryptedFieldsConfig.Defaults.maintenanceTask,\n groupSpecificAuthenticationProvider,\n fetchImpl\n )\n const icureMaintenanceTaskApi = new IccIcureMaintenanceXApi(cryptoApi, maintenanceTaskApi, dataOwnerApi)\n if (newKey && params.createMaintenanceTasksOnNewKey) {\n await icureMaintenanceTaskApi.createMaintenanceTasksForNewKeypair(await userApi.getCurrentUser(), newKey.newKeyPair)\n }\n return {\n cryptoApi,\n healthcarePartyApi,\n deviceApi,\n dataOwnerApi,\n userApi,\n icureMaintenanceTaskApi,\n maintenanceTaskApi,\n }\n}\n\nclass IcureApiImpl implements IcureApi {\n private latestGroupsRequest: Promise<UserGroup[]>\n private _authApi: IccAuthApi | undefined\n private _codeApi: IccCodeXApi | undefined\n private _calendarItemTypeApi: IccCalendarItemTypeApi | undefined\n private _medicalLocationApi: IccMedicallocationApi | undefined\n private _entityReferenceApi: IccEntityrefApi | undefined\n private _permissionApi: IccPermissionApi | undefined\n private _accessLogApi: IccAccesslogXApi | undefined\n private _agendaApi: IccAgendaApi | undefined\n private _contactApi: IccContactXApi | undefined\n private _formApi: IccFormXApi | undefined\n private _groupApi: IccGroupApi | undefined\n private _invoiceApi: IccInvoiceXApi | undefined\n private _insuranceApi: IccInsuranceApi | undefined\n private _documentApi: IccDocumentXApi | undefined\n private _healthcareElementApi: IccHelementXApi | undefined\n private _classificationApi: IccClassificationXApi | undefined\n private _calendarItemApi: IccCalendarItemXApi | undefined\n private _receiptApi: IccReceiptXApi | undefined\n private _timetableApi: IccTimeTableXApi | undefined\n private _patientApi: IccPatientXApi | undefined\n private _messageApi: IccMessageXApi | undefined\n private _anonymousAccessApi: IccAnonymousAccessApi | undefined\n private _applicationSettingsApi: IccApplicationsettingsApi | undefined\n private _articleApi: IccArticleApi | undefined\n private _bekmehrApi: IccBekmehrXApi | undefined\n private _beefactApi: IccBeefactApi | undefined\n private _beresultexportApi: IccBeresultexportApi | undefined\n private _beresultimportApi: IccBeresultimportApi | undefined\n private _besamv2Api: IccBesamv2Api | undefined\n private _classificationTemplateApi: IccClassificationTemplateApi | undefined\n private _doctemplateApi: IccDoctemplateXApi | undefined\n private _entitytemplateApi: IccEntitytemplateApi | undefined\n private _frontendmigrationApi: IccFrontendmigrationApi | undefined\n private _icureApi: IccIcureApi | undefined\n private _keywordApi: IccKeywordApi | undefined\n private _medexApi: IccMedexApi | undefined\n private _placeApi: IccPlaceApi | undefined\n private _pubsubApi: IccPubsubApi | undefined\n private _replicationApi: IccReplicationApi | undefined\n private _tarificationApi: IccTarificationApi | undefined\n private _tmpApi: IccTmpApi | undefined\n\n get cryptoApi(): IccCryptoXApi {\n return this.cryptoInitApis.cryptoApi\n }\n\n get dataOwnerApi(): IccDataOwnerXApi {\n return this.cryptoInitApis.dataOwnerApi\n }\n\n get accessLogApi(): IccAccesslogXApi {\n return (\n this._accessLogApi ??\n (this._accessLogApi = new IccAccesslogXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.params.encryptedFieldsConfig.accessLog ?? EncryptedFieldsConfig.Defaults.accessLog,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get agendaApi(): IccAgendaApi {\n return (\n this._agendaApi ?? (this._agendaApi = new IccAgendaApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get anonymousAccessApi(): IccAnonymousAccessApi {\n return (\n this._anonymousAccessApi ??\n (this._anonymousAccessApi = new IccAnonymousAccessApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get applicationSettingsApi(): IccApplicationsettingsApi {\n return (\n this._applicationSettingsApi ??\n (this._applicationSettingsApi = new IccApplicationsettingsApi(\n this.host,\n this.params.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get articleApi(): IccArticleApi {\n return (\n this._articleApi ?? (this._articleApi = new IccArticleApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get authApi(): IccAuthApi {\n return this._authApi ?? (this._authApi = new IccAuthApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get beefactApi(): IccBeefactApi {\n return (\n this._beefactApi ?? (this._beefactApi = new IccBeefactApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get bekmehrApi(): IccBekmehrXApi {\n return (\n this._bekmehrApi ??\n (this._bekmehrApi = new IccBekmehrXApi(\n this.host,\n this.params.headers,\n this.authApi,\n this.contactApi,\n this.healthcareElementApi,\n this.documentApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get beresultexportApi(): IccBeresultexportApi {\n return (\n this._beresultexportApi ??\n (this._beresultexportApi = new IccBeresultexportApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get beresultimportApi(): IccBeresultimportApi {\n return (\n this._beresultimportApi ??\n (this._beresultimportApi = new IccBeresultimportApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get besamv2Api(): IccBesamv2Api {\n return (\n this._besamv2Api ?? (this._besamv2Api = new IccBesamv2Api(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get calendarItemApi(): IccCalendarItemXApi {\n return (\n this._calendarItemApi ??\n (this._calendarItemApi = new IccCalendarItemXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.params.encryptedFieldsConfig.calendarItem ?? EncryptedFieldsConfig.Defaults.calendarItem,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get calendarItemTypeApi(): IccCalendarItemTypeApi {\n return (\n this._calendarItemTypeApi ??\n (this._calendarItemTypeApi = new IccCalendarItemTypeApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get classificationApi(): IccClassificationXApi {\n return (\n this._classificationApi ??\n (this._classificationApi = new IccClassificationXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get classificationTemplateApi(): IccClassificationTemplateApi {\n return (\n this._classificationTemplateApi ??\n (this._classificationTemplateApi = new IccClassificationTemplateApi(\n this.host,\n this.params.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get codeApi(): IccCodeXApi {\n return this._codeApi ?? (this._codeApi = new IccCodeXApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get contactApi(): IccContactXApi {\n return (\n this._contactApi ??\n (this._contactApi = new IccContactXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.userApi,\n this.authApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch,\n this.params.encryptedFieldsConfig.contact ?? EncryptedFieldsConfig.Defaults.contact,\n this.params.encryptedFieldsConfig.service ?? EncryptedFieldsConfig.Defaults.service\n ))\n )\n }\n get deviceApi(): IccDeviceXApi {\n return this.cryptoInitApis.deviceApi\n }\n get doctemplateApi(): IccDoctemplateXApi {\n return (\n this._doctemplateApi ??\n (this._doctemplateApi = new IccDoctemplateXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get documentApi(): IccDocumentXApi {\n return (\n this._documentApi ??\n (this._documentApi = new IccDocumentXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.authApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get entityReferenceApi(): IccEntityrefApi {\n return (\n this._entityReferenceApi ??\n (this._entityReferenceApi = new IccEntityrefApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get entitytemplateApi(): IccEntitytemplateApi {\n return (\n this._entitytemplateApi ??\n (this._entitytemplateApi = new IccEntitytemplateApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get formApi(): IccFormXApi {\n return (\n this._formApi ??\n (this._formApi = new IccFormXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get frontendmigrationApi(): IccFrontendmigrationApi {\n return (\n this._frontendmigrationApi ??\n (this._frontendmigrationApi = new IccFrontendmigrationApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get groupApi(): IccGroupApi {\n return this._groupApi ?? (this._groupApi = new IccGroupApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get healthcareElementApi(): IccHelementXApi {\n return (\n this._healthcareElementApi ??\n (this._healthcareElementApi = new IccHelementXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.userApi,\n this.authApi,\n this.params.encryptedFieldsConfig.healthElement ?? EncryptedFieldsConfig.Defaults.healthElement,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get healthcarePartyApi(): IccHcpartyXApi {\n return this.cryptoInitApis.healthcarePartyApi\n }\n get icureApi(): IccIcureApi {\n return this._icureApi ?? (this._icureApi = new IccIcureApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get icureMaintenanceTaskApi(): IccIcureMaintenanceXApi {\n return this.cryptoInitApis.icureMaintenanceTaskApi\n }\n get insuranceApi(): IccInsuranceApi {\n return (\n this._insuranceApi ??\n (this._insuranceApi = new IccInsuranceApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get invoiceApi(): IccInvoiceXApi {\n return (\n this._invoiceApi ??\n (this._invoiceApi = new IccInvoiceXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.entityReferenceApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get keywordApi(): IccKeywordApi {\n return (\n this._keywordApi ?? (this._keywordApi = new IccKeywordApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get maintenanceTaskApi(): IccMaintenanceTaskXApi {\n return this.cryptoInitApis.maintenanceTaskApi\n }\n get medexApi(): IccMedexApi {\n return this._medexApi ?? (this._medexApi = new IccMedexApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get medicalLocationApi(): IccMedicallocationApi {\n return (\n this._medicalLocationApi ??\n (this._medicalLocationApi = new IccMedicallocationApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get messageApi(): IccMessageXApi {\n return (\n this._messageApi ??\n (this._messageApi = new IccMessageXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get patientApi(): IccPatientXApi {\n return (\n this._patientApi ??\n (this._patientApi = new IccPatientXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.contactApi,\n this.formApi,\n this.healthcareElementApi,\n this.invoiceApi,\n this.documentApi,\n this.healthcarePartyApi,\n this.classificationApi,\n this.dataOwnerApi,\n this.calendarItemApi,\n this.userApi,\n this.authApi,\n this.params.encryptedFieldsConfig.patient ?? EncryptedFieldsConfig.Defaults.patient,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get permissionApi(): IccPermissionApi {\n return (\n this._permissionApi ??\n (this._permissionApi = new IccPermissionApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get placeApi(): IccPlaceApi {\n return this._placeApi ?? (this._placeApi = new IccPlaceApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get pubsubApi(): IccPubsubApi {\n return (\n this._pubsubApi ?? (this._pubsubApi = new IccPubsubApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get receiptApi(): IccReceiptXApi {\n return (\n this._receiptApi ??\n (this._receiptApi = new IccReceiptXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get replicationApi(): IccReplicationApi {\n return (\n this._replicationApi ??\n (this._replicationApi = new IccReplicationApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get tarificationApi(): IccTarificationApi {\n return (\n this._tarificationApi ??\n (this._tarificationApi = new IccTarificationApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get timetableApi(): IccTimeTableXApi {\n return (\n this._timetableApi ??\n (this._timetableApi = new IccTimeTableXApi(\n this.host,\n this.params.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n get tmpApi(): IccTmpApi {\n return this._tmpApi ?? (this._tmpApi = new IccTmpApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get userApi(): IccUserXApi {\n return this.cryptoInitApis.userApi\n }\n\n constructor(\n private readonly cryptoInitApis: CryptoInitialisationApis,\n private readonly host: string,\n private readonly groupSpecificAuthenticationProvider: AuthenticationProvider,\n private readonly fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n private readonly grouplessUserApi: IccUserApi,\n private readonly latestMatches: UserGroup[],\n private readonly currentGroupInfo: UserGroup,\n private readonly params: IcureApiOptions.WithDefaults,\n private readonly cryptoStrategies: CryptoStrategies\n ) {\n this.latestGroupsRequest = Promise.resolve(latestMatches)\n }\n\n async getGroupsInfo(): Promise<{ currentGroup: UserGroup; availableGroups: UserGroup[] }> {\n this.latestGroupsRequest = this.grouplessUserApi.getMatchingUsers()\n return { currentGroup: this.currentGroupInfo, availableGroups: await this.latestGroupsRequest }\n }\n\n async switchGroup(newGroupId: string): Promise<IcureApi> {\n const availableGroups = await this.latestGroupsRequest\n const switchedProvider = await this.groupSpecificAuthenticationProvider.switchGroup(newGroupId, availableGroups)\n const cryptoInitApis = await initialiseCryptoWithProvider(\n this.host,\n this.fetch,\n switchedProvider,\n this.params,\n this.cryptoStrategies,\n this.cryptoApi.primitives.crypto\n )\n return new IcureApiImpl(\n cryptoInitApis,\n this.host,\n switchedProvider,\n this.fetch,\n this.grouplessUserApi,\n availableGroups,\n availableGroups.find((x) => x.groupId === newGroupId)!,\n this.params,\n this.cryptoStrategies\n )\n }\n}\n\n/**\n * @experimental This function still needs development and will be changed\n * Build apis which do not need crypto and can be used by non-data-owner users\n */\nexport const BasicApis = async function (\n host: string,\n username: string,\n password: string,\n crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n forceBasic: boolean = false\n) {\n const headers = {}\n const authenticationProvider = forceBasic\n ? new BasicAuthenticationProvider(username, password)\n : new EnsembleAuthenticationProvider(new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl), username, password)\n const authApi = new IccAuthApi(host, headers, authenticationProvider, fetchImpl)\n\n const codeApi = new IccCodeXApi(host, headers, authenticationProvider, fetchImpl)\n const entityReferenceApi = new IccEntityrefApi(host, headers, authenticationProvider, fetchImpl)\n const userApi = new IccUserXApi(host, headers, authenticationProvider, authApi, fetchImpl)\n const permissionApi = new IccPermissionApi(host, headers, authenticationProvider, fetchImpl)\n const agendaApi = new IccAgendaApi(host, headers, authenticationProvider, fetchImpl)\n const groupApi = new IccGroupApi(host, headers, authenticationProvider)\n const insuranceApi = new IccInsuranceApi(host, headers, authenticationProvider, fetchImpl)\n const healthcarePartyApi = new IccHcpartyXApi(host, headers, authenticationProvider, authApi, fetchImpl)\n\n return {\n authApi,\n codeApi,\n userApi,\n permissionApi,\n insuranceApi,\n entityReferenceApi,\n agendaApi,\n groupApi,\n healthcarePartyApi,\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icure/api",
3
- "version": "7.1.11",
3
+ "version": "7.1.12",
4
4
  "description": "Typescript version of iCure standalone API client",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",