@icure/api 7.0.0-beta.1 → 7.0.0-beta.3

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 (103) hide show
  1. package/icc-api/api/IccDataownerApi.d.ts +13 -2
  2. package/icc-api/api/IccDataownerApi.js +30 -4
  3. package/icc-api/api/IccDataownerApi.js.map +1 -1
  4. package/icc-api/api/IccPatientApi.d.ts +4 -0
  5. package/icc-api/api/IccPatientApi.js +17 -0
  6. package/icc-api/api/IccPatientApi.js.map +1 -1
  7. package/icc-api/model/CryptoActorStub.d.ts +55 -0
  8. package/icc-api/model/CryptoActorStub.js +35 -0
  9. package/icc-api/model/CryptoActorStub.js.map +1 -0
  10. package/icc-api/model/DataOwnerTypeEnum.d.ts +8 -0
  11. package/icc-api/model/DataOwnerTypeEnum.js +13 -0
  12. package/icc-api/model/DataOwnerTypeEnum.js.map +1 -0
  13. package/icc-api/model/DataOwnerWithType.d.ts +16 -3
  14. package/icc-api/model/DataOwnerWithType.js +22 -7
  15. package/icc-api/model/DataOwnerWithType.js.map +1 -1
  16. package/icc-api/model/Device.d.ts +4 -0
  17. package/icc-api/model/Device.js.map +1 -1
  18. package/icc-api/model/HealthcareParty.d.ts +4 -0
  19. package/icc-api/model/HealthcareParty.js.map +1 -1
  20. package/icc-api/model/Patient.d.ts +4 -0
  21. package/icc-api/model/Patient.js.map +1 -1
  22. package/icc-x-api/basexapi/EncryptedEntityXApi.d.ts +48 -0
  23. package/icc-x-api/basexapi/EncryptedEntityXApi.js +3 -0
  24. package/icc-x-api/basexapi/EncryptedEntityXApi.js.map +1 -0
  25. package/icc-x-api/crypto/AES.js +9 -1
  26. package/icc-x-api/crypto/AES.js.map +1 -1
  27. package/icc-x-api/crypto/BaseExchangeKeysManager.d.ts +4 -2
  28. package/icc-x-api/crypto/BaseExchangeKeysManager.js +32 -31
  29. package/icc-x-api/crypto/BaseExchangeKeysManager.js.map +1 -1
  30. package/icc-x-api/crypto/CryptoStrategies.d.ts +5 -4
  31. package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
  32. package/icc-x-api/crypto/EntitiesEncryption.d.ts +23 -4
  33. package/icc-x-api/crypto/EntitiesEncryption.js +48 -24
  34. package/icc-x-api/crypto/EntitiesEncryption.js.map +1 -1
  35. package/icc-x-api/crypto/ExchangeKeysManager.d.ts +3 -2
  36. package/icc-x-api/crypto/ExchangeKeysManager.js +3 -3
  37. package/icc-x-api/crypto/ExchangeKeysManager.js.map +1 -1
  38. package/icc-x-api/crypto/KeyManager.js +4 -4
  39. package/icc-x-api/crypto/KeyManager.js.map +1 -1
  40. package/icc-x-api/crypto/KeyRecovery.d.ts +2 -1
  41. package/icc-x-api/crypto/KeyRecovery.js.map +1 -1
  42. package/icc-x-api/crypto/LegacyCryptoStrategies.d.ts +5 -4
  43. package/icc-x-api/crypto/LegacyCryptoStrategies.js +1 -1
  44. package/icc-x-api/crypto/LegacyCryptoStrategies.js.map +1 -1
  45. package/icc-x-api/crypto/ShamirKeysManager.d.ts +4 -3
  46. package/icc-x-api/crypto/ShamirKeysManager.js +8 -7
  47. package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
  48. package/icc-x-api/crypto/TransferKeysManager.d.ts +3 -2
  49. package/icc-x-api/crypto/TransferKeysManager.js +6 -6
  50. package/icc-x-api/crypto/TransferKeysManager.js.map +1 -1
  51. package/icc-x-api/crypto/utils.d.ts +7 -6
  52. package/icc-x-api/crypto/utils.js +4 -7
  53. package/icc-x-api/crypto/utils.js.map +1 -1
  54. package/icc-x-api/icc-accesslog-x-api.d.ts +27 -1
  55. package/icc-x-api/icc-accesslog-x-api.js +34 -1
  56. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  57. package/icc-x-api/icc-calendar-item-x-api.d.ts +36 -1
  58. package/icc-x-api/icc-calendar-item-x-api.js +61 -1
  59. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  60. package/icc-x-api/icc-classification-x-api.d.ts +27 -1
  61. package/icc-x-api/icc-classification-x-api.js +34 -1
  62. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  63. package/icc-x-api/icc-contact-x-api.d.ts +27 -1
  64. package/icc-x-api/icc-contact-x-api.js +34 -1
  65. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  66. package/icc-x-api/icc-crypto-x-api.d.ts +6 -6
  67. package/icc-x-api/icc-crypto-x-api.js +4 -4
  68. package/icc-x-api/icc-crypto-x-api.js.map +1 -1
  69. package/icc-x-api/icc-data-owner-x-api.d.ts +21 -52
  70. package/icc-x-api/icc-data-owner-x-api.js +36 -68
  71. package/icc-x-api/icc-data-owner-x-api.js.map +1 -1
  72. package/icc-x-api/icc-document-x-api.d.ts +71 -4
  73. package/icc-x-api/icc-document-x-api.js +96 -6
  74. package/icc-x-api/icc-document-x-api.js.map +1 -1
  75. package/icc-x-api/icc-form-x-api.d.ts +27 -1
  76. package/icc-x-api/icc-form-x-api.js +34 -1
  77. package/icc-x-api/icc-form-x-api.js.map +1 -1
  78. package/icc-x-api/icc-helement-x-api.d.ts +27 -1
  79. package/icc-x-api/icc-helement-x-api.js +34 -1
  80. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  81. package/icc-x-api/icc-icure-maintenance-x-api.js +4 -4
  82. package/icc-x-api/icc-icure-maintenance-x-api.js.map +1 -1
  83. package/icc-x-api/icc-invoice-x-api.d.ts +27 -1
  84. package/icc-x-api/icc-invoice-x-api.js +34 -1
  85. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  86. package/icc-x-api/icc-maintenance-task-x-api.d.ts +25 -2
  87. package/icc-x-api/icc-maintenance-task-x-api.js +26 -2
  88. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  89. package/icc-x-api/icc-message-x-api.d.ts +30 -1
  90. package/icc-x-api/icc-message-x-api.js +37 -1
  91. package/icc-x-api/icc-message-x-api.js.map +1 -1
  92. package/icc-x-api/icc-patient-x-api.d.ts +67 -1
  93. package/icc-x-api/icc-patient-x-api.js +80 -6
  94. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  95. package/icc-x-api/icc-receipt-x-api.d.ts +47 -2
  96. package/icc-x-api/icc-receipt-x-api.js +58 -4
  97. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  98. package/icc-x-api/icc-time-table-x-api.d.ts +25 -1
  99. package/icc-x-api/icc-time-table-x-api.js +27 -2
  100. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  101. package/icc-x-api/index.js +4 -3
  102. package/icc-x-api/index.js.map +1 -1
  103. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"EntitiesEncryption.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/EntitiesEncryption.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oCAA8H;AAC9H,4BAA2B;AAE3B,gEAAuD;AACvD,qEAAiE;AAEjE;;;GAGG;AACH,MAAa,kBAAkB;IAK7B,YAAY,UAA4B,EAAE,YAA8B,EAAE,mBAAwC;QAChH,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAA;IAChD,CAAC;IAED;;;;;;;OAOG;IACG,gBAAgB,CACpB,MAA6C,EAC7C,WAAoB,EACpB,aAAmD,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;;;YAE9E,2DAA2D;YAC3D,OAAO,IAAI,CAAC,4CAA4C,CACtD,MAAM,CAAC,IAAI,CAAC,MAAA,MAAM,CAAC,cAAc,mCAAI,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,cAAe,CAAC,CAAC,CAAC,MAAA,MAAM,CAAC,WAAW,mCAAI,EAAE,EACvG,WAAW,EACX,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC,EACpC,CAAC,CAAC,EAAE,EAA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AAmH,gBAAgB,IAAI;gBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;SACF;IACH,CAAC;CACF;AA93BD,gDA83BC","sourcesContent":["import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { DataOwnerWithType, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ExchangeKeysManager } from './ExchangeKeysManager'\nimport { b2a, crypt, decrypt, hex2ua, string2ua, truncateTrailingNulls, ua2hex, ua2string, ua2utf8, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { arrayEquals } from '../utils/collection-utils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\n\n/**\n * @internal this class is for internal use only and may be changed without notice\n * Give access to functions for retrieving encryption metadata of entities.\n */\nexport class EntitiesEncryption {\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly exchangeKeysManager: ExchangeKeysManager\n\n constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, exchangeKeysManager: ExchangeKeysManager) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.exchangeKeysManager = exchangeKeysManager\n }\n\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n async encryptionKeysOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n // Legacy entities may have encryption keys in delegations.\n return this.extractMergedHierarchyFromDelegationAndOwner(\n Object.keys(entity.encryptionKeys ?? {}).length > 0 ? entity.encryptionKeys! : entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async encryptionKeysForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.encryptionKeys ?? {},\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n async secretIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async secretIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.delegations ?? {},\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n async owningEntityIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.cryptedForeignKeys ?? {},\n dataOwnerId,\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async owningEntityIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.cryptedForeignKeys ?? {},\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * @internal this method is intended only for internal use and may be changed without notice.\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, and encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKeys if false this method will not initialize any encryption keys. Use only for entities which use delegations for\n * access control but don't actually have any encrypted content.\n * @param additionalDelegations automatically shares the\n * @param tags tags to associate with the initial encryption keys and metadata\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKeys: boolean,\n additionalDelegations: string[] = [],\n tags: string[] = []\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const secretId = this.primitives.randomUuid()\n const rawEncryptionKey = initialiseEncryptionKeys ? ua2hex(this.primitives.randomBytes(16)) : undefined\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const allIds = [selfId, ...new Set(additionalDelegations.filter((x) => x !== selfId))]\n const loadKeysResult = await this.loadEncryptionKeysForDelegates(entity, allIds)\n const updatedEntity = await allIds.reduce<Promise<T>>(\n async (prevUpdate, delegateId) =>\n await this.createOrUpdateEntityDelegations(\n await prevUpdate,\n delegateId,\n [],\n [],\n [],\n [secretId],\n initialiseEncryptionKeys ? [rawEncryptionKey!] : [],\n owningEntity ? [owningEntity] : [],\n tags,\n loadKeysResult.keysForDelegates\n ),\n Promise.resolve(loadKeysResult.updatedEntity)\n )\n if (owningEntitySecretId) {\n updatedEntity.secretForeignKeys = [owningEntitySecretId]\n }\n return { updatedEntity, secretId, rawEncryptionKey }\n }\n\n async entityWithAutoExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[] | undefined,\n shareEncryptionKeys: ShareMetadataBehaviour | undefined,\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n ): Promise<T> {\n if (shareSecretIds === undefined) {\n const availableSecretIds = await this.secretIdsOf(entity)\n if (availableSecretIds.length) {\n shareSecretIds = availableSecretIds\n } else {\n shareSecretIds = [this.primitives.randomUuid()]\n }\n }\n let actualShareEncryptionKeys: string[] = []\n if (shareEncryptionKeys !== ShareMetadataBehaviour.NEVER) {\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n if (!availableEncryptionKeys.length && shareEncryptionKeys === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no encryption keys or the current data owner can't access any encryption keys.`)\n }\n actualShareEncryptionKeys = availableEncryptionKeys\n }\n let actualShareOwningEntityIds: string[] = []\n if (shareOwningEntityIds !== ShareMetadataBehaviour.NEVER) {\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n if (!availableOwningEntityIds.length && shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids.`)\n }\n actualShareOwningEntityIds = availableOwningEntityIds\n }\n return this.entityWithExtendedEncryptedMetadata(entity, delegateId, shareSecretIds, actualShareEncryptionKeys, actualShareOwningEntityIds)\n }\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param delegateId id of the delegate to share data with.\n * @param shareSecretIds secret ids to share.\n * @param shareEncryptionKeys encryption keys to share.\n * @param shareOwningEntityIds owning enttiy ids to share.\n * @param newTags tags to associate with the new encryption keys and metadata. Existing data won't be changed.\n * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.\n * @return an updated copy of the entity.\n */\n async entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newTags: string[] = []\n ): Promise<T> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithSharedEncryptedMetadata', arguments)\n async function checkInputAndGet(input: string[], inputName: string, validate: (x: string) => boolean | Promise<boolean>): Promise<string[]> {\n for (const x of input) {\n const validation = validate(x)\n if (validation !== true && validation !== false && !(await validation)) throw new Error(`Invalid input for ${inputName}.`)\n }\n return input\n }\n const secretIdsToShare = await checkInputAndGet(shareSecretIds, 'secretIds', (x) => this.validateSecretId(x))\n const encryptionKeysToShare = await checkInputAndGet(shareEncryptionKeys, 'encryptionKeys', (x) => this.validateEncryptionKey(x))\n const owningEntityIdsToShare = await checkInputAndGet(shareOwningEntityIds, 'owningEntityIds', (x) => this.validateOwningEntityId(x))\n const deduplicateInfoSecretIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.delegations ?? {},\n secretIdsToShare,\n (x) => this.validateSecretId(x)\n )\n const deduplicateInfoEncryptionKeys = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.encryptionKeys ?? {},\n encryptionKeysToShare,\n (x) => this.validateEncryptionKey(x)\n )\n const deduplicateInfoOwningEntityIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.cryptedForeignKeys ?? {},\n owningEntityIdsToShare,\n (x) => this.validateOwningEntityId(x)\n )\n /*TODO\n * Temporary hack since secret id is necessary to create a delegation for access control: if there is no delegation existing from me to the\n * delegate and there is no new secret id to be created create a new random id.\n */\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (deduplicateInfoSecretIds.missingEntries.length === 0 && !deduplicateInfoSecretIds.deduplicatedDelegations.some((d) => d.owner === selfId)) {\n deduplicateInfoSecretIds.missingEntries.push(this.primitives.randomUuid())\n }\n if (\n deduplicateInfoSecretIds.missingEntries.length === 0 &&\n deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&\n deduplicateInfoOwningEntityIds.missingEntries.length === 0\n )\n return _.cloneDeep(entity)\n const { updatedEntity, keysForDelegates } = await this.loadEncryptionKeysForDelegates(entity, [delegateId])\n return this.createOrUpdateEntityDelegations(\n updatedEntity,\n delegateId,\n deduplicateInfoSecretIds.deduplicatedDelegations,\n deduplicateInfoEncryptionKeys.deduplicatedDelegations,\n deduplicateInfoOwningEntityIds.deduplicatedDelegations,\n deduplicateInfoSecretIds.missingEntries,\n deduplicateInfoEncryptionKeys.missingEntries,\n deduplicateInfoOwningEntityIds.missingEntries,\n newTags,\n keysForDelegates\n )\n }\n\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to encrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to use for encryption only keys associated to tags which pass the filter.\n * @return the encrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n async encryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf(await this.ensureEncryptionKeysInitialised(entity), dataOwnerId, tagsFilter)\n if (keys.length === 0)\n throw new Error(\n `Could not extract any encryption keys of entity ${entity} for data owner ${\n dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n }.`\n )\n return this.primitives.AES.encryptWithRawKey(keys[0], content)\n }\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @param tagsFilter allows to use for decryption only keys associated to tags which pass the filter.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n async decryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> = () => Promise.resolve(true),\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf(entity, dataOwnerId, tagsFilter)\n for (const key of keys) {\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(key, content)\n if (await validator(decrypted)) return decrypted\n } catch (e) {\n /* ignore */\n }\n }\n throw new Error(\n `No valid key found to decrypt data of ${entity} for data owner ${dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())}.`\n )\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Decrypts the content of an encrypted entity.\n */\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n ownerId: string,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n if (!entity.encryptedSelf) return { entity, decrypted: true }\n const encryptionKeys = await this.importAllValidKeys(await this.encryptionKeysOf(entity, ownerId))\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decrypt(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries using the provided keys to decrypt some json.\n */\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return undefined\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field\n * which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n dataOwnerId: string,\n cryptedKeys: string[],\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity)\n const encryptionKey = await this.tryImportFirstValidKey(await this.encryptionKeysOf(entity, dataOwnerId), entity.id!)\n if (!!encryptionKey) {\n return constructor(\n await crypt(\n entityWithInitialisedEncryptionKeys,\n (obj) => {\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || v instanceof Uint8Array\n ? b2a(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n cryptedKeys\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n const cryptedCopyWithRandomKey = await crypt(\n _.cloneDeep(entity),\n async (obj: { [key: string]: string }) => Promise.resolve(new ArrayBuffer(1)),\n cryptedKeys\n )\n if (\n !_.isEqual(\n _.omitBy({ ...cryptedCopyWithRandomKey, encryptedSelf: undefined }, _.isNil),\n _.omitBy({ ...entity, encryptedSelf: undefined }, _.isNil)\n )\n ) {\n throw new Error(`Impossible to modify encrypted value of an entity if no encryption key is known.\\n${entity}`)\n }\n return entity\n }\n }\n\n /**\n * @internal This method is for internal use only and may be changed without notice.\n * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of\n * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities\n * which were previously not encrypted.\n */\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T> {\n if (Object.keys(entity.encryptionKeys ?? {}).length > 0) return entity\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * If entity was using delegations as legacy encryption keys we will essentially revoke the access to the encrypted data for all other data\n * owners. This however should not be a problem as this form of legacy entities should not exist anymore, and it should be present only in the\n * databases of hcps without collaborators.\n */\n return await this.entityWithExtendedEncryptedMetadata(\n entity,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n [],\n [ua2hex(this.primitives.randomBytes(16))],\n []\n )\n }\n\n /**\n * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does\n * not consider exchange keys for parents).\n * Note that the retrieved exchange keys are decrypted using the private keys available on the device, and results may vary from other devices.\n * @param dataOwnerId id of a data owner, he should be part of the current data owner hierarchy.\n * @param delegations a delegation-like object containing the encrypted key\n * @param includeFromDelegations if true also considers delegation from the provided data owner (or parents) to look for values. This allows to\n * decrypt delegations associated to exchange keys recovered after a giveAccessBack request.\n * @param validateDecrypted validates the decrypted result, to drop decryption results with wrong key that still gave a valid checksum.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the key which could be decrypted using only keys available on the current device and delegations from/to the provided data owner. May\n * contain duplicates.\n */\n private async extractFromDelegationsForDataOwner(\n dataOwnerId: string,\n delegations: { [delegateId: string]: Delegation[] },\n includeFromDelegations: boolean,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const delegationsWithOwner = includeFromDelegations\n ? Object.entries(delegations).flatMap(([delegateId, delegations]) =>\n dataOwnerId === delegateId\n ? this.populateDelegatedTo(delegateId, delegations)\n : this.populateDelegatedTo(\n delegateId,\n delegations.filter((d) => d.owner === dataOwnerId)\n )\n )\n : delegations[dataOwnerId] ?? []\n const res = []\n for (const delegation of delegationsWithOwner) {\n if (await tagsFilter(delegation.tags ?? [])) {\n const decrypted = await this.tryDecryptDelegation(delegation, (k) => validateDecrypted(k))\n if (decrypted) res.push(decrypted)\n }\n }\n return res\n }\n\n // Ensures that the delegatedTo field of delegations has the appropriate values, else returns a copy of the delegations with the appropriate value.\n private populateDelegatedTo(delegateId: string, delegations: Delegation[]): Delegation[] {\n return delegations.map((d) => (d.delegatedTo === delegateId ? d : { ...d, delegatedTo: delegateId }))\n }\n\n private async extractedHierarchyFromDelegation(\n delegations: { [delegateId: string]: Delegation[] },\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return Promise.all(\n (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).map(async (ownerId) => {\n const extracted = this.deduplicate(\n await this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n return { ownerId, extracted }\n })\n )\n }\n\n /**\n * @internal This method should be private but is currently public/internal to allow to continue supporting legacy methods\n */\n async extractMergedHierarchyFromDelegationAndOwner(\n delegations: { [delegateId: string]: Delegation[] },\n dataOwnerId: string | undefined,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const hierarchy = dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const extractedByOwner = await Promise.all(\n // Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.\n [...hierarchy].reverse().map((ownerId) =>\n this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n )\n return this.deduplicate(extractedByOwner.flatMap((x) => x))\n }\n\n private async tryDecryptDelegation(\n delegation: Delegation,\n validateDecrypted: (result: string) => boolean | Promise<boolean>\n ): Promise<string | undefined> {\n const exchangeKeys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegation.owner!, delegation.delegatedTo!)\n for (const key of exchangeKeys) {\n try {\n // Format of encrypted key for any delegation should be entityId:key, but with the merging of entities the entityId might not match the\n // current id. As a checksum we are only verifying that the decrypted bytes can be represented as a string with exactly one ':'.\n // Additionally, we also have a validator that is specific for each type of delegation content (encryption key, secret id, ...)\n const decrypted = ua2string(await this.primitives.AES.decrypt(key, hex2ua(delegation.key!)))\n const decryptedSplit = decrypted.split(':')\n if (decryptedSplit.length === 2) {\n const validation = validateDecrypted(decryptedSplit[1])\n if (validation === true || (validation !== false && (await validation))) return decryptedSplit[1]\n } else {\n console.warn(\"Error in the decrypted delegation: content should contain exactly 1 ':', the delegation is ignored.\")\n }\n } catch (e) {\n // Do nothing: the delegation uses another exchange key owner->delegator\n }\n }\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(keys, entityId)\n if (!res) throw new Error(`Could not find any valid key for entity ${entityId}.`)\n return res\n }\n\n private async tryImportFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string } | undefined> {\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) return { key: imported, raw: key }\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importAllValidKeys(keys: string[]): Promise<{ key: CryptoKey; raw: string }[]> {\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n private async validateEncryptionKey(key: string): Promise<boolean> {\n return !!(await this.tryImportKey(key))\n }\n\n private validateSecretId(key: string): boolean {\n return !!key\n }\n\n private validateOwningEntityId(key: string): boolean {\n return !!key\n }\n\n private async createEncryptionKeyDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n encryptionKey: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!(await this.validateEncryptionKey(encryptionKey))) throw new Error(`Invalid encryption key ${encryptionKey}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, encryptionKey, newTags)\n }\n\n private async createSecretIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n secretId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateSecretId(secretId)) throw new Error(`Invalid secret id ${secretId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, secretId, newTags)\n }\n\n private async createOwningEntityIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n owningEntityId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateOwningEntityId(owningEntityId)) throw new Error(`Invalid owning id ${owningEntityId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, owningEntityId, newTags)\n }\n\n private async createDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n content: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (entityId.includes(':')) throw new Error(\"Ids for encrypted entities are not allowed to contain ':'\")\n if (content.includes(':')) throw new Error(\"Content of delegations can not contain ':'\")\n return {\n delegatedTo: delegateId,\n owner: await this.dataOwnerApi.getCurrentDataOwnerId(),\n key: ua2hex(await this.primitives.AES.encrypt(exchangeKey, string2ua(entityId + ':' + content))),\n tags: newTags,\n }\n }\n\n private async loadEncryptionKeysForDelegates<T extends EncryptedEntity>(\n entity: T,\n delegates: string[]\n ): Promise<{ updatedEntity: T; keysForDelegates: { [delegateId: string]: CryptoKey[] } }> {\n const { updatedDelegator, keysForDelegates } = await delegates.reduce(\n async (acc, delegateId) => {\n const awaitedAcc = await acc\n const currUpdateResult = await this.exchangeKeysManager.getOrCreateEncryptionExchangeKeysTo(delegateId)\n return {\n updatedDelegator: currUpdateResult.updatedDelegator ?? awaitedAcc.updatedDelegator,\n keysForDelegates: {\n ...awaitedAcc.keysForDelegates,\n [delegateId]: currUpdateResult.keys,\n },\n }\n },\n Promise.resolve({\n updatedDelegator: undefined as DataOwnerWithType | undefined,\n keysForDelegates: {} as { [delegateId: string]: CryptoKey[] },\n })\n )\n const updatedEntity =\n entity.id === updatedDelegator?.dataOwner?.id\n ? {\n ...entity,\n rev: updatedDelegator!.dataOwner.rev,\n hcPartyKeys: updatedDelegator!.dataOwner.hcPartyKeys,\n aesExchangeKeys: updatedDelegator!.dataOwner.aesExchangeKeys,\n }\n : entity\n return { updatedEntity, keysForDelegates }\n }\n\n private async createOrUpdateEntityDelegations<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n existingSecretIds: Delegation[],\n existingEncryptionKeys: Delegation[],\n existingOwningEntityIds: Delegation[],\n newSecretIds: string[],\n newEncryptionKeys: string[],\n newOwningEntityIds: string[],\n newTags: string[],\n keysForDelegates: { [delegateId: string]: CryptoKey[] }\n ): Promise<T> {\n const entityCopy = _.cloneDeep(entity)\n if (newSecretIds.length === 0 && newEncryptionKeys.length === 0 && newOwningEntityIds.length === 0) return entityCopy\n const chosenKey = keysForDelegates[delegateId][0]\n const updatedSecretIds = [\n ...existingSecretIds,\n ...(await Promise.all(newSecretIds.map((x) => this.createSecretIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedEncryptionKeys = [\n ...existingEncryptionKeys,\n ...(await Promise.all(newEncryptionKeys.map((x) => this.createEncryptionKeyDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedOwningEntityIds = [\n ...existingOwningEntityIds,\n ...(await Promise.all(newOwningEntityIds.map((x) => this.createOwningEntityIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n if (updatedSecretIds.length > 0) {\n entityCopy.delegations = {\n ...(entity.delegations ?? {}),\n [delegateId]: updatedSecretIds,\n }\n }\n if (updatedEncryptionKeys.length > 0) {\n entityCopy.encryptionKeys = {\n ...(entity.encryptionKeys ?? {}),\n [delegateId]: updatedEncryptionKeys,\n }\n }\n if (updatedOwningEntityIds.length > 0) {\n entityCopy.cryptedForeignKeys = {\n ...(entity.cryptedForeignKeys ?? {}),\n [delegateId]: updatedOwningEntityIds,\n }\n }\n return entityCopy\n }\n\n /**\n * De-duplicates all currently accessible delegations, by removing any delegations created by the current data owner which have duplicated content,\n * and checks if any of the required entries are currently available to the delegate through the existing delegations.\n * @param delegateId id of the delegate.\n * @param allDelegations delegations of the entity.\n * @param requiredEntries potentially new entries that the delegate needs to be able to access from the delegations.\n * @param validateDecrypted validator for decrypted delegation content\n * @return the deduplicated delegations\n */\n private async deduplicateDelegationsAndFilterRequiredEntries(\n delegateId: string,\n allDelegations: { [delegateId: string]: Delegation[] },\n requiredEntries: string[],\n validateDecrypted: (x: string) => boolean | Promise<boolean>\n ): Promise<{\n deduplicatedDelegations: Delegation[]\n missingEntries: string[]\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const delegationsToDelegate = allDelegations[delegateId] ?? []\n const decryptedDelegations = await Promise.all(\n delegationsToDelegate.map(async (d) => ({\n delegation: d,\n content: d.owner === selfId ? await this.tryDecryptDelegation(d, (x) => validateDecrypted(x)) : undefined,\n }))\n )\n const deduplicatedDelegations: Delegation[] = []\n const deduplicatedContent = new Map<string, string[][]>()\n decryptedDelegations.forEach(({ delegation, content }) => {\n if (content === undefined) {\n // Keep all delegations we could not decrypt or from other data owners\n deduplicatedDelegations.push(delegation)\n } else {\n const deduplicatedTags = deduplicatedContent.get(content)\n if (!deduplicatedTags) {\n deduplicatedContent.set(content, [delegation.tags ?? []])\n deduplicatedDelegations.push(delegation)\n } else if (!deduplicatedTags.some((t) => arrayEquals(t, delegation.tags ?? []))) {\n deduplicatedTags.push(delegation.tags ?? [])\n deduplicatedDelegations.push(delegation)\n }\n }\n })\n const delegationsFromDelegateToSelf = (allDelegations[selfId] ?? []).filter((d) => d.owner === delegateId)\n const decryptedDelegationsFromDelegate = new Set(\n await Promise.all(delegationsFromDelegateToSelf.map((d) => this.tryDecryptDelegation(d, (x) => validateDecrypted(x)))).then((dels) =>\n dels.flatMap((x) => (x ? [x] : []))\n )\n )\n return {\n deduplicatedDelegations,\n missingEntries: requiredEntries.filter((entry) => !(deduplicatedContent.has(entry) || decryptedDelegationsFromDelegate.has(entry))),\n }\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n _.each(argsArray, (arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (existingMetadata.length > 0) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n }\n }\n}\n"]}
