@icure/api 8.0.0-RC.5 → 8.0.0

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 (213) hide show
  1. package/icc-api/api/IccAccesslogApi.d.ts +3 -7
  2. package/icc-api/api/IccAccesslogApi.js +2 -2
  3. package/icc-api/api/IccAccesslogApi.js.map +1 -1
  4. package/icc-api/api/IccAgendaApi.d.ts +1 -1
  5. package/icc-api/api/IccAgendaApi.js +2 -2
  6. package/icc-api/api/IccAgendaApi.js.map +1 -1
  7. package/icc-api/api/IccAnonymousAccessApi.d.ts +10 -0
  8. package/icc-api/api/IccAnonymousAccessApi.js +33 -0
  9. package/icc-api/api/IccAnonymousAccessApi.js.map +1 -1
  10. package/icc-api/api/IccApplicationsettingsApi.d.ts +1 -1
  11. package/icc-api/api/IccApplicationsettingsApi.js +2 -2
  12. package/icc-api/api/IccApplicationsettingsApi.js.map +1 -1
  13. package/icc-api/api/IccArticleApi.d.ts +1 -1
  14. package/icc-api/api/IccArticleApi.js +2 -2
  15. package/icc-api/api/IccArticleApi.js.map +1 -1
  16. package/icc-api/api/IccAuthApi.d.ts +4 -2
  17. package/icc-api/api/IccAuthApi.js +11 -4
  18. package/icc-api/api/IccAuthApi.js.map +1 -1
  19. package/icc-api/api/IccCalendarItemApi.d.ts +4 -12
  20. package/icc-api/api/IccCalendarItemApi.js +2 -2
  21. package/icc-api/api/IccCalendarItemApi.js.map +1 -1
  22. package/icc-api/api/IccCalendarItemTypeApi.d.ts +1 -1
  23. package/icc-api/api/IccCalendarItemTypeApi.js +2 -2
  24. package/icc-api/api/IccCalendarItemTypeApi.js.map +1 -1
  25. package/icc-api/api/IccClassificationApi.d.ts +4 -12
  26. package/icc-api/api/IccClassificationApi.js +2 -2
  27. package/icc-api/api/IccClassificationApi.js.map +1 -1
  28. package/icc-api/api/IccClassificationTemplateApi.d.ts +1 -1
  29. package/icc-api/api/IccClassificationTemplateApi.js +2 -2
  30. package/icc-api/api/IccClassificationTemplateApi.js.map +1 -1
  31. package/icc-api/api/IccCodeApi.d.ts +1 -1
  32. package/icc-api/api/IccCodeApi.js +2 -2
  33. package/icc-api/api/IccCodeApi.js.map +1 -1
  34. package/icc-api/api/IccContactApi.d.ts +3 -11
  35. package/icc-api/api/IccContactApi.js.map +1 -1
  36. package/icc-api/api/IccDataownerApi.d.ts +1 -1
  37. package/icc-api/api/IccDataownerApi.js +2 -2
  38. package/icc-api/api/IccDataownerApi.js.map +1 -1
  39. package/icc-api/api/IccDeviceApi.d.ts +1 -1
  40. package/icc-api/api/IccDeviceApi.js +2 -2
  41. package/icc-api/api/IccDeviceApi.js.map +1 -1
  42. package/icc-api/api/IccDoctemplateApi.d.ts +1 -1
  43. package/icc-api/api/IccDoctemplateApi.js +2 -2
  44. package/icc-api/api/IccDoctemplateApi.js.map +1 -1
  45. package/icc-api/api/IccDocumentApi.d.ts +3 -7
  46. package/icc-api/api/IccDocumentApi.js +2 -2
  47. package/icc-api/api/IccDocumentApi.js.map +1 -1
  48. package/icc-api/api/IccEntityrefApi.d.ts +1 -1
  49. package/icc-api/api/IccEntityrefApi.js +2 -2
  50. package/icc-api/api/IccEntityrefApi.js.map +1 -1
  51. package/icc-api/api/IccEntitytemplateApi.d.ts +1 -1
  52. package/icc-api/api/IccEntitytemplateApi.js +2 -2
  53. package/icc-api/api/IccEntitytemplateApi.js.map +1 -1
  54. package/icc-api/api/IccFormApi.d.ts +4 -12
  55. package/icc-api/api/IccFormApi.js +2 -2
  56. package/icc-api/api/IccFormApi.js.map +1 -1
  57. package/icc-api/api/IccFrontendmigrationApi.d.ts +1 -1
  58. package/icc-api/api/IccFrontendmigrationApi.js +2 -2
  59. package/icc-api/api/IccFrontendmigrationApi.js.map +1 -1
  60. package/icc-api/api/IccGroupApi.d.ts +1 -1
  61. package/icc-api/api/IccGroupApi.js +2 -2
  62. package/icc-api/api/IccGroupApi.js.map +1 -1
  63. package/icc-api/api/IccHcpartyApi.d.ts +1 -1
  64. package/icc-api/api/IccHcpartyApi.js +2 -2
  65. package/icc-api/api/IccHcpartyApi.js.map +1 -1
  66. package/icc-api/api/IccHelementApi.d.ts +4 -12
  67. package/icc-api/api/IccHelementApi.js +2 -2
  68. package/icc-api/api/IccHelementApi.js.map +1 -1
  69. package/icc-api/api/IccIcureApi.d.ts +1 -1
  70. package/icc-api/api/IccIcureApi.js +2 -2
  71. package/icc-api/api/IccIcureApi.js.map +1 -1
  72. package/icc-api/api/IccInsuranceApi.d.ts +1 -1
  73. package/icc-api/api/IccInsuranceApi.js +2 -2
  74. package/icc-api/api/IccInsuranceApi.js.map +1 -1
  75. package/icc-api/api/IccInvoiceApi.d.ts +4 -12
  76. package/icc-api/api/IccInvoiceApi.js +2 -2
  77. package/icc-api/api/IccInvoiceApi.js.map +1 -1
  78. package/icc-api/api/IccKeywordApi.d.ts +1 -1
  79. package/icc-api/api/IccKeywordApi.js +2 -2
  80. package/icc-api/api/IccKeywordApi.js.map +1 -1
  81. package/icc-api/api/IccMaintenanceTaskApi.d.ts +3 -7
  82. package/icc-api/api/IccMaintenanceTaskApi.js +2 -2
  83. package/icc-api/api/IccMaintenanceTaskApi.js.map +1 -1
  84. package/icc-api/api/IccMedexApi.d.ts +1 -1
  85. package/icc-api/api/IccMedexApi.js +2 -2
  86. package/icc-api/api/IccMedexApi.js.map +1 -1
  87. package/icc-api/api/IccMedicallocationApi.d.ts +1 -1
  88. package/icc-api/api/IccMedicallocationApi.js +2 -2
  89. package/icc-api/api/IccMedicallocationApi.js.map +1 -1
  90. package/icc-api/api/IccMessageApi.d.ts +3 -7
  91. package/icc-api/api/IccMessageApi.js +2 -2
  92. package/icc-api/api/IccMessageApi.js.map +1 -1
  93. package/icc-api/api/IccPatientApi.d.ts +3 -7
  94. package/icc-api/api/IccPatientApi.js +2 -2
  95. package/icc-api/api/IccPatientApi.js.map +1 -1
  96. package/icc-api/api/IccPermissionApi.d.ts +1 -1
  97. package/icc-api/api/IccPermissionApi.js +2 -2
  98. package/icc-api/api/IccPermissionApi.js.map +1 -1
  99. package/icc-api/api/IccPlaceApi.d.ts +1 -1
  100. package/icc-api/api/IccPlaceApi.js +2 -2
  101. package/icc-api/api/IccPlaceApi.js.map +1 -1
  102. package/icc-api/api/IccReceiptApi.d.ts +3 -7
  103. package/icc-api/api/IccReceiptApi.js +2 -2
  104. package/icc-api/api/IccReceiptApi.js.map +1 -1
  105. package/icc-api/api/IccReplicationApi.d.ts +1 -1
  106. package/icc-api/api/IccReplicationApi.js +2 -2
  107. package/icc-api/api/IccReplicationApi.js.map +1 -1
  108. package/icc-api/api/IccRoleApi.d.ts +1 -1
  109. package/icc-api/api/IccRoleApi.js +2 -2
  110. package/icc-api/api/IccRoleApi.js.map +1 -1
  111. package/icc-api/api/IccTarificationApi.d.ts +1 -1
  112. package/icc-api/api/IccTarificationApi.js +2 -2
  113. package/icc-api/api/IccTarificationApi.js.map +1 -1
  114. package/icc-api/api/IccTimeTableApi.d.ts +3 -7
  115. package/icc-api/api/IccTimeTableApi.js +2 -2
  116. package/icc-api/api/IccTimeTableApi.js.map +1 -1
  117. package/icc-api/api/IccTopicApi.d.ts +3 -7
  118. package/icc-api/api/IccTopicApi.js +2 -2
  119. package/icc-api/api/IccTopicApi.js.map +1 -1
  120. package/icc-api/api/IccUserApi.d.ts +22 -1
  121. package/icc-api/api/IccUserApi.js +59 -2
  122. package/icc-api/api/IccUserApi.js.map +1 -1
  123. package/icc-api/api/XHR.d.ts +1 -1
  124. package/icc-api/api/XHR.js +4 -3
  125. package/icc-api/api/XHR.js.map +1 -1
  126. package/icc-api/api/internal/IccExchangeDataMapApi.d.ts +0 -3
  127. package/icc-api/api/internal/IccExchangeDataMapApi.js +0 -31
  128. package/icc-api/api/internal/IccExchangeDataMapApi.js.map +1 -1
  129. package/icc-api/api/internal/IccSecureDelegationKeyMapApi.d.ts +2 -6
  130. package/icc-api/api/internal/IccSecureDelegationKeyMapApi.js.map +1 -1
  131. package/icc-api/model/MedicalLocation.d.ts +3 -0
  132. package/icc-api/model/MedicalLocation.js.map +1 -1
  133. package/icc-api/model/PaginatedListMedicalLocation.d.ts +20 -0
  134. package/icc-api/model/PaginatedListMedicalLocation.js +10 -0
  135. package/icc-api/model/PaginatedListMedicalLocation.js.map +1 -0
  136. package/icc-api/model/requests/BulkShareOrUpdateMetadataParams.d.ts +12 -0
  137. package/icc-api/model/requests/BulkShareOrUpdateMetadataParams.js +3 -0
  138. package/icc-api/model/requests/BulkShareOrUpdateMetadataParams.js.map +1 -0
  139. package/icc-x-api/auth/AuthService.d.ts +2 -1
  140. package/icc-x-api/auth/AuthService.js.map +1 -1
  141. package/icc-x-api/auth/AuthenticationProvider.d.ts +1 -1
  142. package/icc-x-api/auth/AuthenticationProvider.js +1 -1
  143. package/icc-x-api/auth/AuthenticationProvider.js.map +1 -1
  144. package/icc-x-api/auth/EnsembleAuthService.d.ts +1 -1
  145. package/icc-x-api/auth/EnsembleAuthService.js +2 -2
  146. package/icc-x-api/auth/EnsembleAuthService.js.map +1 -1
  147. package/icc-x-api/auth/JwtAuthService.d.ts +0 -2
  148. package/icc-x-api/auth/JwtAuthService.js +3 -15
  149. package/icc-x-api/auth/JwtAuthService.js.map +1 -1
  150. package/icc-x-api/auth/JwtBridgedAuthService.d.ts +1 -1
  151. package/icc-x-api/auth/JwtBridgedAuthService.js +4 -4
  152. package/icc-x-api/auth/JwtBridgedAuthService.js.map +1 -1
  153. package/icc-x-api/auth/JwtUtils.d.ts +10 -0
  154. package/icc-x-api/auth/JwtUtils.js +31 -0
  155. package/icc-x-api/auth/JwtUtils.js.map +1 -0
  156. package/icc-x-api/auth/SmartAuthProvider.d.ts +132 -0
  157. package/icc-x-api/auth/SmartAuthProvider.js +419 -0
  158. package/icc-x-api/auth/SmartAuthProvider.js.map +1 -0
  159. package/icc-x-api/crypto/BaseExchangeDataManager.d.ts +20 -0
  160. package/icc-x-api/crypto/BaseExchangeDataManager.js +32 -2
  161. package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -1
  162. package/icc-x-api/crypto/ConfidentialEntities.d.ts +2 -6
  163. package/icc-x-api/crypto/ConfidentialEntities.js.map +1 -1
  164. package/icc-x-api/crypto/CryptoStrategies.d.ts +3 -1
  165. package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
  166. package/icc-x-api/crypto/ExchangeDataManager.d.ts +3 -1
  167. package/icc-x-api/crypto/ExchangeDataManager.js +36 -22
  168. package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -1
  169. package/icc-x-api/crypto/ExchangeDataMapManager.d.ts +0 -5
  170. package/icc-x-api/crypto/ExchangeDataMapManager.js +0 -11
  171. package/icc-x-api/crypto/ExchangeDataMapManager.js.map +1 -1
  172. package/icc-x-api/crypto/ExtendedApisUtils.d.ts +4 -16
  173. package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -1
  174. package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +4 -16
  175. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +12 -3
  176. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
  177. package/icc-x-api/crypto/KeyPairRecoverer.d.ts +34 -0
  178. package/icc-x-api/crypto/KeyPairRecoverer.js +32 -0
  179. package/icc-x-api/crypto/KeyPairRecoverer.js.map +1 -0
  180. package/icc-x-api/crypto/RecoveryDataEncryption.d.ts +85 -0
  181. package/icc-x-api/crypto/RecoveryDataEncryption.js +171 -0
  182. package/icc-x-api/crypto/RecoveryDataEncryption.js.map +1 -0
  183. package/icc-x-api/crypto/SecureDelegationsManager.js +2 -2
  184. package/icc-x-api/crypto/SecureDelegationsManager.js.map +1 -1
  185. package/icc-x-api/crypto/ShamirKeysManager.js +1 -1
  186. package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
  187. package/icc-x-api/crypto/UserEncryptionKeysManager.d.ts +4 -1
  188. package/icc-x-api/crypto/UserEncryptionKeysManager.js +4 -3
  189. package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
  190. package/icc-x-api/icc-bekmehr-x-api.d.ts +1 -0
  191. package/icc-x-api/icc-bekmehr-x-api.js +37 -36
  192. package/icc-x-api/icc-bekmehr-x-api.js.map +1 -1
  193. package/icc-x-api/icc-contact-x-api.js +15 -12
  194. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  195. package/icc-x-api/icc-crypto-x-api.d.ts +1 -0
  196. package/icc-x-api/icc-crypto-x-api.js.map +1 -1
  197. package/icc-x-api/icc-maintenance-task-x-api.d.ts +1 -1
  198. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  199. package/icc-x-api/icc-patient-x-api.d.ts +18 -0
  200. package/icc-x-api/icc-patient-x-api.js +29 -0
  201. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  202. package/icc-x-api/icc-recovery-x-api.d.ts +127 -0
  203. package/icc-x-api/icc-recovery-x-api.js +217 -0
  204. package/icc-x-api/icc-recovery-x-api.js.map +1 -1
  205. package/icc-x-api/icc-user-x-api.js +15 -2
  206. package/icc-x-api/icc-user-x-api.js.map +1 -1
  207. package/icc-x-api/index.d.ts +68 -23
  208. package/icc-x-api/index.js +85 -38
  209. package/icc-x-api/index.js.map +1 -1
  210. package/icc-x-api/utils/collection-utils.d.ts +14 -1
  211. package/icc-x-api/utils/collection-utils.js +49 -3
  212. package/icc-x-api/utils/collection-utils.js.map +1 -1
  213. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ExchangeDataManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExchangeDataManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAOA,mCAAgH;AAEhH,oCAAyC;AACzC,oFAA6E;AAC7E,wFAAmH;AACnH,yEAA6E;AAO7E;;;GAGG;AACH,SAAsB,gDAAgD,CACpE,IAA6B,EAC7B,cAAyC,EACzC,aAAuC,EACvC,mBAA6C,EAC7C,gBAAkC,EAClC,YAA8B,EAC9B,UAA4B,EAC5B,aAAsB,EACtB,qBAA4D,EAAE;;QAE9D,MAAM,YAAY,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["import { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { BaseExchangeDataManager } from './BaseExchangeDataManager'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { UserSignatureKeysManager } from './UserSignatureKeysManager'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { fingerprintV1, getShaVersionForKey, hexPublicKeysWithSha1Of, hexPublicKeysWithSha256Of } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { hex2ua, ua2b64 } from '../utils'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { EntityWithDelegationTypeName, entityWithDelegationTypeNames } from '../utils/EntityWithDelegationTypeName'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\nexport type ExchangeDataManagerOptionalParameters = {\n // Only for not fully cached implementation (data owner can't request all his exchange data), amount of exchange data which can be cached\n lruCacheSize?: number // default = 2000\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice.\n * Initialises and returns the exchange data manager which is most appropriate for the current data owner.\n */\nexport async function initialiseExchangeDataManagerForCurrentDataOwner(\n base: BaseExchangeDataManager,\n encryptionKeys: UserEncryptionKeysManager,\n signatureKeys: UserSignatureKeysManager,\n accessControlSecret: AccessControlSecretUtils,\n cryptoStrategies: CryptoStrategies,\n dataOwnerApi: IccDataOwnerXApi,\n primitives: CryptoPrimitives,\n useParentKeys: boolean,\n optionalParameters: ExchangeDataManagerOptionalParameters = {}\n): Promise<ExchangeDataManager> {\n const currentOwner = CryptoActorStubWithType.fromDataOwner(await dataOwnerApi.getCurrentDataOwner())\n if (cryptoStrategies.dataOwnerRequiresAnonymousDelegation(currentOwner)) {\n const res = new FullyCachedExchangeDataManager(\n base,\n encryptionKeys,\n signatureKeys,\n accessControlSecret,\n cryptoStrategies,\n dataOwnerApi,\n primitives,\n useParentKeys\n )\n await res.clearOrRepopulateCache()\n return res\n } else {\n return new LimitedLruCacheExchangeDataManager(\n base,\n encryptionKeys,\n signatureKeys,\n accessControlSecret,\n cryptoStrategies,\n dataOwnerApi,\n primitives,\n useParentKeys,\n optionalParameters\n )\n }\n}\n\ntype CachedExchangeData = {\n exchangeData: ExchangeData\n decrypted?: {\n accessControlSecret: string\n exchangeKey: CryptoKey\n verified: boolean\n }\n}\n\n/**\n * @internal this class is intended for internal use only and may be changed without notice.\n * Exchange data manager which automatically handles decryption and cache\n */\nexport interface ExchangeDataManager {\n readonly base: BaseExchangeDataManager\n\n /**\n * Updates all exchange data between the current data owner and another data owner to allow the other data owner to access existing exchange data\n * using a new public key. Note that this will make existing exchange keys from the other data owner to the current data owner unverified, therefore\n * invalid for encryption.\n * @param otherDataOwner the other data owner.\n * @param newDataOwnerPublicKey a new public key of the other data owner.\n */\n giveAccessBackTo(otherDataOwner: string, newDataOwnerPublicKey: string): Promise<void>\n\n /**\n * Gets any existing and verified exchange data from the current data owner to the provided delegate or creates new data if no verified data is\n * available, then caches it. The {@link entityType} and {@link entitySecretForeignKeys} will be used for the secure-delegation-hash-based cache\n * of the exchange data and not for actually creating the exchange data.\n * @param delegateId the id of the delegate.\n * @param entityType type of the entity for which you want to create new metadata.\n * @param entitySecretForeignKeys the secret foreign keys of the entity which you want to create new metadata.\n * @return the access control secret and key of the data to use for encryption.\n */\n getOrCreateEncryptionDataTo(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }>\n\n /**\n * Retrieve the cached decrypted exchange data key associated with any of the provided hashes/entry keys of secure delegations. Depending on the\n * implementation the {@link entityType} and {@link entitySecretForeignKeys} may be used to improve the secure-delegation-hash-based cache of\n * exchange data from the other available exchange data caches.\n * @param hashes hashes of access control secrets for a specific entity, as they appear in the key of secure delegation entries\n * @param entityType type of the entity containing the metadata for which you are retrieving the encryption key.\n * @param entitySecretForeignKeys the secret foreign keys of the entity containing the metadata for which you are retrieving the encryption key.\n * @return the exchange data and decrypted key associated to that hash if cached\n */\n getCachedDecryptionDataKeyByAccessControlHash(\n hashes: string[],\n entityType: EntityWithDelegationTypeName,\n entitySecretForeignKeys: string[]\n ): Promise<{ [hash: string]: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey } }>\n\n /**\n * Retrieves the exchange data with the provided id (from the cache if available or from the server otherwise if allowed by\n * {@link retrieveIfNotCached}) and attempts to decrypt it, then caches the result. The {@link entityType} and {@link entitySecretForeignKeys} will\n * be used for the secure-delegation-hash-based cache of the exchange data.\n * @param id id of the exchange data\n * @param entityType type of the entity containing the metadata for which you are retrieving the encryption key.\n * @param entitySecretForeignKeys the secret foreign keys of the entity containing the metadata for which you are retrieving the encryption key.\n * @param retrieveIfNotCached if false and there is no cached exchange data with the provided id the method returns undefined, else the method will\n * attempt to load the exchange data from the server.\n * @return undefined if the exchange data is not cached and {@link retrieveIfNotCached} is false. Else an object containing:\n * - exchangeData: the exchange data with the provided id\n * - exchangeKey: the exchange key corresponding to the provided exchange data if it could be decrypted, else undefined\n * @throws if no exchange data with the given id is cached and {@link retrieveIfNotCached} is true and the data could not be found in the server\n * either.\n */\n getDecryptionDataKeyById(\n id: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n retrieveIfNotCached: boolean\n ): Promise<{ exchangeKey: CryptoKey | undefined; accessControlSecret: string | undefined; exchangeData: ExchangeData } | undefined>\n\n /**\n * Clears the cache or fully repopulates the cache if the current data owner can retrieve all of his exchange data according to the crypto\n * strategies.\n */\n clearOrRepopulateCache(): Promise<void>\n\n /**\n * If the current data owner requires anonymous delegations this returns the base64 representation of the concatenation of all available access\n * control keys for the current data owner.\n */\n getAccessControlKeysValue(entityType: EntityWithDelegationTypeName): Promise<string | undefined>\n\n /**\n * If the current data owner requires anonymous delegations this returns the access control keys which may be used in secure delegations for the\n * data owner, which can be used to search for data.\n */\n getAllDelegationKeys(entityType: EntityWithDelegationTypeName): Promise<string[] | undefined>\n}\n\nabstract class AbstractExchangeDataManager implements ExchangeDataManager {\n constructor(\n readonly base: BaseExchangeDataManager,\n protected readonly encryptionKeys: UserEncryptionKeysManager,\n protected readonly signatureKeys: UserSignatureKeysManager,\n protected readonly accessControlSecret: AccessControlSecretUtils,\n protected readonly cryptoStrategies: CryptoStrategies,\n protected readonly dataOwnerApi: IccDataOwnerXApi,\n protected readonly primitives: CryptoPrimitives,\n private readonly useParentKeys: boolean\n ) {}\n\n protected async decryptData(data: ExchangeData): Promise<\n | {\n accessControlSecret: string\n exchangeKey: CryptoKey\n verified: boolean\n }\n | undefined\n > {\n const decryptionKeys = this.encryptionKeys.getDecryptionKeys()\n const decryptedExchangeKey = (await this.base.tryDecryptExchangeKeys([data], decryptionKeys)).successfulDecryptions[0]\n if (!decryptedExchangeKey) return undefined\n const decryptedAccessControlSecret = (await this.base.tryDecryptAccessControlSecret([data], decryptionKeys)).successfulDecryptions[0]\n if (!decryptedAccessControlSecret)\n throw new Error(`Decryption key could be decrypted but access control secret could not for data ${JSON.stringify(data)}`)\n const decryptedSharedSignatureKey = (await this.base.tryDecryptSharedSignatureKeys([data], decryptionKeys)).successfulDecryptions[0]\n if (!decryptedSharedSignatureKey)\n throw new Error(`Decryption key could be decrypted but shared signature key could not for data ${JSON.stringify(data)}`)\n return {\n accessControlSecret: decryptedAccessControlSecret,\n exchangeKey: decryptedExchangeKey,\n verified: await this.base.verifyExchangeData(\n {\n exchangeData: data,\n decryptedAccessControlSecret,\n decryptedExchangeKey,\n decryptedSharedSignatureKey,\n },\n (fp) => this.signatureKeys.getSignatureVerificationKey(fp),\n true\n ),\n }\n }\n\n protected async createNewExchangeData(\n delegateId: string,\n newDataId?: string\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }> {\n const encryptionKeys: { [fp: string]: CryptoKey } = {}\n this.encryptionKeys.getSelfVerifiedKeys().forEach(({ fingerprint, pair }) => {\n encryptionKeys[fingerprint] = pair.publicKey\n })\n if (delegateId != (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n const sha256KeysOfDelegate = hexPublicKeysWithSha256Of(delegate.stub)\n const sha1KeysOfDelegate = hexPublicKeysWithSha1Of(delegate.stub)\n let allVerifiedDelegateKeys: string[]\n if (this.useParentKeys && (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).includes(delegateId)) {\n allVerifiedDelegateKeys = await this.encryptionKeys.getVerifiedPublicKeysFor(delegate.stub)\n } else {\n allVerifiedDelegateKeys = await this.cryptoStrategies.verifyDelegatePublicKeys(\n delegate,\n [...Array.from(sha256KeysOfDelegate), ...Array.from(sha1KeysOfDelegate)],\n this.primitives\n )\n }\n if (!allVerifiedDelegateKeys.length)\n throw new Error(`Could not create exchange data to ${delegateId} as no public key for the delegate could be verified.`)\n for (const delegateKey of allVerifiedDelegateKeys) {\n if (sha1KeysOfDelegate.has(delegateKey)) {\n encryptionKeys[fingerprintV1(delegateKey)] = await this.primitives.RSA.importKey('spki', hex2ua(delegateKey), ['encrypt'], 'sha-1')\n } else if (sha256KeysOfDelegate.has(delegateKey)) {\n encryptionKeys[fingerprintV1(delegateKey)] = await this.primitives.RSA.importKey('spki', hex2ua(delegateKey), ['encrypt'], 'sha-256')\n } else throw new Error('Illegal state: verified keys should contain only keys for OAPE-SHA1 or OAPE-SHA256.')\n }\n }\n const signatureKey = await this.signatureKeys.getOrCreateSignatureKeyPair()\n const newData = await this.base.createExchangeData(\n delegateId,\n { [signatureKey.fingerprint]: signatureKey.keyPair.privateKey },\n encryptionKeys,\n newDataId ? { id: newDataId } : {}\n )\n return {\n exchangeData: newData.exchangeData,\n accessControlSecret: newData.accessControlSecret,\n exchangeKey: newData.exchangeKey,\n }\n }\n\n async giveAccessBackTo(otherDataOwner: string, newDataOwnerPublicKey: string) {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n const newKeyFp = fingerprintV1(newDataOwnerPublicKey)\n const other = await this.dataOwnerApi.getCryptoActorStub(otherDataOwner)\n const newKeyHashVersion = getShaVersionForKey(other.stub, newDataOwnerPublicKey)\n if (!newKeyHashVersion) throw new Error(`Public key not found for data owner ${otherDataOwner}`)\n const importedNewKey = await this.primitives.RSA.importKey('spki', hex2ua(newDataOwnerPublicKey), ['encrypt'], newKeyHashVersion)\n const signatureKey = await this.signatureKeys.getOrCreateSignatureKeyPair()\n const decryptionKeys = this.encryptionKeys.getDecryptionKeys()\n const allExchangeDataToUpdate =\n self == otherDataOwner\n ? await this.base.getExchangeDataByDelegatorDelegatePair(self, self)\n : [\n ...(await this.base.getExchangeDataByDelegatorDelegatePair(self, otherDataOwner)),\n ...(await this.base.getExchangeDataByDelegatorDelegatePair(otherDataOwner, self)),\n ]\n for (const dataToUpdate of allExchangeDataToUpdate) {\n if (!Object.keys(dataToUpdate.exchangeKey).find((fp) => fp == newKeyFp)) {\n const updated = await this.base.tryUpdateExchangeData(dataToUpdate, decryptionKeys, { [newKeyFp]: importedNewKey })\n if (!updated) {\n console.warn(`Failed to give access back to exchanged data ${JSON.stringify(dataToUpdate)}`)\n }\n }\n }\n }\n\n clearOrRepopulateCache(): Promise<void> {\n throw new Error('Implemented by concrete class')\n }\n\n getOrCreateEncryptionDataTo(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }> {\n throw new Error('Implemented by concrete class')\n }\n\n getCachedDecryptionDataKeyByAccessControlHash(\n hashes: string[],\n entityType: EntityWithDelegationTypeName,\n entitySecretForeignKeys: string[]\n ): Promise<{ [p: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } }> {\n throw new Error('Implemented by concrete class')\n }\n\n getDecryptionDataKeyById(\n id: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n retrieveIfNotCached: boolean\n ): Promise<{ exchangeData: ExchangeData; exchangeKey: CryptoKey | undefined; accessControlSecret: string | undefined } | undefined> {\n throw new Error('Implemented by concrete class')\n }\n\n getAccessControlKeysValue(entityType: EntityWithDelegationTypeName): Promise<string | undefined> {\n throw new Error('Implemented by concrete class')\n }\n\n getAllDelegationKeys(entityType: EntityWithDelegationTypeName): Promise<string[] | undefined> {\n throw new Error('Implemented by concrete class')\n }\n}\n\nclass FullyCachedExchangeDataManager extends AbstractExchangeDataManager {\n private caches: Promise<{\n dataById: { [id: string]: CachedExchangeData }\n hashToId: Map<string, string>\n delegateToVerifiedEncryptionDataId: { [delegate: string]: string }\n entityTypeToAccessControlKeysValue: { [entityType in EntityWithDelegationTypeName]?: string }\n }> = Promise.resolve({ dataById: {}, hashToId: new Map(), delegateToVerifiedEncryptionDataId: {}, entityTypeToAccessControlKeysValue: {} })\n\n async clearOrRepopulateCache(): Promise<void> {\n this.caches = this.doRepopulateCache()\n await this.caches\n }\n\n async getCachedDecryptionDataKeyByAccessControlHash(\n hashes: string[],\n entityType: EntityWithDelegationTypeName,\n entitySecretForeignKeys: string[]\n ): Promise<{ [hash: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } }> {\n function retrieveByHashesFromCaches(caches: {\n dataById: { [id: string]: CachedExchangeData }\n hashToId: Map<string, string>\n delegateToVerifiedEncryptionDataId: { [delegate: string]: string }\n }): { [hash: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } } {\n return hashes.reduce((res, hash) => {\n const id = caches.hashToId.get(hash)\n if (id) {\n const cached = caches.dataById[id]\n if (cached?.decrypted) {\n res[hash] = {\n exchangeData: cached.exchangeData,\n exchangeKey: cached.decrypted.exchangeKey,\n accessControlSecret: cached.decrypted.accessControlSecret,\n }\n }\n }\n return res\n }, {} as { [hash: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } })\n }\n\n const retrievedFromHashesCache = retrieveByHashesFromCaches(await this.caches)\n if (Object.keys(retrievedFromHashesCache).length) {\n return retrievedFromHashesCache\n } else {\n this.caches = this.caches.then(async (caches) => {\n for (const currData of Object.values(caches.dataById)) {\n if (currData.decrypted) {\n const currDataHashes = await this.accessControlSecret.secureDelegationKeysFor(\n currData.decrypted.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n currDataHashes.forEach((hash) => caches.hashToId.set(hash, currData.exchangeData.id!))\n }\n }\n return caches\n })\n return retrieveByHashesFromCaches(await this.caches)\n }\n }\n\n async getOrCreateEncryptionDataTo(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }> {\n const caches = await this.caches\n const dataId = caches.delegateToVerifiedEncryptionDataId[delegateId]\n const cached = dataId ? caches.dataById[dataId] : undefined\n if (cached && cached?.decrypted) {\n return {\n exchangeData: cached.exchangeData,\n accessControlSecret: cached.decrypted.accessControlSecret,\n exchangeKey: cached.decrypted.exchangeKey,\n }\n }\n const created = await this.createNewExchangeData(delegateId)\n this.cacheData(\n created.exchangeData,\n { accessControlSecret: created.accessControlSecret, exchangeKey: created.exchangeKey, verified: true },\n entityType,\n entitySecretForeignKeys\n )\n return created\n }\n\n async getDecryptionDataKeyById(\n id: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n retrieveIfNotCached: boolean\n ): Promise<{ exchangeData: ExchangeData; exchangeKey: CryptoKey | undefined; accessControlSecret: string | undefined } | undefined> {\n const caches = await this.caches\n const cachedData = caches.dataById[id]\n if (cachedData) {\n return {\n exchangeData: cachedData.exchangeData,\n exchangeKey: cachedData.decrypted?.exchangeKey,\n accessControlSecret: cachedData.decrypted?.accessControlSecret,\n }\n } else if (retrieveIfNotCached) {\n const data = await this.base.getExchangeDataById(id)\n if (!data) throw new Error(`Could not find exchange data with id ${id}`)\n const decrypted = await this.decryptData(data)\n this.cacheData(data, decrypted, entityType, entitySecretForeignKeys)\n return { exchangeData: data, exchangeKey: decrypted?.exchangeKey, accessControlSecret: decrypted?.accessControlSecret }\n } else return undefined\n }\n\n private cacheData(\n exchangeData: ExchangeData,\n decrypted: { accessControlSecret: string; exchangeKey: CryptoKey; verified: boolean } | undefined,\n entityType?: EntityWithDelegationTypeName,\n entitySecretForeignKeys?: string[]\n ): void {\n this.caches = this.caches.then(async (caches) => {\n caches.dataById[exchangeData.id!] = { exchangeData, decrypted }\n if (decrypted) {\n // Usage of sfks in secure delegation key should be configurable: it is not necessary for all users and it has some performance impact\n // `secureDelegationKeysFor` is currently ignoring the sfks\n if (entityType && entitySecretForeignKeys) {\n const hashes = await this.accessControlSecret.secureDelegationKeysFor(decrypted.accessControlSecret, entityType, entitySecretForeignKeys)\n hashes.forEach((hash) => {\n caches.hashToId.set(hash, exchangeData.id!)\n })\n }\n if (decrypted.verified) {\n caches.delegateToVerifiedEncryptionDataId[exchangeData.delegate] = exchangeData.id!\n }\n }\n return caches\n })\n }\n\n private async doRepopulateCache(): Promise<{\n dataById: { [id: string]: CachedExchangeData }\n hashToId: Map<string, string>\n delegateToVerifiedEncryptionDataId: { [delegate: string]: string }\n entityTypeToAccessControlKeysValue: { [entityType in EntityWithDelegationTypeName]?: string }\n }> {\n const allData = await this.base.getAllExchangeDataForCurrentDataOwnerIfAllowed()\n if (!allData) throw new Error('Impossible to use fully cached exchange data manager for current data owner.')\n const dataById: { [id: string]: CachedExchangeData } = {}\n const hashToId = new Map<string, string>()\n const delegateToVerifiedEncryptionDataId: { [delegate: string]: string } = {}\n for (const currData of allData) {\n const currDecrypted = await this.decryptData(currData)\n dataById[currData.id!] = { exchangeData: currData, decrypted: currDecrypted }\n if (currDecrypted?.verified) {\n delegateToVerifiedEncryptionDataId[currData.delegate] = currData.id!\n }\n }\n const entityTypeToAccessControlKeysValue: { [entityType in EntityWithDelegationTypeName]?: string } = {}\n return { dataById, hashToId, delegateToVerifiedEncryptionDataId, entityTypeToAccessControlKeysValue }\n }\n\n async getAccessControlKeysValue(entityType: EntityWithDelegationTypeName): Promise<string | undefined> {\n const caches = await this.caches\n const cached = caches.entityTypeToAccessControlKeysValue[entityType]\n if (cached) return cached\n const accessControlSecrets = Object.values(caches.dataById).flatMap((x) => (x.decrypted ? [x.decrypted.accessControlSecret] : []))\n const fullData = await this.accessControlSecret.getEncodedAccessControlKeys(accessControlSecrets, entityType)\n caches.entityTypeToAccessControlKeysValue[entityType] = fullData\n return fullData\n }\n\n async getAllDelegationKeys(entityType: EntityWithDelegationTypeName): Promise<string[] | undefined> {\n const caches = await this.caches\n const accessControlSecrets = Object.values(caches.dataById).flatMap((x) => (x.decrypted ? [x.decrypted.accessControlSecret] : []))\n const res: string[] = []\n for (const accessControlSecret of accessControlSecrets) {\n // Usage of sfks in secure delegation key should be configurable: it is not necessary for all users and it has some performance impact\n res.push(await this.accessControlSecret.secureDelegationKeyFor(accessControlSecret, entityType, undefined))\n }\n return res\n }\n}\n\nclass LimitedLruCacheExchangeDataManager extends AbstractExchangeDataManager {\n private readonly idToDataCache: LruTemporisedAsyncCache<string, CachedExchangeData & { hashes: string[] }>\n private readonly hashToId: Map<string, string> = new Map()\n private readonly delegateToVerifiedEncryptionDataId: Map<string, string> = new Map()\n\n constructor(\n base: BaseExchangeDataManager,\n encryptionKeys: UserEncryptionKeysManager,\n signatureKeys: UserSignatureKeysManager,\n accessControlSecret: AccessControlSecretUtils,\n cryptoStrategies: CryptoStrategies,\n dataOwnerApi: IccDataOwnerXApi,\n primitives: CryptoPrimitives,\n useParentKeys: boolean,\n optionalParameters: {\n lruCacheSize?: number\n }\n ) {\n super(base, encryptionKeys, signatureKeys, accessControlSecret, cryptoStrategies, dataOwnerApi, primitives, useParentKeys)\n this.idToDataCache = new LruTemporisedAsyncCache(optionalParameters.lruCacheSize ?? 2000, () => -1)\n }\n\n async clearOrRepopulateCache(): Promise<void> {\n this.idToDataCache.clear(false)\n this.hashToId.clear()\n this.delegateToVerifiedEncryptionDataId.clear()\n }\n\n async getCachedDecryptionDataKeyByAccessControlHash(\n hashes: string[],\n entityType: EntityWithDelegationTypeName,\n entitySecretForeignKeys: string[]\n ): Promise<{ [p: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } }> {\n const res: { [p: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } } = {}\n for (const hash of hashes) {\n const dataId = this.hashToId.get(hash)\n if (dataId) {\n const retrieved = await this.idToDataCache.get(dataId, () => {\n throw new Error(`Data with id ${dataId} should have been already cached.`)\n })\n if (retrieved.decrypted) {\n res[hash] = {\n exchangeData: retrieved.exchangeData,\n exchangeKey: retrieved.decrypted.exchangeKey,\n accessControlSecret: retrieved.decrypted.accessControlSecret,\n }\n }\n }\n }\n return res\n }\n\n private async secureDelegationKeysForAllEntitiesNoSfkAndSpecificEntitySfksPairs(\n accessControlSecret: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined\n ): Promise<string[]> {\n const noSfkDelegationKeys = await Promise.all(\n [...entityWithDelegationTypeNames].map((t) => this.accessControlSecret.secureDelegationKeyFor(accessControlSecret, t, undefined))\n )\n if (entityType && entitySecretForeignKeys?.length) {\n // Usage of sfks in secure delegation key should be configurable: it is not necessary for all users and it has some performance impact\n // `secureDelegationKeysFor` is currently ignoring the sfks\n return [\n ...noSfkDelegationKeys,\n ...(await this.accessControlSecret.secureDelegationKeysFor(accessControlSecret, entityType, entitySecretForeignKeys)),\n ]\n } else {\n return noSfkDelegationKeys\n }\n }\n\n async getDecryptionDataKeyById(\n id: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n retrieveIfNotCached: boolean\n ): Promise<{ exchangeData: ExchangeData; exchangeKey: CryptoKey | undefined; accessControlSecret: string | undefined } | undefined> {\n const cached = await this.idToDataCache.getIfCachedJob(id)\n if (cached) {\n const updated = await this.idToDataCache.get(\n id,\n async (prevData) => {\n const toUpdate = prevData ?? cached.item\n if (toUpdate.decrypted) {\n // Usage of sfks in secure delegation key should be configurable: it is not necessary for all users, and it has some performance impact\n // `secureDelegationKeysFor` is currently ignoring the sfks\n if (entityType && entitySecretForeignKeys) {\n const hashes = await this.accessControlSecret.secureDelegationKeysFor(\n toUpdate.decrypted.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n hashes.forEach((hash) => {\n this.hashToId.set(hash, toUpdate.exchangeData.id!)\n })\n toUpdate.hashes.push(...hashes)\n }\n }\n return { item: toUpdate, onEviction: (b) => this.doOnEvictionJob(b, toUpdate) }\n },\n () => true\n )\n return {\n exchangeData: updated.exchangeData,\n exchangeKey: updated.decrypted?.exchangeKey,\n accessControlSecret: updated.decrypted?.accessControlSecret,\n }\n } else if (retrieveIfNotCached) {\n return await this.idToDataCache\n .get(id, async () =>\n this.cacheJob(async () => {\n const data = await this.base.getExchangeDataById(id)\n if (!data) throw new Error(`Could not find exchange data with id ${id}`)\n const decrypted = await this.decryptData(data)\n if (decrypted) {\n const hashes = await this.secureDelegationKeysForAllEntitiesNoSfkAndSpecificEntitySfksPairs(\n decrypted.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n return { exchangeData: data, hashes, decrypted, verified: decrypted.verified }\n } else {\n return { exchangeData: data, hashes: [], verified: false }\n }\n })\n )\n .then((x) => ({ exchangeData: x.exchangeData, exchangeKey: x.decrypted?.exchangeKey, accessControlSecret: x.decrypted?.accessControlSecret }))\n } else return undefined\n }\n\n async getOrCreateEncryptionDataTo(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }> {\n let existingId = this.delegateToVerifiedEncryptionDataId.get(delegateId)\n if (!existingId) {\n await this.populateCacheToDelegate(delegateId, entityType, entitySecretForeignKeys)\n existingId = this.delegateToVerifiedEncryptionDataId.get(delegateId)\n }\n if (existingId) {\n const cached = await this.idToDataCache.getIfCachedJob(existingId)\n if (!cached) throw new Error(`Illegal state: data with id ${existingId} should have been in cache`)\n if (cached.item.decrypted) {\n return {\n exchangeData: cached.item.exchangeData,\n exchangeKey: cached.item.decrypted.exchangeKey,\n accessControlSecret: cached.item.decrypted.accessControlSecret,\n }\n } else throw new Error(`Illegal state: cached verified data should be decrypted.`)\n } else {\n const newDataId = this.primitives.randomUuid()\n this.delegateToVerifiedEncryptionDataId.set(delegateId, newDataId)\n const createdAndCachedData = await this.idToDataCache.get(newDataId, () =>\n this.cacheJob(async () => {\n const created = await this.createNewExchangeData(delegateId, newDataId)\n const hashes = await this.secureDelegationKeysForAllEntitiesNoSfkAndSpecificEntitySfksPairs(\n created.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n return {\n exchangeData: created.exchangeData,\n decrypted: {\n accessControlSecret: created.accessControlSecret,\n exchangeKey: created.exchangeKey,\n verified: true,\n },\n hashes,\n }\n })\n )\n if (!createdAndCachedData) throw new Error('Data should have been successfully created')\n return {\n exchangeData: createdAndCachedData.exchangeData,\n exchangeKey: createdAndCachedData.decrypted!.exchangeKey,\n accessControlSecret: createdAndCachedData.decrypted!.accessControlSecret,\n }\n }\n }\n\n // Loads and adds to the cache all exchange data from the current data owner to the given delegate. Allows to check if there is already data from\n // the current data owner to the delegate which is good for encryption.\n private async populateCacheToDelegate(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined\n ): Promise<void> {\n const dataToDelegate = await this.base.getExchangeDataByDelegatorDelegatePair(await this.dataOwnerApi.getCurrentDataOwnerId(), delegateId)\n await Promise.all(\n dataToDelegate.map(async (data) => {\n await this.idToDataCache.get(data.id!, () =>\n this.cacheJob(async () => {\n const decrypted = await this.decryptData(data)\n if (decrypted) {\n const hashes = await this.secureDelegationKeysForAllEntitiesNoSfkAndSpecificEntitySfksPairs(\n decrypted.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n return { exchangeData: data, hashes, decrypted }\n } else {\n return { exchangeData: data, hashes: [] }\n }\n })\n )\n })\n )\n }\n\n private async cacheJob(\n retrieveDecryptedDataInfo: () => Promise<CachedExchangeData & { hashes: string[] }>\n ): Promise<{ item: CachedExchangeData & { hashes: string[] }; onEviction: (isReplacement: boolean) => void }> {\n const info = await retrieveDecryptedDataInfo()\n info.hashes.forEach((hash) => this.hashToId.set(hash, info?.exchangeData.id!))\n if (info.decrypted?.verified) this.delegateToVerifiedEncryptionDataId.set(info.exchangeData.delegate, info.exchangeData.id!)\n const item = {\n exchangeData: info.exchangeData,\n hashes: info.hashes,\n decrypted: info.decrypted,\n }\n return {\n item,\n onEviction: (b) => this.doOnEvictionJob(b, item),\n }\n }\n\n private async doOnEvictionJob(isReplacement: boolean, item: CachedExchangeData & { hashes: string[] }) {\n if (!isReplacement) {\n item.hashes.forEach((hash) => this.hashToId.delete(hash))\n if (this.delegateToVerifiedEncryptionDataId.get(item.exchangeData.delegate) === item.exchangeData.id) {\n this.delegateToVerifiedEncryptionDataId.delete(item.exchangeData.delegate)\n }\n }\n }\n\n getAccessControlKeysValue(entityType: EntityWithDelegationTypeName): Promise<string | undefined> {\n return Promise.resolve(undefined)\n }\n\n getAllDelegationKeys(entityType: EntityWithDelegationTypeName): Promise<string[] | undefined> {\n return Promise.resolve(undefined)\n }\n}\n"]}
