@icure/api 8.0.49 → 8.0.50

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.
Files changed (55) hide show
  1. package/icc-x-api/crypto/ConfidentialEntities.js +1 -1
  2. package/icc-x-api/crypto/ConfidentialEntities.js.map +1 -1
  3. package/icc-x-api/crypto/DelegationsDeAnonymization.js +5 -2
  4. package/icc-x-api/crypto/DelegationsDeAnonymization.js.map +1 -1
  5. package/icc-x-api/crypto/ExtendedApisUtils.d.ts +5 -8
  6. package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -1
  7. package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +5 -5
  8. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +4 -14
  9. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
  10. package/icc-x-api/crypto/utils.js +5 -2
  11. package/icc-x-api/crypto/utils.js.map +1 -1
  12. package/icc-x-api/icc-accesslog-x-api.d.ts +6 -0
  13. package/icc-x-api/icc-accesslog-x-api.js +9 -3
  14. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  15. package/icc-x-api/icc-calendar-item-x-api.d.ts +6 -0
  16. package/icc-x-api/icc-calendar-item-x-api.js +9 -3
  17. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  18. package/icc-x-api/icc-classification-x-api.d.ts +6 -0
  19. package/icc-x-api/icc-classification-x-api.js +9 -3
  20. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  21. package/icc-x-api/icc-contact-x-api.d.ts +6 -0
  22. package/icc-x-api/icc-contact-x-api.js +9 -3
  23. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  24. package/icc-x-api/icc-document-x-api.d.ts +6 -0
  25. package/icc-x-api/icc-document-x-api.js +9 -3
  26. package/icc-x-api/icc-document-x-api.js.map +1 -1
  27. package/icc-x-api/icc-form-x-api.d.ts +6 -0
  28. package/icc-x-api/icc-form-x-api.js +9 -3
  29. package/icc-x-api/icc-form-x-api.js.map +1 -1
  30. package/icc-x-api/icc-helement-x-api.d.ts +6 -0
  31. package/icc-x-api/icc-helement-x-api.js +9 -3
  32. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  33. package/icc-x-api/icc-invoice-x-api.d.ts +6 -0
  34. package/icc-x-api/icc-invoice-x-api.js +9 -3
  35. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  36. package/icc-x-api/icc-maintenance-task-x-api.d.ts +6 -0
  37. package/icc-x-api/icc-maintenance-task-x-api.js +9 -3
  38. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  39. package/icc-x-api/icc-message-x-api.js +5 -2
  40. package/icc-x-api/icc-message-x-api.js.map +1 -1
  41. package/icc-x-api/icc-patient-x-api.js +5 -2
  42. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  43. package/icc-x-api/icc-receipt-x-api.d.ts +6 -0
  44. package/icc-x-api/icc-receipt-x-api.js +9 -3
  45. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  46. package/icc-x-api/icc-time-table-x-api.d.ts +6 -0
  47. package/icc-x-api/icc-time-table-x-api.js +9 -3
  48. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  49. package/icc-x-api/icc-topic-x-api.d.ts +6 -0
  50. package/icc-x-api/icc-topic-x-api.js +9 -3
  51. package/icc-x-api/icc-topic-x-api.js.map +1 -1
  52. package/package.json +1 -1
  53. package/test/icc-x-api/help-meddi.d.ts +1 -0
  54. package/test/icc-x-api/help-meddi.js +53 -0
  55. package/test/icc-x-api/help-meddi.js.map +1 -0