1
+ {"version":3,"file":"EntitiesEncryption.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/EntitiesEncryption.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oCAA8H;AAC9H,4BAA2B;AAE3B,gEAAuD;AACvD,qEAAiE;AAGjE;;;GAGG;AACH,MAAa,kBAAkB;IAK7B,YAAY,UAA4B,EAAE,YAA8B,EAAE,mBAAwC;QAChH,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAA;IAChD,CAAC;IAED;;;OAGG;IACG,yBAAyB,CAAC,MAAuB;;;YAIrD,OAAO;gBACL,wBAAwB,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,MAAA,MAAM,CAAC,WAAW,mCAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;gBAC5G,6BAA6B,EAAE,KAAK;aACrC,CAAA;;KACF;IAED;;;;;;;OAOG;IACG,gBAAgB,CACpB,MAA6C,EAC7C,WAAoB,EACpB,aAAmD,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;;;YAE9E,2DAA2D;YAC3D,OAAO,IAAI,CAAC,4CAA4C,CACtD,MAAM,CAAC,IAAI,CAAC,MAAA,MAAM,CAAC,cAA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AEO,4BAA4B,CAAC,MAAuB;QAC1D,MAAM,gBAAgB,GAAG,EAAE,CAAA;QAC3B,IAAI,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;QACtG,IAAI,MAAM,CAAC,kBAAkB,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAA;QAC3H,IAAI,MAAM,CAAC,cAAc,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;QAC/G,IAAI,MAAM,CAAC,iBAAiB,IAAI,MAAM,CAAC,iBAAiB,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;QAC3G,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;gBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;SACF;IACH,CAAC;CACF;AA95BD,gDA85BC","sourcesContent":["import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ExchangeKeysManager } from './ExchangeKeysManager'\nimport { b2a, crypt, decrypt, hex2ua, string2ua, truncateTrailingNulls, ua2hex, ua2string, ua2utf8, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { arrayEquals } from '../utils/collection-utils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is for internal use only and may be changed without notice\n * Give access to functions for retrieving encryption metadata of entities.\n */\nexport class EntitiesEncryption {\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly exchangeKeysManager: ExchangeKeysManager\n\n constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, exchangeKeysManager: ExchangeKeysManager) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.exchangeKeysManager = exchangeKeysManager\n }\n\n /**\n * Get the data owners which can access the entity\n * @param entity an entity.\n */\n async getDataOwnersWithAccessTo(entity: EncryptedEntity): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: 'WRITE' }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entity.delegations ?? {}).map((x) => [x, 'WRITE'])),\n hasUnknownAnonymousDataOwners: false,\n }\n }\n\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n async encryptionKeysOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n // Legacy entities may have encryption keys in delegations.\n return this.extractMergedHierarchyFromDelegationAndOwner(\n Object.keys(entity.encryptionKeys ?? {}).length > 0 ? entity.encryptionKeys! : entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async encryptionKeysForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.encryptionKeys ?? {},\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n async secretIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async secretIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.delegations ?? {},\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n async owningEntityIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.cryptedForeignKeys ?? {},\n dataOwnerId,\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async owningEntityIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.cryptedForeignKeys ?? {},\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * @internal this method is intended only for internal use and may be changed without notice.\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, and encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKeys if false this method will not initialize any encryption keys. Use only for entities which use delegations for\n * access control but don't actually have any encrypted content.\n * @param additionalDelegations automatically shares the\n * @param tags tags to associate with the initial encryption keys and metadata\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKeys: boolean,\n additionalDelegations: string[] = [],\n tags: string[] = []\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const secretId = this.primitives.randomUuid()\n const rawEncryptionKey = initialiseEncryptionKeys ? ua2hex(this.primitives.randomBytes(16)) : undefined\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const allIds = [selfId, ...new Set(additionalDelegations.filter((x) => x !== selfId))]\n const loadKeysResult = await this.loadEncryptionKeysForDelegates(entity, allIds)\n const updatedEntity = await allIds.reduce<Promise<T>>(\n async (prevUpdate, delegateId) =>\n await this.createOrUpdateEntityDelegations(\n await prevUpdate,\n delegateId,\n [],\n [],\n [],\n [secretId],\n initialiseEncryptionKeys ? [rawEncryptionKey!] : [],\n owningEntity ? [owningEntity] : [],\n tags,\n loadKeysResult.keysForDelegates\n ),\n Promise.resolve(loadKeysResult.updatedEntity)\n )\n if (owningEntitySecretId) {\n updatedEntity.secretForeignKeys = [owningEntitySecretId]\n }\n return { updatedEntity, secretId, rawEncryptionKey }\n }\n\n async entityWithAutoExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n autoShareSecretIds: boolean,\n delegatesShareInfo: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKey?: ShareMetadataBehaviour\n shareOwningEntityIds?: ShareMetadataBehaviour\n }\n }\n ): Promise<T> {\n if (!Object.keys(delegatesShareInfo).length) {\n throw new Error('Must specify at least a delegate')\n }\n let defaultSecretIds: string[] | undefined\n if (autoShareSecretIds) {\n const availableSecretIds = await this.secretIdsOf(entity)\n if (availableSecretIds.length) {\n defaultSecretIds = availableSecretIds\n } else {\n defaultSecretIds = [this.primitives.randomUuid()]\n }\n }\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let updatedEntity = entity\n for (const [delegateId, requests] of Object.entries(delegatesShareInfo)) {\n let shareSecretIds: string[] = autoShareSecretIds ? defaultSecretIds! : requests.shareSecretIds ?? []\n let actualShareEncryptionKeys: string[] = []\n if (requests.shareEncryptionKey !== ShareMetadataBehaviour.NEVER) {\n if (!availableEncryptionKeys.length && requests.shareEncryptionKey === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no encryption keys or the current data owner can't access any encryption keys.`)\n }\n actualShareEncryptionKeys = availableEncryptionKeys\n }\n let actualShareOwningEntityIds: string[] = []\n if (requests.shareOwningEntityIds !== ShareMetadataBehaviour.NEVER) {\n if (!availableOwningEntityIds.length && requests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids.`)\n }\n actualShareOwningEntityIds = availableOwningEntityIds\n }\n updatedEntity = await this.entityWithExtendedEncryptedMetadata(\n updatedEntity,\n delegateId,\n shareSecretIds,\n actualShareEncryptionKeys,\n actualShareOwningEntityIds\n )\n }\n return updatedEntity\n }\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param delegateId id of the delegate to share data with.\n * @param shareSecretIds secret ids to share.\n * @param shareEncryptionKeys encryption keys to share.\n * @param shareOwningEntityIds owning enttiy ids to share.\n * @param newTags tags to associate with the new encryption keys and metadata. Existing data won't be changed.\n * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.\n * @return an updated copy of the entity.\n */\n async entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newTags: string[] = []\n ): Promise<T> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithSharedEncryptedMetadata', arguments)\n async function checkInputAndGet(input: string[], inputName: string, validate: (x: string) => boolean | Promise<boolean>): Promise<string[]> {\n for (const x of input) {\n const validation = validate(x)\n if (validation !== true && validation !== false && !(await validation)) throw new Error(`Invalid input for ${inputName}.`)\n }\n return input\n }\n const secretIdsToShare = await checkInputAndGet(shareSecretIds, 'secretIds', (x) => this.validateSecretId(x))\n const encryptionKeysToShare = await checkInputAndGet(shareEncryptionKeys, 'encryptionKeys', (x) => this.validateEncryptionKey(x))\n const owningEntityIdsToShare = await checkInputAndGet(shareOwningEntityIds, 'owningEntityIds', (x) => this.validateOwningEntityId(x))\n const deduplicateInfoSecretIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.delegations ?? {},\n secretIdsToShare,\n (x) => this.validateSecretId(x)\n )\n const deduplicateInfoEncryptionKeys = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.encryptionKeys ?? {},\n encryptionKeysToShare,\n (x) => this.validateEncryptionKey(x)\n )\n const deduplicateInfoOwningEntityIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.cryptedForeignKeys ?? {},\n owningEntityIdsToShare,\n (x) => this.validateOwningEntityId(x)\n )\n /*TODO\n * Temporary hack since secret id is necessary to create a delegation for access control: if there is no delegation existing from me to the\n * delegate and there is no new secret id to be created create a new random id.\n */\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (deduplicateInfoSecretIds.missingEntries.length === 0 && !deduplicateInfoSecretIds.deduplicatedDelegations.some((d) => d.owner === selfId)) {\n deduplicateInfoSecretIds.missingEntries.push(this.primitives.randomUuid())\n }\n if (\n deduplicateInfoSecretIds.missingEntries.length === 0 &&\n deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&\n deduplicateInfoOwningEntityIds.missingEntries.length === 0\n )\n return _.cloneDeep(entity)\n const { updatedEntity, keysForDelegates } = await this.loadEncryptionKeysForDelegates(entity, [delegateId])\n return this.createOrUpdateEntityDelegations(\n updatedEntity,\n delegateId,\n deduplicateInfoSecretIds.deduplicatedDelegations,\n deduplicateInfoEncryptionKeys.deduplicatedDelegations,\n deduplicateInfoOwningEntityIds.deduplicatedDelegations,\n deduplicateInfoSecretIds.missingEntries,\n deduplicateInfoEncryptionKeys.missingEntries,\n deduplicateInfoOwningEntityIds.missingEntries,\n newTags,\n keysForDelegates\n )\n }\n\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to encrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to use for encryption only keys associated to tags which pass the filter.\n * @return the encrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n async encryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf(await this.ensureEncryptionKeysInitialised(entity), dataOwnerId, tagsFilter)\n if (keys.length === 0)\n throw new Error(\n `Could not extract any encryption keys of entity ${entity} for data owner ${\n dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n }.`\n )\n return this.primitives.AES.encryptWithRawKey(keys[0], content)\n }\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @param tagsFilter allows to use for decryption only keys associated to tags which pass the filter.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n async tryDecryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> = () => Promise.resolve(true),\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const keys = await this.encryptionKeysOf(entity, dataOwnerId, tagsFilter)\n for (const key of keys) {\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(key, content)\n if (await validator(decrypted)) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n /* ignore */\n }\n }\n return { data: content, wasDecrypted: false }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Decrypts the content of an encrypted entity.\n */\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n ownerId: string | undefined,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n if (!entity.encryptedSelf) return { entity, decrypted: true }\n const encryptionKeys = await this.importAllValidKeys(await this.encryptionKeysOf(entity, ownerId))\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decrypt(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries using the provided keys to decrypt some json.\n */\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n const text = ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted)\n return JSON.parse(text)\n } catch (e) {}\n }\n return undefined\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field\n * which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n dataOwnerId: string | undefined,\n cryptedKeys: string[],\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity)\n const encryptionKey = await this.tryImportFirstValidKey(await this.encryptionKeysOf(entity, dataOwnerId), entity.id!)\n if (!!encryptionKey) {\n return constructor(\n await crypt(\n entityWithInitialisedEncryptionKeys,\n (obj) => {\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || v instanceof Uint8Array\n ? b2a(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n cryptedKeys\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n const cryptedCopyWithRandomKey = await crypt(\n _.cloneDeep(entity),\n async (obj: { [key: string]: string }) => Promise.resolve(new ArrayBuffer(1)),\n cryptedKeys\n )\n if (\n !_.isEqual(\n _.omitBy({ ...cryptedCopyWithRandomKey, encryptedSelf: undefined }, _.isNil),\n _.omitBy({ ...entity, encryptedSelf: undefined }, _.isNil)\n )\n ) {\n throw new Error(`Impossible to modify encrypted value of an entity if no encryption key is known.\\n${entity}`)\n }\n return entity\n }\n }\n\n /**\n * @internal This method is for internal use only and may be changed without notice.\n * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of\n * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities\n * which were previously not encrypted.\n */\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T> {\n if (Object.keys(entity.encryptionKeys ?? {}).length > 0) return entity\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * If entity was using delegations as legacy encryption keys we will essentially revoke the access to the encrypted data for all other data\n * owners. This however should not be a problem as this form of legacy entities should not exist anymore, and it should be present only in the\n * databases of hcps without collaborators.\n */\n return await this.entityWithExtendedEncryptedMetadata(\n entity,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n [],\n [ua2hex(this.primitives.randomBytes(16))],\n []\n )\n }\n\n /**\n * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does\n * not consider exchange keys for parents).\n * Note that the retrieved exchange keys are decrypted using the private keys available on the device, and results may vary from other devices.\n * @param dataOwnerId id of a data owner, he should be part of the current data owner hierarchy.\n * @param delegations a delegation-like object containing the encrypted key\n * @param includeFromDelegations if true also considers delegation from the provided data owner (or parents) to look for values. This allows to\n * decrypt delegations associated to exchange keys recovered after a giveAccessBack request.\n * @param validateDecrypted validates the decrypted result, to drop decryption results with wrong key that still gave a valid checksum.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the key which could be decrypted using only keys available on the current device and delegations from/to the provided data owner. May\n * contain duplicates.\n */\n private async extractFromDelegationsForDataOwner(\n dataOwnerId: string,\n delegations: { [delegateId: string]: Delegation[] },\n includeFromDelegations: boolean,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const delegationsWithOwner = includeFromDelegations\n ? Object.entries(delegations).flatMap(([delegateId, delegations]) =>\n dataOwnerId === delegateId\n ? this.populateDelegatedTo(delegateId, delegations)\n : this.populateDelegatedTo(\n delegateId,\n delegations.filter((d) => d.owner === dataOwnerId)\n )\n )\n : delegations[dataOwnerId] ?? []\n const res = []\n for (const delegation of delegationsWithOwner) {\n if (await tagsFilter(delegation.tags ?? [])) {\n const decrypted = await this.tryDecryptDelegation(delegation, (k) => validateDecrypted(k))\n if (decrypted) res.push(decrypted)\n }\n }\n return res\n }\n\n // Ensures that the delegatedTo field of delegations has the appropriate values, else returns a copy of the delegations with the appropriate value.\n private populateDelegatedTo(delegateId: string, delegations: Delegation[]): Delegation[] {\n return delegations.map((d) => (d.delegatedTo === delegateId ? d : { ...d, delegatedTo: delegateId }))\n }\n\n private async extractedHierarchyFromDelegation(\n delegations: { [delegateId: string]: Delegation[] },\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return Promise.all(\n (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).map(async (ownerId) => {\n const extracted = this.deduplicate(\n await this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n return { ownerId, extracted }\n })\n )\n }\n\n /**\n * @internal This method should be private but is currently public/internal to allow to continue supporting legacy methods\n */\n async extractMergedHierarchyFromDelegationAndOwner(\n delegations: { [delegateId: string]: Delegation[] },\n dataOwnerId: string | undefined,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const hierarchy = dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const extractedByOwner = await Promise.all(\n // Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.\n [...hierarchy].reverse().map((ownerId) =>\n this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n )\n return this.deduplicate(extractedByOwner.flatMap((x) => x))\n }\n\n private async tryDecryptDelegation(\n delegation: Delegation,\n validateDecrypted: (result: string) => boolean | Promise<boolean>\n ): Promise<string | undefined> {\n const exchangeKeys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegation.owner!, delegation.delegatedTo!)\n for (const key of exchangeKeys) {\n try {\n // Format of encrypted key for any delegation should be entityId:key, but with the merging of entities the entityId might not match the\n // current id. As a checksum we are only verifying that the decrypted bytes can be represented as a string with exactly one ':'.\n // Additionally, we also have a validator that is specific for each type of delegation content (encryption key, secret id, ...)\n const decrypted = ua2string(await this.primitives.AES.decrypt(key, hex2ua(delegation.key!)))\n const decryptedSplit = decrypted.split(':')\n if (decryptedSplit.length === 2) {\n const validation = validateDecrypted(decryptedSplit[1])\n if (validation === true || (validation !== false && (await validation))) return decryptedSplit[1]\n } else {\n console.warn(\"Error in the decrypted delegation: content should contain exactly 1 ':', the delegation is ignored.\")\n }\n } catch (e) {\n // Do nothing: the delegation uses another exchange key owner->delegator\n }\n }\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(keys, entityId)\n if (!res) throw new Error(`Could not find any valid key for entity ${entityId}.`)\n return res\n }\n\n private async tryImportFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string } | undefined> {\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) return { key: imported, raw: key }\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importAllValidKeys(keys: string[]): Promise<{ key: CryptoKey; raw: string }[]> {\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n private async validateEncryptionKey(key: string): Promise<boolean> {\n return !!(await this.tryImportKey(key))\n }\n\n private validateSecretId(key: string): boolean {\n return !!key\n }\n\n private validateOwningEntityId(key: string): boolean {\n return !!key\n }\n\n private async createEncryptionKeyDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n encryptionKey: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!(await this.validateEncryptionKey(encryptionKey))) throw new Error(`Invalid encryption key ${encryptionKey}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, encryptionKey, newTags)\n }\n\n private async createSecretIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n secretId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateSecretId(secretId)) throw new Error(`Invalid secret id ${secretId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, secretId, newTags)\n }\n\n private async createOwningEntityIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n owningEntityId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateOwningEntityId(owningEntityId)) throw new Error(`Invalid owning id ${owningEntityId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, owningEntityId, newTags)\n }\n\n private async createDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n content: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (entityId.includes(':')) throw new Error(\"Ids for encrypted entities are not allowed to contain ':'\")\n if (content.includes(':')) throw new Error(\"Content of delegations can not contain ':'\")\n return {\n delegatedTo: delegateId,\n owner: await this.dataOwnerApi.getCurrentDataOwnerId(),\n key: ua2hex(await this.primitives.AES.encrypt(exchangeKey, string2ua(entityId + ':' + content))),\n tags: newTags,\n }\n }\n\n private async loadEncryptionKeysForDelegates<T extends EncryptedEntity>(\n entity: T,\n delegates: string[]\n ): Promise<{ updatedEntity: T; keysForDelegates: { [delegateId: string]: CryptoKey[] } }> {\n const { updatedDelegator, keysForDelegates } = await delegates.reduce(\n async (acc, delegateId) => {\n const awaitedAcc = await acc\n const currUpdateResult = await this.exchangeKeysManager.getOrCreateEncryptionExchangeKeysTo(delegateId)\n return {\n updatedDelegator: currUpdateResult.updatedDelegator ?? awaitedAcc.updatedDelegator,\n keysForDelegates: {\n ...awaitedAcc.keysForDelegates,\n [delegateId]: currUpdateResult.keys,\n },\n }\n },\n Promise.resolve({\n updatedDelegator: undefined as CryptoActorStubWithType | undefined,\n keysForDelegates: {} as { [delegateId: string]: CryptoKey[] },\n })\n )\n const updatedEntity =\n entity.id === updatedDelegator?.stub?.id\n ? {\n ...entity,\n rev: updatedDelegator!.stub.rev,\n hcPartyKeys: updatedDelegator!.stub.hcPartyKeys,\n aesExchangeKeys: updatedDelegator!.stub.aesExchangeKeys,\n }\n : entity\n return { updatedEntity, keysForDelegates }\n }\n\n private async createOrUpdateEntityDelegations<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n existingSecretIds: Delegation[],\n existingEncryptionKeys: Delegation[],\n existingOwningEntityIds: Delegation[],\n newSecretIds: string[],\n newEncryptionKeys: string[],\n newOwningEntityIds: string[],\n newTags: string[],\n keysForDelegates: { [delegateId: string]: CryptoKey[] }\n ): Promise<T> {\n const entityCopy = _.cloneDeep(entity)\n if (newSecretIds.length === 0 && newEncryptionKeys.length === 0 && newOwningEntityIds.length === 0) return entityCopy\n const chosenKey = keysForDelegates[delegateId][0]\n const updatedSecretIds = [\n ...existingSecretIds,\n ...(await Promise.all(newSecretIds.map((x) => this.createSecretIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedEncryptionKeys = [\n ...existingEncryptionKeys,\n ...(await Promise.all(newEncryptionKeys.map((x) => this.createEncryptionKeyDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedOwningEntityIds = [\n ...existingOwningEntityIds,\n ...(await Promise.all(newOwningEntityIds.map((x) => this.createOwningEntityIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n if (updatedSecretIds.length > 0) {\n entityCopy.delegations = {\n ...(entity.delegations ?? {}),\n [delegateId]: updatedSecretIds,\n }\n }\n if (updatedEncryptionKeys.length > 0) {\n entityCopy.encryptionKeys = {\n ...(entity.encryptionKeys ?? {}),\n [delegateId]: updatedEncryptionKeys,\n }\n }\n if (updatedOwningEntityIds.length > 0) {\n entityCopy.cryptedForeignKeys = {\n ...(entity.cryptedForeignKeys ?? {}),\n [delegateId]: updatedOwningEntityIds,\n }\n }\n return entityCopy\n }\n\n /**\n * De-duplicates all currently accessible delegations, by removing any delegations created by the current data owner which have duplicated content,\n * and checks if any of the required entries are currently available to the delegate through the existing delegations.\n * @param delegateId id of the delegate.\n * @param allDelegations delegations of the entity.\n * @param requiredEntries potentially new entries that the delegate needs to be able to access from the delegations.\n * @param validateDecrypted validator for decrypted delegation content\n * @return the deduplicated delegations\n */\n private async deduplicateDelegationsAndFilterRequiredEntries(\n delegateId: string,\n allDelegations: { [delegateId: string]: Delegation[] },\n requiredEntries: string[],\n validateDecrypted: (x: string) => boolean | Promise<boolean>\n ): Promise<{\n deduplicatedDelegations: Delegation[]\n missingEntries: string[]\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const delegationsToDelegate = allDelegations[delegateId] ?? []\n const decryptedDelegations = await Promise.all(\n delegationsToDelegate.map(async (d) => ({\n delegation: d,\n content: d.owner === selfId ? await this.tryDecryptDelegation(d, (x) => validateDecrypted(x)) : undefined,\n }))\n )\n const deduplicatedDelegations: Delegation[] = []\n const deduplicatedContent = new Map<string, string[][]>()\n decryptedDelegations.forEach(({ delegation, content }) => {\n if (content === undefined) {\n // Keep all delegations we could not decrypt or from other data owners\n deduplicatedDelegations.push(delegation)\n } else {\n const deduplicatedTags = deduplicatedContent.get(content)\n if (!deduplicatedTags) {\n deduplicatedContent.set(content, [delegation.tags ?? []])\n deduplicatedDelegations.push(delegation)\n } else if (!deduplicatedTags.some((t) => arrayEquals(t, delegation.tags ?? []))) {\n deduplicatedTags.push(delegation.tags ?? [])\n deduplicatedDelegations.push(delegation)\n }\n }\n })\n const delegationsFromDelegateToSelf = (allDelegations[selfId] ?? []).filter((d) => d.owner === delegateId)\n const decryptedDelegationsFromDelegate = new Set(\n await Promise.all(delegationsFromDelegateToSelf.map((d) => this.tryDecryptDelegation(d, (x) => validateDecrypted(x)))).then((dels) =>\n dels.flatMap((x) => (x ? [x] : []))\n )\n )\n return {\n deduplicatedDelegations,\n missingEntries: requiredEntries.filter((entry) => !(deduplicatedContent.has(entry) || decryptedDelegationsFromDelegate.has(entry))),\n }\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n _.each(argsArray, (arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (existingMetadata.length > 0) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n }\n }\n}\n"]}
@@ -1,9 +1,10 @@
1
1
  import { KeyManager } from './KeyManager';