1
+ {"version":3,"file":"ExchangeDataManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExchangeDataManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAOA,mCAAgH;AAEhH,oCAAyC;AACzC,oFAA6E;AAC7E,wFAAmH;AACnH,yEAA6E;AAO7E;;;GAGG;AACH,SAAsB,gDAAgD,CACpE,IAA6B,EAC7B,cAAyC,EACzC,aAAuC,EACvC,mBAA6C,EAC7C,gBAAkC,EAClC,YAA8B,EAC9B,UAA4B,EAC5B,aAAsB,EACtB,qBAA4D,EAAE;;QAE9D,MAAM,YAAY,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;;KACF;IAEa,eAAe,CAAC,aAAsB,EAAE,IAA+C;;YACnG,IAAI,CAAC,aAAa,EAAE;gBAClB,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;gBACzD,IAAI,IAAI,CAAC,kCAAkC,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE;oBACpG,IAAI,CAAC,kCAAkC,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAA;iBAC3E;aACF;QACH,CAAC;KAAA;IAED,yBAAyB,CAAC,UAAwC;QAChE,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;IACnC,CAAC;IAED,oBAAoB,CAAC,UAAwC;QAC3D,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;IACnC,CAAC;CACF","sourcesContent":["import { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { BaseExchangeDataManager } from './BaseExchangeDataManager'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { UserSignatureKeysManager } from './UserSignatureKeysManager'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { fingerprintV1, getShaVersionForKey, hexPublicKeysWithSha1Of, hexPublicKeysWithSha256Of } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { hex2ua, ua2b64 } from '../utils'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { EntityWithDelegationTypeName, entityWithDelegationTypeNames } from '../utils/EntityWithDelegationTypeName'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\nexport type ExchangeDataManagerOptionalParameters = {\n // Only for not fully cached implementation (data owner can't request all his exchange data), amount of exchange data which can be cached\n lruCacheSize?: number // default = 2000\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice.\n * Initialises and returns the exchange data manager which is most appropriate for the current data owner.\n */\nexport async function initialiseExchangeDataManagerForCurrentDataOwner(\n base: BaseExchangeDataManager,\n encryptionKeys: UserEncryptionKeysManager,\n signatureKeys: UserSignatureKeysManager,\n accessControlSecret: AccessControlSecretUtils,\n cryptoStrategies: CryptoStrategies,\n dataOwnerApi: IccDataOwnerXApi,\n primitives: CryptoPrimitives,\n useParentKeys: boolean,\n optionalParameters: ExchangeDataManagerOptionalParameters = {}\n): Promise<ExchangeDataManager> {\n const currentOwner = CryptoActorStubWithType.fromDataOwner(await dataOwnerApi.getCurrentDataOwner())\n if (cryptoStrategies.dataOwnerRequiresAnonymousDelegation(currentOwner)) {\n const res = new FullyCachedExchangeDataManager(\n base,\n encryptionKeys,\n signatureKeys,\n accessControlSecret,\n cryptoStrategies,\n dataOwnerApi,\n primitives,\n useParentKeys\n )\n await res.clearOrRepopulateCache()\n return res\n } else {\n return new LimitedLruCacheExchangeDataManager(\n base,\n encryptionKeys,\n signatureKeys,\n accessControlSecret,\n cryptoStrategies,\n dataOwnerApi,\n primitives,\n useParentKeys,\n optionalParameters\n )\n }\n}\n\ntype CachedExchangeData = {\n exchangeData: ExchangeData\n decrypted?: {\n accessControlSecret: string\n exchangeKey: CryptoKey\n verified: boolean\n }\n}\n\n/**\n * @internal this class is intended for internal use only and may be changed without notice.\n * Exchange data manager which automatically handles decryption and cache\n */\nexport interface ExchangeDataManager {\n readonly base: BaseExchangeDataManager\n\n /**\n * Updates all exchange data between the current data owner and another data owner to allow the other data owner to access existing exchange data\n * using a new public key. Note that this will make existing exchange keys from the other data owner to the current data owner unverified, therefore\n * invalid for encryption.\n * @param otherDataOwner the other data owner.\n * @param newDataOwnerPublicKey a new public key of the other data owner.\n */\n giveAccessBackTo(otherDataOwner: string, newDataOwnerPublicKey: string): Promise<void>\n\n /**\n * Gets any existing and verified exchange data from the current data owner to the provided delegate or creates new data if no verified data is\n * available, then caches it. The {@link entityType} and {@link entitySecretForeignKeys} will be used for the secure-delegation-hash-based cache\n * of the exchange data and not for actually creating the exchange data.\n * @param delegateId the id of the delegate.\n * @param entityType type of the entity for which you want to create new metadata.\n * @param entitySecretForeignKeys the secret foreign keys of the entity which you want to create new metadata.\n * @param allowCreationWithoutDelegateKey if true, when creating new exchange data, even if no verified key is available for the delegate the method\n * will create the new exchange data anyway (will not be usable by the delegate without additional steps).\n * @return the access control secret and key of the data to use for encryption.\n */\n getOrCreateEncryptionDataTo(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n allowCreationWithoutDelegateKey: boolean\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }>\n\n /**\n * Retrieve the cached decrypted exchange data key associated with any of the provided hashes/entry keys of secure delegations. Depending on the\n * implementation the {@link entityType} and {@link entitySecretForeignKeys} may be used to improve the secure-delegation-hash-based cache of\n * exchange data from the other available exchange data caches.\n * @param hashes hashes of access control secrets for a specific entity, as they appear in the key of secure delegation entries\n * @param entityType type of the entity containing the metadata for which you are retrieving the encryption key.\n * @param entitySecretForeignKeys the secret foreign keys of the entity containing the metadata for which you are retrieving the encryption key.\n * @return the exchange data and decrypted key associated to that hash if cached\n */\n getCachedDecryptionDataKeyByAccessControlHash(\n hashes: string[],\n entityType: EntityWithDelegationTypeName,\n entitySecretForeignKeys: string[]\n ): Promise<{ [hash: string]: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey } }>\n\n /**\n * Retrieves the exchange data with the provided id (from the cache if available or from the server otherwise if allowed by\n * {@link retrieveIfNotCached}) and attempts to decrypt it, then caches the result. The {@link entityType} and {@link entitySecretForeignKeys} will\n * be used for the secure-delegation-hash-based cache of the exchange data.\n * @param id id of the exchange data\n * @param entityType type of the entity containing the metadata for which you are retrieving the encryption key.\n * @param entitySecretForeignKeys the secret foreign keys of the entity containing the metadata for which you are retrieving the encryption key.\n * @param retrieveIfNotCached if false and there is no cached exchange data with the provided id the method returns undefined, else the method will\n * attempt to load the exchange data from the server.\n * @return undefined if the exchange data is not cached and {@link retrieveIfNotCached} is false. Else an object containing:\n * - exchangeData: the exchange data with the provided id\n * - exchangeKey: the exchange key corresponding to the provided exchange data if it could be decrypted, else undefined\n * @throws if no exchange data with the given id is cached and {@link retrieveIfNotCached} is true and the data could not be found in the server\n * either.\n */\n getDecryptionDataKeyById(\n id: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n retrieveIfNotCached: boolean\n ): Promise<{ exchangeKey: CryptoKey | undefined; accessControlSecret: string | undefined; exchangeData: ExchangeData } | undefined>\n\n /**\n * Clears the cache or fully repopulates the cache if the current data owner can retrieve all of his exchange data according to the crypto\n * strategies.\n */\n clearOrRepopulateCache(): Promise<void>\n\n /**\n * If the current data owner requires anonymous delegations this returns the base64 representation of the concatenation of all available access\n * control keys for the current data owner.\n */\n getAccessControlKeysValue(entityType: EntityWithDelegationTypeName): Promise<string | undefined>\n\n /**\n * If the current data owner requires anonymous delegations this returns the access control keys which may be used in secure delegations for the\n * data owner, which can be used to search for data.\n */\n getAllDelegationKeys(entityType: EntityWithDelegationTypeName): Promise<string[] | undefined>\n}\n\nabstract class AbstractExchangeDataManager implements ExchangeDataManager {\n constructor(\n readonly base: BaseExchangeDataManager,\n protected readonly encryptionKeys: UserEncryptionKeysManager,\n protected readonly signatureKeys: UserSignatureKeysManager,\n protected readonly accessControlSecret: AccessControlSecretUtils,\n protected readonly cryptoStrategies: CryptoStrategies,\n protected readonly dataOwnerApi: IccDataOwnerXApi,\n protected readonly primitives: CryptoPrimitives,\n private readonly useParentKeys: boolean\n ) {}\n\n protected async decryptData(data: ExchangeData): Promise<\n | {\n accessControlSecret: string\n exchangeKey: CryptoKey\n verified: boolean\n }\n | undefined\n > {\n const decryptionKeys = this.encryptionKeys.getDecryptionKeys()\n const decryptedExchangeKey = (await this.base.tryDecryptExchangeKeys([data], decryptionKeys)).successfulDecryptions[0]\n if (!decryptedExchangeKey) return undefined\n const decryptedAccessControlSecret = (await this.base.tryDecryptAccessControlSecret([data], decryptionKeys)).successfulDecryptions[0]\n if (!decryptedAccessControlSecret)\n throw new Error(`Decryption key could be decrypted but access control secret could not for data ${JSON.stringify(data)}`)\n const decryptedSharedSignatureKey = (await this.base.tryDecryptSharedSignatureKeys([data], decryptionKeys)).successfulDecryptions[0]\n if (!decryptedSharedSignatureKey)\n throw new Error(`Decryption key could be decrypted but shared signature key could not for data ${JSON.stringify(data)}`)\n return {\n accessControlSecret: decryptedAccessControlSecret,\n exchangeKey: decryptedExchangeKey,\n verified: await this.base.verifyExchangeData(\n {\n exchangeData: data,\n decryptedAccessControlSecret,\n decryptedExchangeKey,\n decryptedSharedSignatureKey,\n },\n (fp) => this.signatureKeys.getSignatureVerificationKey(fp),\n true\n ),\n }\n }\n\n protected async createNewExchangeData(\n delegateId: string,\n options: {\n newDataId?: string\n allowNoDelegateKeys?: boolean\n }\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }> {\n const encryptionKeys: { [fp: string]: CryptoKey } = {}\n this.encryptionKeys.getSelfVerifiedKeys().forEach(({ fingerprint, pair }) => {\n encryptionKeys[fingerprint] = pair.publicKey\n })\n if (delegateId != (await this.dataOwnerApi.getCurrentDataOwnerId())) {\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n const sha256KeysOfDelegate = hexPublicKeysWithSha256Of(delegate.stub)\n const sha1KeysOfDelegate = hexPublicKeysWithSha1Of(delegate.stub)\n let allVerifiedDelegateKeys: string[]\n if (!sha256KeysOfDelegate.size && !sha1KeysOfDelegate.size) {\n if (!options.allowNoDelegateKeys)\n throw new Error(`Could not create exchange data to ${delegateId} as no public key for the delegate was found.`)\n allVerifiedDelegateKeys = []\n } else if (this.useParentKeys && (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).includes(delegateId)) {\n allVerifiedDelegateKeys = await this.encryptionKeys.getVerifiedPublicKeysFor(delegate.stub)\n } else {\n allVerifiedDelegateKeys = await this.cryptoStrategies.verifyDelegatePublicKeys(\n delegate,\n [...Array.from(sha256KeysOfDelegate), ...Array.from(sha1KeysOfDelegate)],\n this.primitives\n )\n }\n if (!allVerifiedDelegateKeys.length && !options.allowNoDelegateKeys)\n throw new Error(`Could not create exchange data to ${delegateId} as no public key for the delegate could be verified.`)\n for (const delegateKey of allVerifiedDelegateKeys) {\n if (sha1KeysOfDelegate.has(delegateKey)) {\n encryptionKeys[fingerprintV1(delegateKey)] = await this.primitives.RSA.importKey('spki', hex2ua(delegateKey), ['encrypt'], 'sha-1')\n } else if (sha256KeysOfDelegate.has(delegateKey)) {\n encryptionKeys[fingerprintV1(delegateKey)] = await this.primitives.RSA.importKey('spki', hex2ua(delegateKey), ['encrypt'], 'sha-256')\n } else throw new Error('Illegal state: verified keys should contain only keys for OAPE-SHA1 or OAPE-SHA256.')\n }\n }\n const signatureKey = await this.signatureKeys.getOrCreateSignatureKeyPair()\n const newData = await this.base.createExchangeData(\n delegateId,\n { [signatureKey.fingerprint]: signatureKey.keyPair.privateKey },\n encryptionKeys,\n options.newDataId ? { id: options.newDataId } : {}\n )\n return {\n exchangeData: newData.exchangeData,\n accessControlSecret: newData.accessControlSecret,\n exchangeKey: newData.exchangeKey,\n }\n }\n\n async giveAccessBackTo(otherDataOwner: string, newDataOwnerPublicKey: string) {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n const newKeyFp = fingerprintV1(newDataOwnerPublicKey)\n const other = await this.dataOwnerApi.getCryptoActorStub(otherDataOwner)\n const newKeyHashVersion = getShaVersionForKey(other.stub, newDataOwnerPublicKey)\n if (!newKeyHashVersion) throw new Error(`Public key not found for data owner ${otherDataOwner}`)\n const importedNewKey = await this.primitives.RSA.importKey('spki', hex2ua(newDataOwnerPublicKey), ['encrypt'], newKeyHashVersion)\n const signatureKey = await this.signatureKeys.getOrCreateSignatureKeyPair()\n const decryptionKeys = this.encryptionKeys.getDecryptionKeys()\n const allExchangeDataToUpdate =\n self == otherDataOwner\n ? await this.base.getExchangeDataByDelegatorDelegatePair(self, self)\n : [\n ...(await this.base.getExchangeDataByDelegatorDelegatePair(self, otherDataOwner)),\n ...(await this.base.getExchangeDataByDelegatorDelegatePair(otherDataOwner, self)),\n ]\n for (const dataToUpdate of allExchangeDataToUpdate) {\n if (!Object.keys(dataToUpdate.exchangeKey).find((fp) => fp == newKeyFp)) {\n const updated = await this.base.tryUpdateExchangeData(dataToUpdate, decryptionKeys, { [newKeyFp]: importedNewKey })\n if (!updated) {\n console.warn(`Failed to give access back to exchanged data ${JSON.stringify(dataToUpdate)}`)\n }\n }\n }\n }\n\n clearOrRepopulateCache(): Promise<void> {\n throw new Error('Implemented by concrete class')\n }\n\n getOrCreateEncryptionDataTo(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n allowCreationWithoutDelegateKey: boolean\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }> {\n throw new Error('Implemented by concrete class')\n }\n\n getCachedDecryptionDataKeyByAccessControlHash(\n hashes: string[],\n entityType: EntityWithDelegationTypeName,\n entitySecretForeignKeys: string[]\n ): Promise<{ [p: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } }> {\n throw new Error('Implemented by concrete class')\n }\n\n getDecryptionDataKeyById(\n id: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n retrieveIfNotCached: boolean\n ): Promise<{ exchangeData: ExchangeData; exchangeKey: CryptoKey | undefined; accessControlSecret: string | undefined } | undefined> {\n throw new Error('Implemented by concrete class')\n }\n\n getAccessControlKeysValue(entityType: EntityWithDelegationTypeName): Promise<string | undefined> {\n throw new Error('Implemented by concrete class')\n }\n\n getAllDelegationKeys(entityType: EntityWithDelegationTypeName): Promise<string[] | undefined> {\n throw new Error('Implemented by concrete class')\n }\n}\n\nclass FullyCachedExchangeDataManager extends AbstractExchangeDataManager {\n private caches: Promise<{\n dataById: { [id: string]: CachedExchangeData }\n hashToId: Map<string, string>\n delegateToVerifiedEncryptionDataId: { [delegate: string]: string }\n entityTypeToAccessControlKeysValue: { [entityType in EntityWithDelegationTypeName]?: string }\n }> = Promise.resolve({ dataById: {}, hashToId: new Map(), delegateToVerifiedEncryptionDataId: {}, entityTypeToAccessControlKeysValue: {} })\n\n async clearOrRepopulateCache(): Promise<void> {\n this.caches = this.doRepopulateCache()\n await this.caches\n }\n\n async getCachedDecryptionDataKeyByAccessControlHash(\n hashes: string[],\n entityType: EntityWithDelegationTypeName,\n entitySecretForeignKeys: string[]\n ): Promise<{ [hash: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } }> {\n function retrieveByHashesFromCaches(caches: {\n dataById: { [id: string]: CachedExchangeData }\n hashToId: Map<string, string>\n delegateToVerifiedEncryptionDataId: { [delegate: string]: string }\n }): { [hash: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } } {\n return hashes.reduce((res, hash) => {\n const id = caches.hashToId.get(hash)\n if (id) {\n const cached = caches.dataById[id]\n if (cached?.decrypted) {\n res[hash] = {\n exchangeData: cached.exchangeData,\n exchangeKey: cached.decrypted.exchangeKey,\n accessControlSecret: cached.decrypted.accessControlSecret,\n }\n }\n }\n return res\n }, {} as { [hash: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } })\n }\n\n const retrievedFromHashesCache = retrieveByHashesFromCaches(await this.caches)\n if (Object.keys(retrievedFromHashesCache).length) {\n return retrievedFromHashesCache\n } else {\n this.caches = this.caches.then(async (caches) => {\n for (const currData of Object.values(caches.dataById)) {\n if (currData.decrypted) {\n const currDataHashes = await this.accessControlSecret.secureDelegationKeysFor(\n currData.decrypted.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n currDataHashes.forEach((hash) => caches.hashToId.set(hash, currData.exchangeData.id!))\n }\n }\n return caches\n })\n return retrieveByHashesFromCaches(await this.caches)\n }\n }\n\n async getOrCreateEncryptionDataTo(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n allowCreationWithoutDelegateKey: boolean\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }> {\n const caches = await this.caches\n const dataId = caches.delegateToVerifiedEncryptionDataId[delegateId]\n const cached = dataId ? caches.dataById[dataId] : undefined\n if (cached && cached?.decrypted) {\n return {\n exchangeData: cached.exchangeData,\n accessControlSecret: cached.decrypted.accessControlSecret,\n exchangeKey: cached.decrypted.exchangeKey,\n }\n }\n // TODO this could technically allow for 2 concurrent exchange data creations, needs fix\n const created = await this.createNewExchangeData(delegateId, { allowNoDelegateKeys: allowCreationWithoutDelegateKey })\n this.cacheData(\n created.exchangeData,\n true,\n { accessControlSecret: created.accessControlSecret, exchangeKey: created.exchangeKey, verified: true },\n entityType,\n entitySecretForeignKeys\n )\n return created\n }\n\n async getDecryptionDataKeyById(\n id: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n retrieveIfNotCached: boolean\n ): Promise<{ exchangeData: ExchangeData; exchangeKey: CryptoKey | undefined; accessControlSecret: string | undefined } | undefined> {\n const caches = await this.caches\n const cachedData = caches.dataById[id]\n if (cachedData) {\n return {\n exchangeData: cachedData.exchangeData,\n exchangeKey: cachedData.decrypted?.exchangeKey,\n accessControlSecret: cachedData.decrypted?.accessControlSecret,\n }\n } else if (retrieveIfNotCached) {\n const data = await this.base.getExchangeDataById(id)\n if (!data) throw new Error(`Could not find exchange data with id ${id}`)\n const decrypted = await this.decryptData(data)\n this.cacheData(data, false, decrypted, entityType, entitySecretForeignKeys)\n return { exchangeData: data, exchangeKey: decrypted?.exchangeKey, accessControlSecret: decrypted?.accessControlSecret }\n } else return undefined\n }\n\n private cacheData(\n exchangeData: ExchangeData,\n isNewData: boolean,\n decrypted: { accessControlSecret: string; exchangeKey: CryptoKey; verified: boolean } | undefined,\n entityType?: EntityWithDelegationTypeName,\n entitySecretForeignKeys?: string[]\n ): void {\n this.caches = this.caches.then(async (caches) => {\n caches.dataById[exchangeData.id!] = { exchangeData, decrypted }\n if (decrypted) {\n // Usage of sfks in secure delegation key should be configurable: it is not necessary for all users and it has some performance impact\n // `secureDelegationKeysFor` is currently ignoring the sfks\n if (entityType && entitySecretForeignKeys) {\n const hashes = await this.accessControlSecret.secureDelegationKeysFor(decrypted.accessControlSecret, entityType, entitySecretForeignKeys)\n hashes.forEach((hash) => {\n caches.hashToId.set(hash, exchangeData.id!)\n })\n }\n if (decrypted.verified) {\n caches.delegateToVerifiedEncryptionDataId[exchangeData.delegate] = exchangeData.id!\n }\n }\n if (isNewData) caches.entityTypeToAccessControlKeysValue = {}\n return caches\n })\n }\n\n private async doRepopulateCache(): Promise<{\n dataById: { [id: string]: CachedExchangeData }\n hashToId: Map<string, string>\n delegateToVerifiedEncryptionDataId: { [delegate: string]: string }\n entityTypeToAccessControlKeysValue: { [entityType in EntityWithDelegationTypeName]?: string }\n }> {\n const allData = await this.base.getAllExchangeDataForCurrentDataOwnerIfAllowed()\n if (!allData) throw new Error('Impossible to use fully cached exchange data manager for current data owner.')\n const dataById: { [id: string]: CachedExchangeData } = {}\n const hashToId = new Map<string, string>()\n const delegateToVerifiedEncryptionDataId: { [delegate: string]: string } = {}\n for (const currData of allData) {\n const currDecrypted = await this.decryptData(currData)\n dataById[currData.id!] = { exchangeData: currData, decrypted: currDecrypted }\n if (currDecrypted?.verified) {\n delegateToVerifiedEncryptionDataId[currData.delegate] = currData.id!\n }\n }\n const entityTypeToAccessControlKeysValue: { [entityType in EntityWithDelegationTypeName]?: string } = {}\n return { dataById, hashToId, delegateToVerifiedEncryptionDataId, entityTypeToAccessControlKeysValue }\n }\n\n async getAccessControlKeysValue(entityType: EntityWithDelegationTypeName): Promise<string | undefined> {\n const caches = await this.caches\n const cached = caches.entityTypeToAccessControlKeysValue[entityType]\n if (cached) return cached\n const accessControlSecrets = Object.values(caches.dataById).flatMap((x) => (x.decrypted ? [x.decrypted.accessControlSecret] : []))\n const fullData = await this.accessControlSecret.getEncodedAccessControlKeys(accessControlSecrets, entityType)\n caches.entityTypeToAccessControlKeysValue[entityType] = fullData\n return fullData\n }\n\n async getAllDelegationKeys(entityType: EntityWithDelegationTypeName): Promise<string[] | undefined> {\n const caches = await this.caches\n const accessControlSecrets = Object.values(caches.dataById).flatMap((x) => (x.decrypted ? [x.decrypted.accessControlSecret] : []))\n const res: string[] = []\n for (const accessControlSecret of accessControlSecrets) {\n // Usage of sfks in secure delegation key should be configurable: it is not necessary for all users and it has some performance impact\n res.push(await this.accessControlSecret.secureDelegationKeyFor(accessControlSecret, entityType, undefined))\n }\n return res\n }\n}\n\nclass LimitedLruCacheExchangeDataManager extends AbstractExchangeDataManager {\n private readonly idToDataCache: LruTemporisedAsyncCache<string, CachedExchangeData & { hashes: string[] }>\n private readonly hashToId: Map<string, string> = new Map()\n private readonly delegateToVerifiedEncryptionDataId: Map<string, string> = new Map()\n\n constructor(\n base: BaseExchangeDataManager,\n encryptionKeys: UserEncryptionKeysManager,\n signatureKeys: UserSignatureKeysManager,\n accessControlSecret: AccessControlSecretUtils,\n cryptoStrategies: CryptoStrategies,\n dataOwnerApi: IccDataOwnerXApi,\n primitives: CryptoPrimitives,\n useParentKeys: boolean,\n optionalParameters: {\n lruCacheSize?: number\n }\n ) {\n super(base, encryptionKeys, signatureKeys, accessControlSecret, cryptoStrategies, dataOwnerApi, primitives, useParentKeys)\n this.idToDataCache = new LruTemporisedAsyncCache(optionalParameters.lruCacheSize ?? 2000, () => -1)\n }\n\n async clearOrRepopulateCache(): Promise<void> {\n this.idToDataCache.clear(false)\n this.hashToId.clear()\n this.delegateToVerifiedEncryptionDataId.clear()\n }\n\n async getCachedDecryptionDataKeyByAccessControlHash(\n hashes: string[],\n entityType: EntityWithDelegationTypeName,\n entitySecretForeignKeys: string[]\n ): Promise<{ [p: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } }> {\n const res: { [p: string]: { exchangeData: ExchangeData; exchangeKey: CryptoKey; accessControlSecret: string } } = {}\n for (const hash of hashes) {\n const dataId = this.hashToId.get(hash)\n if (dataId) {\n const retrieved = await this.idToDataCache.get(dataId, () => {\n throw new Error(`Data with id ${dataId} should have been already cached.`)\n })\n if (retrieved.decrypted) {\n res[hash] = {\n exchangeData: retrieved.exchangeData,\n exchangeKey: retrieved.decrypted.exchangeKey,\n accessControlSecret: retrieved.decrypted.accessControlSecret,\n }\n }\n }\n }\n return res\n }\n\n private async secureDelegationKeysForAllEntitiesNoSfkAndSpecificEntitySfksPairs(\n accessControlSecret: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined\n ): Promise<string[]> {\n const noSfkDelegationKeys = await Promise.all(\n [...entityWithDelegationTypeNames].map((t) => this.accessControlSecret.secureDelegationKeyFor(accessControlSecret, t, undefined))\n )\n if (entityType && entitySecretForeignKeys?.length) {\n // Usage of sfks in secure delegation key should be configurable: it is not necessary for all users and it has some performance impact\n // `secureDelegationKeysFor` is currently ignoring the sfks\n return [\n ...noSfkDelegationKeys,\n ...(await this.accessControlSecret.secureDelegationKeysFor(accessControlSecret, entityType, entitySecretForeignKeys)),\n ]\n } else {\n return noSfkDelegationKeys\n }\n }\n\n async getDecryptionDataKeyById(\n id: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n retrieveIfNotCached: boolean\n ): Promise<{ exchangeData: ExchangeData; exchangeKey: CryptoKey | undefined; accessControlSecret: string | undefined } | undefined> {\n const cached = await this.idToDataCache.getIfCachedJob(id)\n if (cached) {\n const updated = await this.idToDataCache.get(\n id,\n async (prevData) => {\n const toUpdate = prevData ?? cached.item\n if (toUpdate.decrypted) {\n // Usage of sfks in secure delegation key should be configurable: it is not necessary for all users, and it has some performance impact\n // `secureDelegationKeysFor` is currently ignoring the sfks\n if (entityType && entitySecretForeignKeys) {\n const hashes = await this.accessControlSecret.secureDelegationKeysFor(\n toUpdate.decrypted.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n hashes.forEach((hash) => {\n this.hashToId.set(hash, toUpdate.exchangeData.id!)\n })\n toUpdate.hashes.push(...hashes)\n }\n }\n return { item: toUpdate, onEviction: (b) => this.doOnEvictionJob(b, toUpdate) }\n },\n () => true\n )\n return {\n exchangeData: updated.exchangeData,\n exchangeKey: updated.decrypted?.exchangeKey,\n accessControlSecret: updated.decrypted?.accessControlSecret,\n }\n } else if (retrieveIfNotCached) {\n return await this.idToDataCache\n .get(id, async () =>\n this.cacheJob(async () => {\n const data = await this.base.getExchangeDataById(id)\n if (!data) throw new Error(`Could not find exchange data with id ${id}`)\n const decrypted = await this.decryptData(data)\n if (decrypted) {\n const hashes = await this.secureDelegationKeysForAllEntitiesNoSfkAndSpecificEntitySfksPairs(\n decrypted.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n return { exchangeData: data, hashes, decrypted, verified: decrypted.verified }\n } else {\n return { exchangeData: data, hashes: [], verified: false }\n }\n })\n )\n .then((x) => ({ exchangeData: x.exchangeData, exchangeKey: x.decrypted?.exchangeKey, accessControlSecret: x.decrypted?.accessControlSecret }))\n } else return undefined\n }\n\n async getOrCreateEncryptionDataTo(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined,\n allowCreationWithoutDelegateKey: boolean\n ): Promise<{ exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey }> {\n let existingId = this.delegateToVerifiedEncryptionDataId.get(delegateId)\n if (!existingId) {\n await this.populateCacheToDelegate(delegateId, entityType, entitySecretForeignKeys)\n existingId = this.delegateToVerifiedEncryptionDataId.get(delegateId)\n }\n if (existingId) {\n const cached = await this.idToDataCache.getIfCachedJob(existingId)\n if (!cached) throw new Error(`Illegal state: data with id ${existingId} should have been in cache`)\n if (cached.item.decrypted) {\n return {\n exchangeData: cached.item.exchangeData,\n exchangeKey: cached.item.decrypted.exchangeKey,\n accessControlSecret: cached.item.decrypted.accessControlSecret,\n }\n } else throw new Error(`Illegal state: cached verified data should be decrypted.`)\n } else {\n const newDataId = this.primitives.randomUuid()\n this.delegateToVerifiedEncryptionDataId.set(delegateId, newDataId)\n const createdAndCachedData = await this.idToDataCache.get(newDataId, () =>\n this.cacheJob(async () => {\n try {\n const created = await this.createNewExchangeData(delegateId, { newDataId, allowNoDelegateKeys: allowCreationWithoutDelegateKey })\n const hashes = await this.secureDelegationKeysForAllEntitiesNoSfkAndSpecificEntitySfksPairs(\n created.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n return {\n exchangeData: created.exchangeData,\n decrypted: {\n accessControlSecret: created.accessControlSecret,\n exchangeKey: created.exchangeKey,\n verified: true,\n },\n hashes,\n }\n } catch (e) {\n this.delegateToVerifiedEncryptionDataId.delete(delegateId)\n throw e\n }\n })\n )\n if (!createdAndCachedData) throw new Error('Data should have been successfully created')\n return {\n exchangeData: createdAndCachedData.exchangeData,\n exchangeKey: createdAndCachedData.decrypted!.exchangeKey,\n accessControlSecret: createdAndCachedData.decrypted!.accessControlSecret,\n }\n }\n }\n\n // Loads and adds to the cache all exchange data from the current data owner to the given delegate. Allows to check if there is already data from\n // the current data owner to the delegate which is good for encryption.\n private async populateCacheToDelegate(\n delegateId: string,\n entityType: EntityWithDelegationTypeName | undefined,\n entitySecretForeignKeys: string[] | undefined\n ): Promise<void> {\n const dataToDelegate = await this.base.getExchangeDataByDelegatorDelegatePair(await this.dataOwnerApi.getCurrentDataOwnerId(), delegateId)\n await Promise.all(\n dataToDelegate.map(async (data) => {\n await this.idToDataCache.get(data.id!, () =>\n this.cacheJob(async () => {\n const decrypted = await this.decryptData(data)\n if (decrypted) {\n const hashes = await this.secureDelegationKeysForAllEntitiesNoSfkAndSpecificEntitySfksPairs(\n decrypted.accessControlSecret,\n entityType,\n entitySecretForeignKeys\n )\n return { exchangeData: data, hashes, decrypted }\n } else {\n return { exchangeData: data, hashes: [] }\n }\n })\n )\n })\n )\n }\n\n private async cacheJob(\n retrieveDecryptedDataInfo: () => Promise<CachedExchangeData & { hashes: string[] }>\n ): Promise<{ item: CachedExchangeData & { hashes: string[] }; onEviction: (isReplacement: boolean) => void }> {\n const info = await retrieveDecryptedDataInfo()\n info.hashes.forEach((hash) => this.hashToId.set(hash, info?.exchangeData.id!))\n if (info.decrypted?.verified) this.delegateToVerifiedEncryptionDataId.set(info.exchangeData.delegate, info.exchangeData.id!)\n const item = {\n exchangeData: info.exchangeData,\n hashes: info.hashes,\n decrypted: info.decrypted,\n }\n return {\n item,\n onEviction: (b) => this.doOnEvictionJob(b, item),\n }\n }\n\n private async doOnEvictionJob(isReplacement: boolean, item: CachedExchangeData & { hashes: string[] }) {\n if (!isReplacement) {\n item.hashes.forEach((hash) => this.hashToId.delete(hash))\n if (this.delegateToVerifiedEncryptionDataId.get(item.exchangeData.delegate) === item.exchangeData.id) {\n this.delegateToVerifiedEncryptionDataId.delete(item.exchangeData.delegate)\n }\n }\n }\n\n getAccessControlKeysValue(entityType: EntityWithDelegationTypeName): Promise<string | undefined> {\n return Promise.resolve(undefined)\n }\n\n getAllDelegationKeys(entityType: EntityWithDelegationTypeName): Promise<string[] | undefined> {\n return Promise.resolve(undefined)\n }\n}\n"]}
@@ -19,11 +19,6 @@ export declare class ExchangeDataMapManager {
19
19
  [fp: string]: string;
20
20
  };
