@icure/api 7.1.0 → 7.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/icc-api/model/Annotation.d.ts +0 -4
- package/icc-api/model/Annotation.js.map +1 -1
- package/icc-x-api/crypto/EntitiesEncryption.d.ts +2 -1
- package/icc-x-api/crypto/EntitiesEncryption.js +11 -5
- package/icc-x-api/crypto/EntitiesEncryption.js.map +1 -1
- package/icc-x-api/crypto/ExchangeKeysManager.d.ts +4 -5
- package/icc-x-api/crypto/ExchangeKeysManager.js +4 -4
- package/icc-x-api/crypto/ExchangeKeysManager.js.map +1 -1
- package/icc-x-api/crypto/KeyManager.d.ts +3 -2
- package/icc-x-api/crypto/KeyManager.js +5 -4
- package/icc-x-api/crypto/KeyManager.js.map +1 -1
- package/icc-x-api/filters/filters.d.ts +15 -1
- package/icc-x-api/filters/filters.js.map +1 -1
- package/icc-x-api/icc-contact-x-api.js +2 -2
- package/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/icc-x-api/index.d.ts +19 -7
- package/icc-x-api/index.js +5 -4
- package/icc-x-api/index.js.map +1 -1
- package/icc-x-api/utils/websocket.d.ts +1 -1
- package/icc-x-api/utils/websocket.js +6 -3
- package/icc-x-api/utils/websocket.js.map +1 -1
- package/package.json +1 -1
|
@@ -40,10 +40,6 @@ export declare class Annotation {
|
|
|
40
40
|
markdown?: {
|
|
41
41
|
[lang in ISO639_1]?: string;
|
|
42
42
|
};
|
|
43
|
-
/**
|
|
44
|
-
* If true, the note is confidential and should be encrypted.
|
|
45
|
-
*/
|
|
46
|
-
confidential?: boolean;
|
|
47
43
|
/**
|
|
48
44
|
* A tag is an item from a codification system that qualifies an entity as being member of a certain class, whatever the value it might have taken. If the tag qualifies the content of a field, it means that whatever the content of the field, the tag will always apply. For example, the label of a field is qualified using a tag. LOINC is a codification system typically used for tags.
|
|
49
45
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Annotation.js","sourceRoot":"","sources":["../../../icc-api/model/Annotation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAKH;;GAEG;AACH,MAAa,UAAU;IACrB,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAAkB,EAAE,IAAI,CAAC,CAAA;IACzC,CAAC;
|
|
1
|
+
{"version":3,"file":"Annotation.js","sourceRoot":"","sources":["../../../icc-api/model/Annotation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAKH;;GAEG;AACH,MAAa,UAAU;IACrB,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAAkB,EAAE,IAAI,CAAC,CAAA;IACzC,CAAC;CAqCF;AAxCD,gCAwCC","sourcesContent":["/**\n * iCure Data Stack API Documentation\n * The iCure Data Stack Application API is the native interface to iCure. This version is obsolete, please use v2.\n *\n * OpenAPI spec version: v1\n *\n *\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen.git\n * Do not edit the class manually.\n */\n\nimport { ISO639_1 } from './ISO639_1'\nimport { CodeStub } from './CodeStub'\n\n/**\n * Text node with attribution. Could be written by a healthcare party, as a side node of a |medical record. For example, after taking a temperature, the HCP adds a node explaining the |thermometer is faulty.\n */\nexport class Annotation {\n constructor(json: JSON | any) {\n Object.assign(this as Annotation, json)\n }\n\n /**\n * The Id of the Annotation. We encourage using either a v4 UUID or a HL7 Id.\n */\n id?: string\n author?: string\n /**\n * The timestamp (unix epoch in ms) of creation of this note, will be filled automatically if missing. Not enforced by the application server.\n */\n created?: number\n /**\n * The timestamp (unix epoch in ms) of the latest modification of this note, will be filled automatically if missing. Not enforced by the application server.\n */\n modified?: number\n /**\n * Text contained in the note, written as markdown.\n * @deprecated use markdown instead\n */\n text?: string\n\n /**\n * Text contained in the note, written as markdown.\n */\n markdown?: { [lang in ISO639_1]?: string }\n\n /**\n * A tag is an item from a codification system that qualifies an entity as being member of a certain class, whatever the value it might have taken. If the tag qualifies the content of a field, it means that whatever the content of the field, the tag will always apply. For example, the label of a field is qualified using a tag. LOINC is a codification system typically used for tags.\n */\n tags?: Array<CodeStub>\n\n /**\n * Defines to which part of the corresponding information the note is related to.\n */\n location?: string\n\n encryptedSelf?: string\n}\n"]}
|
|
@@ -12,7 +12,8 @@ export declare class EntitiesEncryption {
|
|
|
12
12
|
private readonly primitives;
|
|
13
13
|
private readonly dataOwnerApi;
|
|
14
14
|
private readonly exchangeKeysManager;
|
|
15
|
-
|
|
15
|
+
private readonly useParentKeys;
|
|
16
|
+
constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, exchangeKeysManager: ExchangeKeysManager, useParentKeys: boolean);
|
|
16
17
|
/**
|
|
17
18
|
* Get the data owners which can access the entity
|
|
18
19
|
* @param entity an entity.
|
|
@@ -19,10 +19,11 @@ const ShareMetadataBehaviour_1 = require("./ShareMetadataBehaviour");
|
|
|
19
19
|
* Give access to functions for retrieving encryption metadata of entities.
|
|
20
20
|
*/
|
|
21
21
|
class EntitiesEncryption {
|
|
22
|
-
constructor(primitives, dataOwnerApi, exchangeKeysManager) {
|
|
22
|
+
constructor(primitives, dataOwnerApi, exchangeKeysManager, useParentKeys) {
|
|
23
23
|
this.primitives = primitives;
|
|
24
24
|
this.dataOwnerApi = dataOwnerApi;
|
|
25
25
|
this.exchangeKeysManager = exchangeKeysManager;
|
|
26
|
+
this.useParentKeys = useParentKeys;
|
|
26
27
|
}
|
|
27
28
|
/**
|
|
28
29
|
* Get the data owners which can access the entity
|
|
@@ -453,7 +454,10 @@ class EntitiesEncryption {
|
|
|
453
454
|
}
|
|
454
455
|
extractedHierarchyFromDelegation(delegations, validateDecrypted, tagsFilter) {
|
|
455
456
|
return __awaiter(this, void 0, void 0, function* () {
|
|
456
|
-
|
|
457
|
+
const canDecryptOwnerIds = this.useParentKeys
|
|
458
|
+
? yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()
|
|
459
|
+
: [yield this.dataOwnerApi.getCurrentDataOwnerId()];
|
|
460
|
+
return Promise.all(canDecryptOwnerIds.map((ownerId) => __awaiter(this, void 0, void 0, function* () {
|
|
457
461
|
const extracted = this.deduplicate(yield this.extractFromDelegationsForDataOwner(ownerId, delegations, true, (k) => validateDecrypted(k), (t) => tagsFilter(t)));
|
|
458
462
|
return { ownerId, extracted };
|
|
459
463
|
})));
|
|
@@ -464,9 +468,11 @@ class EntitiesEncryption {
|
|
|
464
468
|
*/
|
|
465
469
|
extractMergedHierarchyFromDelegationAndOwner(delegations, dataOwnerId, validateDecrypted, tagsFilter) {
|
|
466
470
|
return __awaiter(this, void 0, void 0, function* () {
|
|
467
|
-
const hierarchy =
|
|
468
|
-
?
|
|
469
|
-
|
|
471
|
+
const hierarchy = this.useParentKeys
|
|
472
|
+
? dataOwnerId
|
|
473
|
+
? yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)
|
|
474
|
+
: yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()
|
|
475
|
+
: [dataOwnerId !== null && dataOwnerId !== void 0 ? dataOwnerId : (yield this.dataOwnerApi.getCurrentDataOwnerId())];
|
|
470
476
|
const extractedByOwner = yield Promise.all(
|
|
471
477
|
// Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.
|
|
472
478
|
[...hierarchy].reverse().map((ownerId) => this.extractFromDelegationsForDataOwner(ownerId, delegations, true, (k) => validateDecrypted(k), (t) => tagsFilter(t))));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EntitiesEncryption.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/EntitiesEncryption.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oCAaiB;AACjB,4BAA2B;AAE3B,gEAAuD;AACvD,qEAAiE;AAGjE;;;GAGG;AACH,MAAa,kBAAkB;IAK7B,YAAY,UAA4B,EAAE,YAA8B,EAAE,mBAAwC;QAChH,IAAI,CAAC,UAAU,GAAG,UAAU,CA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,IAAI,MAAM,CAAC,cAAc,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;QAC/G,IAAI,MAAM,CAAC,iBAAiB,IAAI,MAAM,CAAC,iBAAiB,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;QAC3G,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;gBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;SACF;IACH,CAAC;CACF;AAr6BD,gDAq6BC","sourcesContent":["import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ExchangeKeysManager } from './ExchangeKeysManager'\nimport {\n b2a,\n encryptObject,\n decryptObject,\n EncryptedFieldsManifest,\n hex2ua,\n parseEncryptedFields,\n string2ua,\n truncateTrailingNulls,\n ua2hex,\n ua2string,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport * as _ from 'lodash'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { arrayEquals } from '../utils/collection-utils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is for internal use only and may be changed without notice\n * Give access to functions for retrieving encryption metadata of entities.\n */\nexport class EntitiesEncryption {\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly exchangeKeysManager: ExchangeKeysManager\n\n constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, exchangeKeysManager: ExchangeKeysManager) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.exchangeKeysManager = exchangeKeysManager\n }\n\n /**\n * Get the data owners which can access the entity\n * @param entity an entity.\n */\n async getDataOwnersWithAccessTo(entity: EncryptedEntity): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: 'WRITE' }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entity.delegations ?? {}).map((x) => [x, 'WRITE'])),\n hasUnknownAnonymousDataOwners: false,\n }\n }\n\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n async encryptionKeysOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n // Legacy entities may have encryption keys in delegations.\n return this.extractMergedHierarchyFromDelegationAndOwner(\n Object.keys(entity.encryptionKeys ?? {}).length > 0 ? entity.encryptionKeys! : entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async encryptionKeysForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.encryptionKeys ?? {},\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n async secretIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async secretIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.delegations ?? {},\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n async owningEntityIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.cryptedForeignKeys ?? {},\n dataOwnerId,\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async owningEntityIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.cryptedForeignKeys ?? {},\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * @internal this method is intended only for internal use and may be changed without notice.\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, and encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKeys if false this method will not initialize any encryption keys. Use only for entities which use delegations for\n * access control but don't actually have any encrypted content.\n * @param additionalDelegations automatically shares the\n * @param tags tags to associate with the initial encryption keys and metadata\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKeys: boolean,\n additionalDelegations: string[] = [],\n tags: string[] = []\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const secretId = this.primitives.randomUuid()\n const rawEncryptionKey = initialiseEncryptionKeys ? ua2hex(this.primitives.randomBytes(16)) : undefined\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const allIds = [selfId, ...new Set(additionalDelegations.filter((x) => x !== selfId))]\n const loadKeysResult = await this.loadEncryptionKeysForDelegates(entity, allIds)\n const updatedEntity = await allIds.reduce<Promise<T>>(\n async (prevUpdate, delegateId) =>\n await this.createOrUpdateEntityDelegations(\n await prevUpdate,\n delegateId,\n [],\n [],\n [],\n [secretId],\n initialiseEncryptionKeys ? [rawEncryptionKey!] : [],\n owningEntity ? [owningEntity] : [],\n tags,\n loadKeysResult.keysForDelegates\n ),\n Promise.resolve(loadKeysResult.updatedEntity)\n )\n if (owningEntitySecretId) {\n updatedEntity.secretForeignKeys = [owningEntitySecretId]\n }\n return { updatedEntity, secretId, rawEncryptionKey }\n }\n\n async entityWithAutoExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n autoShareSecretIds: boolean,\n delegatesShareInfo: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKey?: ShareMetadataBehaviour\n shareOwningEntityIds?: ShareMetadataBehaviour\n }\n }\n ): Promise<T | undefined> {\n if (!Object.keys(delegatesShareInfo).length) {\n throw new Error('Must specify at least a delegate')\n }\n let defaultSecretIds: string[] | undefined\n if (autoShareSecretIds) {\n const availableSecretIds = await this.secretIdsOf(entity)\n if (availableSecretIds.length) {\n defaultSecretIds = availableSecretIds\n } else {\n defaultSecretIds = [this.primitives.randomUuid()]\n }\n }\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let updatedEntity = undefined\n for (const [delegateId, requests] of Object.entries(delegatesShareInfo)) {\n let shareSecretIds: string[] = autoShareSecretIds ? defaultSecretIds! : requests.shareSecretIds ?? []\n let actualShareEncryptionKeys: string[] = []\n if (requests.shareEncryptionKey !== ShareMetadataBehaviour.NEVER) {\n if (!availableEncryptionKeys.length && requests.shareEncryptionKey === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no encryption keys or the current data owner can't access any encryption keys.`)\n }\n actualShareEncryptionKeys = availableEncryptionKeys\n }\n let actualShareOwningEntityIds: string[] = []\n if (requests.shareOwningEntityIds !== ShareMetadataBehaviour.NEVER) {\n if (!availableOwningEntityIds.length && requests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids.`)\n }\n actualShareOwningEntityIds = availableOwningEntityIds\n }\n updatedEntity =\n (await this.entityWithExtendedEncryptedMetadata(\n updatedEntity ?? entity,\n delegateId,\n shareSecretIds,\n actualShareEncryptionKeys,\n actualShareOwningEntityIds\n )) ?? updatedEntity\n }\n return updatedEntity\n }\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param delegateId id of the delegate to share data with.\n * @param shareSecretIds secret ids to share.\n * @param shareEncryptionKeys encryption keys to share.\n * @param shareOwningEntityIds owning enttiy ids to share.\n * @param newTags tags to associate with the new encryption keys and metadata. Existing data won't be changed.\n * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.\n * @return an updated copy of the entity.\n */\n async entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newTags: string[] = []\n ): Promise<T | undefined> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithSharedEncryptedMetadata', arguments)\n async function checkInputAndGet(input: string[], inputName: string, validate: (x: string) => boolean | Promise<boolean>): Promise<string[]> {\n for (const x of input) {\n const validation = validate(x)\n if (validation !== true && validation !== false && !(await validation)) throw new Error(`Invalid input for ${inputName}.`)\n }\n return input\n }\n const secretIdsToShare = await checkInputAndGet(shareSecretIds, 'secretIds', (x) => this.validateSecretId(x))\n const encryptionKeysToShare = await checkInputAndGet(shareEncryptionKeys, 'encryptionKeys', (x) => this.validateEncryptionKey(x))\n const owningEntityIdsToShare = await checkInputAndGet(shareOwningEntityIds, 'owningEntityIds', (x) => this.validateOwningEntityId(x))\n const deduplicateInfoSecretIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.delegations ?? {},\n secretIdsToShare,\n (x) => this.validateSecretId(x)\n )\n const deduplicateInfoEncryptionKeys = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.encryptionKeys ?? {},\n encryptionKeysToShare,\n (x) => this.validateEncryptionKey(x)\n )\n const deduplicateInfoOwningEntityIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.cryptedForeignKeys ?? {},\n owningEntityIdsToShare,\n (x) => this.validateOwningEntityId(x)\n )\n /*TODO\n * Temporary hack since secret id is necessary to create a delegation for access control: if there is no delegation existing from me to the\n * delegate and there is no new secret id to be created create a new random id.\n */\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (deduplicateInfoSecretIds.missingEntries.length === 0 && !deduplicateInfoSecretIds.deduplicatedDelegations.some((d) => d.owner === selfId)) {\n deduplicateInfoSecretIds.missingEntries.push(this.primitives.randomUuid())\n }\n if (\n deduplicateInfoSecretIds.missingEntries.length === 0 &&\n deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&\n deduplicateInfoOwningEntityIds.missingEntries.length === 0\n )\n return undefined\n const { updatedEntity, keysForDelegates } = await this.loadEncryptionKeysForDelegates(entity, [delegateId])\n return this.createOrUpdateEntityDelegations(\n updatedEntity,\n delegateId,\n deduplicateInfoSecretIds.deduplicatedDelegations,\n deduplicateInfoEncryptionKeys.deduplicatedDelegations,\n deduplicateInfoOwningEntityIds.deduplicatedDelegations,\n deduplicateInfoSecretIds.missingEntries,\n deduplicateInfoEncryptionKeys.missingEntries,\n deduplicateInfoOwningEntityIds.missingEntries,\n newTags,\n keysForDelegates\n )\n }\n\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to encrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to use for encryption only keys associated to tags which pass the filter.\n * @return the encrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n async encryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf((await this.ensureEncryptionKeysInitialised(entity)) ?? entity, dataOwnerId, tagsFilter)\n if (keys.length === 0)\n throw new Error(\n `Could not extract any encryption keys of entity ${entity} for data owner ${\n dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n }.`\n )\n return this.primitives.AES.encryptWithRawKey(keys[0], content)\n }\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @param tagsFilter allows to use for decryption only keys associated to tags which pass the filter.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n async tryDecryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> = () => Promise.resolve(true),\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const keys = await this.encryptionKeysOf(entity, dataOwnerId, tagsFilter)\n for (const key of keys) {\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(key, content)\n if (await validator(decrypted)) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n /* ignore */\n }\n }\n return { data: content, wasDecrypted: false }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Decrypts the content of an encrypted entity.\n */\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n ownerId: string | undefined,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n const encryptionKeys = await this.importAllValidKeys(await this.encryptionKeysOf(entity, ownerId))\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries using the provided keys to decrypt some json.\n */\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n const text = ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted)\n return JSON.parse(text)\n } catch (e) {}\n }\n return undefined\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field\n * which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n dataOwnerId: string | undefined,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity)\n const encryptionKey = await this.tryImportFirstValidKey(await this.encryptionKeysOf(entity, dataOwnerId), entity.id!)\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n entityWithInitialisedEncryptionKeys ?? entity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || v instanceof Uint8Array\n ? b2a(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n 'entity'\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n /**\n * @internal This method is for internal use only and may be changed without notice.\n * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of\n * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities\n * which were previously not encrypted.\n */\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T | undefined> {\n if (Object.keys(entity.encryptionKeys ?? {}).length > 0) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * If entity was using delegations as legacy encryption keys we will essentially revoke the access to the encrypted data for all other data\n * owners. This however should not be a problem as this form of legacy entities should not exist anymore, and it should be present only in the\n * databases of hcps without collaborators.\n */\n return await this.entityWithExtendedEncryptedMetadata(\n entity,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n [],\n [ua2hex(this.primitives.randomBytes(16))],\n []\n )\n }\n\n /**\n * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does\n * not consider exchange keys for parents).\n * Note that the retrieved exchange keys are decrypted using the private keys available on the device, and results may vary from other devices.\n * @param dataOwnerId id of a data owner, he should be part of the current data owner hierarchy.\n * @param delegations a delegation-like object containing the encrypted key\n * @param includeFromDelegations if true also considers delegation from the provided data owner (or parents) to look for values. This allows to\n * decrypt delegations associated to exchange keys recovered after a giveAccessBack request.\n * @param validateDecrypted validates the decrypted result, to drop decryption results with wrong key that still gave a valid checksum.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the key which could be decrypted using only keys available on the current device and delegations from/to the provided data owner. May\n * contain duplicates.\n */\n private async extractFromDelegationsForDataOwner(\n dataOwnerId: string,\n delegations: { [delegateId: string]: Delegation[] },\n includeFromDelegations: boolean,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const delegationsWithOwner = includeFromDelegations\n ? Object.entries(delegations).flatMap(([delegateId, delegations]) =>\n dataOwnerId === delegateId\n ? this.populateDelegatedTo(delegateId, delegations)\n : this.populateDelegatedTo(\n delegateId,\n delegations.filter((d) => d.owner === dataOwnerId)\n )\n )\n : delegations[dataOwnerId] ?? []\n const res = []\n for (const delegation of delegationsWithOwner) {\n if (await tagsFilter(delegation.tags ?? [])) {\n const decrypted = await this.tryDecryptDelegation(delegation, (k) => validateDecrypted(k))\n if (decrypted) res.push(decrypted)\n }\n }\n return res\n }\n\n // Ensures that the delegatedTo field of delegations has the appropriate values, else returns a copy of the delegations with the appropriate value.\n private populateDelegatedTo(delegateId: string, delegations: Delegation[]): Delegation[] {\n return delegations.map((d) => (d.delegatedTo === delegateId ? d : { ...d, delegatedTo: delegateId }))\n }\n\n private async extractedHierarchyFromDelegation(\n delegations: { [delegateId: string]: Delegation[] },\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return Promise.all(\n (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).map(async (ownerId) => {\n const extracted = this.deduplicate(\n await this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n return { ownerId, extracted }\n })\n )\n }\n\n /**\n * @internal This method should be private but is currently public/internal to allow to continue supporting legacy methods\n */\n async extractMergedHierarchyFromDelegationAndOwner(\n delegations: { [delegateId: string]: Delegation[] },\n dataOwnerId: string | undefined,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const hierarchy = dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const extractedByOwner = await Promise.all(\n // Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.\n [...hierarchy].reverse().map((ownerId) =>\n this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n )\n return this.deduplicate(extractedByOwner.flatMap((x) => x))\n }\n\n private async tryDecryptDelegation(\n delegation: Delegation,\n validateDecrypted: (result: string) => boolean | Promise<boolean>\n ): Promise<string | undefined> {\n const exchangeKeys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegation.owner!, delegation.delegatedTo!)\n for (const key of exchangeKeys) {\n try {\n // Format of encrypted key for any delegation should be entityId:key, but with the merging of entities the entityId might not match the\n // current id. As a checksum we are only verifying that the decrypted bytes can be represented as a string with exactly one ':'.\n // Additionally, we also have a validator that is specific for each type of delegation content (encryption key, secret id, ...)\n const decrypted = ua2string(await this.primitives.AES.decrypt(key, hex2ua(delegation.key!)))\n const decryptedSplit = decrypted.split(':')\n if (decryptedSplit.length === 2) {\n const validation = validateDecrypted(decryptedSplit[1])\n if (validation === true || (validation !== false && (await validation))) return decryptedSplit[1]\n } else {\n console.warn(\"Error in the decrypted delegation: content should contain exactly 1 ':', the delegation is ignored.\")\n }\n } catch (e) {\n // Do nothing: the delegation uses another exchange key owner->delegator\n }\n }\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(keys, entityId)\n if (!res) throw new Error(`Could not find any valid key for entity ${entityId}.`)\n return res\n }\n\n private async tryImportFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string } | undefined> {\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) return { key: imported, raw: key }\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importAllValidKeys(keys: string[]): Promise<{ key: CryptoKey; raw: string }[]> {\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n private async validateEncryptionKey(key: string): Promise<boolean> {\n return !!(await this.tryImportKey(key))\n }\n\n private validateSecretId(key: string): boolean {\n return !!key\n }\n\n private validateOwningEntityId(key: string): boolean {\n return !!key\n }\n\n private async createEncryptionKeyDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n encryptionKey: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!(await this.validateEncryptionKey(encryptionKey))) throw new Error(`Invalid encryption key ${encryptionKey}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, encryptionKey, newTags)\n }\n\n private async createSecretIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n secretId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateSecretId(secretId)) throw new Error(`Invalid secret id ${secretId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, secretId, newTags)\n }\n\n private async createOwningEntityIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n owningEntityId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateOwningEntityId(owningEntityId)) throw new Error(`Invalid owning id ${owningEntityId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, owningEntityId, newTags)\n }\n\n private async createDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n content: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (entityId.includes(':')) throw new Error(\"Ids for encrypted entities are not allowed to contain ':'\")\n if (content.includes(':')) throw new Error(\"Content of delegations can not contain ':'\")\n return {\n delegatedTo: delegateId,\n owner: await this.dataOwnerApi.getCurrentDataOwnerId(),\n key: ua2hex(await this.primitives.AES.encrypt(exchangeKey, string2ua(entityId + ':' + content))),\n tags: newTags,\n }\n }\n\n private async loadEncryptionKeysForDelegates<T extends EncryptedEntity>(\n entity: T,\n delegates: string[]\n ): Promise<{ updatedEntity: T; keysForDelegates: { [delegateId: string]: CryptoKey[] } }> {\n const { updatedDelegator, keysForDelegates } = await delegates.reduce(\n async (acc, delegateId) => {\n const awaitedAcc = await acc\n const currUpdateResult = await this.exchangeKeysManager.getOrCreateEncryptionExchangeKeysTo(delegateId)\n return {\n updatedDelegator: currUpdateResult.updatedDelegator ?? awaitedAcc.updatedDelegator,\n keysForDelegates: {\n ...awaitedAcc.keysForDelegates,\n [delegateId]: currUpdateResult.keys,\n },\n }\n },\n Promise.resolve({\n updatedDelegator: undefined as CryptoActorStubWithType | undefined,\n keysForDelegates: {} as { [delegateId: string]: CryptoKey[] },\n })\n )\n const updatedEntity =\n entity.id === updatedDelegator?.stub?.id\n ? {\n ...entity,\n rev: updatedDelegator!.stub.rev,\n hcPartyKeys: updatedDelegator!.stub.hcPartyKeys,\n aesExchangeKeys: updatedDelegator!.stub.aesExchangeKeys,\n }\n : entity\n return { updatedEntity, keysForDelegates }\n }\n\n private async createOrUpdateEntityDelegations<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n existingSecretIds: Delegation[],\n existingEncryptionKeys: Delegation[],\n existingOwningEntityIds: Delegation[],\n newSecretIds: string[],\n newEncryptionKeys: string[],\n newOwningEntityIds: string[],\n newTags: string[],\n keysForDelegates: { [delegateId: string]: CryptoKey[] }\n ): Promise<T> {\n const entityCopy = _.cloneDeep(entity)\n if (newSecretIds.length === 0 && newEncryptionKeys.length === 0 && newOwningEntityIds.length === 0) return entityCopy\n const chosenKey = keysForDelegates[delegateId][0]\n const updatedSecretIds = [\n ...existingSecretIds,\n ...(await Promise.all(newSecretIds.map((x) => this.createSecretIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedEncryptionKeys = [\n ...existingEncryptionKeys,\n ...(await Promise.all(newEncryptionKeys.map((x) => this.createEncryptionKeyDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedOwningEntityIds = [\n ...existingOwningEntityIds,\n ...(await Promise.all(newOwningEntityIds.map((x) => this.createOwningEntityIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n if (updatedSecretIds.length > 0) {\n entityCopy.delegations = {\n ...(entity.delegations ?? {}),\n [delegateId]: updatedSecretIds,\n }\n }\n if (updatedEncryptionKeys.length > 0) {\n entityCopy.encryptionKeys = {\n ...(entity.encryptionKeys ?? {}),\n [delegateId]: updatedEncryptionKeys,\n }\n }\n if (updatedOwningEntityIds.length > 0) {\n entityCopy.cryptedForeignKeys = {\n ...(entity.cryptedForeignKeys ?? {}),\n [delegateId]: updatedOwningEntityIds,\n }\n }\n return entityCopy\n }\n\n /**\n * De-duplicates all currently accessible delegations, by removing any delegations created by the current data owner which have duplicated content,\n * and checks if any of the required entries are currently available to the delegate through the existing delegations.\n * @param delegateId id of the delegate.\n * @param allDelegations delegations of the entity.\n * @param requiredEntries potentially new entries that the delegate needs to be able to access from the delegations.\n * @param validateDecrypted validator for decrypted delegation content\n * @return the deduplicated delegations\n */\n private async deduplicateDelegationsAndFilterRequiredEntries(\n delegateId: string,\n allDelegations: { [delegateId: string]: Delegation[] },\n requiredEntries: string[],\n validateDecrypted: (x: string) => boolean | Promise<boolean>\n ): Promise<{\n deduplicatedDelegations: Delegation[]\n missingEntries: string[]\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const delegationsToDelegate = allDelegations[delegateId] ?? []\n const decryptedDelegations = await Promise.all(\n delegationsToDelegate.map(async (d) => ({\n delegation: d,\n content: d.owner === selfId ? await this.tryDecryptDelegation(d, (x) => validateDecrypted(x)) : undefined,\n }))\n )\n const deduplicatedDelegations: Delegation[] = []\n const deduplicatedContent = new Map<string, string[][]>()\n decryptedDelegations.forEach(({ delegation, content }) => {\n if (content === undefined) {\n // Keep all delegations we could not decrypt or from other data owners\n deduplicatedDelegations.push(delegation)\n } else {\n const deduplicatedTags = deduplicatedContent.get(content)\n if (!deduplicatedTags) {\n deduplicatedContent.set(content, [delegation.tags ?? []])\n deduplicatedDelegations.push(delegation)\n } else if (!deduplicatedTags.some((t) => arrayEquals(t, delegation.tags ?? []))) {\n deduplicatedTags.push(delegation.tags ?? [])\n deduplicatedDelegations.push(delegation)\n }\n }\n })\n const delegationsFromDelegateToSelf = (allDelegations[selfId] ?? []).filter((d) => d.owner === delegateId)\n const decryptedDelegationsFromDelegate = new Set(\n await Promise.all(delegationsFromDelegateToSelf.map((d) => this.tryDecryptDelegation(d, (x) => validateDecrypted(x)))).then((dels) =>\n dels.flatMap((x) => (x ? [x] : []))\n )\n )\n return {\n deduplicatedDelegations,\n missingEntries: requiredEntries.filter((entry) => !(deduplicatedContent.has(entry) || decryptedDelegationsFromDelegate.has(entry))),\n }\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n _.each(argsArray, (arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (existingMetadata.length > 0) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"EntitiesEncryption.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/EntitiesEncryption.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oCAaiB;AACjB,4BAA2B;AAE3B,gEAAuD;AACvD,qEAAiE;AAGjE;;;GAGG;AACH,MAAa,kBAAkB;IAC7B,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,mBAAwC,EACxC,aAAsB;QAHtB,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,wBAAmB,GAAnB,mBAAmB,CAAqB;QACxC,kBAAa,GAAb,aAAa,CAAS;IACtC,CAAC;IAEJ;;;OAGG;IACG,yBAAyB,CAAC,MAAuB;;;YAIrD,OAAO;gBACL,wBAAwB,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,MAAA,MAAM,CAAC,WAAW,mCAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;gBAC5G,6BAA6B,EAAE,KAAK;aACrC,CAAA;;KACF;IAED;;;;;;;OAOG;IACG,gBAAgB,CACpB,MAA6C,EAC7C,WAAoB,EACpB,aAAmD,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;;;YAE9E,2DAA2D;YAC3D,OAAO,IAAI,CAAC,4CAA4C,CACtD,MAAM,CAAC,IAAI,CAAC,MAAA,MAAM,CAAC,cAAc,mCAAI,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,cAAe,CAAC,CAAC,CAAC,MAAA,MAAM,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AAA;SACF;IACH,CAAC;CACF;AAv6BD,gDAu6BC","sourcesContent":["import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ExchangeKeysManager } from './ExchangeKeysManager'\nimport {\n b2a,\n encryptObject,\n decryptObject,\n EncryptedFieldsManifest,\n hex2ua,\n parseEncryptedFields,\n string2ua,\n truncateTrailingNulls,\n ua2hex,\n ua2string,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport * as _ from 'lodash'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { arrayEquals } from '../utils/collection-utils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is for internal use only and may be changed without notice\n * Give access to functions for retrieving encryption metadata of entities.\n */\nexport class EntitiesEncryption {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly exchangeKeysManager: ExchangeKeysManager,\n private readonly useParentKeys: boolean\n ) {}\n\n /**\n * Get the data owners which can access the entity\n * @param entity an entity.\n */\n async getDataOwnersWithAccessTo(entity: EncryptedEntity): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: 'WRITE' }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entity.delegations ?? {}).map((x) => [x, 'WRITE'])),\n hasUnknownAnonymousDataOwners: false,\n }\n }\n\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n async encryptionKeysOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n // Legacy entities may have encryption keys in delegations.\n return this.extractMergedHierarchyFromDelegationAndOwner(\n Object.keys(entity.encryptionKeys ?? {}).length > 0 ? entity.encryptionKeys! : entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async encryptionKeysForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.encryptionKeys ?? {},\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n async secretIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async secretIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.delegations ?? {},\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n async owningEntityIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.cryptedForeignKeys ?? {},\n dataOwnerId,\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async owningEntityIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.cryptedForeignKeys ?? {},\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * @internal this method is intended only for internal use and may be changed without notice.\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, and encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKeys if false this method will not initialize any encryption keys. Use only for entities which use delegations for\n * access control but don't actually have any encrypted content.\n * @param additionalDelegations automatically shares the\n * @param tags tags to associate with the initial encryption keys and metadata\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKeys: boolean,\n additionalDelegations: string[] = [],\n tags: string[] = []\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const secretId = this.primitives.randomUuid()\n const rawEncryptionKey = initialiseEncryptionKeys ? ua2hex(this.primitives.randomBytes(16)) : undefined\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const allIds = [selfId, ...new Set(additionalDelegations.filter((x) => x !== selfId))]\n const loadKeysResult = await this.loadEncryptionKeysForDelegates(entity, allIds)\n const updatedEntity = await allIds.reduce<Promise<T>>(\n async (prevUpdate, delegateId) =>\n await this.createOrUpdateEntityDelegations(\n await prevUpdate,\n delegateId,\n [],\n [],\n [],\n [secretId],\n initialiseEncryptionKeys ? [rawEncryptionKey!] : [],\n owningEntity ? [owningEntity] : [],\n tags,\n loadKeysResult.keysForDelegates\n ),\n Promise.resolve(loadKeysResult.updatedEntity)\n )\n if (owningEntitySecretId) {\n updatedEntity.secretForeignKeys = [owningEntitySecretId]\n }\n return { updatedEntity, secretId, rawEncryptionKey }\n }\n\n async entityWithAutoExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n autoShareSecretIds: boolean,\n delegatesShareInfo: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKey?: ShareMetadataBehaviour\n shareOwningEntityIds?: ShareMetadataBehaviour\n }\n }\n ): Promise<T | undefined> {\n if (!Object.keys(delegatesShareInfo).length) {\n throw new Error('Must specify at least a delegate')\n }\n let defaultSecretIds: string[] | undefined\n if (autoShareSecretIds) {\n const availableSecretIds = await this.secretIdsOf(entity)\n if (availableSecretIds.length) {\n defaultSecretIds = availableSecretIds\n } else {\n defaultSecretIds = [this.primitives.randomUuid()]\n }\n }\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let updatedEntity = undefined\n for (const [delegateId, requests] of Object.entries(delegatesShareInfo)) {\n let shareSecretIds: string[] = autoShareSecretIds ? defaultSecretIds! : requests.shareSecretIds ?? []\n let actualShareEncryptionKeys: string[] = []\n if (requests.shareEncryptionKey !== ShareMetadataBehaviour.NEVER) {\n if (!availableEncryptionKeys.length && requests.shareEncryptionKey === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no encryption keys or the current data owner can't access any encryption keys.`)\n }\n actualShareEncryptionKeys = availableEncryptionKeys\n }\n let actualShareOwningEntityIds: string[] = []\n if (requests.shareOwningEntityIds !== ShareMetadataBehaviour.NEVER) {\n if (!availableOwningEntityIds.length && requests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids.`)\n }\n actualShareOwningEntityIds = availableOwningEntityIds\n }\n updatedEntity =\n (await this.entityWithExtendedEncryptedMetadata(\n updatedEntity ?? entity,\n delegateId,\n shareSecretIds,\n actualShareEncryptionKeys,\n actualShareOwningEntityIds\n )) ?? updatedEntity\n }\n return updatedEntity\n }\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param delegateId id of the delegate to share data with.\n * @param shareSecretIds secret ids to share.\n * @param shareEncryptionKeys encryption keys to share.\n * @param shareOwningEntityIds owning enttiy ids to share.\n * @param newTags tags to associate with the new encryption keys and metadata. Existing data won't be changed.\n * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.\n * @return an updated copy of the entity.\n */\n async entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newTags: string[] = []\n ): Promise<T | undefined> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithSharedEncryptedMetadata', arguments)\n async function checkInputAndGet(input: string[], inputName: string, validate: (x: string) => boolean | Promise<boolean>): Promise<string[]> {\n for (const x of input) {\n const validation = validate(x)\n if (validation !== true && validation !== false && !(await validation)) throw new Error(`Invalid input for ${inputName}.`)\n }\n return input\n }\n const secretIdsToShare = await checkInputAndGet(shareSecretIds, 'secretIds', (x) => this.validateSecretId(x))\n const encryptionKeysToShare = await checkInputAndGet(shareEncryptionKeys, 'encryptionKeys', (x) => this.validateEncryptionKey(x))\n const owningEntityIdsToShare = await checkInputAndGet(shareOwningEntityIds, 'owningEntityIds', (x) => this.validateOwningEntityId(x))\n const deduplicateInfoSecretIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.delegations ?? {},\n secretIdsToShare,\n (x) => this.validateSecretId(x)\n )\n const deduplicateInfoEncryptionKeys = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.encryptionKeys ?? {},\n encryptionKeysToShare,\n (x) => this.validateEncryptionKey(x)\n )\n const deduplicateInfoOwningEntityIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.cryptedForeignKeys ?? {},\n owningEntityIdsToShare,\n (x) => this.validateOwningEntityId(x)\n )\n /*TODO\n * Temporary hack since secret id is necessary to create a delegation for access control: if there is no delegation existing from me to the\n * delegate and there is no new secret id to be created create a new random id.\n */\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (deduplicateInfoSecretIds.missingEntries.length === 0 && !deduplicateInfoSecretIds.deduplicatedDelegations.some((d) => d.owner === selfId)) {\n deduplicateInfoSecretIds.missingEntries.push(this.primitives.randomUuid())\n }\n if (\n deduplicateInfoSecretIds.missingEntries.length === 0 &&\n deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&\n deduplicateInfoOwningEntityIds.missingEntries.length === 0\n )\n return undefined\n const { updatedEntity, keysForDelegates } = await this.loadEncryptionKeysForDelegates(entity, [delegateId])\n return this.createOrUpdateEntityDelegations(\n updatedEntity,\n delegateId,\n deduplicateInfoSecretIds.deduplicatedDelegations,\n deduplicateInfoEncryptionKeys.deduplicatedDelegations,\n deduplicateInfoOwningEntityIds.deduplicatedDelegations,\n deduplicateInfoSecretIds.missingEntries,\n deduplicateInfoEncryptionKeys.missingEntries,\n deduplicateInfoOwningEntityIds.missingEntries,\n newTags,\n keysForDelegates\n )\n }\n\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to encrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to use for encryption only keys associated to tags which pass the filter.\n * @return the encrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n async encryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf((await this.ensureEncryptionKeysInitialised(entity)) ?? entity, dataOwnerId, tagsFilter)\n if (keys.length === 0)\n throw new Error(\n `Could not extract any encryption keys of entity ${entity} for data owner ${\n dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n }.`\n )\n return this.primitives.AES.encryptWithRawKey(keys[0], content)\n }\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @param tagsFilter allows to use for decryption only keys associated to tags which pass the filter.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n async tryDecryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> = () => Promise.resolve(true),\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const keys = await this.encryptionKeysOf(entity, dataOwnerId, tagsFilter)\n for (const key of keys) {\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(key, content)\n if (await validator(decrypted)) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n /* ignore */\n }\n }\n return { data: content, wasDecrypted: false }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Decrypts the content of an encrypted entity.\n */\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n ownerId: string | undefined,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n const encryptionKeys = await this.importAllValidKeys(await this.encryptionKeysOf(entity, ownerId))\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries using the provided keys to decrypt some json.\n */\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n const text = ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted)\n return JSON.parse(text)\n } catch (e) {}\n }\n return undefined\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field\n * which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n dataOwnerId: string | undefined,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity)\n const encryptionKey = await this.tryImportFirstValidKey(await this.encryptionKeysOf(entity, dataOwnerId), entity.id!)\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n entityWithInitialisedEncryptionKeys ?? entity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || v instanceof Uint8Array\n ? b2a(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n 'entity'\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n /**\n * @internal This method is for internal use only and may be changed without notice.\n * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of\n * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities\n * which were previously not encrypted.\n */\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T | undefined> {\n if (Object.keys(entity.encryptionKeys ?? {}).length > 0) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * If entity was using delegations as legacy encryption keys we will essentially revoke the access to the encrypted data for all other data\n * owners. This however should not be a problem as this form of legacy entities should not exist anymore, and it should be present only in the\n * databases of hcps without collaborators.\n */\n return await this.entityWithExtendedEncryptedMetadata(\n entity,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n [],\n [ua2hex(this.primitives.randomBytes(16))],\n []\n )\n }\n\n /**\n * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does\n * not consider exchange keys for parents).\n * Note that the retrieved exchange keys are decrypted using the private keys available on the device, and results may vary from other devices.\n * @param dataOwnerId id of a data owner, he should be part of the current data owner hierarchy.\n * @param delegations a delegation-like object containing the encrypted key\n * @param includeFromDelegations if true also considers delegation from the provided data owner (or parents) to look for values. This allows to\n * decrypt delegations associated to exchange keys recovered after a giveAccessBack request.\n * @param validateDecrypted validates the decrypted result, to drop decryption results with wrong key that still gave a valid checksum.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the key which could be decrypted using only keys available on the current device and delegations from/to the provided data owner. May\n * contain duplicates.\n */\n private async extractFromDelegationsForDataOwner(\n dataOwnerId: string,\n delegations: { [delegateId: string]: Delegation[] },\n includeFromDelegations: boolean,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const delegationsWithOwner = includeFromDelegations\n ? Object.entries(delegations).flatMap(([delegateId, delegations]) =>\n dataOwnerId === delegateId\n ? this.populateDelegatedTo(delegateId, delegations)\n : this.populateDelegatedTo(\n delegateId,\n delegations.filter((d) => d.owner === dataOwnerId)\n )\n )\n : delegations[dataOwnerId] ?? []\n const res = []\n for (const delegation of delegationsWithOwner) {\n if (await tagsFilter(delegation.tags ?? [])) {\n const decrypted = await this.tryDecryptDelegation(delegation, (k) => validateDecrypted(k))\n if (decrypted) res.push(decrypted)\n }\n }\n return res\n }\n\n // Ensures that the delegatedTo field of delegations has the appropriate values, else returns a copy of the delegations with the appropriate value.\n private populateDelegatedTo(delegateId: string, delegations: Delegation[]): Delegation[] {\n return delegations.map((d) => (d.delegatedTo === delegateId ? d : { ...d, delegatedTo: delegateId }))\n }\n\n private async extractedHierarchyFromDelegation(\n delegations: { [delegateId: string]: Delegation[] },\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n return Promise.all(\n canDecryptOwnerIds.map(async (ownerId) => {\n const extracted = this.deduplicate(\n await this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n return { ownerId, extracted }\n })\n )\n }\n\n /**\n * @internal This method should be private but is currently public/internal to allow to continue supporting legacy methods\n */\n async extractMergedHierarchyFromDelegationAndOwner(\n delegations: { [delegateId: string]: Delegation[] },\n dataOwnerId: string | undefined,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const extractedByOwner = await Promise.all(\n // Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.\n [...hierarchy].reverse().map((ownerId) =>\n this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n )\n return this.deduplicate(extractedByOwner.flatMap((x) => x))\n }\n\n private async tryDecryptDelegation(\n delegation: Delegation,\n validateDecrypted: (result: string) => boolean | Promise<boolean>\n ): Promise<string | undefined> {\n const exchangeKeys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegation.owner!, delegation.delegatedTo!)\n for (const key of exchangeKeys) {\n try {\n // Format of encrypted key for any delegation should be entityId:key, but with the merging of entities the entityId might not match the\n // current id. As a checksum we are only verifying that the decrypted bytes can be represented as a string with exactly one ':'.\n // Additionally, we also have a validator that is specific for each type of delegation content (encryption key, secret id, ...)\n const decrypted = ua2string(await this.primitives.AES.decrypt(key, hex2ua(delegation.key!)))\n const decryptedSplit = decrypted.split(':')\n if (decryptedSplit.length === 2) {\n const validation = validateDecrypted(decryptedSplit[1])\n if (validation === true || (validation !== false && (await validation))) return decryptedSplit[1]\n } else {\n console.warn(\"Error in the decrypted delegation: content should contain exactly 1 ':', the delegation is ignored.\")\n }\n } catch (e) {\n // Do nothing: the delegation uses another exchange key owner->delegator\n }\n }\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(keys, entityId)\n if (!res) throw new Error(`Could not find any valid key for entity ${entityId}.`)\n return res\n }\n\n private async tryImportFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string } | undefined> {\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) return { key: imported, raw: key }\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importAllValidKeys(keys: string[]): Promise<{ key: CryptoKey; raw: string }[]> {\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n private async validateEncryptionKey(key: string): Promise<boolean> {\n return !!(await this.tryImportKey(key))\n }\n\n private validateSecretId(key: string): boolean {\n return !!key\n }\n\n private validateOwningEntityId(key: string): boolean {\n return !!key\n }\n\n private async createEncryptionKeyDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n encryptionKey: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!(await this.validateEncryptionKey(encryptionKey))) throw new Error(`Invalid encryption key ${encryptionKey}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, encryptionKey, newTags)\n }\n\n private async createSecretIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n secretId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateSecretId(secretId)) throw new Error(`Invalid secret id ${secretId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, secretId, newTags)\n }\n\n private async createOwningEntityIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n owningEntityId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateOwningEntityId(owningEntityId)) throw new Error(`Invalid owning id ${owningEntityId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, owningEntityId, newTags)\n }\n\n private async createDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n content: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (entityId.includes(':')) throw new Error(\"Ids for encrypted entities are not allowed to contain ':'\")\n if (content.includes(':')) throw new Error(\"Content of delegations can not contain ':'\")\n return {\n delegatedTo: delegateId,\n owner: await this.dataOwnerApi.getCurrentDataOwnerId(),\n key: ua2hex(await this.primitives.AES.encrypt(exchangeKey, string2ua(entityId + ':' + content))),\n tags: newTags,\n }\n }\n\n private async loadEncryptionKeysForDelegates<T extends EncryptedEntity>(\n entity: T,\n delegates: string[]\n ): Promise<{ updatedEntity: T; keysForDelegates: { [delegateId: string]: CryptoKey[] } }> {\n const { updatedDelegator, keysForDelegates } = await delegates.reduce(\n async (acc, delegateId) => {\n const awaitedAcc = await acc\n const currUpdateResult = await this.exchangeKeysManager.getOrCreateEncryptionExchangeKeysTo(delegateId)\n return {\n updatedDelegator: currUpdateResult.updatedDelegator ?? awaitedAcc.updatedDelegator,\n keysForDelegates: {\n ...awaitedAcc.keysForDelegates,\n [delegateId]: currUpdateResult.keys,\n },\n }\n },\n Promise.resolve({\n updatedDelegator: undefined as CryptoActorStubWithType | undefined,\n keysForDelegates: {} as { [delegateId: string]: CryptoKey[] },\n })\n )\n const updatedEntity =\n entity.id === updatedDelegator?.stub?.id\n ? {\n ...entity,\n rev: updatedDelegator!.stub.rev,\n hcPartyKeys: updatedDelegator!.stub.hcPartyKeys,\n aesExchangeKeys: updatedDelegator!.stub.aesExchangeKeys,\n }\n : entity\n return { updatedEntity, keysForDelegates }\n }\n\n private async createOrUpdateEntityDelegations<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n existingSecretIds: Delegation[],\n existingEncryptionKeys: Delegation[],\n existingOwningEntityIds: Delegation[],\n newSecretIds: string[],\n newEncryptionKeys: string[],\n newOwningEntityIds: string[],\n newTags: string[],\n keysForDelegates: { [delegateId: string]: CryptoKey[] }\n ): Promise<T> {\n const entityCopy = _.cloneDeep(entity)\n if (newSecretIds.length === 0 && newEncryptionKeys.length === 0 && newOwningEntityIds.length === 0) return entityCopy\n const chosenKey = keysForDelegates[delegateId][0]\n const updatedSecretIds = [\n ...existingSecretIds,\n ...(await Promise.all(newSecretIds.map((x) => this.createSecretIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedEncryptionKeys = [\n ...existingEncryptionKeys,\n ...(await Promise.all(newEncryptionKeys.map((x) => this.createEncryptionKeyDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedOwningEntityIds = [\n ...existingOwningEntityIds,\n ...(await Promise.all(newOwningEntityIds.map((x) => this.createOwningEntityIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n if (updatedSecretIds.length > 0) {\n entityCopy.delegations = {\n ...(entity.delegations ?? {}),\n [delegateId]: updatedSecretIds,\n }\n }\n if (updatedEncryptionKeys.length > 0) {\n entityCopy.encryptionKeys = {\n ...(entity.encryptionKeys ?? {}),\n [delegateId]: updatedEncryptionKeys,\n }\n }\n if (updatedOwningEntityIds.length > 0) {\n entityCopy.cryptedForeignKeys = {\n ...(entity.cryptedForeignKeys ?? {}),\n [delegateId]: updatedOwningEntityIds,\n }\n }\n return entityCopy\n }\n\n /**\n * De-duplicates all currently accessible delegations, by removing any delegations created by the current data owner which have duplicated content,\n * and checks if any of the required entries are currently available to the delegate through the existing delegations.\n * @param delegateId id of the delegate.\n * @param allDelegations delegations of the entity.\n * @param requiredEntries potentially new entries that the delegate needs to be able to access from the delegations.\n * @param validateDecrypted validator for decrypted delegation content\n * @return the deduplicated delegations\n */\n private async deduplicateDelegationsAndFilterRequiredEntries(\n delegateId: string,\n allDelegations: { [delegateId: string]: Delegation[] },\n requiredEntries: string[],\n validateDecrypted: (x: string) => boolean | Promise<boolean>\n ): Promise<{\n deduplicatedDelegations: Delegation[]\n missingEntries: string[]\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const delegationsToDelegate = allDelegations[delegateId] ?? []\n const decryptedDelegations = await Promise.all(\n delegationsToDelegate.map(async (d) => ({\n delegation: d,\n content: d.owner === selfId ? await this.tryDecryptDelegation(d, (x) => validateDecrypted(x)) : undefined,\n }))\n )\n const deduplicatedDelegations: Delegation[] = []\n const deduplicatedContent = new Map<string, string[][]>()\n decryptedDelegations.forEach(({ delegation, content }) => {\n if (content === undefined) {\n // Keep all delegations we could not decrypt or from other data owners\n deduplicatedDelegations.push(delegation)\n } else {\n const deduplicatedTags = deduplicatedContent.get(content)\n if (!deduplicatedTags) {\n deduplicatedContent.set(content, [delegation.tags ?? []])\n deduplicatedDelegations.push(delegation)\n } else if (!deduplicatedTags.some((t) => arrayEquals(t, delegation.tags ?? []))) {\n deduplicatedTags.push(delegation.tags ?? [])\n deduplicatedDelegations.push(delegation)\n }\n }\n })\n const delegationsFromDelegateToSelf = (allDelegations[selfId] ?? []).filter((d) => d.owner === delegateId)\n const decryptedDelegationsFromDelegate = new Set(\n await Promise.all(delegationsFromDelegateToSelf.map((d) => this.tryDecryptDelegation(d, (x) => validateDecrypted(x)))).then((dels) =>\n dels.flatMap((x) => (x ? [x] : []))\n )\n )\n return {\n deduplicatedDelegations,\n missingEntries: requiredEntries.filter((entry) => !(deduplicatedContent.has(entry) || decryptedDelegationsFromDelegate.has(entry))),\n }\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n _.each(argsArray, (arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (existingMetadata.length > 0) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n }\n }\n}\n"]}
|
|
@@ -3,7 +3,6 @@ import { BaseExchangeKeysManager } from './BaseExchangeKeysManager';
|
|
|
3
3
|
import { IccDataOwnerXApi } from '../icc-data-owner-x-api';
|
|
4
4
|
import { CryptoPrimitives } from './CryptoPrimitives';
|
|
5
5
|
import { CryptoStrategies } from './CryptoStrategies';
|
|
6
|
-
import { IcureStorageFacade } from '../storage/IcureStorageFacade';
|
|
7
6
|
import { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub';
|
|
8
7
|
/**
|
|
9
8
|
* @internal This class is meant only for internal use and may be changed without notice.
|
|
@@ -14,16 +13,16 @@ import { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub';
|
|
|
14
13
|
* - Automatically retrieves the private keys to use during decryption.
|
|
15
14
|
*/
|
|
16
15
|
export declare class ExchangeKeysManager {
|
|
16
|
+
private readonly cryptoStrategies;
|
|
17
|
+
private readonly primitives;
|
|
17
18
|
private readonly keyManager;
|
|
18
19
|
private readonly baseExchangeKeysManager;
|
|
19
20
|
private readonly dataOwnerApi;
|
|
20
|
-
private readonly
|
|
21
|
-
private readonly primitives;
|
|
22
|
-
private readonly icureStorage;
|
|
21
|
+
private readonly useParentKeys;
|
|
23
22
|
private delegatorExchangeKeysCache;
|
|
24
23
|
private delegatedExchangeKeysCache;
|
|
25
24
|
get base(): BaseExchangeKeysManager;
|
|
26
|
-
constructor(delegatorKeysCacheSize: number, delegatedKeysCacheSize: number, delegatedKeysCacheLifetimeMsBase: number, delegatedKeysCacheLifetimeMsNoKeys: number, cryptoStrategies: CryptoStrategies, primitives: CryptoPrimitives, keyManager: KeyManager, baseExchangeKeysManager: BaseExchangeKeysManager, dataOwnerApi: IccDataOwnerXApi,
|
|
25
|
+
constructor(delegatorKeysCacheSize: number, delegatedKeysCacheSize: number, delegatedKeysCacheLifetimeMsBase: number, delegatedKeysCacheLifetimeMsNoKeys: number, cryptoStrategies: CryptoStrategies, primitives: CryptoPrimitives, keyManager: KeyManager, baseExchangeKeysManager: BaseExchangeKeysManager, dataOwnerApi: IccDataOwnerXApi, useParentKeys: boolean);
|
|
27
26
|
/**
|
|
28
27
|
* Get exchange keys from the current data owner to the provided delegate which are safe for encryption according to the locally verified keys.
|
|
29
28
|
* If currently there is no exchange key towards the provided delegate which is safe for encryption a new one will be automatically created.
|
|
@@ -24,15 +24,15 @@ class ExchangeKeysManager {
|
|
|
24
24
|
get base() {
|
|
25
25
|
return this.baseExchangeKeysManager;
|
|
26
26
|
}
|
|
27
|
-
constructor(delegatorKeysCacheSize, delegatedKeysCacheSize, delegatedKeysCacheLifetimeMsBase, delegatedKeysCacheLifetimeMsNoKeys, cryptoStrategies, primitives, keyManager, baseExchangeKeysManager, dataOwnerApi,
|
|
28
|
-
this.primitives = primitives;
|
|
27
|
+
constructor(delegatorKeysCacheSize, delegatedKeysCacheSize, delegatedKeysCacheLifetimeMsBase, delegatedKeysCacheLifetimeMsNoKeys, cryptoStrategies, primitives, keyManager, baseExchangeKeysManager, dataOwnerApi, useParentKeys) {
|
|
29
28
|
this.cryptoStrategies = cryptoStrategies;
|
|
29
|
+
this.primitives = primitives;
|
|
30
30
|
this.keyManager = keyManager;
|
|
31
31
|
this.baseExchangeKeysManager = baseExchangeKeysManager;
|
|
32
32
|
this.dataOwnerApi = dataOwnerApi;
|
|
33
|
+
this.useParentKeys = useParentKeys;
|
|
33
34
|
this.delegatedExchangeKeysCache = new lru_temporised_async_cache_1.LruTemporisedAsyncCache(delegatedKeysCacheSize, (keys) => keys.length > 0 ? delegatedKeysCacheLifetimeMsBase : delegatedKeysCacheLifetimeMsNoKeys);
|
|
34
35
|
this.delegatorExchangeKeysCache = new lru_temporised_async_cache_1.LruTemporisedAsyncCache(delegatorKeysCacheSize, () => -1);
|
|
35
|
-
this.icureStorage = icureStorage;
|
|
36
36
|
}
|
|
37
37
|
/**
|
|
38
38
|
* Get exchange keys from the current data owner to the provided delegate which are safe for encryption according to the locally verified keys.
|
|
@@ -129,7 +129,7 @@ class ExchangeKeysManager {
|
|
|
129
129
|
const delegate = yield this.dataOwnerApi.getCryptoActorStub(delegateId);
|
|
130
130
|
const delegatePublicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(delegate.stub));
|
|
131
131
|
let verifiedDelegatePublicKeys;
|
|
132
|
-
if ((yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).includes(delegateId)) {
|
|
132
|
+
if (this.useParentKeys && (yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).includes(delegateId)) {
|
|
133
133
|
verifiedDelegatePublicKeys = yield this.keyManager.getVerifiedPublicKeysFor(delegate.stub);
|
|
134
134
|
}
|
|
135
135
|
else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExchangeKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExchangeKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oFAA6E;AAC7E,mCAAwC;AAMxC;;;;;;;GAOG;AACH,MAAa,mBAAmB;IAoB9B,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,uBAAuB,CAAA;IACrC,CAAC;IAED,YACE,sBAA8B,EAC9B,sBAA8B,EAC9B,gCAAwC,EACxC,kCAA0C,EAC1C,gBAAkC,EAClC,UAA4B,EAC5B,UAAsB,EACtB,uBAAgD,EAChD,YAA8B,EAC9B,YAAgC;QAEhC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;QACxC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAA;QACtD,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,0BAA0B,GAAG,IAAI,oDAAuB,CAAC,sBAAsB,EAAE,CAAC,IAAI,EAAE,EAAE,CAC7F,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,gCAAgC,CAAC,CAAC,CAAC,kCAAkC,CACxF,CAAA;QACD,IAAI,CAAC,0BAA0B,GAAG,IAAI,oDAAuB,CAAC,sBAAsB,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;QAC/F,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;IAClC,CAAC;IAED;;;;;;;OAOG;IACG,mCAAmC,CAAC,UAAkB;;YAC1D,MAAM,WAAW,GAAG,MAAM,IAA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AC,QAAQ,CAAC,UAAU,CAAC,EAAE;oBACpF,0BAA0B,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,wBAAwB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;iBAC3F;qBAAM;oBACL,0BAA0B,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,wBAAwB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;iBACjI;gBACD,IAAI,CAAC,0BAA0B,IAAI,0BAA0B,CAAC,MAAM,IAAI,CAAC;oBACvE,MAAM,IAAI,KAAK,CAAC,wCAAwC,UAAU,0CAA0C,CAAC,CAAA;gBAC/G,eAAe,mCACV,eAAe,GACf,CAAC,MAAM,IAAA,sBAAc,EAAC,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,0BAA0B,CAAC,CAAC,CAC3E,CAAA;aACF;YACD,OAAO,MAAM,IAAI,CAAC,uBAAuB,CAAC,oCAAoC,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;QAC3H,CAAC;KAAA;CACF;AAzJD,kDAyJC","sourcesContent":["import { KeyManager } from './KeyManager'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { loadPublicKeys } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * More powerful version of {@link BaseExchangeKeysManager} with a simplified interface. Has the following functionalities:\n * - Caches results\n * - Automatically creates new exchange keys if none is available\n * - Automatically choose the public keys to use during the creation of new exchange keys\n * - Automatically retrieves the private keys to use during decryption.\n */\nexport class ExchangeKeysManager {\n private readonly keyManager: KeyManager\n private readonly baseExchangeKeysManager: BaseExchangeKeysManager\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly cryptoStrategies: CryptoStrategies\n private readonly primitives: CryptoPrimitives\n private readonly icureStorage: IcureStorageFacade\n /*\n * Exchange keys cache where the current user is the delegator. The keys where the delegator is the current user should never change without\n * an action from the delegator (unless he does this action from another device), so it should be safe to store them without expiration. However,\n * the delegator may still have a lot of exchange keys (e.g. doctor -> all patients), so it is not safe to have a cache with unlimited size.\n */\n private delegatorExchangeKeysCache: LruTemporisedAsyncCache<string, CryptoKey[]>\n /*\n * Exchange keys cache where the current user is not the delegator. There may be many keys where the current user is the delegate,\n * and they may change over time without any action from the current data owner, since the delegator is someone else. For this reason the cache must\n * be limited in size and it should not use data that is too old, as it may be outdated.\n */\n private delegatedExchangeKeysCache: LruTemporisedAsyncCache<string, CryptoKey[]>\n\n get base(): BaseExchangeKeysManager {\n return this.baseExchangeKeysManager\n }\n\n constructor(\n delegatorKeysCacheSize: number,\n delegatedKeysCacheSize: number,\n delegatedKeysCacheLifetimeMsBase: number,\n delegatedKeysCacheLifetimeMsNoKeys: number,\n cryptoStrategies: CryptoStrategies,\n primitives: CryptoPrimitives,\n keyManager: KeyManager,\n baseExchangeKeysManager: BaseExchangeKeysManager,\n dataOwnerApi: IccDataOwnerXApi,\n icureStorage: IcureStorageFacade\n ) {\n this.primitives = primitives\n this.cryptoStrategies = cryptoStrategies\n this.keyManager = keyManager\n this.baseExchangeKeysManager = baseExchangeKeysManager\n this.dataOwnerApi = dataOwnerApi\n this.delegatedExchangeKeysCache = new LruTemporisedAsyncCache(delegatedKeysCacheSize, (keys) =>\n keys.length > 0 ? delegatedKeysCacheLifetimeMsBase : delegatedKeysCacheLifetimeMsNoKeys\n )\n this.delegatorExchangeKeysCache = new LruTemporisedAsyncCache(delegatorKeysCacheSize, () => -1)\n this.icureStorage = icureStorage\n }\n\n /**\n * Get exchange keys from the current data owner to the provided delegate which are safe for encryption according to the locally verified keys.\n * If currently there is no exchange key towards the provided delegate which is safe for encryption a new one will be automatically created.\n * @param delegateId a delegate\n * @return an object with the following fields:\n * - keys: all available exchange keys which are safe for encryption.\n * - updatedDelegator (optional): if a new key creation job was started when the function was invoked the updated delegator, else undefined.\n */\n async getOrCreateEncryptionExchangeKeysTo(delegateId: string): Promise<{ updatedDelegator?: CryptoActorStubWithType; keys: CryptoKey[] }> {\n const currentKeys = await this.getSelfExchangeKeysTo(delegateId)\n if (currentKeys.length > 0) {\n return { keys: currentKeys }\n } else {\n while (true) {\n let updatedDelegatorJob: Promise<CryptoActorStubWithType> | undefined = undefined\n const keysWithNew = await this.delegatorExchangeKeysCache.get(\n delegateId,\n async (previous) => {\n const fullJob = this.forceCreateVerifiedExchangeKeyTo(delegateId)\n updatedDelegatorJob = fullJob.then(({ updatedDelegator }) => updatedDelegator)\n let existingKeys = previous ? previous : await this.forceGetSelfExchangeKeysTo(delegateId)\n return fullJob.then(({ key }) => [...existingKeys, key])\n },\n (v) => !v.length\n )\n if (keysWithNew.length > 0) {\n const updatedDelegator = updatedDelegatorJob ? await updatedDelegatorJob : undefined\n return updatedDelegator ? { keys: keysWithNew, updatedDelegator } : { keys: keysWithNew }\n }\n }\n /*NOTE:\n * in case of two concurrent calls to `getOrCreateEncryptionExchangeKeysTo` only one of the calls will receive the updated delegator. This could\n * be a problem if one of the callers would want to update the delegator for other reasons as well, as the request would result in a database\n * conflict. This situation however should be very rare and will be fully resolved in the near future when delegations will be moved out of the\n * data owner objects and into a specific database.\n */\n }\n }\n\n /**\n * Get all keys currently available for a delegator-delegate pair. At least one of the two data owners must be part of the hierarchy for the current\n * data owner.\n * @param delegatorId id of a delegator\n * @param delegateId id of a delegate\n * @throws if neither the delegator nor the delegate is part of the hierarchy of the current data owner.\n * @return all available exchange keys from the delegator-delegate pair.\n */\n async getDecryptionExchangeKeysFor(delegatorId: string, delegateId: string): Promise<CryptoKey[]> {\n if (delegatorId === (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n return await this.getSelfExchangeKeysTo(delegateId)\n } else {\n const key = `${delegatorId}->${delegateId}`\n const hierarchyIds = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n if (!hierarchyIds.some((x) => x === delegateId || x === delegatorId))\n throw new Error(`Trying to retrieve exchange key ${key} but current data owner hierarchy is ${hierarchyIds}`)\n return await this.delegatedExchangeKeysCache.get(key, () => this.forceGetExchangeKeysFor(delegatorId, delegateId))\n }\n }\n\n /**\n * Empties the exchange keys cache.\n * @param includeKeysFromCurrentDataOwner if true also clears the\n */\n clearCache(includeKeysFromCurrentDataOwner: boolean) {\n if (includeKeysFromCurrentDataOwner) this.delegatorExchangeKeysCache.clear()\n this.delegatedExchangeKeysCache.clear()\n }\n\n private async forceGetExchangeKeysFor(delegatorId: string, delegateId: string): Promise<CryptoKey[]> {\n const encKeys = await this.baseExchangeKeysManager.getEncryptedExchangeKeysFor(delegatorId, delegateId)\n return (await this.baseExchangeKeysManager.tryDecryptExchangeKeys(encKeys, this.keyManager.getDecryptionKeys())).successfulDecryptions\n }\n\n private async getSelfExchangeKeysTo(delegateId: string): Promise<CryptoKey[]> {\n return await this.delegatorExchangeKeysCache.get(delegateId, () => this.forceGetSelfExchangeKeysTo(delegateId))\n }\n\n private async forceGetSelfExchangeKeysTo(delegateId: string): Promise<CryptoKey[]> {\n // Retrieve then try to decrypt with own and parent key pairs\n const encKeys = await this.baseExchangeKeysManager.getEncryptedExchangeKeysFor(await this.dataOwnerApi.getCurrentDataOwnerId(), delegateId)\n const { successfulDecryptions } = await this.baseExchangeKeysManager.tryDecryptExchangeKeys(encKeys, this.keyManager.getDecryptionKeys())\n return successfulDecryptions\n }\n\n private async forceCreateVerifiedExchangeKeyTo(delegateId: string): Promise<{ updatedDelegator: CryptoActorStubWithType; key: CryptoKey }> {\n const [mainKey, ...otherSelfKeys] = this.keyManager.getSelfVerifiedKeys()\n let otherPublicKeys = Object.fromEntries(otherSelfKeys.map((x) => [x.fingerprint, x.pair.publicKey]))\n if (delegateId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n const delegatePublicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(delegate.stub))\n let verifiedDelegatePublicKeys: string[]\n if ((await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).includes(delegateId)) {\n verifiedDelegatePublicKeys = await this.keyManager.getVerifiedPublicKeysFor(delegate.stub)\n } else {\n verifiedDelegatePublicKeys = await this.cryptoStrategies.verifyDelegatePublicKeys(delegate, delegatePublicKeys, this.primitives)\n }\n if (!verifiedDelegatePublicKeys || verifiedDelegatePublicKeys.length == 0)\n throw new Error(`No verified public keys for delegate ${delegateId}: impossible to create new exchange key.`)\n otherPublicKeys = {\n ...otherPublicKeys,\n ...(await loadPublicKeys(this.primitives.RSA, verifiedDelegatePublicKeys)),\n }\n }\n return await this.baseExchangeKeysManager.createOrUpdateEncryptedExchangeKeyTo(delegateId, mainKey.pair, otherPublicKeys)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ExchangeKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExchangeKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oFAA6E;AAC7E,mCAAwC;AAKxC;;;;;;;GAOG;AACH,MAAa,mBAAmB;IAc9B,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,uBAAuB,CAAA;IACrC,CAAC;IAED,YACE,sBAA8B,EAC9B,sBAA8B,EAC9B,gCAAwC,EACxC,kCAA0C,EACzB,gBAAkC,EAClC,UAA4B,EAC5B,UAAsB,EACtB,uBAAgD,EAChD,YAA8B,EAC9B,aAAsB;QALtB,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,eAAU,GAAV,UAAU,CAAkB;QAC5B,eAAU,GAAV,UAAU,CAAY;QACtB,4BAAuB,GAAvB,uBAAuB,CAAyB;QAChD,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,kBAAa,GAAb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AAA;YACrG,IAAI,UAAU,KAAK,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC,EAAE;gBACpE,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,UAAU,CAAC,CAAA;gBACvE,MAAM,kBAAkB,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAA;gBAC1F,IAAI,0BAAoC,CAAA;gBACxC,IAAI,IAAI,CAAC,aAAa,IAAI,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,+BAA+B,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;oBAC1G,0BAA0B,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,wBAAwB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;iBAC3F;qBAAM;oBACL,0BAA0B,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,wBAAwB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;iBACjI;gBACD,IAAI,CAAC,0BAA0B,IAAI,0BAA0B,CAAC,MAAM,IAAI,CAAC;oBACvE,MAAM,IAAI,KAAK,CAAC,wCAAwC,UAAU,0CAA0C,CAAC,CAAA;gBAC/G,eAAe,mCACV,eAAe,GACf,CAAC,MAAM,IAAA,sBAAc,EAAC,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,0BAA0B,CAAC,CAAC,CAC3E,CAAA;aACF;YACD,OAAO,MAAM,IAAI,CAAC,uBAAuB,CAAC,oCAAoC,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;QAC3H,CAAC;KAAA;CACF;AA7ID,kDA6IC","sourcesContent":["import { KeyManager } from './KeyManager'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { loadPublicKeys } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * More powerful version of {@link BaseExchangeKeysManager} with a simplified interface. Has the following functionalities:\n * - Caches results\n * - Automatically creates new exchange keys if none is available\n * - Automatically choose the public keys to use during the creation of new exchange keys\n * - Automatically retrieves the private keys to use during decryption.\n */\nexport class ExchangeKeysManager {\n /*\n * Exchange keys cache where the current user is the delegator. The keys where the delegator is the current user should never change without\n * an action from the delegator (unless he does this action from another device), so it should be safe to store them without expiration. However,\n * the delegator may still have a lot of exchange keys (e.g. doctor -> all patients), so it is not safe to have a cache with unlimited size.\n */\n private delegatorExchangeKeysCache: LruTemporisedAsyncCache<string, CryptoKey[]>\n /*\n * Exchange keys cache where the current user is not the delegator. There may be many keys where the current user is the delegate,\n * and they may change over time without any action from the current data owner, since the delegator is someone else. For this reason the cache must\n * be limited in size and it should not use data that is too old, as it may be outdated.\n */\n private delegatedExchangeKeysCache: LruTemporisedAsyncCache<string, CryptoKey[]>\n\n get base(): BaseExchangeKeysManager {\n return this.baseExchangeKeysManager\n }\n\n constructor(\n delegatorKeysCacheSize: number,\n delegatedKeysCacheSize: number,\n delegatedKeysCacheLifetimeMsBase: number,\n delegatedKeysCacheLifetimeMsNoKeys: number,\n private readonly cryptoStrategies: CryptoStrategies,\n private readonly primitives: CryptoPrimitives,\n private readonly keyManager: KeyManager,\n private readonly baseExchangeKeysManager: BaseExchangeKeysManager,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly useParentKeys: boolean\n ) {\n this.delegatedExchangeKeysCache = new LruTemporisedAsyncCache(delegatedKeysCacheSize, (keys) =>\n keys.length > 0 ? delegatedKeysCacheLifetimeMsBase : delegatedKeysCacheLifetimeMsNoKeys\n )\n this.delegatorExchangeKeysCache = new LruTemporisedAsyncCache(delegatorKeysCacheSize, () => -1)\n }\n\n /**\n * Get exchange keys from the current data owner to the provided delegate which are safe for encryption according to the locally verified keys.\n * If currently there is no exchange key towards the provided delegate which is safe for encryption a new one will be automatically created.\n * @param delegateId a delegate\n * @return an object with the following fields:\n * - keys: all available exchange keys which are safe for encryption.\n * - updatedDelegator (optional): if a new key creation job was started when the function was invoked the updated delegator, else undefined.\n */\n async getOrCreateEncryptionExchangeKeysTo(delegateId: string): Promise<{ updatedDelegator?: CryptoActorStubWithType; keys: CryptoKey[] }> {\n const currentKeys = await this.getSelfExchangeKeysTo(delegateId)\n if (currentKeys.length > 0) {\n return { keys: currentKeys }\n } else {\n while (true) {\n let updatedDelegatorJob: Promise<CryptoActorStubWithType> | undefined = undefined\n const keysWithNew = await this.delegatorExchangeKeysCache.get(\n delegateId,\n async (previous) => {\n const fullJob = this.forceCreateVerifiedExchangeKeyTo(delegateId)\n updatedDelegatorJob = fullJob.then(({ updatedDelegator }) => updatedDelegator)\n let existingKeys = previous ? previous : await this.forceGetSelfExchangeKeysTo(delegateId)\n return fullJob.then(({ key }) => [...existingKeys, key])\n },\n (v) => !v.length\n )\n if (keysWithNew.length > 0) {\n const updatedDelegator = updatedDelegatorJob ? await updatedDelegatorJob : undefined\n return updatedDelegator ? { keys: keysWithNew, updatedDelegator } : { keys: keysWithNew }\n }\n }\n /*NOTE:\n * in case of two concurrent calls to `getOrCreateEncryptionExchangeKeysTo` only one of the calls will receive the updated delegator. This could\n * be a problem if one of the callers would want to update the delegator for other reasons as well, as the request would result in a database\n * conflict. This situation however should be very rare and will be fully resolved in the near future when delegations will be moved out of the\n * data owner objects and into a specific database.\n */\n }\n }\n\n /**\n * Get all keys currently available for a delegator-delegate pair. At least one of the two data owners must be part of the hierarchy for the current\n * data owner.\n * @param delegatorId id of a delegator\n * @param delegateId id of a delegate\n * @throws if neither the delegator nor the delegate is part of the hierarchy of the current data owner.\n * @return all available exchange keys from the delegator-delegate pair.\n */\n async getDecryptionExchangeKeysFor(delegatorId: string, delegateId: string): Promise<CryptoKey[]> {\n if (delegatorId === (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n return await this.getSelfExchangeKeysTo(delegateId)\n } else {\n const key = `${delegatorId}->${delegateId}`\n const hierarchyIds = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n if (!hierarchyIds.some((x) => x === delegateId || x === delegatorId))\n throw new Error(`Trying to retrieve exchange key ${key} but current data owner hierarchy is ${hierarchyIds}`)\n return await this.delegatedExchangeKeysCache.get(key, () => this.forceGetExchangeKeysFor(delegatorId, delegateId))\n }\n }\n\n /**\n * Empties the exchange keys cache.\n * @param includeKeysFromCurrentDataOwner if true also clears the\n */\n clearCache(includeKeysFromCurrentDataOwner: boolean) {\n if (includeKeysFromCurrentDataOwner) this.delegatorExchangeKeysCache.clear()\n this.delegatedExchangeKeysCache.clear()\n }\n\n private async forceGetExchangeKeysFor(delegatorId: string, delegateId: string): Promise<CryptoKey[]> {\n const encKeys = await this.baseExchangeKeysManager.getEncryptedExchangeKeysFor(delegatorId, delegateId)\n return (await this.baseExchangeKeysManager.tryDecryptExchangeKeys(encKeys, this.keyManager.getDecryptionKeys())).successfulDecryptions\n }\n\n private async getSelfExchangeKeysTo(delegateId: string): Promise<CryptoKey[]> {\n return await this.delegatorExchangeKeysCache.get(delegateId, () => this.forceGetSelfExchangeKeysTo(delegateId))\n }\n\n private async forceGetSelfExchangeKeysTo(delegateId: string): Promise<CryptoKey[]> {\n // Retrieve then try to decrypt with own and parent key pairs\n const encKeys = await this.baseExchangeKeysManager.getEncryptedExchangeKeysFor(await this.dataOwnerApi.getCurrentDataOwnerId(), delegateId)\n const { successfulDecryptions } = await this.baseExchangeKeysManager.tryDecryptExchangeKeys(encKeys, this.keyManager.getDecryptionKeys())\n return successfulDecryptions\n }\n\n private async forceCreateVerifiedExchangeKeyTo(delegateId: string): Promise<{ updatedDelegator: CryptoActorStubWithType; key: CryptoKey }> {\n const [mainKey, ...otherSelfKeys] = this.keyManager.getSelfVerifiedKeys()\n let otherPublicKeys = Object.fromEntries(otherSelfKeys.map((x) => [x.fingerprint, x.pair.publicKey]))\n if (delegateId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n const delegatePublicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(delegate.stub))\n let verifiedDelegatePublicKeys: string[]\n if (this.useParentKeys && (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).includes(delegateId)) {\n verifiedDelegatePublicKeys = await this.keyManager.getVerifiedPublicKeysFor(delegate.stub)\n } else {\n verifiedDelegatePublicKeys = await this.cryptoStrategies.verifyDelegatePublicKeys(delegate, delegatePublicKeys, this.primitives)\n }\n if (!verifiedDelegatePublicKeys || verifiedDelegatePublicKeys.length == 0)\n throw new Error(`No verified public keys for delegate ${delegateId}: impossible to create new exchange key.`)\n otherPublicKeys = {\n ...otherPublicKeys,\n ...(await loadPublicKeys(this.primitives.RSA, verifiedDelegatePublicKeys)),\n }\n }\n return await this.baseExchangeKeysManager.createOrUpdateEncryptedExchangeKeyTo(delegateId, mainKey.pair, otherPublicKeys)\n }\n}\n"]}
|
|
@@ -11,14 +11,15 @@ import { CryptoStrategies } from './CryptoStrategies';
|
|
|
11
11
|
export declare class KeyManager {
|
|
12
12
|
private readonly primitives;
|
|
13
13
|
private readonly dataOwnerApi;
|
|
14
|
-
private readonly keyRecovery;
|
|
15
14
|
private readonly icureStorage;
|
|
15
|
+
private readonly keyRecovery;
|
|
16
16
|
private readonly baseExchangeKeyManager;
|
|
17
17
|
private readonly strategies;
|
|
18
|
+
private readonly initialiseParentKeys;
|
|
18
19
|
private selfId;
|
|
19
20
|
private selfLegacyPublicKey;
|
|
20
21
|
private keysCache;
|
|
21
|
-
constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, icureStorage: IcureStorageFacade, keyRecovery: KeyRecovery, baseExchangeKeyManager: BaseExchangeKeysManager, strategies: CryptoStrategies);
|
|
22
|
+
constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, icureStorage: IcureStorageFacade, keyRecovery: KeyRecovery, baseExchangeKeyManager: BaseExchangeKeysManager, strategies: CryptoStrategies, initialiseParentKeys: boolean);
|
|
22
23
|
/**
|
|
23
24
|
* 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
|
|
24
25
|
* server).
|
|
@@ -16,14 +16,15 @@ const utils_2 = require("./utils");
|
|
|
16
16
|
* Allows to manage public and private keys for the current user and his parent hierarchy.
|
|
17
17
|
*/
|
|
18
18
|
class KeyManager {
|
|
19
|
-
constructor(primitives, dataOwnerApi, icureStorage, keyRecovery, baseExchangeKeyManager, strategies) {
|
|
20
|
-
this.keysCache = undefined;
|
|
19
|
+
constructor(primitives, dataOwnerApi, icureStorage, keyRecovery, baseExchangeKeyManager, strategies, initialiseParentKeys) {
|
|
21
20
|
this.primitives = primitives;
|
|
22
|
-
this.icureStorage = icureStorage;
|
|
23
21
|
this.dataOwnerApi = dataOwnerApi;
|
|
22
|
+
this.icureStorage = icureStorage;
|
|
24
23
|
this.keyRecovery = keyRecovery;
|
|
25
24
|
this.baseExchangeKeyManager = baseExchangeKeyManager;
|
|
26
25
|
this.strategies = strategies;
|
|
26
|
+
this.initialiseParentKeys = initialiseParentKeys;
|
|
27
|
+
this.keysCache = undefined;
|
|
27
28
|
}
|
|
28
29
|
/**
|
|
29
30
|
* 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
|
|
@@ -162,7 +163,7 @@ class KeyManager {
|
|
|
162
163
|
const self = hierarchy[hierarchy.length - 1];
|
|
163
164
|
this.selfId = self.dataOwner.id;
|
|
164
165
|
const keysData = [];
|
|
165
|
-
for (const dowt of hierarchy) {
|
|
166
|
+
for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {
|
|
166
167
|
const availableKeys = yield this.loadAndRecoverKeysFor(dowt);
|
|
167
168
|
const verifiedKeysMap = yield this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id);
|
|
168
169
|
const allPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dowt.dataOwner);
|