2
2
  import { BaseExchangeKeysManager } from './BaseExchangeKeysManager';
3
- import { DataOwnerWithType, IccDataOwnerXApi } from '../icc-data-owner-x-api';
3
+ import { IccDataOwnerXApi } from '../icc-data-owner-x-api';
4
4
  import { CryptoPrimitives } from './CryptoPrimitives';
5
5
  import { CryptoStrategies } from './CryptoStrategies';
6
6
  import { IcureStorageFacade } from '../storage/IcureStorageFacade';
7
+ import { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub';
7
8
  /**
8
9
  * @internal This class is meant only for internal use and may be changed without notice.
9
10
  * More powerful version of {@link BaseExchangeKeysManager} with a simplified interface. Has the following functionalities:
@@ -32,7 +33,7 @@ export declare class ExchangeKeysManager {
32
33
  * - updatedDelegator (optional): if a new key creation job was started when the function was invoked the updated delegator, else undefined.
33
34
  */
34
35
  getOrCreateEncryptionExchangeKeysTo(delegateId: string): Promise<{
35
- updatedDelegator?: DataOwnerWithType;
36
+ updatedDelegator?: CryptoActorStubWithType;
36
37
  keys: CryptoKey[];
37
38
  }>;
38
39
  /**
@@ -126,11 +126,11 @@ class ExchangeKeysManager {
126
126
  const [mainKey, ...otherSelfKeys] = this.keyManager.getSelfVerifiedKeys();
127
127
  let otherPublicKeys = Object.fromEntries(otherSelfKeys.map((x) => [x.fingerprint, x.pair.publicKey]));
128
128
  if (delegateId !== (yield this.dataOwnerApi.getCurrentDataOwnerId())) {
129
- const delegate = (yield this.dataOwnerApi.getDataOwner(delegateId)).dataOwner;
130
- const delegatePublicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(delegate));
129
+ const delegate = yield this.dataOwnerApi.getCryptoActorStub(delegateId);
130
+ const delegatePublicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(delegate.stub));
131
131
  let verifiedDelegatePublicKeys;
132
132
  if ((yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).includes(delegateId)) {
133
- verifiedDelegatePublicKeys = yield this.keyManager.getVerifiedPublicKeysFor(delegate);
133
+ verifiedDelegatePublicKeys = yield this.keyManager.getVerifiedPublicKeysFor(delegate.stub);
134
134
  }
135
135
  else {
136
136
  verifiedDelegatePublicKeys = yield this.cryptoStrategies.verifyDelegatePublicKeys(delegate, delegatePublicKeys, this.primitives);
@@ -1 +1 @@
1
- {"version":3,"file":"ExchangeKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExchangeKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oFAA6E;AAC7E,mCAAwC;AAKxC;;;;;;;GAOG;AACH,MAAa,mBAAmB;IAoB9B,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,uBAAuB,CAAA;IACrC,CAAC;IAED,YACE,sBAA8B,EAC9B,sBAA8B,EAC9B,gCAAwC,EACxC,kCAA0C,EAC1C,gBAAkC,EAClC,UAA4B,EAC5B,UAAsB,EACtB,uBAAgD,EAChD,YAA8B,EAC9B,YAAgC;QAEhC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;QACxC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAA;QACtD,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,0BAA0B,GAAG,IAAI,oDAAuB,CAAC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,KAAK,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC,EAAE;gBACpE,MAAM,QAAQ,GAAG,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAA;gBAC7E,MAAM,kBAAkB,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC,CAAA;gBACrF,IAAI,0BAAoC,CAAA;gBACxC,IAAI,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,+BAA+B,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;oBACpF,0BAA0B,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,wBAAwB,CAAC,QAAQ,CAAC,CAAA;iBACtF;qBAAM;oBACL,0BAA0B,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,wBAAwB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;iBACjI;gBACD,IAAI,CAAC,0BAA0B,IAAI,0BAA0B,CAAC,MAAM,IAAI,CAAC;oBACvE,MAAM,IAAI,KAAK,CAAC,wCAAwC,UAAU,0CAA0C,CAAC,CAAA;gBAC/G,eAAe,mCACV,eAAe,GACf,CAAC,MAAM,IAAA,sBAAc,EAAC,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,0BAA0B,CAAC,CAAC,CAC3E,CAAA;aACF;YACD,OAAO,MAAM,IAAI,CAAC,uBAAuB,CAAC,oCAAoC,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;QAC3H,CAAC;KAAA;CACF;AAzJD,kDAyJC","sourcesContent":["import { KeyManager } from './KeyManager'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { DataOwnerWithType, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { loadPublicKeys } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * More powerful version of {@link BaseExchangeKeysManager} with a simplified interface. Has the following functionalities:\n * - Caches results\n * - Automatically creates new exchange keys if none is available\n * - Automatically choose the public keys to use during the creation of new exchange keys\n * - Automatically retrieves the private keys to use during decryption.\n */\nexport class ExchangeKeysManager {\n private readonly keyManager: KeyManager\n private readonly baseExchangeKeysManager: BaseExchangeKeysManager\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly cryptoStrategies: CryptoStrategies\n private readonly primitives: CryptoPrimitives\n private readonly icureStorage: IcureStorageFacade\n /*\n * Exchange keys cache where the current user is the delegator. The keys where the delegator is the current user should never change without\n * an action from the delegator (unless he does this action from another device), so it should be safe to store them without expiration. However,\n * the delegator may still have a lot of exchange keys (e.g. doctor -> all patients), so it is not safe to have a cache with unlimited size.\n */\n private delegatorExchangeKeysCache: LruTemporisedAsyncCache<string, CryptoKey[]>\n /*\n * Exchange keys cache where the current user is not the delegator. There may be many keys where the current user is the delegate,\n * and they may change over time without any action from the current data owner, since the delegator is someone else. For this reason the cache must\n * be limited in size and it should not use data that is too old, as it may be outdated.\n */\n private delegatedExchangeKeysCache: LruTemporisedAsyncCache<string, CryptoKey[]>\n\n get base(): BaseExchangeKeysManager {\n return this.baseExchangeKeysManager\n }\n\n constructor(\n delegatorKeysCacheSize: number,\n delegatedKeysCacheSize: number,\n delegatedKeysCacheLifetimeMsBase: number,\n delegatedKeysCacheLifetimeMsNoKeys: number,\n cryptoStrategies: CryptoStrategies,\n primitives: CryptoPrimitives,\n keyManager: KeyManager,\n baseExchangeKeysManager: BaseExchangeKeysManager,\n dataOwnerApi: IccDataOwnerXApi,\n icureStorage: IcureStorageFacade\n ) {\n this.primitives = primitives\n this.cryptoStrategies = cryptoStrategies\n this.keyManager = keyManager\n this.baseExchangeKeysManager = baseExchangeKeysManager\n this.dataOwnerApi = dataOwnerApi\n this.delegatedExchangeKeysCache = new LruTemporisedAsyncCache(delegatedKeysCacheSize, (keys) =>\n keys.length > 0 ? delegatedKeysCacheLifetimeMsBase : delegatedKeysCacheLifetimeMsNoKeys\n )\n this.delegatorExchangeKeysCache = new LruTemporisedAsyncCache(delegatorKeysCacheSize, () => -1)\n this.icureStorage = icureStorage\n }\n\n /**\n * Get exchange keys from the current data owner to the provided delegate which are safe for encryption according to the locally verified keys.\n * If currently there is no exchange key towards the provided delegate which is safe for encryption a new one will be automatically created.\n * @param delegateId a delegate\n * @return an object with the following fields:\n * - keys: all available exchange keys which are safe for encryption.\n * - updatedDelegator (optional): if a new key creation job was started when the function was invoked the updated delegator, else undefined.\n */\n async getOrCreateEncryptionExchangeKeysTo(delegateId: string): Promise<{ updatedDelegator?: DataOwnerWithType; keys: CryptoKey[] }> {\n const currentKeys = await this.getSelfExchangeKeysTo(delegateId)\n if (currentKeys.length > 0) {\n return { keys: currentKeys }\n } else {\n while (true) {\n let updatedDelegatorJob: Promise<DataOwnerWithType> | undefined = undefined\n const keysWithNew = await this.delegatorExchangeKeysCache.get(\n delegateId,\n async (previous) => {\n const fullJob = this.forceCreateVerifiedExchangeKeyTo(delegateId)\n updatedDelegatorJob = fullJob.then(({ updatedDelegator }) => updatedDelegator)\n let existingKeys = previous ? previous : await this.forceGetSelfExchangeKeysTo(delegateId)\n return fullJob.then(({ key }) => [...existingKeys, key])\n },\n (v) => !v.length\n )\n if (keysWithNew.length > 0) {\n const updatedDelegator = updatedDelegatorJob ? await updatedDelegatorJob : undefined\n return updatedDelegator ? { keys: keysWithNew, updatedDelegator } : { keys: keysWithNew }\n }\n }\n /*NOTE:\n * in case of two concurrent calls to `getOrCreateEncryptionExchangeKeysTo` only one of the calls will receive the updated delegator. This could\n * be a problem if one of the callers would want to update the delegator for other reasons as well, as the request would result in a database\n * conflict. This situation however should be very rare and will be fully resolved in the near future when delegations will be moved out of the\n * data owner objects and into a specific database.\n */\n }\n }\n\n /**\n * Get all keys currently available for a delegator-delegate pair. At least one of the two data owners must be part of the hierarchy for the current\n * data owner.\n * @param delegatorId id of a delegator\n * @param delegateId id of a delegate\n * @throws if neither the delegator nor the delegate is part of the hierarchy of the current data owner.\n * @return all available exchange keys from the delegator-delegate pair.\n */\n async getDecryptionExchangeKeysFor(delegatorId: string, delegateId: string): Promise<CryptoKey[]> {\n if (delegatorId === (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n return await this.getSelfExchangeKeysTo(delegateId)\n } else {\n const key = `${delegatorId}->${delegateId}`\n const hierarchyIds = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n if (!hierarchyIds.some((x) => x === delegateId || x === delegatorId))\n throw new Error(`Trying to retrieve exchange key ${key} but current data owner hierarchy is ${hierarchyIds}`)\n return await this.delegatedExchangeKeysCache.get(key, () => this.forceGetExchangeKeysFor(delegatorId, delegateId))\n }\n }\n\n /**\n * Empties the exchange keys cache.\n * @param includeKeysFromCurrentDataOwner if true also clears the\n */\n clearCache(includeKeysFromCurrentDataOwner: boolean) {\n if (includeKeysFromCurrentDataOwner) this.delegatorExchangeKeysCache.clear()\n this.delegatedExchangeKeysCache.clear()\n }\n\n private async forceGetExchangeKeysFor(delegatorId: string, delegateId: string): Promise<CryptoKey[]> {\n const encKeys = await this.baseExchangeKeysManager.getEncryptedExchangeKeysFor(delegatorId, delegateId)\n return (await this.baseExchangeKeysManager.tryDecryptExchangeKeys(encKeys, this.keyManager.getDecryptionKeys())).successfulDecryptions\n }\n\n private async getSelfExchangeKeysTo(delegateId: string): Promise<CryptoKey[]> {\n return await this.delegatorExchangeKeysCache.get(delegateId, () => this.forceGetSelfExchangeKeysTo(delegateId))\n }\n\n private async forceGetSelfExchangeKeysTo(delegateId: string): Promise<CryptoKey[]> {\n // Retrieve then try to decrypt with own and parent key pairs\n const encKeys = await this.baseExchangeKeysManager.getEncryptedExchangeKeysFor(await this.dataOwnerApi.getCurrentDataOwnerId(), delegateId)\n const { successfulDecryptions } = await this.baseExchangeKeysManager.tryDecryptExchangeKeys(encKeys, this.keyManager.getDecryptionKeys())\n return successfulDecryptions\n }\n\n private async forceCreateVerifiedExchangeKeyTo(delegateId: string): Promise<{ updatedDelegator: DataOwnerWithType; key: CryptoKey }> {\n const [mainKey, ...otherSelfKeys] = this.keyManager.getSelfVerifiedKeys()\n let otherPublicKeys = Object.fromEntries(otherSelfKeys.map((x) => [x.fingerprint, x.pair.publicKey]))\n if (delegateId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n const delegate = (await this.dataOwnerApi.getDataOwner(delegateId)).dataOwner\n const delegatePublicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(delegate))\n let verifiedDelegatePublicKeys: string[]\n if ((await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).includes(delegateId)) {\n verifiedDelegatePublicKeys = await this.keyManager.getVerifiedPublicKeysFor(delegate)\n } else {\n verifiedDelegatePublicKeys = await this.cryptoStrategies.verifyDelegatePublicKeys(delegate, delegatePublicKeys, this.primitives)\n }\n if (!verifiedDelegatePublicKeys || verifiedDelegatePublicKeys.length == 0)\n throw new Error(`No verified public keys for delegate ${delegateId}: impossible to create new exchange key.`)\n otherPublicKeys = {\n ...otherPublicKeys,\n ...(await loadPublicKeys(this.primitives.RSA, verifiedDelegatePublicKeys)),\n }\n }\n return await this.baseExchangeKeysManager.createOrUpdateEncryptedExchangeKeyTo(delegateId, mainKey.pair, otherPublicKeys)\n }\n}\n"]}
1
+ {"version":3,"file":"ExchangeKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExchangeKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oFAA6E;AAC7E,mCAAwC;AAMxC;;;;;;;GAOG;AACH,MAAa,mBAAmB;IAoB9B,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,uBAAuB,CAAA;IACrC,CAAC;IA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e,mCACV,eAAe,GACf,CAAC,MAAM,IAAA,sBAAc,EAAC,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,0BAA0B,CAAC,CAAC,CAC3E,CAAA;aACF;YACD,OAAO,MAAM,IAAI,CAAC,uBAAuB,CAAC,oCAAoC,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;QAC3H,CAAC;KAAA;CACF;AAzJD,kDAyJC","sourcesContent":["import { KeyManager } from './KeyManager'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { loadPublicKeys } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * More powerful version of {@link BaseExchangeKeysManager} with a simplified interface. Has the following functionalities:\n * - Caches results\n * - Automatically creates new exchange keys if none is available\n * - Automatically choose the public keys to use during the creation of new exchange keys\n * - Automatically retrieves the private keys to use during decryption.\n */\nexport class ExchangeKeysManager {\n private readonly keyManager: KeyManager\n private readonly baseExchangeKeysManager: BaseExchangeKeysManager\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly cryptoStrategies: CryptoStrategies\n private readonly primitives: CryptoPrimitives\n private readonly icureStorage: IcureStorageFacade\n /*\n * Exchange keys cache where the current user is the delegator. The keys where the delegator is the current user should never change without\n * an action from the delegator (unless he does this action from another device), so it should be safe to store them without expiration. However,\n * the delegator may still have a lot of exchange keys (e.g. doctor -> all patients), so it is not safe to have a cache with unlimited size.\n */\n private delegatorExchangeKeysCache: LruTemporisedAsyncCache<string, CryptoKey[]>\n /*\n * Exchange keys cache where the current user is not the delegator. There may be many keys where the current user is the delegate,\n * and they may change over time without any action from the current data owner, since the delegator is someone else. For this reason the cache must\n * be limited in size and it should not use data that is too old, as it may be outdated.\n */\n private delegatedExchangeKeysCache: LruTemporisedAsyncCache<string, CryptoKey[]>\n\n get base(): BaseExchangeKeysManager {\n return this.baseExchangeKeysManager\n }\n\n constructor(\n delegatorKeysCacheSize: number,\n delegatedKeysCacheSize: number,\n delegatedKeysCacheLifetimeMsBase: number,\n delegatedKeysCacheLifetimeMsNoKeys: number,\n cryptoStrategies: CryptoStrategies,\n primitives: CryptoPrimitives,\n keyManager: KeyManager,\n baseExchangeKeysManager: BaseExchangeKeysManager,\n dataOwnerApi: IccDataOwnerXApi,\n icureStorage: IcureStorageFacade\n ) {\n this.primitives = primitives\n this.cryptoStrategies = cryptoStrategies\n this.keyManager = keyManager\n this.baseExchangeKeysManager = baseExchangeKeysManager\n this.dataOwnerApi = dataOwnerApi\n this.delegatedExchangeKeysCache = new LruTemporisedAsyncCache(delegatedKeysCacheSize, (keys) =>\n keys.length > 0 ? delegatedKeysCacheLifetimeMsBase : delegatedKeysCacheLifetimeMsNoKeys\n )\n this.delegatorExchangeKeysCache = new LruTemporisedAsyncCache(delegatorKeysCacheSize, () => -1)\n this.icureStorage = icureStorage\n }\n\n /**\n * Get exchange keys from the current data owner to the provided delegate which are safe for encryption according to the locally verified keys.\n * If currently there is no exchange key towards the provided delegate which is safe for encryption a new one will be automatically created.\n * @param delegateId a delegate\n * @return an object with the following fields:\n * - keys: all available exchange keys which are safe for encryption.\n * - updatedDelegator (optional): if a new key creation job was started when the function was invoked the updated delegator, else undefined.\n */\n async getOrCreateEncryptionExchangeKeysTo(delegateId: string): Promise<{ updatedDelegator?: CryptoActorStubWithType; keys: CryptoKey[] }> {\n const currentKeys = await this.getSelfExchangeKeysTo(delegateId)\n if (currentKeys.length > 0) {\n return { keys: currentKeys }\n } else {\n while (true) {\n let updatedDelegatorJob: Promise<CryptoActorStubWithType> | undefined = undefined\n const keysWithNew = await this.delegatorExchangeKeysCache.get(\n delegateId,\n async (previous) => {\n const fullJob = this.forceCreateVerifiedExchangeKeyTo(delegateId)\n updatedDelegatorJob = fullJob.then(({ updatedDelegator }) => updatedDelegator)\n let existingKeys = previous ? previous : await this.forceGetSelfExchangeKeysTo(delegateId)\n return fullJob.then(({ key }) => [...existingKeys, key])\n },\n (v) => !v.length\n )\n if (keysWithNew.length > 0) {\n const updatedDelegator = updatedDelegatorJob ? await updatedDelegatorJob : undefined\n return updatedDelegator ? { keys: keysWithNew, updatedDelegator } : { keys: keysWithNew }\n }\n }\n /*NOTE:\n * in case of two concurrent calls to `getOrCreateEncryptionExchangeKeysTo` only one of the calls will receive the updated delegator. This could\n * be a problem if one of the callers would want to update the delegator for other reasons as well, as the request would result in a database\n * conflict. This situation however should be very rare and will be fully resolved in the near future when delegations will be moved out of the\n * data owner objects and into a specific database.\n */\n }\n }\n\n /**\n * Get all keys currently available for a delegator-delegate pair. At least one of the two data owners must be part of the hierarchy for the current\n * data owner.\n * @param delegatorId id of a delegator\n * @param delegateId id of a delegate\n * @throws if neither the delegator nor the delegate is part of the hierarchy of the current data owner.\n * @return all available exchange keys from the delegator-delegate pair.\n */\n async getDecryptionExchangeKeysFor(delegatorId: string, delegateId: string): Promise<CryptoKey[]> {\n if (delegatorId === (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n return await this.getSelfExchangeKeysTo(delegateId)\n } else {\n const key = `${delegatorId}->${delegateId}`\n const hierarchyIds = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n if (!hierarchyIds.some((x) => x === delegateId || x === delegatorId))\n throw new Error(`Trying to retrieve exchange key ${key} but current data owner hierarchy is ${hierarchyIds}`)\n return await this.delegatedExchangeKeysCache.get(key, () => this.forceGetExchangeKeysFor(delegatorId, delegateId))\n }\n }\n\n /**\n * Empties the exchange keys cache.\n * @param includeKeysFromCurrentDataOwner if true also clears the\n */\n clearCache(includeKeysFromCurrentDataOwner: boolean) {\n if (includeKeysFromCurrentDataOwner) this.delegatorExchangeKeysCache.clear()\n this.delegatedExchangeKeysCache.clear()\n }\n\n private async forceGetExchangeKeysFor(delegatorId: string, delegateId: string): Promise<CryptoKey[]> {\n const encKeys = await this.baseExchangeKeysManager.getEncryptedExchangeKeysFor(delegatorId, delegateId)\n return (await this.baseExchangeKeysManager.tryDecryptExchangeKeys(encKeys, this.keyManager.getDecryptionKeys())).successfulDecryptions\n }\n\n private async getSelfExchangeKeysTo(delegateId: string): Promise<CryptoKey[]> {\n return await this.delegatorExchangeKeysCache.get(delegateId, () => this.forceGetSelfExchangeKeysTo(delegateId))\n }\n\n private async forceGetSelfExchangeKeysTo(delegateId: string): Promise<CryptoKey[]> {\n // Retrieve then try to decrypt with own and parent key pairs\n const encKeys = await this.baseExchangeKeysManager.getEncryptedExchangeKeysFor(await this.dataOwnerApi.getCurrentDataOwnerId(), delegateId)\n const { successfulDecryptions } = await this.baseExchangeKeysManager.tryDecryptExchangeKeys(encKeys, this.keyManager.getDecryptionKeys())\n return successfulDecryptions\n }\n\n private async forceCreateVerifiedExchangeKeyTo(delegateId: string): Promise<{ updatedDelegator: CryptoActorStubWithType; key: CryptoKey }> {\n const [mainKey, ...otherSelfKeys] = this.keyManager.getSelfVerifiedKeys()\n let otherPublicKeys = Object.fromEntries(otherSelfKeys.map((x) => [x.fingerprint, x.pair.publicKey]))\n if (delegateId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n const delegatePublicKeys = Array.from(this.dataOwnerApi.getHexPublicKeysOf(delegate.stub))\n let verifiedDelegatePublicKeys: string[]\n if ((await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).includes(delegateId)) {\n verifiedDelegatePublicKeys = await this.keyManager.getVerifiedPublicKeysFor(delegate.stub)\n } else {\n verifiedDelegatePublicKeys = await this.cryptoStrategies.verifyDelegatePublicKeys(delegate, delegatePublicKeys, this.primitives)\n }\n if (!verifiedDelegatePublicKeys || verifiedDelegatePublicKeys.length == 0)\n throw new Error(`No verified public keys for delegate ${delegateId}: impossible to create new exchange key.`)\n otherPublicKeys = {\n ...otherPublicKeys,\n ...(await loadPublicKeys(this.primitives.RSA, verifiedDelegatePublicKeys)),\n }\n }\n return await this.baseExchangeKeysManager.createOrUpdateEncryptedExchangeKeyTo(delegateId, mainKey.pair, otherPublicKeys)\n }\n}\n"]}
@@ -91,7 +91,7 @@ class KeyManager {
91
91
  */
92
92
  reloadKeys() {
93
93
  return __awaiter(this, void 0, void 0, function* () {
94
- yield this.doLoadKeys((x) => Promise.resolve(x.reduce((acc, { dataOwner }) => (Object.assign(Object.assign({}, acc), { [dataOwner.id]: { recoveredKeys: {}, keyAuthenticity: {} } })), {})), (x) => {
94
+ yield this.doLoadKeys((x) => Promise.resolve(x.reduce((acc, { dataOwner }) => (Object.assign(Object.assign({}, acc), { [dataOwner.dataOwner.id]: { recoveredKeys: {}, keyAuthenticity: {} } })), {})), (x) => {
95
95
  throw new Error("Can't create new keys at reload time: it should have already been created on initialisation");
96
96
  });
97
97
  });
@@ -174,7 +174,7 @@ class KeyManager {
174
174
  const unknownKeys = Array.from(allPublicKeys).filter((x) => { var _a; return !(x.slice(-32) in verifiedKeysMap) && !(((_a = availableKeys === null || availableKeys === void 0 ? void 0 : availableKeys[x.slice(-32)]) === null || _a === void 0 ? void 0 : _a.isDevice) === true); });
175
175
  keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys });
176
176
  }
177
- const recoveryAndVerificationResult = yield keyRecovererAndVerifier(keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt.dataOwner, unavailableKeys, unknownKeys })));
177
+ const recoveryAndVerificationResult = yield keyRecovererAndVerifier(keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys })));
178
178
  const keysCache = {};
179
179
  for (const keyData of keysData) {
180
180
  const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id].keyAuthenticity);
@@ -198,14 +198,14 @@ class KeyManager {
198
198
  return undefined;
199
199
  }
200
200
  else {
201
- const whatToDo = yield currentOwnerKeyGenerator(self.dataOwner);
201
+ const whatToDo = yield currentOwnerKeyGenerator(self);
202
202
  if (whatToDo === false) {
203
203
  throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`);
204
204
  }
205
205
  else {
206
206
  const updateInfo = yield this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self);
207
207
  // self may be outdated now
208
- this.selfLegacyPublicKey = updateInfo.updatedSelf.dataOwner.publicKey;
208
+ this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey;
209
209
  this.keysCache = Object.assign(Object.assign({}, keysCache), { [self.dataOwner.id]: Object.assign(Object.assign({}, keysCache[self.dataOwner.id]), { [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true } }) });
210
210
  return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint };
211
211
  }