21
21
  }): Promise<void>;
22
- /**
23
- * Retrieves an Exchange Data Map.
24
- * @param accessControlKeyHash the hex-encoded hash of the Exchange Data Map to retrieve.
25
- */
26
- getExchangeDataMap(accessControlKeyHash: string): Promise<ExchangeDataMap>;
27
22
  /**
28
23
  * Retrieves a batch of Exchange Data Maps.
29
24
  * @param accessControlKeyHashes the hex-encoded hashes of the Exchange Data Maps to retrieve.
@@ -41,17 +41,6 @@ class ExchangeDataMapManager {
41
41
  })));
42
42
  });
43
43
  }
44
- /**
45
- * Retrieves an Exchange Data Map.
46
- * @param accessControlKeyHash the hex-encoded hash of the Exchange Data Map to retrieve.
47
- */
48
- getExchangeDataMap(accessControlKeyHash) {
49
- return __awaiter(this, void 0, void 0, function* () {
50
- const exchangeDataMap = yield this.api.getExchangeDataMapById(accessControlKeyHash);
51
- yield this.exchangeDataMapCache.get(exchangeDataMap.id, () => Promise.resolve({ item: null }));
52
- return exchangeDataMap;
53
- });
54
- }
55
44
  /**
56
45
  * Retrieves a batch of Exchange Data Maps.
57
46
  * @param accessControlKeyHashes the hex-encoded hashes of the Exchange Data Maps to retrieve.
@@ -1 +1 @@
1
- {"version":3,"file":"ExchangeDataMapManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExchangeDataMapManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,oFAA6E;AAE7E,mGAA+F;AAE/F;;;GAGG;AACH,MAAa,sBAAsB;IACjC,YAA6B,GAA0B;QAA1B,QAAG,GAAH,GAAG,CAAuB;QAE/C,yBAAoB,GAA0C,IAAI,oDAAuB,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IAFvD,CAAC;IAI3D;;;;;OAKG;IACG,sBAAsB,CAAC,KAA+D;;YAC1F,MAAM,eAAe,GAA6D,EAAE,CAAA;YACpF,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBAC1C,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,EAAE;oBACxD,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;iBACvB;aACF;YACD,MAAM,IAAI,CAAC,GAAG,CAAC,0BAA0B,CAAC,IAAI,2DAA4B,CAAC,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC,CAA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Cache } from '../utils/lru-temporised-async-cache'\nimport { ExchangeDataMap } from '../../icc-api/model/internal/ExchangeDataMap'\nimport { ExchangeDataMapCreationBatch } from '../../icc-api/model/ExchangeDataMapCreationBatch'\n\n/**\n * @internal this class is intended for internal use only and may be modified without notice\n * This class manages the Exchange Data Map entities, caching with an LRU cache on retrieval.\n */\nexport class ExchangeDataMapManager {\n constructor(private readonly api: IccExchangeDataMapApi) {}\n\n private exchangeDataMapCache: LruTemporisedAsyncCache<string, null> = new LruTemporisedAsyncCache(1000, () => -1)\n\n /**\n * This function creates a batch of Exchange Data Map, ignoring the one that already exist and are already present in the cache.\n * The ones that are not are created and their ids are cached.\n * @param batch a map where each key is the hex-encoded access control key to another map that associates the encoded id of an\n * Exchange Data entity to the fingerprint of the key used to encrypt it.\n */\n async createExchangeDataMaps(batch: { [accessControlKey: string]: { [fp: string]: string } }): Promise<void> {\n const entriesToCreate: { [accessControlKey: string]: { [fp: string]: string } } = {}\n for (const [k, v] of Object.entries(batch)) {\n if (!(await this.exchangeDataMapCache.getIfCachedJob(k))) {\n entriesToCreate[k] = v\n }\n }\n await this.api.createExchangeDataMapBatch(new ExchangeDataMapCreationBatch({ batch: entriesToCreate }))\n await Promise.all(\n Object.keys(entriesToCreate).map(async (entry) => {\n await this.exchangeDataMapCache.get(entry, () => Promise.resolve({ item: null }))\n })\n )\n }\n\n /**\n * Retrieves an Exchange Data Map.\n * @param accessControlKeyHash the hex-encoded hash of the Exchange Data Map to retrieve.\n */\n async getExchangeDataMap(accessControlKeyHash: string): Promise<ExchangeDataMap> {\n const exchangeDataMap = await this.api.getExchangeDataMapById(accessControlKeyHash)\n await this.exchangeDataMapCache.get(exchangeDataMap.id, () => Promise.resolve({ item: null }))\n return exchangeDataMap\n }\n\n /**\n * Retrieves a batch of Exchange Data Maps.\n * @param accessControlKeyHashes the hex-encoded hashes of the Exchange Data Maps to retrieve.\n */\n async getExchangeDataMapBatch(accessControlKeyHashes: string[]): Promise<ExchangeDataMap[]> {\n const exchangeDataMaps = await this.api.getExchangeDataMapByBatch(accessControlKeyHashes)\n await Promise.all(\n exchangeDataMaps.map(async (entry) => {\n await this.exchangeDataMapCache.get(entry.id, () => Promise.resolve({ item: null }))\n })\n )\n return exchangeDataMaps\n }\n}\n"]}
1
+ {"version":3,"file":"ExchangeDataMapManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExchangeDataMapManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,oFAA6E;AAE7E,mGAA+F;AAE/F;;;GAGG;AACH,MAAa,sBAAsB;IACjC,YAA6B,GAA0B;QAA1B,QAAG,GAAH,GAAG,CAAuB;QAE/C,yBAAoB,GAA0C,IAAI,oDAAuB,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IAFvD,CAAC;IAI3D;;;;;OAKG;IACG,sBAAsB,CAAC,KAA+D;;YAC1F,MAAM,eAAe,GAA6D,EAAE,CAAA;YACpF,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBAC1C,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,EAAE;oBACxD,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;iBACvB;aACF;YACD,MAAM,IAAI,CAAC,GAAG,CAAC,0BAA0B,CAAC,IAAI,2DAA4B,CAAC,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC,CAAC,CAAA;YACvG,MAAM,OAAO,CAAC,GAAG,CACf,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,GAAG,CAAC,CAAO,KAAK,EAAE,EAAE;gBAC/C,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;YACnF,CAAC,CAAA,CAAC,CACH,CAAA;QACH,CAAC;KAAA;IAED;;;OAGG;IACG,uBAAuB,CAAC,sBAAgC;;YAC5D,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,yBAAyB,CAAC,sBAAsB,CAAC,CAAA;YACzF,MAAM,OAAO,CAAC,GAAG,CACf,gBAAgB,CAAC,GAAG,CAAC,CAAO,KAAK,EAAE,EAAE;gBACnC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;YACtF,CAAC,CAAA,CAAC,CACH,CAAA;YACD,OAAO,gBAAgB,CAAA;QACzB,CAAC;KAAA;CACF;AAvCD,wDAuCC","sourcesContent":["import { IccExchangeDataMapApi } from '../../icc-api/api/internal/IccExchangeDataMapApi'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { ExchangeDataMap } from '../../icc-api/model/internal/ExchangeDataMap'\nimport { ExchangeDataMapCreationBatch } from '../../icc-api/model/ExchangeDataMapCreationBatch'\n\n/**\n * @internal this class is intended for internal use only and may be modified without notice\n * This class manages the Exchange Data Map entities, caching with an LRU cache on retrieval.\n */\nexport class ExchangeDataMapManager {\n constructor(private readonly api: IccExchangeDataMapApi) {}\n\n private exchangeDataMapCache: LruTemporisedAsyncCache<string, null> = new LruTemporisedAsyncCache(1000, () => -1)\n\n /**\n * This function creates a batch of Exchange Data Map, ignoring the one that already exist and are already present in the cache.\n * The ones that are not are created and their ids are cached.\n * @param batch a map where each key is the hex-encoded access control key to another map that associates the encoded id of an\n * Exchange Data entity to the fingerprint of the key used to encrypt it.\n */\n async createExchangeDataMaps(batch: { [accessControlKey: string]: { [fp: string]: string } }): Promise<void> {\n const entriesToCreate: { [accessControlKey: string]: { [fp: string]: string } } = {}\n for (const [k, v] of Object.entries(batch)) {\n if (!(await this.exchangeDataMapCache.getIfCachedJob(k))) {\n entriesToCreate[k] = v\n }\n }\n await this.api.createExchangeDataMapBatch(new ExchangeDataMapCreationBatch({ batch: entriesToCreate }))\n await Promise.all(\n Object.keys(entriesToCreate).map(async (entry) => {\n await this.exchangeDataMapCache.get(entry, () => Promise.resolve({ item: null }))\n })\n )\n }\n\n /**\n * Retrieves a batch of Exchange Data Maps.\n * @param accessControlKeyHashes the hex-encoded hashes of the Exchange Data Maps to retrieve.\n */\n async getExchangeDataMapBatch(accessControlKeyHashes: string[]): Promise<ExchangeDataMap[]> {\n const exchangeDataMaps = await this.api.getExchangeDataMapByBatch(accessControlKeyHashes)\n await Promise.all(\n exchangeDataMaps.map(async (entry) => {\n await this.exchangeDataMapCache.get(entry.id, () => Promise.resolve({ item: null }))\n })\n )\n return exchangeDataMaps\n }\n}\n"]}
@@ -2,7 +2,6 @@ import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models
2
2
  import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName';