@@ -43,7 +43,7 @@ class ConfidentialEntities {
43
43
  if (yield this.getConfidentialSecretId({ entity, type: entityType }))
44
44
  return undefined;
45
45
  const confidentialSecretId = this.primitives.randomUuid();
46
- return (yield this.entitiesEncryption.simpleShareOrUpdateEncryptedEntityMetadata({ entity, type: entityType }, false, {
46
+ return (yield this.entitiesEncryption.simpleShareOrUpdateEncryptedEntityMetadata({ entity, type: entityType }, {
47
47
  [yield this.dataOwnerApi.getCurrentDataOwnerId()]: {
48
48
  shareEncryptionKeys: ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER,
49
49
  shareOwningEntityIds: ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER,
@@ -1 +1 @@
1
- {"version":3,"file":"ConfidentialEntities.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ConfidentialEntities.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,qEAAiE;AACjE,wFAAoF;AACpF,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAK3E;;;;;;;GAOG;AACH,MAAa,oBAAoB;IAC/B,YACmB,kBAAqC,EACrC,UAA4B,EAC5B,YAA8B;QAF9B,uBAAkB,GAAlB,kBAAkB,CAAmB;QACrC,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;IAC9C,CAAC;IAEJ;;;;;;;;;;OAUG;IACG,8BAA8B,CAClC,MAAS,EACT,UAAwC,EACxC,0BAA6G;;YAE7G,IAAI,MAAM,IAAI,CAAC,uBAAuB,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;gBAAE,OAAO,SAAS,CAAA;YACtF,MAAM,oBAAoB,GAAG,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,CAAA;YACzD,OAAO,CACL,MAAM,IAAI,CAAC,kBAAkB,CAAC,0CAA0C,CACtE,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,EAC5B,KAAK,EACL;gBACE,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC,EAAE;oBACjD,mBAAmB,EAAE,+CAAsB,CAAC,KAAK;oBACjD,oBAAoB,EAAE,+CAAsB,CAAC,KAAK;oBAClD,cAAc,EAAE,CAAC,oBAAoB,CAAC;oBACtC,oBAAoB,EAAE,uBAAuB,CAAC,SAAS;iBACxD;aACF,EACD,CAAC,OAA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AAC,CAAC,CAAA;QAC9I,CAAC;KAAA;IAED;;;;;;OAMG;IACG,+BAA+B,CAAC,MAA+B;;YACnE,OAAO,CAAC,MAAM,IAAI,CAAC,6BAA6B,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QAC9D,CAAC;KAAA;IAED;;;;;OAKG;IACG,6BAA6B,CAAC,MAA+B;;YACjE,OAAO,CAAC,MAAM,IAAI,CAAC,kBAAkB,CAAC,0BAA0B,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;QACxF,CAAC;KAAA;CACF;AA7FD,oDA6FC","sourcesContent":["import { EncryptedEntity } from '../../icc-api/model/models'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { BulkShareOrUpdateMetadataParams } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this class is intended for internal use only and may be changed without notice.\n * This class helps to create confidential medical data in systems where multiple hcps share data with each other using parent hcps: while normally\n * the hcps would share all data with other hcps part of the same \"family\" (e.g. an hospital) there are situations where the medical data is\n * confidential and should only be known by the doctor which created the data. In these situations it is also important that the secret foreign key\n * used in the confidential data is not known by other members of the hcp family, otherwise they may be able to draw some links between the medical\n * data and the patient.\n */\nexport class ConfidentialEntities {\n constructor(\n private readonly entitiesEncryption: ExtendedApisUtils,\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi\n ) {}\n\n /**\n * Ensures that the current data owner has access to a confidential secret id for the provided entity: this is an id that is known to the data owner\n * but is not known by any of his parents. If there is currently no confidential secret id for this entity the method returns a copy of the entity\n * with a new confidential secret id for the current data owner (the entity in the database won't be updated), else this method returns undefined.\n * New confidential secret ids will have an appropriate tag, but existing confidential secret ids may not necessarily have it.\n * @param entity an entity which needs to have a confidential secret id for the current data owner\n * @param entityType the type of the entity\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return undefined if the entity already had a confidential secret id for the current user, or the updated AND SAVED entity with the new\n * confidential secret id.\n */\n async initialiseConfidentialSecretId<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<T | undefined> {\n if (await this.getConfidentialSecretId({ entity, type: entityType })) return undefined\n const confidentialSecretId = this.primitives.randomUuid()\n return (\n await this.entitiesEncryption.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity, type: entityType },\n false,\n {\n [await this.dataOwnerApi.getCurrentDataOwnerId()]: {\n shareEncryptionKeys: ShareMetadataBehaviour.NEVER,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [confidentialSecretId],\n requestedPermissions: RequestedPermissionEnum.MAX_WRITE,\n },\n },\n (request) => doRequestBulkShareOrUpdate(request)\n )\n ).updatedEntityOrThrow\n }\n\n /**\n * Get an existing confidential secret id of the provided entity for the provided data owner (current data owner by default). A confidential secret\n * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.\n * @param entity an entity for which you want to retrieve the confidential secret id.\n * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.\n * @return the confidential secret id or undefined if there is no confidential secret id for the provided data owner.\n */\n async getConfidentialSecretId(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string | undefined> {\n return this.getConfidentialSecretIds(entity, dataOwnerId).then((x) => x[0])\n }\n\n /**\n * Get all existing confidential secret ids of the provided entity for the provided data owner (current data owner by default). A confidential secret\n * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.\n * @param entity an entity for which you want to retrieve the confidential secret id.\n * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.\n * @return the confidential secret ids for the data owner (may be empty).\n */\n async getConfidentialSecretIds(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n // TODO throw exception if any parent key is not available? if we are missing even only one single parent key we can't be sure it is confidential\n const chosenDataOwnerId = dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n const dataOwnerHierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(chosenDataOwnerId)\n const hierarchySecretIds = (await this.entitiesEncryption.secretIdsForHcpHierarchyOf(entity)).filter((x) =>\n dataOwnerHierarchy.includes(x.ownerId)\n )\n const keysForDataOwner = hierarchySecretIds.find((x) => x.ownerId === chosenDataOwnerId)\n\n if (!keysForDataOwner) return []\n return keysForDataOwner.extracted.filter((k) => !hierarchySecretIds.some((x) => x.ownerId !== chosenDataOwnerId && x.extracted.includes(k)))\n }\n\n /**\n * Gets a secret id known by the topmost parent of the current data owner hierarchy. If there is multiple secret ids shared with the topmost parent\n * there is no guarantee on which one will be chosen.\n * @param entity an entity.\n * @return a secret id known by the topmost parent of the current data owner hierarchy, or undefined if there is no secret id currently available\n * for the topmost parent.\n */\n async getAnySecretIdSharedWithParents(entity: EncryptedEntityWithType): Promise<string | undefined> {\n return (await this.getSecretIdsSharedWithParents(entity))[0]\n }\n\n /**\n * Gets all secret ids known by the topmost parent of the current data owner hierarchy (or all secret ids known by the current data owner if he is\n * not part of any data owner hierarchy).\n * @param entity an entity.\n * @return all secret ids known by the topmost parent of the current data owner hierarchy, may be empty.\n */\n async getSecretIdsSharedWithParents(entity: EncryptedEntityWithType): Promise<string[]> {\n return (await this.entitiesEncryption.secretIdsForHcpHierarchyOf(entity))[0].extracted\n }\n}\n"]}
1
+ {"version":3,"file":"ConfidentialEntities.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ConfidentialEntities.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,qEAAiE;AACjE,wFAAoF;AACpF,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAK3E;;;;;;;GAOG;AACH,MAAa,oBAAoB;IAC/B,YACmB,kBAAqC,EACrC,UAA4B,EAC5B,YAA8B;QAF9B,uBAAkB,GAAlB,kBAAkB,CAAmB;QACrC,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;IAC9C,CAAC;IAEJ;;;;;;;;;;OAUG;IACG,8BAA8B,CAClC,MAAS,EACT,UAAwC,EACxC,0BAA6G;;YAE7G,IAAI,MAAM,IAAI,CAAC,uBAAuB,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;gBAAE,OAAO,SAAS,CAAA;YACtF,MAAM,oBAAoB,GAAG,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,CAAA;YACzD,OAAO,CACL,MAAM,IAAI,CAAC,kBAAkB,CAAC,0CAA0C,CACtE,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,EAC5B;gBACE,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC,EAAE;oBACjD,mBAAmB,EAAE,+CAAsB,CAAC,KAAK;oBACjD,oBAAoB,EAAE,+CAAsB,CAAC,KAAK;oBAClD,cAAc,EAAE,CAAC,oBAAoB,CAAC;oBACtC,oBAAoB,EAAE,uBAAuB,CAAC,SAAS;iBACxD;aACF,EACD,CAAC,OAAO,EAAE,EAAE,CAAC,0BAA0B,CAAC,OAAO,CAAC,CACjD,CACF,CAAC,oBAAoB,CAAA;QACxB,CAAC;KAAA;IAED;;;;;;OAMG;IACG,uBAAu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,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QAC9D,CAAC;KAAA;IAED;;;;;OAKG;IACG,6BAA6B,CAAC,MAA+B;;YACjE,OAAO,CAAC,MAAM,IAAI,CAAC,kBAAkB,CAAC,0BAA0B,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;QACxF,CAAC;KAAA;CACF;AA5FD,oDA4FC","sourcesContent":["import { EncryptedEntity } from '../../icc-api/model/models'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { BulkShareOrUpdateMetadataParams } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this class is intended for internal use only and may be changed without notice.\n * This class helps to create confidential medical data in systems where multiple hcps share data with each other using parent hcps: while normally\n * the hcps would share all data with other hcps part of the same \"family\" (e.g. an hospital) there are situations where the medical data is\n * confidential and should only be known by the doctor which created the data. In these situations it is also important that the secret foreign key\n * used in the confidential data is not known by other members of the hcp family, otherwise they may be able to draw some links between the medical\n * data and the patient.\n */\nexport class ConfidentialEntities {\n constructor(\n private readonly entitiesEncryption: ExtendedApisUtils,\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi\n ) {}\n\n /**\n * Ensures that the current data owner has access to a confidential secret id for the provided entity: this is an id that is known to the data owner\n * but is not known by any of his parents. If there is currently no confidential secret id for this entity the method returns a copy of the entity\n * with a new confidential secret id for the current data owner (the entity in the database won't be updated), else this method returns undefined.\n * New confidential secret ids will have an appropriate tag, but existing confidential secret ids may not necessarily have it.\n * @param entity an entity which needs to have a confidential secret id for the current data owner\n * @param entityType the type of the entity\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return undefined if the entity already had a confidential secret id for the current user, or the updated AND SAVED entity with the new\n * confidential secret id.\n */\n async initialiseConfidentialSecretId<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<T | undefined> {\n if (await this.getConfidentialSecretId({ entity, type: entityType })) return undefined\n const confidentialSecretId = this.primitives.randomUuid()\n return (\n await this.entitiesEncryption.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity, type: entityType },\n {\n [await this.dataOwnerApi.getCurrentDataOwnerId()]: {\n shareEncryptionKeys: ShareMetadataBehaviour.NEVER,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [confidentialSecretId],\n requestedPermissions: RequestedPermissionEnum.MAX_WRITE,\n },\n },\n (request) => doRequestBulkShareOrUpdate(request)\n )\n ).updatedEntityOrThrow\n }\n\n /**\n * Get an existing confidential secret id of the provided entity for the provided data owner (current data owner by default). A confidential secret\n * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.\n * @param entity an entity for which you want to retrieve the confidential secret id.\n * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.\n * @return the confidential secret id or undefined if there is no confidential secret id for the provided data owner.\n */\n async getConfidentialSecretId(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string | undefined> {\n return this.getConfidentialSecretIds(entity, dataOwnerId).then((x) => x[0])\n }\n\n /**\n * Get all existing confidential secret ids of the provided entity for the provided data owner (current data owner by default). A confidential secret\n * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.\n * @param entity an entity for which you want to retrieve the confidential secret id.\n * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.\n * @return the confidential secret ids for the data owner (may be empty).\n */\n async getConfidentialSecretIds(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n // TODO throw exception if any parent key is not available? if we are missing even only one single parent key we can't be sure it is confidential\n const chosenDataOwnerId = dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n const dataOwnerHierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(chosenDataOwnerId)\n const hierarchySecretIds = (await this.entitiesEncryption.secretIdsForHcpHierarchyOf(entity)).filter((x) =>\n dataOwnerHierarchy.includes(x.ownerId)\n )\n const keysForDataOwner = hierarchySecretIds.find((x) => x.ownerId === chosenDataOwnerId)\n\n if (!keysForDataOwner) return []\n return keysForDataOwner.extracted.filter((k) => !hierarchySecretIds.some((x) => x.ownerId !== chosenDataOwnerId && x.extracted.includes(k)))\n }\n\n /**\n * Gets a secret id known by the topmost parent of the current data owner hierarchy. If there is multiple secret ids shared with the topmost parent\n * there is no guarantee on which one will be chosen.\n * @param entity an entity.\n * @return a secret id known by the topmost parent of the current data owner hierarchy, or undefined if there is no secret id currently available\n * for the topmost parent.\n */\n async getAnySecretIdSharedWithParents(entity: EncryptedEntityWithType): Promise<string | undefined> {\n return (await this.getSecretIdsSharedWithParents(entity))[0]\n }\n\n /**\n * Gets all secret ids known by the topmost parent of the current data owner hierarchy (or all secret ids known by the current data owner if he is\n * not part of any data owner hierarchy).\n * @param entity an entity.\n * @return all secret ids known by the topmost parent of the current data owner hierarchy, may be empty.\n */\n async getSecretIdsSharedWithParents(entity: EncryptedEntityWithType): Promise<string[]> {\n return (await this.entitiesEncryption.secretIdsForHcpHierarchyOf(entity))[0].extracted\n }\n}\n"]}
@@ -196,7 +196,10 @@ class DelegationsDeAnonymization {
196
196
  const dataOwnersNeedingShare = delegates.filter((x) => !dataOwnersWithAccessToMap.has(x));
197
197
  if (dataOwnersNeedingShare.length) {
198
198
  ;
199
- (yield this.xapis.simpleShareOrUpdateEncryptedEntityMetadata({ entity: keyMap, type: entityType }, false, Object.fromEntries(dataOwnersNeedingShare.map((x) => [
199
+ (yield this.xapis.simpleShareOrUpdateEncryptedEntityMetadata({
200
+ entity: keyMap,
201
+ type: entityType,
202
+ }, Object.fromEntries(dataOwnersNeedingShare.map((x) => [
200
203
  x,
201
204
  {
202
205
  shareSecretIds: [],
@@ -225,7 +228,7 @@ class DelegationsDeAnonymization {
225
228
  delegate: delegationMembersDetails.delegate,
226
229
  delegator: delegationMembersDetails.delegator,
227
230
  delegationKey: delegationKey,
228
- }, entityType, undefined, undefined, true, false, Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ])));
231
+ }, entityType, undefined, undefined, true, Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ])));
229
232
  const encryptedKeyMap = yield this.xapis.tryEncryptEntity(initalisedMapInfo.updatedEntity, entityType, this.delegationKeyMapFieldsToEncrypt, false, true, (x) => new SecureDelegationKeyMap_1.SecureDelegationKeyMap(x));
230
233
  yield this.delegationKeyMapApi.create(encryptedKeyMap, new XHR_1.XHR.Header(AccessControlKeysHeadersProvider_1.ACCESS_CONTROL_KEYS_HEADER, yield this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)));
231
234
  });
@@ -1 +1 @@
1
- {"version":3,"file":"DelegationsDeAnonymization.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/DelegationsDeAnonymization.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,2EAAuE;AACvE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAEzD,gGAA4F;AAE5F,qEAAiE;AACjE,wFAAoF;AACpF,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E,oCAAwE;AACxE,0GAAsG;AAC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CACZ,6DAA0B,EAC1B,MAAM,IAAI,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,wBAAwB,CAAC,mBAAmB,CAAC,EAAE,UAAU,CAAC,CAC5H,CACF,CAAA;QACH,CAAC;KAAA;CACF;AA3QD,gEA2QC","sourcesContent":["import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { DelegationMembersDetails, SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { SecureDelegationKeyMap } from '../../icc-api/model/internal/SecureDelegationKeyMap'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedFieldsManifest, parseEncryptedFields } from '../utils'\nimport { IccSecureDelegationKeyMapApi } from '../../icc-api/api/internal/IccSecureDelegationKeyMapApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { AuthenticationProvider, NoAuthenticationProvider } from '../auth/AuthenticationProvider'\nimport { ACCESS_CONTROL_KEYS_HEADER, AccessControlKeysHeadersProvider } from './AccessControlKeysHeadersProvider'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\n\n// TODO could be optimised using bulk methods\nexport class DelegationsDeAnonymization {\n private readonly delegationKeyMapFieldsToEncrypt: EncryptedFieldsManifest\n private readonly delegationKeyMapApi: IccSecureDelegationKeyMapApi\n\n constructor(\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly secureDelegationsMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly xapis: ExtendedApisUtils,\n private readonly cryptoPrimitives: CryptoPrimitives,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n private readonly accessControlKeysHeadersProvider: AccessControlKeysHeadersProvider\n ) {\n this.delegationKeyMapFieldsToEncrypt = parseEncryptedFields(['delegate', 'delegator'], 'SecureDelegationKeyMap')\n this.delegationKeyMapApi = new IccSecureDelegationKeyMapApi(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Creates / updates information to allow the data owners in {@link shareWithDataOwners} to de-anonymize the delegations contained within\n * {@link entity}.\n * Note that the delegation de-anonymization information may be used also with other entities of the same type.\n */\n async createOrUpdateDeAnonymizationInfo(entityWithType: EncryptedEntityWithType, shareWithDataOwners: string[]) {\n const delegationsDetails = Object.entries(await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)).flatMap(\n ([canonicalKey, delegation]) => {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [[canonicalKey, delegation], ...aliases.map((alias) => [alias, delegation])] as [string, DelegationMembersDetails][]\n }\n )\n const delegationsForDeanonInfoSharing = delegationsDetails.filter(([_, delegationInfo]) => {\n // Drop fully explicit ones: they don't need de-anonymization info\n return !delegationInfo.fullyExplicit\n })\n // A subset of delegations for which deanon info is relevant AND for which we can also create new info instead of sharing only existing one.\n const delegationsForNewDeanonInfoCreation = delegationsForDeanonInfoSharing.filter(([_, delegationInfo]) => {\n // Drop those for which we don't have the full information needed for the creation of new data.\n return !!delegationInfo.delegate && !!delegationInfo.delegator && !!delegationInfo.accessControlSecret\n })\n const existingDelegationsMap = await this.getDecryptedSecureDelegationKeyMaps(\n delegationsForDeanonInfoSharing.map((x) => x[0]),\n entityWithType.type\n )\n for (const delMapToShare of existingDelegationsMap) {\n await this.ensureDelegationKeyMapSharedWith(entityWithType.type, delMapToShare, shareWithDataOwners)\n }\n const existingDelegationsMapKeys = new Set(existingDelegationsMap.map((x) => x.delegationKey))\n const delegationsToCreate = delegationsForNewDeanonInfoCreation.filter(([k, _]) => !existingDelegationsMapKeys.has(k))\n for (const [delKey, membersDetails] of delegationsToCreate) {\n await this.createSecureDelegationKeyMap(entityWithType.type, delKey, membersDetails, shareWithDataOwners)\n }\n }\n\n /**\n * Get the data owners which can access the entity. See {@link EncryptedEntityXApi.getDataOwnersWithAccessTo} for more details.\n * @param entityWithType an entity.\n */\n async getDataOwnersWithAccessTo(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return this.mergePermissions([\n await this.getDataOwnersWithAccessToSecureDelegations(entityWithType),\n {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entityWithType.entity.delegations ?? {}).map((k) => [k, AccessLevelEnum.WRITE])),\n hasUnknownAnonymousDataOwners: false,\n },\n ])\n }\n\n private async getDataOwnersWithAccessToSecureDelegations(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const secureDelegationDetails = await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const secureDelegationWithUnknownMembers = Object.entries(secureDelegationDetails).flatMap(([canonicalKey, delegation]) => {\n if (!delegation.delegate || !delegation.delegator) {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [{ keys: [canonicalKey, ...aliases], delegation }]\n } else {\n return []\n }\n })\n const secureDelegationKeyMapsByDelegationKey = Object.fromEntries(\n (\n await this.getDecryptedSecureDelegationKeyMaps(\n secureDelegationWithUnknownMembers.flatMap(({ keys }) => keys),\n entityWithType.type\n )\n ).map((x) => [x.delegationKey, x])\n )\n const permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n function addAccess(dataOwnerId: string, level: AccessLevelEnum) {\n if (permissionsByDataOwnerId[dataOwnerId] !== AccessLevelEnum.WRITE) {\n permissionsByDataOwnerId[dataOwnerId] = level\n }\n }\n for (const delegation of Object.values(secureDelegationDetails)) {\n if (delegation.delegate) addAccess(delegation.delegate, delegation.accessLevel)\n if (delegation.delegator) addAccess(delegation.delegator, delegation.accessLevel)\n }\n for (const { keys, delegation } of secureDelegationWithUnknownMembers) {\n const bestKey = keys.find((k) => {\n const currMap = secureDelegationKeyMapsByDelegationKey[k]\n return currMap && !!currMap.delegator && !!currMap.delegate\n })\n if (bestKey) {\n const keyMap = secureDelegationKeyMapsByDelegationKey[bestKey]\n addAccess(keyMap.delegate!, delegation.accessLevel)\n addAccess(keyMap.delegator!, delegation.accessLevel)\n } else {\n hasUnknownAnonymousDataOwners = true\n }\n }\n return { permissionsByDataOwnerId, hasUnknownAnonymousDataOwners }\n }\n\n private async mergePermissions(\n values: {\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }[]\n ): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const accumulatedPermissions: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n for (const v of values) {\n hasUnknownAnonymousDataOwners = hasUnknownAnonymousDataOwners || v.hasUnknownAnonymousDataOwners\n for (const [dataOwnerId, level] of Object.entries(v.permissionsByDataOwnerId)) {\n if (accumulatedPermissions[dataOwnerId] !== AccessLevelEnum.WRITE) {\n accumulatedPermissions[dataOwnerId] = level\n }\n }\n }\n return {\n permissionsByDataOwnerId: accumulatedPermissions,\n hasUnknownAnonymousDataOwners,\n }\n }\n\n private async getDecryptedSecureDelegationKeyMaps(\n delegationIds: string[],\n entityType: EntityWithDelegationTypeName\n ): Promise<SecureDelegationKeyMap[]> {\n if (delegationIds.length) {\n const encryptedMaps = await this.delegationKeyMapApi.getByDelegationKeys(\n { ids: delegationIds },\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n const res: SecureDelegationKeyMap[] = []\n for (const encryptedMap of encryptedMaps) {\n // Use the original entity type\n const decryptionResult = await this.xapis.decryptEntity(encryptedMap, entityType, (x) => new SecureDelegationKeyMap(x))\n if (decryptionResult.decrypted) {\n res.push(decryptionResult.entity)\n }\n }\n return res\n } else return []\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async ensureDelegationKeyMapSharedWith(entityType: EntityWithDelegationTypeName, keyMap: SecureDelegationKeyMap, delegates: string[]) {\n if (!keyMap.delegator || !keyMap.delegate) throw new Error('Illegal state: key map is missing delegator or delegate info.')\n const dataOwnersWithAccessToMapThroughDelegation = Object.values(\n await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails({\n type: entityType,\n entity: keyMap,\n })\n )\n .flatMap((x) => [x.delegate, x.delegator])\n .filter((x) => !!x) as string[]\n // Delegator and delegate got access to the entity when it was first created: no need to share with them ever.\n const dataOwnersWithAccessToMap = new Set([keyMap.delegate, keyMap.delegator, ...dataOwnersWithAccessToMapThroughDelegation])\n const dataOwnersNeedingShare = delegates.filter((x) => !dataOwnersWithAccessToMap.has(x))\n if (dataOwnersNeedingShare.length) {\n ;(\n await this.xapis.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity: keyMap, type: entityType },\n false,\n Object.fromEntries(\n dataOwnersNeedingShare.map((x) => [\n x,\n {\n shareSecretIds: [],\n shareEncryptionKeys: ShareMetadataBehaviour.REQUIRED,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n },\n ])\n ),\n async (request) =>\n this.delegationKeyMapApi.bulkShareSecureDelegationKeyMap(\n request,\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n )\n ).updatedEntityOrThrow\n }\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async createSecureDelegationKeyMap(\n entityType: EntityWithDelegationTypeName,\n delegationKey: string,\n delegationMembersDetails: DelegationMembersDetails,\n delegates: string[]\n ) {\n if (!delegationMembersDetails.delegate || !delegationMembersDetails.delegator || !delegationMembersDetails.accessControlSecret)\n throw new Error('Illegal state: delegation members details are missing delegate, delegator or access control secret info.')\n const selfDoId = await this.dataOwnerApi.getCurrentDataOwnerId()\n // Ensure that both the delegator and delegate of the delegation this map refers tho can share it later on, even if they did not create it.\n // Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.\n const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId)\n const initalisedMapInfo = await this.xapis.entityWithInitialisedEncryptedMetadata<SecureDelegationKeyMap>(\n {\n id: this.cryptoPrimitives.randomUuid(),\n delegate: delegationMembersDetails.delegate,\n delegator: delegationMembersDetails.delegator,\n delegationKey: delegationKey,\n },\n entityType,\n undefined,\n undefined,\n true,\n false,\n Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ]))\n )\n const encryptedKeyMap = await this.xapis.tryEncryptEntity(\n initalisedMapInfo.updatedEntity,\n entityType,\n this.delegationKeyMapFieldsToEncrypt,\n false,\n true,\n (x) => new SecureDelegationKeyMap(x)\n )\n await this.delegationKeyMapApi.create(\n encryptedKeyMap,\n new XHR.Header(\n ACCESS_CONTROL_KEYS_HEADER,\n await this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)\n )\n )\n }\n}\n"]}
1
+ {"version":3,"file":"DelegationsDeAnonymization.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/DelegationsDeAnonymization.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,2EAAuE;AACvE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAEzD,gGAA4F;AAE5F,qEAAiE;AACjE,wFAAoF;AACpF,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E,oCAAwE;AACxE,0GAAsG;AACtG,+CAA2C;AAC3C,2EAAiG;AACjG,yFAAiH;AAIjH,6CAA6C;AAC7C,MAAa,0BAA0B;IAIrC,YACmB,YAA8B,EAC9B,kCAA8E,EAC9E,KAAwB,EACxB,gBAAkC,EAClC,wBAAkD,EACnE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK,EACQ,gCAAkE;QAblE,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,uCAAkC,GAAlC,kCAAkC,CAA4C;QAC9E,UAAK,GAAL,KAAK,CAAmB;QACxB,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,6BAAwB,GAAxB,wBAAwB,CAA0B;QASlD,qCAAgC,GAAhC,gCAAgC,CAAkC;QAEnF,IAAI,CAAC,+BAA+B,GAAG,IAAA,4BAAoB,EAAC,CAAC,UAAU,EAAE,WAAW,CAAC,EAAE,wBAAwB,CAAC,CAAA;QAChH,IAAI,CAAC,mBAAmB,GAAG,IAAI,2DAA4B,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;IAC/G,CAAC;IAED;;;;OAIG;IACG,iCAAiC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3E,CAAA;YACD,MAAM,eAAe,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,gBAAgB,CACvD,iBAAiB,CAAC,aAAa,EAC/B,UAAU,EACV,IAAI,CAAC,+BAA+B,EACpC,KAAK,EACL,IAAI,EACJ,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,+CAAsB,CAAC,CAAC,CAAC,CACrC,CAAA;YACD,MAAM,IAAI,CAAC,mBAAmB,CAAC,MAAM,CACnC,eAAe,EACf,IAAI,SAAG,CAAC,MAAM,CACZ,6DAA0B,EAC1B,MAAM,IAAI,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,wBAAwB,CAAC,mBAAmB,CAAC,EAAE,UAAU,CAAC,CAC5H,CACF,CAAA;QACH,CAAC;KAAA;CACF;AA5QD,gEA4QC","sourcesContent":["import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { DelegationMembersDetails, SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { SecureDelegationKeyMap } from '../../icc-api/model/internal/SecureDelegationKeyMap'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedFieldsManifest, parseEncryptedFields } from '../utils'\nimport { IccSecureDelegationKeyMapApi } from '../../icc-api/api/internal/IccSecureDelegationKeyMapApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { AuthenticationProvider, NoAuthenticationProvider } from '../auth/AuthenticationProvider'\nimport { ACCESS_CONTROL_KEYS_HEADER, AccessControlKeysHeadersProvider } from './AccessControlKeysHeadersProvider'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\n\n// TODO could be optimised using bulk methods\nexport class DelegationsDeAnonymization {\n private readonly delegationKeyMapFieldsToEncrypt: EncryptedFieldsManifest\n private readonly delegationKeyMapApi: IccSecureDelegationKeyMapApi\n\n constructor(\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly secureDelegationsMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly xapis: ExtendedApisUtils,\n private readonly cryptoPrimitives: CryptoPrimitives,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n private readonly accessControlKeysHeadersProvider: AccessControlKeysHeadersProvider\n ) {\n this.delegationKeyMapFieldsToEncrypt = parseEncryptedFields(['delegate', 'delegator'], 'SecureDelegationKeyMap')\n this.delegationKeyMapApi = new IccSecureDelegationKeyMapApi(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Creates / updates information to allow the data owners in {@link shareWithDataOwners} to de-anonymize the delegations contained within\n * {@link entity}.\n * Note that the delegation de-anonymization information may be used also with other entities of the same type.\n */\n async createOrUpdateDeAnonymizationInfo(entityWithType: EncryptedEntityWithType, shareWithDataOwners: string[]) {\n const delegationsDetails = Object.entries(await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)).flatMap(\n ([canonicalKey, delegation]) => {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [[canonicalKey, delegation], ...aliases.map((alias) => [alias, delegation])] as [string, DelegationMembersDetails][]\n }\n )\n const delegationsForDeanonInfoSharing = delegationsDetails.filter(([_, delegationInfo]) => {\n // Drop fully explicit ones: they don't need de-anonymization info\n return !delegationInfo.fullyExplicit\n })\n // A subset of delegations for which deanon info is relevant AND for which we can also create new info instead of sharing only existing one.\n const delegationsForNewDeanonInfoCreation = delegationsForDeanonInfoSharing.filter(([_, delegationInfo]) => {\n // Drop those for which we don't have the full information needed for the creation of new data.\n return !!delegationInfo.delegate && !!delegationInfo.delegator && !!delegationInfo.accessControlSecret\n })\n const existingDelegationsMap = await this.getDecryptedSecureDelegationKeyMaps(\n delegationsForDeanonInfoSharing.map((x) => x[0]),\n entityWithType.type\n )\n for (const delMapToShare of existingDelegationsMap) {\n await this.ensureDelegationKeyMapSharedWith(entityWithType.type, delMapToShare, shareWithDataOwners)\n }\n const existingDelegationsMapKeys = new Set(existingDelegationsMap.map((x) => x.delegationKey))\n const delegationsToCreate = delegationsForNewDeanonInfoCreation.filter(([k, _]) => !existingDelegationsMapKeys.has(k))\n for (const [delKey, membersDetails] of delegationsToCreate) {\n await this.createSecureDelegationKeyMap(entityWithType.type, delKey, membersDetails, shareWithDataOwners)\n }\n }\n\n /**\n * Get the data owners which can access the entity. See {@link EncryptedEntityXApi.getDataOwnersWithAccessTo} for more details.\n * @param entityWithType an entity.\n */\n async getDataOwnersWithAccessTo(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return this.mergePermissions([\n await this.getDataOwnersWithAccessToSecureDelegations(entityWithType),\n {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entityWithType.entity.delegations ?? {}).map((k) => [k, AccessLevelEnum.WRITE])),\n hasUnknownAnonymousDataOwners: false,\n },\n ])\n }\n\n private async getDataOwnersWithAccessToSecureDelegations(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const secureDelegationDetails = await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const secureDelegationWithUnknownMembers = Object.entries(secureDelegationDetails).flatMap(([canonicalKey, delegation]) => {\n if (!delegation.delegate || !delegation.delegator) {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [{ keys: [canonicalKey, ...aliases], delegation }]\n } else {\n return []\n }\n })\n const secureDelegationKeyMapsByDelegationKey = Object.fromEntries(\n (\n await this.getDecryptedSecureDelegationKeyMaps(\n secureDelegationWithUnknownMembers.flatMap(({ keys }) => keys),\n entityWithType.type\n )\n ).map((x) => [x.delegationKey, x])\n )\n const permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n function addAccess(dataOwnerId: string, level: AccessLevelEnum) {\n if (permissionsByDataOwnerId[dataOwnerId] !== AccessLevelEnum.WRITE) {\n permissionsByDataOwnerId[dataOwnerId] = level\n }\n }\n for (const delegation of Object.values(secureDelegationDetails)) {\n if (delegation.delegate) addAccess(delegation.delegate, delegation.accessLevel)\n if (delegation.delegator) addAccess(delegation.delegator, delegation.accessLevel)\n }\n for (const { keys, delegation } of secureDelegationWithUnknownMembers) {\n const bestKey = keys.find((k) => {\n const currMap = secureDelegationKeyMapsByDelegationKey[k]\n return currMap && !!currMap.delegator && !!currMap.delegate\n })\n if (bestKey) {\n const keyMap = secureDelegationKeyMapsByDelegationKey[bestKey]\n addAccess(keyMap.delegate!, delegation.accessLevel)\n addAccess(keyMap.delegator!, delegation.accessLevel)\n } else {\n hasUnknownAnonymousDataOwners = true\n }\n }\n return { permissionsByDataOwnerId, hasUnknownAnonymousDataOwners }\n }\n\n private async mergePermissions(\n values: {\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }[]\n ): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const accumulatedPermissions: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n for (const v of values) {\n hasUnknownAnonymousDataOwners = hasUnknownAnonymousDataOwners || v.hasUnknownAnonymousDataOwners\n for (const [dataOwnerId, level] of Object.entries(v.permissionsByDataOwnerId)) {\n if (accumulatedPermissions[dataOwnerId] !== AccessLevelEnum.WRITE) {\n accumulatedPermissions[dataOwnerId] = level\n }\n }\n }\n return {\n permissionsByDataOwnerId: accumulatedPermissions,\n hasUnknownAnonymousDataOwners,\n }\n }\n\n private async getDecryptedSecureDelegationKeyMaps(\n delegationIds: string[],\n entityType: EntityWithDelegationTypeName\n ): Promise<SecureDelegationKeyMap[]> {\n if (delegationIds.length) {\n const encryptedMaps = await this.delegationKeyMapApi.getByDelegationKeys(\n { ids: delegationIds },\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n const res: SecureDelegationKeyMap[] = []\n for (const encryptedMap of encryptedMaps) {\n // Use the original entity type\n const decryptionResult = await this.xapis.decryptEntity(encryptedMap, entityType, (x) => new SecureDelegationKeyMap(x))\n if (decryptionResult.decrypted) {\n res.push(decryptionResult.entity)\n }\n }\n return res\n } else return []\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async ensureDelegationKeyMapSharedWith(entityType: EntityWithDelegationTypeName, keyMap: SecureDelegationKeyMap, delegates: string[]) {\n if (!keyMap.delegator || !keyMap.delegate) throw new Error('Illegal state: key map is missing delegator or delegate info.')\n const dataOwnersWithAccessToMapThroughDelegation = Object.values(\n await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails({\n type: entityType,\n entity: keyMap,\n })\n )\n .flatMap((x) => [x.delegate, x.delegator])\n .filter((x) => !!x) as string[]\n // Delegator and delegate got access to the entity when it was first created: no need to share with them ever.\n const dataOwnersWithAccessToMap = new Set([keyMap.delegate, keyMap.delegator, ...dataOwnersWithAccessToMapThroughDelegation])\n const dataOwnersNeedingShare = delegates.filter((x) => !dataOwnersWithAccessToMap.has(x))\n if (dataOwnersNeedingShare.length) {\n ;(\n await this.xapis.simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: keyMap,\n type: entityType,\n },\n Object.fromEntries(\n dataOwnersNeedingShare.map((x) => [\n x,\n {\n shareSecretIds: [],\n shareEncryptionKeys: ShareMetadataBehaviour.REQUIRED,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n },\n ])\n ),\n async (request) =>\n this.delegationKeyMapApi.bulkShareSecureDelegationKeyMap(\n request,\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n )\n ).updatedEntityOrThrow\n }\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async createSecureDelegationKeyMap(\n entityType: EntityWithDelegationTypeName,\n delegationKey: string,\n delegationMembersDetails: DelegationMembersDetails,\n delegates: string[]\n ) {\n if (!delegationMembersDetails.delegate || !delegationMembersDetails.delegator || !delegationMembersDetails.accessControlSecret)\n throw new Error('Illegal state: delegation members details are missing delegate, delegator or access control secret info.')\n const selfDoId = await this.dataOwnerApi.getCurrentDataOwnerId()\n // Ensure that both the delegator and delegate of the delegation this map refers tho can share it later on, even if they did not create it.\n // Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.\n const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId)\n const initalisedMapInfo = await this.xapis.entityWithInitialisedEncryptedMetadata<SecureDelegationKeyMap>(\n {\n id: this.cryptoPrimitives.randomUuid(),\n delegate: delegationMembersDetails.delegate,\n delegator: delegationMembersDetails.delegator,\n delegationKey: delegationKey,\n },\n entityType,\n undefined,\n undefined,\n true,\n Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ]))\n )\n const encryptedKeyMap = await this.xapis.tryEncryptEntity(\n initalisedMapInfo.updatedEntity,\n entityType,\n this.delegationKeyMapFieldsToEncrypt,\n false,\n true,\n (x) => new SecureDelegationKeyMap(x)\n )\n await this.delegationKeyMapApi.create(\n encryptedKeyMap,\n new XHR.Header(\n ACCESS_CONTROL_KEYS_HEADER,\n await this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)\n )\n )\n }\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models';
2
2
  import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName';
3
3
  import { SecureDelegation } from '../../icc-api/model/SecureDelegation';
4
- import AccessLevelEnum = SecureDelegation.AccessLevelEnum;
5
4
  import { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest';
6
5
  import { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult';
7
6
  import RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum;
@@ -104,14 +103,13 @@ export interface ExtendedApisUtils {
104
103
  * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.
105
104
  * @param initialiseEncryptionKey if false this method will not initialize an encryption key for the entity. Use only for entities which use
106
105
  * delegations for access control but don't actually have any encrypted content.
107
- * @param initialiseSecretId if false this method will not initialize any secret id, use it for entities which can not be 'owning entities' (e.g.
108
106
  * HealthcareElement).
109
107
  * @param autoDelegations automatically shares the metadata with the provided data owners, with the provided access level.
110
108
  * @throws if the entity already has non-empty values for encryption metadata.
111
109
  * @return an updated copy of the entity.
112
110
  */
113
- entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName, owningEntity: string | undefined, owningEntitySecretId: string | undefined, initialiseEncryptionKey: boolean, initialiseSecretId: boolean, autoDelegations: {
114
- [dataOwnerId: string]: AccessLevelEnum;
111
+ entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName, owningEntity: string | undefined, owningEntitySecretId: string | undefined, initialiseEncryptionKey: boolean, autoDelegations: {
112
+ [p: string]: SecureDelegation.AccessLevelEnum;
115
113
  }): Promise<{
116
114
  updatedEntity: T;
117
115
  rawEncryptionKey: string | undefined;
@@ -202,7 +200,6 @@ export interface ExtendedApisUtils {
202
200
  * and owning entity ids if requested. NOTE: this method can only be used with entities which already exist in the cloud (the entity must have
203
201
  * been saved).
204
202
  * @param entity an entity.
205
- * @param unusedSecretIds specifies if the entity should not actually use secret ids but may have some if it was created using older iCure sdk
206
203
  * versions. If true the method expects `shareSecretIds` options to always be undefined and will always share any available secret ids. If false
207
204
  * it expects `shareSecretIds` options to always be defined and will only share the secret ids specified in the options.
208
205
  * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:
@@ -220,12 +217,12 @@ export interface ExtendedApisUtils {
220
217
  simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(entity: {
221
218
  entity: T;
222
219
  type: EntityWithDelegationTypeName;
223
- }, unusedSecretIds: boolean, delegates: {
224
- [delegateId: string]: {
220
+ }, delegates: {
221
+ [p: string]: {
225
222
  shareSecretIds: string[] | undefined;
226
223
  shareEncryptionKeys: ShareMetadataBehaviour | undefined;
227
224
  shareOwningEntityIds: ShareMetadataBehaviour | undefined;
228
- requestedPermissions: RequestedPermissionEnum | undefined;
225
+ requestedPermissions: EntityShareRequest.RequestedPermissionEnum | undefined;
229
226
  };
230
227
  }, doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>): Promise<ShareResult<T>>;
231
228
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ExtendedApisUtils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtils.ts"],"names":[],"mappings":"","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { ShareResult } from '../utils/ShareResult'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { EncryptedFieldsManifest } from '../utils'\nimport { BulkShareOrUpdateMetadataParams } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this interface is meant only for internal use and may be changed without notice.\n * Gives access to several functions to access encrypted entities metadata.\n */\nexport interface ExtendedApisUtils {\n // region metadata decryption\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 * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\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 * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\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 * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get if the current data owner has write access to the content of the entity.\n * @param entity an entity\n * @return if the current data owner (or one of his parents) has write access to the content of the entity.\n */\n hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean>\n\n /**\n * @param entity an entity\n * @return if the entity has no encryption metadata and can be safely initialised using .\n */\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean\n // endregion\n\n // region metadata initialisation and share\n /**\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, 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 and DOES NOT SAVE the entity to the cloud/DB: you will have to save the entity manually.\n * @param entity entity which requires encryption metadata initialisation.\n * @param entityType type of the entity.\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 initialiseEncryptionKey if false this method will not initialize an encryption key for the entity. Use only for entities which use\n * delegations for access control but don't actually have any encrypted content.\n * @param initialiseSecretId if false this method will not initialize any secret id, use it for entities which can not be 'owning entities' (e.g.\n * HealthcareElement).\n * @param autoDelegations automatically shares the metadata with the provided data owners, with the provided access level.\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n initialiseSecretId: boolean,\n autoDelegations: { [dataOwnerId: string]: AccessLevelEnum }\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string | undefined\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 updates the entity in the cloud/DB (the updated entities in the returned promise are already saved in the DB). NOTE: this method can only\n * be used with entities which already exist in the cloud (the entities must have been saved).\n * @param entitiesType type of entities to update\n * @param entitiesUpdates share/update requests for each entity. An array of objects containing:\n * - The entity to share/update (or at least its encrypted metadata)\n * - The data to share/update for each delegate. An object associating to each delegate id the data to share/update for that delegate, and the\n * permissions requested for the delegate (ignored if the request will only update already existing shared metadata).\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @throws if there are duplicate entities in the requested updates.\n * @return a promise which will be completed with an object containing:\n * - the updated entities, only for entities were at least one update was successful\n * - information on the individual requests failed, containing the id of the entity, id of the delegate that the request was for, the content,\n * an error code mirroring an http status code, and a human-friendly description of the error (but not necessarily end-user friendly).\n */\n bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n /**\n * Simplified version of {@link bulkShareOrUpdateEncryptedEntityMetadata} for a single entity and with automatic retrieval of the encryption keys\n * and owning entity ids if requested. NOTE: this method can only be used with entities which already exist in the cloud (the entity must have\n * been saved).\n * @param entity an entity.\n * @param unusedSecretIds specifies if the entity should not actually use secret ids but may have some if it was created using older iCure sdk\n * versions. If true the method expects `shareSecretIds` options to always be undefined and will always share any available secret ids. If false\n * it expects `shareSecretIds` options to always be defined and will only share the secret ids specified in the options.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareEncryptionKeys specifies if the encryption keys of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareOwningEntityIds specifies if the owning entity ids of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareSecretIds specifies which secret ids of the entity should be shared. Should be defined only if {@link unusedSecretIds} is false.\n * - requestedPermissions requested permissions for the delegate. Defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return a promise which will be completed with the result of the operation\n * @throws if shareEncryptionKeys or shareOwningEntityIds is {@link ShareMetadataBehaviour.REQUIRED} and the current data owner can't access any\n * value for the required metadata.\n */\n simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n unusedSecretIds: boolean,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>>\n // endregion\n\n // region content encryption and decryption\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 type type of the entity.\n * @param content data of the entity which you want to encrypt.\n * @param saveEntity a function which saves the entity to the cloud/DB. Used only if a new encryption key needed to be initialised for the entity.\n * @return the encrypted data and, if a new encryption key was initialised for the entity, the updated entity.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }>\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 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 * @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 tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }>\n\n /**\n * TODO work on this\n * Decrypts the content of an encrypted entity.\n */\n decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }>\n\n /**\n * Tries to decrypt data to a json object using the provided keys.\n */\n tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined>\n\n /**\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 using the default configuration). If the entity specifies\n * a value for any field which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T>\n\n /**\n * Returns the first encryption key which could be properly decrypted from the entity using the current data owner.\n * @throws if no key could be decrypted.\n */\n decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }>\n\n /**\n * Returns all encryption keys which could be properly decrypted from the entity using the current data owner. The keys returned by this method\n * should not be used for encryption of the entity, but only for decryption.\n * This is because this for data from pre-2018 users this method may return also keys from old formats of entities which are not safe anymore for\n * encryption.\n */\n decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]>\n\n /**\n * Verifies if the entity has valid encryption keys (regardless of whether the current data owner has access to them or not). If not this method\n * will throw an error, otherwise it will return undefined. For pre-2018 users there are some cases where the data may have been encrypted with a\n * key not safe for encryption anymore, in which case this method will return the entity with a new and safe encryption key.\n * After this method is called, if it returns an entity it should also be re-encrypted (using the new key) and saved to the cloud.\n */\n ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined>\n // endregion\n}\n"]}
1
+ {"version":3,"file":"ExtendedApisUtils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtils.ts"],"names":[],"mappings":"","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { ShareResult } from '../utils/ShareResult'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { EncryptedFieldsManifest } from '../utils'\nimport { BulkShareOrUpdateMetadataParams } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this interface is meant only for internal use and may be changed without notice.\n * Gives access to several functions to access encrypted entities metadata.\n */\nexport interface ExtendedApisUtils {\n // region metadata decryption\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 * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\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 * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\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 * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get if the current data owner has write access to the content of the entity.\n * @param entity an entity\n * @return if the current data owner (or one of his parents) has write access to the content of the entity.\n */\n hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean>\n\n /**\n * @param entity an entity\n * @return if the entity has no encryption metadata and can be safely initialised using .\n */\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean\n // endregion\n\n // region metadata initialisation and share\n /**\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, 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 and DOES NOT SAVE the entity to the cloud/DB: you will have to save the entity manually.\n * @param entity entity which requires encryption metadata initialisation.\n * @param entityType type of the entity.\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 initialiseEncryptionKey if false this method will not initialize an encryption key for the entity. Use only for entities which use\n * delegations for access control but don't actually have any encrypted content.\n * HealthcareElement).\n * @param autoDelegations automatically shares the metadata with the provided data owners, with the provided access level.\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<{ updatedEntity: T; rawEncryptionKey: string | undefined; secretId: string | undefined }>\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 updates the entity in the cloud/DB (the updated entities in the returned promise are already saved in the DB). NOTE: this method can only\n * be used with entities which already exist in the cloud (the entities must have been saved).\n * @param entitiesType type of entities to update\n * @param entitiesUpdates share/update requests for each entity. An array of objects containing:\n * - The entity to share/update (or at least its encrypted metadata)\n * - The data to share/update for each delegate. An object associating to each delegate id the data to share/update for that delegate, and the\n * permissions requested for the delegate (ignored if the request will only update already existing shared metadata).\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @throws if there are duplicate entities in the requested updates.\n * @return a promise which will be completed with an object containing:\n * - the updated entities, only for entities were at least one update was successful\n * - information on the individual requests failed, containing the id of the entity, id of the delegate that the request was for, the content,\n * an error code mirroring an http status code, and a human-friendly description of the error (but not necessarily end-user friendly).\n */\n bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n /**\n * Simplified version of {@link bulkShareOrUpdateEncryptedEntityMetadata} for a single entity and with automatic retrieval of the encryption keys\n * and owning entity ids if requested. NOTE: this method can only be used with entities which already exist in the cloud (the entity must have\n * been saved).\n * @param entity an entity.\n * versions. If true the method expects `shareSecretIds` options to always be undefined and will always share any available secret ids. If false\n * it expects `shareSecretIds` options to always be defined and will only share the secret ids specified in the options.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareEncryptionKeys specifies if the encryption keys of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareOwningEntityIds specifies if the owning entity ids of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareSecretIds specifies which secret ids of the entity should be shared. Should be defined only if {@link unusedSecretIds} is false.\n * - requestedPermissions requested permissions for the delegate. Defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return a promise which will be completed with the result of the operation\n * @throws if shareEncryptionKeys or shareOwningEntityIds is {@link ShareMetadataBehaviour.REQUIRED} and the current data owner can't access any\n * value for the required metadata.\n */\n simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n delegates: {\n [p: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>>\n // endregion\n\n // region content encryption and decryption\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 type type of the entity.\n * @param content data of the entity which you want to encrypt.\n * @param saveEntity a function which saves the entity to the cloud/DB. Used only if a new encryption key needed to be initialised for the entity.\n * @return the encrypted data and, if a new encryption key was initialised for the entity, the updated entity.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }>\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 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 * @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 tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }>\n\n /**\n * TODO work on this\n * Decrypts the content of an encrypted entity.\n */\n decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }>\n\n /**\n * Tries to decrypt data to a json object using the provided keys.\n */\n tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined>\n\n /**\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 using the default configuration). If the entity specifies\n * a value for any field which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T>\n\n /**\n * Returns the first encryption key which could be properly decrypted from the entity using the current data owner.\n * @throws if no key could be decrypted.\n */\n decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }>\n\n /**\n * Returns all encryption keys which could be properly decrypted from the entity using the current data owner. The keys returned by this method\n * should not be used for encryption of the entity, but only for decryption.\n * This is because this for data from pre-2018 users this method may return also keys from old formats of entities which are not safe anymore for\n * encryption.\n */\n decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]>\n\n /**\n * Verifies if the entity has valid encryption keys (regardless of whether the current data owner has access to them or not). If not this method\n * will throw an error, otherwise it will return undefined. For pre-2018 users there are some cases where the data may have been encrypted with a\n * key not safe for encryption anymore, in which case this method will return the entity with a new and safe encryption key.\n * After this method is called, if it returns an entity it should also be re-encrypted (using the new key) and saved to the cloud.\n */\n ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined>\n // endregion\n}\n"]}
@@ -46,12 +46,12 @@ export declare class ExtendedApisUtilsImpl implements ExtendedApisUtils {
46
46
  extracted: string[];
47
47
  }[]>;
48
48
  hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean>;
49
- entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName, owningEntity: string | undefined, owningEntitySecretId: string | undefined, initialiseEncryptionKey: boolean, initialiseSecretId: boolean, autoDelegations: {
49
+ entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName, owningEntity: string | undefined, owningEntitySecretId: string | undefined, initialiseEncryptionKey: boolean, autoDelegations: {
50
50
  [p: string]: SecureDelegation.AccessLevelEnum;
51
51
  }): Promise<{
52
52
  updatedEntity: T;
53
53
  rawEncryptionKey: string | undefined;
54
- secretId: string | undefined;
54
+ secretId: string;
55
55
  }>;
56
56
  bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(entitiesType: EntityWithDelegationTypeName, entitiesUpdates: {
57
57
  entity: EncryptedEntityStub;
@@ -114,12 +114,12 @@ export declare class ExtendedApisUtilsImpl implements ExtendedApisUtils {
114
114
  simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(entity: {
115
115
  entity: T;
116
116
  type: EntityWithDelegationTypeName;
117
- }, unusedSecretIds: boolean, delegates: {
118
- [delegateId: string]: {
117
+ }, delegates: {
118
+ [p: string]: {
119
119
  shareSecretIds: string[] | undefined;
120
120
  shareEncryptionKeys: ShareMetadataBehaviour | undefined;
121
121
  shareOwningEntityIds: ShareMetadataBehaviour | undefined;
122
- requestedPermissions: RequestedPermissionEnum | undefined;
122
+ requestedPermissions: EntityShareRequest.RequestedPermissionEnum | undefined;
123
123
  };
124
124
  }, doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>): Promise<ShareResult<T>>;
125
125
  private makeMigrationRequestsIfNeeded;
@@ -72,12 +72,12 @@ class ExtendedApisUtilsImpl {
72
72
  AccessLevel.WRITE);
73
73
  });
74
74
  }
75
- entityWithInitialisedEncryptedMetadata(entity, entityType, owningEntity, owningEntitySecretId, initialiseEncryptionKey, initialiseSecretId, autoDelegations) {
75
+ entityWithInitialisedEncryptedMetadata(entity, entityType, owningEntity, owningEntitySecretId, initialiseEncryptionKey, autoDelegations) {
76
76
  return __awaiter(this, arguments, void 0, function* () {
77
77
  this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments);
78
78
  this.checkEmptyEncryptionMetadata(entity);
79
79
  const newRawKey = initialiseEncryptionKey ? yield this.primitives.AES.generateCryptoKey(true) : undefined;
80
- const newSecretId = initialiseSecretId ? this.primitives.randomUuid() : undefined;
80
+ const newSecretId = this.primitives.randomUuid();
81
81
  return {
82
82
  updatedEntity: yield this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(Object.assign(Object.assign({}, entity), { secretForeignKeys: owningEntitySecretId ? [owningEntitySecretId] : [] }), entityType, newSecretId ? [newSecretId] : [], !!owningEntity ? [owningEntity] : [], newRawKey ? [newRawKey] : [], autoDelegations),
83
83
  rawEncryptionKey: newRawKey,
@@ -205,15 +205,11 @@ class ExtendedApisUtilsImpl {
205
205
  return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId };
206
206
  });
207
207
  }
208
- simpleShareOrUpdateEncryptedEntityMetadata(entity, unusedSecretIds, delegates, doRequestBulkShareOrUpdate) {
208
+ simpleShareOrUpdateEncryptedEntityMetadata(entity, delegates, doRequestBulkShareOrUpdate) {
209
209
  var _a, _b;
210
210
  return __awaiter(this, void 0, void 0, function* () {
211
211
  const availableEncryptionKeys = yield this.encryptionKeysOf(entity);
212
212
  const availableOwningEntityIds = yield this.owningEntityIdsOf(entity);
213
- let availableSecretIds;
214
- if (unusedSecretIds) {
215
- availableSecretIds = yield this.secretIdsOf(entity);
216
- }
217
213
  const dataForDelegates = {};
218
214
  for (const [delegateId, delegateRequests] of Object.entries(delegates)) {
219
215
  if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour_1.ShareMetadataBehaviour.REQUIRED) {
@@ -222,14 +218,8 @@ class ExtendedApisUtilsImpl {
222
218
  if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour_1.ShareMetadataBehaviour.REQUIRED) {
223
219
  throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`);
224
220
  }
225
- if (!delegateRequests.shareSecretIds && !unusedSecretIds) {
226
- throw new Error(`Share secret ids parameter is mandatory for entities of type ${entity.type}.`);
227
- }
228
- else if (delegateRequests.shareSecretIds && unusedSecretIds) {
229
- throw new Error(`Share secret ids parameter must not be unused with entities of type ${entity.type}.`);
230
- }
231
221
  dataForDelegates[delegateId] = {
232
- shareSecretIds: (_a = delegateRequests.shareSecretIds) !== null && _a !== void 0 ? _a : availableSecretIds,
222
+ shareSecretIds: (_a = delegateRequests.shareSecretIds) !== null && _a !== void 0 ? _a : (yield this.secretIdsOf(entity)),
233
223
  shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,
234
224
  shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,
235
225
  requestedPermissions: (_b = delegateRequests.requestedPermissions) !== null && _b !== void 0 ? _b : RequestedPermissionEnum.MAX_WRITE,