3
3
  import { SecureDelegation } from '../../icc-api/model/SecureDelegation';
4
4
  import AccessLevelEnum = SecureDelegation.AccessLevelEnum;
5
- import { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest';
6
5
  import { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest';
7
6
  import { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult';
8
7
  import RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum;
@@ -10,6 +9,7 @@ import { ShareMetadataBehaviour } from './ShareMetadataBehaviour';
10
9
  import { ShareResult } from '../utils/ShareResult';
11
10
  import { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult';
12
11
  import { EncryptedFieldsManifest } from '../utils';
12
+ import { BulkShareOrUpdateMetadataParams } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams';
13
13
  /**
14
14
  * @internal this interface is meant only for internal use and may be changed without notice.
15
15
  * Gives access to several functions to access encrypted entities metadata.
@@ -150,11 +150,7 @@ export interface ExtendedApisUtils {
150
150
  requestedPermissions: RequestedPermissionEnum;
151
151
  };
152
152
  };
153
- }[], doRequestBulkShareOrUpdate: (request: {
154
- [entityId: string]: {
155
- [requestId: string]: EntityShareOrMetadataUpdateRequest;
156
- };
157
- }) => Promise<EntityBulkShareResult<T>[]>): Promise<{
153
+ }[], doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>): Promise<{
158
154
  updatedEntities: T[];
159
155
  unmodifiedEntitiesIds: string[];
160
156
  updateErrors: {
@@ -181,11 +177,7 @@ export interface ExtendedApisUtils {
181
177
  requestedPermissions: RequestedPermissionEnum;
182
178
  };
183
179
  };
184
- }[], doRequestBulkShareOrUpdate: (request: {
185
- [entityId: string]: {
186
- [requestId: string]: EntityShareOrMetadataUpdateRequest;
187
- };
188
- }) => Promise<MinimalEntityBulkShareResult[]>): Promise<{
180
+ }[], doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>): Promise<{
189
181
  unmodifiedEntitiesIds: string[];
190
182
  successfulUpdates: {
191
183
  entityId: string;
@@ -235,11 +227,7 @@ export interface ExtendedApisUtils {
235
227
  shareOwningEntityIds: ShareMetadataBehaviour | undefined;
236
228
  requestedPermissions: RequestedPermissionEnum | undefined;
237
229
  };
238
- }, doRequestBulkShareOrUpdate: (request: {
239
- [entityId: string]: {
240
- [requestId: string]: EntityShareOrMetadataUpdateRequest;
241
- };
242
- }) => Promise<EntityBulkShareResult<T>[]>): Promise<ShareResult<T>>;
230
+ }, doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>): Promise<ShareResult<T>>;
243
231
  /**
244
232
  * 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
245
233
  * access multiple encryption keys of the entity there is no guarantee on which key will be used.
@@ -1 +1 @@
1
- {"version":3,"file":"ExtendedApisUtils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtils.ts"],"names":[],"mappings":"","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { ShareResult } from '../utils/ShareResult'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { EncryptedFieldsManifest } from '../utils'\n\n/**\n * @internal this interface is meant only for internal use and may be changed without notice.\n * Gives access to several functions to access encrypted entities metadata.\n */\nexport interface ExtendedApisUtils {\n // region metadata decryption\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get if the current data owner has write access to the content of the entity.\n * @param entity an entity\n * @return if the current data owner (or one of his parents) has write access to the content of the entity.\n */\n hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean>\n\n /**\n * @param entity an entity\n * @return if the entity has no encryption metadata and can be safely initialised using .\n */\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean\n // endregion\n\n // region metadata initialisation and share\n /**\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity and DOES NOT SAVE the entity to the cloud/DB: you will have to save the entity manually.\n * @param entity entity which requires encryption metadata initialisation.\n * @param entityType type of the entity.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKey if false this method will not initialize an encryption key for the entity. Use only for entities which use\n * delegations for access control but don't actually have any encrypted content.\n * @param initialiseSecretId if false this method will not initialize any secret id, use it for entities which can not be 'owning entities' (e.g.\n * HealthcareElement).\n * @param autoDelegations automatically shares the metadata with the provided data owners, with the provided access level.\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n initialiseSecretId: boolean,\n autoDelegations: { [dataOwnerId: string]: AccessLevelEnum }\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string | undefined\n }>\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This updates the entity in the cloud/DB (the updated entities in the returned promise are already saved in the DB). NOTE: this method can only\n * be used with entities which already exist in the cloud (the entities must have been saved).\n * @param entitiesType type of entities to update\n * @param entitiesUpdates share/update requests for each entity. An array of objects containing:\n * - The entity to share/update (or at least its encrypted metadata)\n * - The data to share/update for each delegate. An object associating to each delegate id the data to share/update for that delegate, and the\n * permissions requested for the delegate (ignored if the request will only update already existing shared metadata).\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @throws if there are duplicate entities in the requested updates.\n * @return a promise which will be completed with an object containing:\n * - the updated entities, only for entities were at least one update was successful\n * - information on the individual requests failed, containing the id of the entity, id of the delegate that the request was for, the content,\n * an error code mirroring an http status code, and a human-friendly description of the error (but not necessarily end-user friendly).\n */\n bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: {\n [entityId: string]: { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n }) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: {\n [entityId: string]: { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n }) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n /**\n * Simplified version of {@link bulkShareOrUpdateEncryptedEntityMetadata} for a single entity and with automatic retrieval of the encryption keys\n * and owning entity ids if requested. NOTE: this method can only be used with entities which already exist in the cloud (the entity must have\n * been saved).\n * @param entity an entity.\n * @param unusedSecretIds specifies if the entity should not actually use secret ids but may have some if it was created using older iCure sdk\n * versions. If true the method expects `shareSecretIds` options to always be undefined and will always share any available secret ids. If false\n * it expects `shareSecretIds` options to always be defined and will only share the secret ids specified in the options.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareEncryptionKeys specifies if the encryption keys of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareOwningEntityIds specifies if the owning entity ids of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareSecretIds specifies which secret ids of the entity should be shared. Should be defined only if {@link unusedSecretIds} is false.\n * - requestedPermissions requested permissions for the delegate. Defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return a promise which will be completed with the result of the operation\n * @throws if shareEncryptionKeys or shareOwningEntityIds is {@link ShareMetadataBehaviour.REQUIRED} and the current data owner can't access any\n * value for the required metadata.\n */\n simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n unusedSecretIds: boolean,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: {\n [entityId: string]: { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n }) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>>\n // endregion\n\n // region content encryption and decryption\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param type type of the entity.\n * @param content data of the entity which you want to encrypt.\n * @param saveEntity a function which saves the entity to the cloud/DB. Used only if a new encryption key needed to be initialised for the entity.\n * @return the encrypted data and, if a new encryption key was initialised for the entity, the updated entity.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }>\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }>\n\n /**\n * TODO work on this\n * Decrypts the content of an encrypted entity.\n */\n decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }>\n\n /**\n * Tries to decrypt data to a json object using the provided keys.\n */\n tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined>\n\n /**\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient using the default configuration). If the entity specifies\n * a value for any field which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T>\n\n /**\n * Returns the first encryption key which could be properly decrypted from the entity using the current data owner.\n * @throws if no key could be decrypted.\n */\n decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }>\n\n /**\n * Returns all encryption keys which could be properly decrypted from the entity using the current data owner. The keys returned by this method\n * should not be used for encryption of the entity, but only for decryption.\n * This is because this for data from pre-2018 users this method may return also keys from old formats of entities which are not safe anymore for\n * encryption.\n */\n decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]>\n\n /**\n * Verifies if the entity has valid encryption keys (regardless of whether the current data owner has access to them or not). If not this method\n * will throw an error, otherwise it will return undefined. For pre-2018 users there are some cases where the data may have been encrypted with a\n * key not safe for encryption anymore, in which case this method will return the entity with a new and safe encryption key.\n * After this method is called, if it returns an entity it should also be re-encrypted (using the new key) and saved to the cloud.\n */\n ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined>\n // endregion\n}\n"]}
1
+ {"version":3,"file":"ExtendedApisUtils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtils.ts"],"names":[],"mappings":"","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { ShareResult } from '../utils/ShareResult'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { EncryptedFieldsManifest } from '../utils'\nimport { BulkShareOrUpdateMetadataParams } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this interface is meant only for internal use and may be changed without notice.\n * Gives access to several functions to access encrypted entities metadata.\n */\nexport interface ExtendedApisUtils {\n // region metadata decryption\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get if the current data owner has write access to the content of the entity.\n * @param entity an entity\n * @return if the current data owner (or one of his parents) has write access to the content of the entity.\n */\n hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean>\n\n /**\n * @param entity an entity\n * @return if the entity has no encryption metadata and can be safely initialised using .\n */\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean\n // endregion\n\n // region metadata initialisation and share\n /**\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity and DOES NOT SAVE the entity to the cloud/DB: you will have to save the entity manually.\n * @param entity entity which requires encryption metadata initialisation.\n * @param entityType type of the entity.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKey if false this method will not initialize an encryption key for the entity. Use only for entities which use\n * delegations for access control but don't actually have any encrypted content.\n * @param initialiseSecretId if false this method will not initialize any secret id, use it for entities which can not be 'owning entities' (e.g.\n * HealthcareElement).\n * @param autoDelegations automatically shares the metadata with the provided data owners, with the provided access level.\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n initialiseSecretId: boolean,\n autoDelegations: { [dataOwnerId: string]: AccessLevelEnum }\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string | undefined\n }>\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This updates the entity in the cloud/DB (the updated entities in the returned promise are already saved in the DB). NOTE: this method can only\n * be used with entities which already exist in the cloud (the entities must have been saved).\n * @param entitiesType type of entities to update\n * @param entitiesUpdates share/update requests for each entity. An array of objects containing:\n * - The entity to share/update (or at least its encrypted metadata)\n * - The data to share/update for each delegate. An object associating to each delegate id the data to share/update for that delegate, and the\n * permissions requested for the delegate (ignored if the request will only update already existing shared metadata).\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @throws if there are duplicate entities in the requested updates.\n * @return a promise which will be completed with an object containing:\n * - the updated entities, only for entities were at least one update was successful\n * - information on the individual requests failed, containing the id of the entity, id of the delegate that the request was for, the content,\n * an error code mirroring an http status code, and a human-friendly description of the error (but not necessarily end-user friendly).\n */\n bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n /**\n * Simplified version of {@link bulkShareOrUpdateEncryptedEntityMetadata} for a single entity and with automatic retrieval of the encryption keys\n * and owning entity ids if requested. NOTE: this method can only be used with entities which already exist in the cloud (the entity must have\n * been saved).\n * @param entity an entity.\n * @param unusedSecretIds specifies if the entity should not actually use secret ids but may have some if it was created using older iCure sdk\n * versions. If true the method expects `shareSecretIds` options to always be undefined and will always share any available secret ids. If false\n * it expects `shareSecretIds` options to always be defined and will only share the secret ids specified in the options.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareEncryptionKeys specifies if the encryption keys of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareOwningEntityIds specifies if the owning entity ids of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareSecretIds specifies which secret ids of the entity should be shared. Should be defined only if {@link unusedSecretIds} is false.\n * - requestedPermissions requested permissions for the delegate. Defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return a promise which will be completed with the result of the operation\n * @throws if shareEncryptionKeys or shareOwningEntityIds is {@link ShareMetadataBehaviour.REQUIRED} and the current data owner can't access any\n * value for the required metadata.\n */\n simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n unusedSecretIds: boolean,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>>\n // endregion\n\n // region content encryption and decryption\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param type type of the entity.\n * @param content data of the entity which you want to encrypt.\n * @param saveEntity a function which saves the entity to the cloud/DB. Used only if a new encryption key needed to be initialised for the entity.\n * @return the encrypted data and, if a new encryption key was initialised for the entity, the updated entity.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }>\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }>\n\n /**\n * TODO work on this\n * Decrypts the content of an encrypted entity.\n */\n decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }>\n\n /**\n * Tries to decrypt data to a json object using the provided keys.\n */\n tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined>\n\n /**\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient using the default configuration). If the entity specifies\n * a value for any field which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T>\n\n /**\n * Returns the first encryption key which could be properly decrypted from the entity using the current data owner.\n * @throws if no key could be decrypted.\n */\n decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }>\n\n /**\n * Returns all encryption keys which could be properly decrypted from the entity using the current data owner. The keys returned by this method\n * should not be used for encryption of the entity, but only for decryption.\n * This is because this for data from pre-2018 users this method may return also keys from old formats of entities which are not safe anymore for\n * encryption.\n */\n decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]>\n\n /**\n * Verifies if the entity has valid encryption keys (regardless of whether the current data owner has access to them or not). If not this method\n * will throw an error, otherwise it will return undefined. For pre-2018 users there are some cases where the data may have been encrypted with a\n * key not safe for encryption anymore, in which case this method will return the entity with a new and safe encryption key.\n * After this method is called, if it returns an entity it should also be re-encrypted (using the new key) and saved to the cloud.\n */\n ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined>\n // endregion\n}\n"]}
@@ -5,7 +5,6 @@ import { CryptoPrimitives } from './CryptoPrimitives';
5
5
  import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName';
6
6
  import { SecureDelegation } from '../../icc-api/model/SecureDelegation';
7
7
  import { ExtendedApisUtils } from './ExtendedApisUtils';
8
- import { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest';
9
8
  import { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult';
10
9
  import { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest';
11
10
  import { SecureDelegationsManager } from './SecureDelegationsManager';
@@ -16,6 +15,7 @@ import { ShareMetadataBehaviour } from './ShareMetadataBehaviour';
16
15
  import { IccUserXApi } from '../icc-user-x-api';
17
16
  import { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult';
18
17
  import RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum;
18
+ import { BulkShareOrUpdateMetadataParams } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams';
19
19
  /**
20
20
  * @internal this class is for internal use only and may be changed without notice.
21
21
  * Methods to support extended apis.
@@ -63,11 +63,7 @@ export declare class ExtendedApisUtilsImpl implements ExtendedApisUtils {
63
63
  requestedPermissions: RequestedPermissionEnum;
64
64
  };
65
65
  };
66
- }[], doRequestBulkShareOrUpdate: (request: {
67
- [entityId: string]: {
68
- [requestId: string]: EntityShareOrMetadataUpdateRequest;
69
- };
70
- }) => Promise<EntityBulkShareResult<T>[]>): Promise<{
66
+ }[], doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>): Promise<{
71
67
  updatedEntities: T[];
72
68
  unmodifiedEntitiesIds: string[];
73
69
  updateErrors: {
@@ -94,11 +90,7 @@ export declare class ExtendedApisUtilsImpl implements ExtendedApisUtils {
94
90
  requestedPermissions: EntityShareRequest.RequestedPermissionEnum;
95
91
  };
96
92
  };
97
- }[], doRequestBulkShareOrUpdate: (request: {
98
- [p: string]: {
99
- [p: string]: EntityShareOrMetadataUpdateRequest;
100
- };
101
- }) => Promise<MinimalEntityBulkShareResult[]>): Promise<{
93
+ }[], doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>): Promise<{
102
94
  unmodifiedEntitiesIds: string[];
103
95
  successfulUpdates: {
104
96
  entityId: string;
@@ -129,11 +121,7 @@ export declare class ExtendedApisUtilsImpl implements ExtendedApisUtils {
129
121
  shareOwningEntityIds: ShareMetadataBehaviour | undefined;
130
122
  requestedPermissions: RequestedPermissionEnum | undefined;
131
123
  };
132
- }, doRequestBulkShareOrUpdate: (request: {
133
- [p: string]: {
134
- [p: string]: EntityShareOrMetadataUpdateRequest;
135
- };
136
- }) => Promise<EntityBulkShareResult<T>[]>): Promise<ShareResult<T>>;
124
+ }, doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>): Promise<ShareResult<T>>;
137
125
  private makeMigrationRequestsIfNeeded;
138
126
  private makeMigrationRequestForMemberOfHierarchy;
139
127
  tryDecryptDataOf(entity: EncryptedEntityWithType, content: ArrayBuffer | Uint8Array, validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined): Promise<{
@@ -89,7 +89,7 @@ class ExtendedApisUtilsImpl {
89
89
  var _a;
90
90
  return __awaiter(this, void 0, void 0, function* () {
91
91
  const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = yield this.prepareBulkShareRequests(entitiesType, entitiesUpdates);
92
- const results = yield doRequestBulkShareOrUpdate(allRequestsByEntityId);
92
+ const results = yield doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId });
93
93
  const updatedEntities = [];
94
94
  const updateErrors = [];
95
95
  for (const result of results) {
@@ -121,7 +121,7 @@ class ExtendedApisUtilsImpl {
121
121
  var _a;
122
122
  return __awaiter(this, void 0, void 0, function* () {
123
123
  const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = yield this.prepareBulkShareRequests(entitiesType, entitiesUpdates);
124
- const results = yield doRequestBulkShareOrUpdate(allRequestsByEntityId);
124
+ const results = yield doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId });
125
125
  const updateErrors = [];
126
126
  for (const result of results) {
127
127
  for (const [errorRequestId, error] of Object.entries((_a = result.rejectedRequests) !== null && _a !== void 0 ? _a : {})) {
@@ -186,7 +186,16 @@ class ExtendedApisUtilsImpl {
186
186
  }
187
187
  }
188
188
  if (Object.keys(currentRequests).length > 0) {
189
- allRequestsByEntityId[entityId] = currentRequests;
189
+ const existingDelegationMembersDetails = yield this.secDelMetadataDecryptor.getDelegationMemberDetails(entityWithType);
190
+ const accessibleMembers = new Set(this.useParentKeys ? yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds() : yield this.dataOwnerApi.getCurrentDataOwnerId());
191
+ const potentialParentDelegations = Object.entries(existingDelegationMembersDetails).flatMap(([k, members]) => {
192
+ if ((!!members.delegate && accessibleMembers.has(members.delegate)) || (!!members.delegator && accessibleMembers.has(members.delegator))) {
193
+ return [k];
194
+ }
195
+ else
196
+ return [];
197
+ });
198
+ allRequestsByEntityId[entityId] = { requests: currentRequests, potentialParentDelegations };
190
199
  orderedRequestsInfoByEntityId[entityId] = currentOrderedRequests;
191
200
  }
192
201
  else {