@icure/api 7.1.14 → 8.0.0-RC.1

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 (322) hide show
  1. package/icc-api/api/IccAccesslogApi.d.ts +12 -1
  2. package/icc-api/api/IccAccesslogApi.js +142 -98
  3. package/icc-api/api/IccAccesslogApi.js.map +1 -1
  4. package/icc-api/api/IccBemikronoApi.d.ts +81 -0
  5. package/icc-api/api/IccBemikronoApi.js +163 -0
  6. package/icc-api/api/IccBemikronoApi.js.map +1 -0
  7. package/icc-api/api/IccCalendarItemApi.d.ts +21 -1
  8. package/icc-api/api/IccCalendarItemApi.js +183 -117
  9. package/icc-api/api/IccCalendarItemApi.js.map +1 -1
  10. package/icc-api/api/IccClassificationApi.d.ts +21 -1
  11. package/icc-api/api/IccClassificationApi.js +119 -63
  12. package/icc-api/api/IccClassificationApi.js.map +1 -1
  13. package/icc-api/api/IccContactApi.d.ts +21 -1
  14. package/icc-api/api/IccContactApi.js +385 -294
  15. package/icc-api/api/IccContactApi.js.map +1 -1
  16. package/icc-api/api/IccDocumentApi.d.ts +32 -25
  17. package/icc-api/api/IccDocumentApi.js +264 -212
  18. package/icc-api/api/IccDocumentApi.js.map +1 -1
  19. package/icc-api/api/IccExchangeDataApi.d.ts +19 -0
  20. package/icc-api/api/IccExchangeDataApi.js +85 -0
  21. package/icc-api/api/IccExchangeDataApi.js.map +1 -0
  22. package/icc-api/api/IccExchangeDataMapApi.d.ts +18 -0
  23. package/icc-api/api/IccExchangeDataMapApi.js +65 -0
  24. package/icc-api/api/IccExchangeDataMapApi.js.map +1 -0
  25. package/icc-api/api/IccFormApi.d.ts +21 -1
  26. package/icc-api/api/IccFormApi.js +321 -229
  27. package/icc-api/api/IccFormApi.js.map +1 -1
  28. package/icc-api/api/IccHelementApi.d.ts +21 -1
  29. package/icc-api/api/IccHelementApi.js +207 -137
  30. package/icc-api/api/IccHelementApi.js.map +1 -1
  31. package/icc-api/api/IccInvoiceApi.d.ts +21 -1
  32. package/icc-api/api/IccInvoiceApi.js +404 -298
  33. package/icc-api/api/IccInvoiceApi.js.map +1 -1
  34. package/icc-api/api/IccMaintenanceTaskApi.d.ts +12 -1
  35. package/icc-api/api/IccMaintenanceTaskApi.js +79 -43
  36. package/icc-api/api/IccMaintenanceTaskApi.js.map +1 -1
  37. package/icc-api/api/IccMessageApi.d.ts +12 -1
  38. package/icc-api/api/IccMessageApi.js +257 -191
  39. package/icc-api/api/IccMessageApi.js.map +1 -1
  40. package/icc-api/api/IccPatientApi.d.ts +12 -1
  41. package/icc-api/api/IccPatientApi.js +447 -351
  42. package/icc-api/api/IccPatientApi.js.map +1 -1
  43. package/icc-api/api/IccReceiptApi.d.ts +22 -8
  44. package/icc-api/api/IccReceiptApi.js +121 -64
  45. package/icc-api/api/IccReceiptApi.js.map +1 -1
  46. package/icc-api/api/IccRestApiPath.js +1 -1
  47. package/icc-api/api/IccRestApiPath.js.map +1 -1
  48. package/icc-api/api/IccTimeTableApi.d.ts +12 -1
  49. package/icc-api/api/IccTimeTableApi.js +86 -48
  50. package/icc-api/api/IccTimeTableApi.js.map +1 -1
  51. package/icc-api/index.d.ts +1 -0
  52. package/icc-api/index.js +1 -0
  53. package/icc-api/index.js.map +1 -1
  54. package/icc-api/model/AccessLog.d.ts +4 -0
  55. package/icc-api/model/AccessLog.js +1 -0
  56. package/icc-api/model/AccessLog.js.map +1 -1
  57. package/icc-api/model/Article.d.ts +4 -0
  58. package/icc-api/model/Article.js +1 -0
  59. package/icc-api/model/Article.js.map +1 -1
  60. package/icc-api/model/CalendarItem.d.ts +4 -0
  61. package/icc-api/model/CalendarItem.js +1 -0
  62. package/icc-api/model/CalendarItem.js.map +1 -1
  63. package/icc-api/model/Classification.d.ts +4 -0
  64. package/icc-api/model/Classification.js +1 -0
  65. package/icc-api/model/Classification.js.map +1 -1
  66. package/icc-api/model/ClassificationTemplate.d.ts +2 -0
  67. package/icc-api/model/ClassificationTemplate.js.map +1 -1
  68. package/icc-api/model/Contact.d.ts +4 -0
  69. package/icc-api/model/Contact.js +1 -0
  70. package/icc-api/model/Contact.js.map +1 -1
  71. package/icc-api/model/Device.d.ts +4 -4
  72. package/icc-api/model/Device.js.map +1 -1
  73. package/icc-api/model/Document.d.ts +4 -0
  74. package/icc-api/model/Document.js +1 -0
  75. package/icc-api/model/Document.js.map +1 -1
  76. package/icc-api/model/ExchangeData.d.ts +61 -0
  77. package/icc-api/model/ExchangeData.js +12 -0
  78. package/icc-api/model/ExchangeData.js.map +1 -0
  79. package/icc-api/model/ExchangeDataMap.d.ts +21 -0
  80. package/icc-api/model/ExchangeDataMap.js +10 -0
  81. package/icc-api/model/ExchangeDataMap.js.map +1 -0
  82. package/icc-api/model/ExchangeDataMapCreationBatch.d.ts +13 -0
  83. package/icc-api/model/ExchangeDataMapCreationBatch.js +10 -0
  84. package/icc-api/model/ExchangeDataMapCreationBatch.js.map +1 -0
  85. package/icc-api/model/Form.d.ts +4 -0
  86. package/icc-api/model/Form.js +1 -0
  87. package/icc-api/model/Form.js.map +1 -1
  88. package/icc-api/model/HealthElement.d.ts +4 -0
  89. package/icc-api/model/HealthElement.js +1 -0
  90. package/icc-api/model/HealthElement.js.map +1 -1
  91. package/icc-api/model/HealthcareParty.d.ts +2 -2
  92. package/icc-api/model/HealthcareParty.js.map +1 -1
  93. package/icc-api/model/IcureStub.d.ts +2 -0
  94. package/icc-api/model/IcureStub.js.map +1 -1
  95. package/icc-api/model/Invoice.d.ts +4 -0
  96. package/icc-api/model/Invoice.js +1 -0
  97. package/icc-api/model/Invoice.js.map +1 -1
  98. package/icc-api/model/MaintenanceTask.d.ts +4 -0
  99. package/icc-api/model/MaintenanceTask.js +1 -0
  100. package/icc-api/model/MaintenanceTask.js.map +1 -1
  101. package/icc-api/model/Message.d.ts +4 -0
  102. package/icc-api/model/Message.js +1 -0
  103. package/icc-api/model/Message.js.map +1 -1
  104. package/icc-api/model/PaginatedListExchangeData.d.ts +9 -0
  105. package/icc-api/model/PaginatedListExchangeData.js +10 -0
  106. package/icc-api/model/PaginatedListExchangeData.js.map +1 -0
  107. package/icc-api/model/Patient.d.ts +6 -2
  108. package/icc-api/model/Patient.js +1 -0
  109. package/icc-api/model/Patient.js.map +1 -1
  110. package/icc-api/model/PatientByHcPartyGenderEducationProfession.d.ts +31 -0
  111. package/icc-api/model/PatientByHcPartyGenderEducationProfession.js +32 -0
  112. package/icc-api/model/PatientByHcPartyGenderEducationProfession.js.map +1 -0
  113. package/icc-api/model/Receipt.d.ts +4 -0
  114. package/icc-api/model/Receipt.js +1 -0
  115. package/icc-api/model/Receipt.js.map +1 -1
  116. package/icc-api/model/SecureDelegation.d.ts +52 -0
  117. package/icc-api/model/SecureDelegation.js +16 -0
  118. package/icc-api/model/SecureDelegation.js.map +1 -0
  119. package/icc-api/model/SecurityMetadata.d.ts +33 -0
  120. package/icc-api/model/SecurityMetadata.js +13 -0
  121. package/icc-api/model/SecurityMetadata.js.map +1 -0
  122. package/icc-api/model/Service.d.ts +2 -0
  123. package/icc-api/model/Service.js.map +1 -1
  124. package/icc-api/model/TimeTable.d.ts +4 -0
  125. package/icc-api/model/TimeTable.js +1 -0
  126. package/icc-api/model/TimeTable.js.map +1 -1
  127. package/icc-api/model/models.d.ts +20 -39
  128. package/icc-api/model/models.js +15 -37
  129. package/icc-api/model/models.js.map +1 -1
  130. package/icc-api/model/requests/EntityBulkShareResult.d.ts +28 -0
  131. package/icc-api/model/requests/EntityBulkShareResult.js +16 -0
  132. package/icc-api/model/requests/EntityBulkShareResult.js.map +1 -0
  133. package/icc-api/model/requests/EntityShareOrMetadataUpdateRequest.d.ts +10 -0
  134. package/icc-api/model/requests/EntityShareOrMetadataUpdateRequest.js +17 -0
  135. package/icc-api/model/requests/EntityShareOrMetadataUpdateRequest.js.map +1 -0
  136. package/icc-api/model/requests/EntityShareRequest.d.ts +110 -0
  137. package/icc-api/model/requests/EntityShareRequest.js +63 -0
  138. package/icc-api/model/requests/EntityShareRequest.js.map +1 -0
  139. package/icc-api/model/requests/EntitySharedMetadataUpdateRequest.d.ts +54 -0
  140. package/icc-api/model/requests/EntitySharedMetadataUpdateRequest.js +24 -0
  141. package/icc-api/model/requests/EntitySharedMetadataUpdateRequest.js.map +1 -0
  142. package/icc-api/model/requests/MinimalEntityBulkShareResult.d.ts +23 -0
  143. package/icc-api/model/requests/MinimalEntityBulkShareResult.js +13 -0
  144. package/icc-api/model/requests/MinimalEntityBulkShareResult.js.map +1 -0
  145. package/icc-api/model/requests/RejectedShareOrMetadataUpdateRequest.d.ts +21 -0
  146. package/icc-api/model/requests/RejectedShareOrMetadataUpdateRequest.js +14 -0
  147. package/icc-api/model/requests/RejectedShareOrMetadataUpdateRequest.js.map +1 -0
  148. package/icc-x-api/basexapi/EncryptedEntityXApi.d.ts +3 -2
  149. package/icc-x-api/basexapi/EncryptedEntityXApi.js.map +1 -1
  150. package/icc-x-api/crypto/AES.js +1 -1
  151. package/icc-x-api/crypto/AES.js.map +1 -1
  152. package/icc-x-api/crypto/AccessControlKeysHeadersProvider.d.ts +16 -0
  153. package/icc-x-api/crypto/AccessControlKeysHeadersProvider.js +41 -0
  154. package/icc-x-api/crypto/AccessControlKeysHeadersProvider.js.map +1 -0
  155. package/icc-x-api/crypto/AccessControlSecretUtils.d.ts +42 -0
  156. package/icc-x-api/crypto/AccessControlSecretUtils.js +86 -0
  157. package/icc-x-api/crypto/AccessControlSecretUtils.js.map +1 -0
  158. package/icc-x-api/crypto/BaseExchangeDataManager.d.ts +146 -0
  159. package/icc-x-api/crypto/BaseExchangeDataManager.js +342 -0
  160. package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -0
  161. package/icc-x-api/crypto/BaseExchangeKeysManager.d.ts +0 -18
  162. package/icc-x-api/crypto/BaseExchangeKeysManager.js +11 -85
  163. package/icc-x-api/crypto/BaseExchangeKeysManager.js.map +1 -1
  164. package/icc-x-api/crypto/ConfidentialEntities.d.ts +26 -16
  165. package/icc-x-api/crypto/ConfidentialEntities.js +30 -17
  166. package/icc-x-api/crypto/ConfidentialEntities.js.map +1 -1
  167. package/icc-x-api/crypto/CryptoStrategies.d.ts +8 -1
  168. package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
  169. package/icc-x-api/crypto/ExchangeDataManager.d.ts +95 -0
  170. package/icc-x-api/crypto/ExchangeDataManager.js +493 -0
  171. package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -0
  172. package/icc-x-api/crypto/ExchangeDataMapManager.d.ts +32 -0
  173. package/icc-x-api/crypto/ExchangeDataMapManager.js +70 -0
  174. package/icc-x-api/crypto/ExchangeDataMapManager.js.map +1 -0
  175. package/icc-x-api/crypto/ExchangeKeysManager.d.ts +4 -16
  176. package/icc-x-api/crypto/ExchangeKeysManager.js +4 -62
  177. package/icc-x-api/crypto/ExchangeKeysManager.js.map +1 -1
  178. package/icc-x-api/crypto/ExtendedApisUtils.d.ts +336 -0
  179. package/icc-x-api/crypto/ExtendedApisUtils.js +3 -0
  180. package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -0
  181. package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +181 -0
  182. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +562 -0
  183. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -0
  184. package/icc-x-api/crypto/KeyRecovery.d.ts +5 -2
  185. package/icc-x-api/crypto/KeyRecovery.js +59 -29
  186. package/icc-x-api/crypto/KeyRecovery.js.map +1 -1
  187. package/icc-x-api/crypto/LegacyCryptoStrategies.d.ts +7 -2
  188. package/icc-x-api/crypto/LegacyCryptoStrategies.js +8 -1
  189. package/icc-x-api/crypto/LegacyCryptoStrategies.js.map +1 -1
  190. package/icc-x-api/crypto/LegacyDelegationSecurityMetadataDecryptor.d.ts +39 -0
  191. package/icc-x-api/crypto/LegacyDelegationSecurityMetadataDecryptor.js +150 -0
  192. package/icc-x-api/crypto/LegacyDelegationSecurityMetadataDecryptor.js.map +1 -0
  193. package/icc-x-api/crypto/RSA.d.ts +34 -8
  194. package/icc-x-api/crypto/RSA.js +80 -13
  195. package/icc-x-api/crypto/RSA.js.map +1 -1
  196. package/icc-x-api/crypto/SecureDelegationsEncryption.d.ts +54 -0
  197. package/icc-x-api/crypto/SecureDelegationsEncryption.js +178 -0
  198. package/icc-x-api/crypto/SecureDelegationsEncryption.js.map +1 -0
  199. package/icc-x-api/crypto/SecureDelegationsManager.d.ts +66 -0
  200. package/icc-x-api/crypto/SecureDelegationsManager.js +261 -0
  201. package/icc-x-api/crypto/SecureDelegationsManager.js.map +1 -0
  202. package/icc-x-api/crypto/SecureDelegationsSecurityMetadataDecryptor.d.ts +37 -0
  203. package/icc-x-api/crypto/SecureDelegationsSecurityMetadataDecryptor.js +294 -0
  204. package/icc-x-api/crypto/SecureDelegationsSecurityMetadataDecryptor.js.map +1 -0
  205. package/icc-x-api/crypto/SecurityMetadataDecryptor.d.ts +114 -0
  206. package/icc-x-api/crypto/SecurityMetadataDecryptor.js +98 -0
  207. package/icc-x-api/crypto/SecurityMetadataDecryptor.js.map +1 -0
  208. package/icc-x-api/crypto/ShamirKeysManager.d.ts +5 -5
  209. package/icc-x-api/crypto/ShamirKeysManager.js +6 -9
  210. package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
  211. package/icc-x-api/crypto/TransferKeysManager.d.ts +8 -6
  212. package/icc-x-api/crypto/TransferKeysManager.js +75 -52
  213. package/icc-x-api/crypto/TransferKeysManager.js.map +1 -1
  214. package/icc-x-api/crypto/{KeyManager.d.ts → UserEncryptionKeysManager.d.ts} +4 -6
  215. package/icc-x-api/crypto/{KeyManager.js → UserEncryptionKeysManager.js} +43 -23
  216. package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -0
  217. package/icc-x-api/crypto/UserSignatureKeysManager.d.ts +26 -0
  218. package/icc-x-api/crypto/UserSignatureKeysManager.js +74 -0
  219. package/icc-x-api/crypto/UserSignatureKeysManager.js.map +1 -0
  220. package/icc-x-api/crypto/utils.d.ts +61 -11
  221. package/icc-x-api/crypto/utils.js +113 -44
  222. package/icc-x-api/crypto/utils.js.map +1 -1
  223. package/icc-x-api/filters/filters.js.map +1 -1
  224. package/icc-x-api/icc-accesslog-x-api.d.ts +46 -11
  225. package/icc-x-api/icc-accesslog-x-api.js +75 -42
  226. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  227. package/icc-x-api/icc-calendar-item-x-api.d.ts +50 -14
  228. package/icc-x-api/icc-calendar-item-x-api.js +99 -49
  229. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  230. package/icc-x-api/icc-classification-x-api.d.ts +44 -9
  231. package/icc-x-api/icc-classification-x-api.js +56 -31
  232. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  233. package/icc-x-api/icc-contact-x-api.d.ts +56 -32
  234. package/icc-x-api/icc-contact-x-api.js +95 -64
  235. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  236. package/icc-x-api/icc-crypto-x-api.d.ts +28 -334
  237. package/icc-x-api/icc-crypto-x-api.js +41 -765
  238. package/icc-x-api/icc-crypto-x-api.js.map +1 -1
  239. package/icc-x-api/icc-data-owner-x-api.d.ts +20 -8
  240. package/icc-x-api/icc-data-owner-x-api.js +31 -10
  241. package/icc-x-api/icc-data-owner-x-api.js.map +1 -1
  242. package/icc-x-api/icc-document-x-api.d.ts +48 -11
  243. package/icc-x-api/icc-document-x-api.js +111 -64
  244. package/icc-x-api/icc-document-x-api.js.map +1 -1
  245. package/icc-x-api/icc-form-x-api.d.ts +45 -10
  246. package/icc-x-api/icc-form-x-api.js +65 -35
  247. package/icc-x-api/icc-form-x-api.js.map +1 -1
  248. package/icc-x-api/icc-hcparty-x-api.d.ts +2 -2
  249. package/icc-x-api/icc-hcparty-x-api.js +3 -3
  250. package/icc-x-api/icc-hcparty-x-api.js.map +1 -1
  251. package/icc-x-api/icc-helement-x-api.d.ts +55 -18
  252. package/icc-x-api/icc-helement-x-api.js +76 -41
  253. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  254. package/icc-x-api/icc-icure-maintenance-x-api.d.ts +7 -2
  255. package/icc-x-api/icc-icure-maintenance-x-api.js +38 -27
  256. package/icc-x-api/icc-icure-maintenance-x-api.js.map +1 -1
  257. package/icc-x-api/icc-invoice-x-api.d.ts +50 -15
  258. package/icc-x-api/icc-invoice-x-api.js +63 -33
  259. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  260. package/icc-x-api/icc-maintenance-task-x-api.d.ts +53 -21
  261. package/icc-x-api/icc-maintenance-task-x-api.js +72 -35
  262. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  263. package/icc-x-api/icc-message-x-api.d.ts +53 -15
  264. package/icc-x-api/icc-message-x-api.js +65 -36
  265. package/icc-x-api/icc-message-x-api.js.map +1 -1
  266. package/icc-x-api/icc-patient-x-api.d.ts +84 -29
  267. package/icc-x-api/icc-patient-x-api.js +313 -378
  268. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  269. package/icc-x-api/icc-receipt-x-api.d.ts +44 -12
  270. package/icc-x-api/icc-receipt-x-api.js +67 -35
  271. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  272. package/icc-x-api/icc-time-table-x-api.d.ts +43 -12
  273. package/icc-x-api/icc-time-table-x-api.js +56 -26
  274. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  275. package/icc-x-api/icc-user-x-api.d.ts +2 -2
  276. package/icc-x-api/icc-user-x-api.js +3 -3
  277. package/icc-x-api/icc-user-x-api.js.map +1 -1
  278. package/icc-x-api/index.d.ts +4 -2
  279. package/icc-x-api/index.js +154 -135
  280. package/icc-x-api/index.js.map +1 -1
  281. package/icc-x-api/storage/DefaultStorageEntryKeysFactory.d.ts +2 -0
  282. package/icc-x-api/storage/DefaultStorageEntryKeysFactory.js +9 -2
  283. package/icc-x-api/storage/DefaultStorageEntryKeysFactory.js.map +1 -1
  284. package/icc-x-api/storage/IcureStorageFacade.d.ts +23 -2
  285. package/icc-x-api/storage/IcureStorageFacade.js +36 -2
  286. package/icc-x-api/storage/IcureStorageFacade.js.map +1 -1
  287. package/icc-x-api/storage/KeyStorageFacade.d.ts +12 -0
  288. package/icc-x-api/storage/KeyStorageFacade.js.map +1 -1
  289. package/icc-x-api/storage/KeyStorageImpl.d.ts +2 -0
  290. package/icc-x-api/storage/KeyStorageImpl.js +10 -0
  291. package/icc-x-api/storage/KeyStorageImpl.js.map +1 -1
  292. package/icc-x-api/storage/StorageEntryKeysFactory.d.ts +14 -1
  293. package/icc-x-api/storage/StorageEntryKeysFactory.js.map +1 -1
  294. package/icc-x-api/utils/EntityWithDelegationTypeName.d.ts +32 -0
  295. package/icc-x-api/utils/EntityWithDelegationTypeName.js +75 -0
  296. package/icc-x-api/utils/EntityWithDelegationTypeName.js.map +1 -0
  297. package/icc-x-api/utils/ShareResult.d.ts +74 -0
  298. package/icc-x-api/utils/ShareResult.js +61 -0
  299. package/icc-x-api/utils/ShareResult.js.map +1 -0
  300. package/icc-x-api/utils/binary-utils.d.ts +1 -0
  301. package/icc-x-api/utils/binary-utils.js +8 -1
  302. package/icc-x-api/utils/binary-utils.js.map +1 -1
  303. package/icc-x-api/utils/collection-utils.d.ts +5 -0
  304. package/icc-x-api/utils/collection-utils.js +26 -1
  305. package/icc-x-api/utils/collection-utils.js.map +1 -1
  306. package/icc-x-api/utils/crypto-utils.d.ts +4 -3
  307. package/icc-x-api/utils/crypto-utils.js +5 -4
  308. package/icc-x-api/utils/crypto-utils.js.map +1 -1
  309. package/icc-x-api/utils/lru-temporised-async-cache.d.ts +26 -3
  310. package/icc-x-api/utils/lru-temporised-async-cache.js +75 -15
  311. package/icc-x-api/utils/lru-temporised-async-cache.js.map +1 -1
  312. package/icc-x-api/utils/websocket.d.ts +10 -10
  313. package/icc-x-api/utils/websocket.js +18 -9
  314. package/icc-x-api/utils/websocket.js.map +1 -1
  315. package/index.d.ts +1 -1
  316. package/index.js +3 -1
  317. package/index.js.map +1 -1
  318. package/package.json +2 -3
  319. package/icc-x-api/crypto/EntitiesEncryption.d.ts +0 -275
  320. package/icc-x-api/crypto/EntitiesEncryption.js +0 -734
  321. package/icc-x-api/crypto/EntitiesEncryption.js.map +0 -1
  322. package/icc-x-api/crypto/KeyManager.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"EntitiesEncryption.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/EntitiesEncryption.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oCAaiB;AACjB,4BAA2B;AAE3B,gEAAuD;AACvD,qEAAiE;AAGjE;;;GAGG;AACH,MAAa,kBAAkB;IAC7B,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,mBAAwC,EACxC,aAAsB;QAHtB,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,wBAAmB,GAAnB,mBAAmB,CAAqB;QACxC,kBAAa,GAAb,aAAa,CAAS;IACtC,CAAC;IAEJ;;;OAGG;IACG,yBAAyB,CAAC,MAAuB;;;YAIrD,OAAO;gBACL,wBAAwB,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,MAAA,MAAM,CAAC,WAAW,mCAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;gBAC5G,6BAA6B,EAAE,KAAK;aACrC,CAAA;;KACF;IAED;;;;;;;OAOG;IACG,gBAAgB,CACpB,MAA6C,EAC7C,WAAoB,EACpB,aAAmD,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;;;YAE9E,2DAA2D;YAC3D,OAAO,IAAI,CAAC,4CAA4C,CACtD,MAAM,CAAC,IAAI,CAAC,MAAA,MAAM,CAAC,cAAc,mCAAI,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,cAAe,CAAC,CAAC,CAAC,MAAA,MAAM,CAAC,WAAW,m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CACvC,CAAA;SACF;IACH,CAAC;CACF;AAv6BD,gDAu6BC","sourcesContent":["import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ExchangeKeysManager } from './ExchangeKeysManager'\nimport {\n b2a,\n encryptObject,\n decryptObject,\n EncryptedFieldsManifest,\n hex2ua,\n parseEncryptedFields,\n string2ua,\n truncateTrailingNulls,\n ua2hex,\n ua2string,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport * as _ from 'lodash'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { arrayEquals } from '../utils/collection-utils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is for internal use only and may be changed without notice\n * Give access to functions for retrieving encryption metadata of entities.\n */\nexport class EntitiesEncryption {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly exchangeKeysManager: ExchangeKeysManager,\n private readonly useParentKeys: boolean\n ) {}\n\n /**\n * Get the data owners which can access the entity\n * @param entity an entity.\n */\n async getDataOwnersWithAccessTo(entity: EncryptedEntity): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: 'WRITE' }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entity.delegations ?? {}).map((x) => [x, 'WRITE'])),\n hasUnknownAnonymousDataOwners: false,\n }\n }\n\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n async encryptionKeysOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n // Legacy entities may have encryption keys in delegations.\n return this.extractMergedHierarchyFromDelegationAndOwner(\n Object.keys(entity.encryptionKeys ?? {}).length > 0 ? entity.encryptionKeys! : entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async encryptionKeysForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.encryptionKeys ?? {},\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n async secretIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async secretIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.delegations ?? {},\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n async owningEntityIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.cryptedForeignKeys ?? {},\n dataOwnerId,\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async owningEntityIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.cryptedForeignKeys ?? {},\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * @internal this method is intended only for internal use and may be changed without notice.\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, and encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKeys if false this method will not initialize any encryption keys. Use only for entities which use delegations for\n * access control but don't actually have any encrypted content.\n * @param additionalDelegations automatically shares the\n * @param tags tags to associate with the initial encryption keys and metadata\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKeys: boolean,\n additionalDelegations: string[] = [],\n tags: string[] = []\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const secretId = this.primitives.randomUuid()\n const rawEncryptionKey = initialiseEncryptionKeys ? ua2hex(this.primitives.randomBytes(16)) : undefined\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const allIds = [selfId, ...new Set(additionalDelegations.filter((x) => x !== selfId))]\n const loadKeysResult = await this.loadEncryptionKeysForDelegates(entity, allIds)\n const updatedEntity = await allIds.reduce<Promise<T>>(\n async (prevUpdate, delegateId) =>\n await this.createOrUpdateEntityDelegations(\n await prevUpdate,\n delegateId,\n [],\n [],\n [],\n [secretId],\n initialiseEncryptionKeys ? [rawEncryptionKey!] : [],\n owningEntity ? [owningEntity] : [],\n tags,\n loadKeysResult.keysForDelegates\n ),\n Promise.resolve(loadKeysResult.updatedEntity)\n )\n if (owningEntitySecretId) {\n updatedEntity.secretForeignKeys = [owningEntitySecretId]\n }\n return { updatedEntity, secretId, rawEncryptionKey }\n }\n\n async entityWithAutoExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n autoShareSecretIds: boolean,\n delegatesShareInfo: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKey?: ShareMetadataBehaviour\n shareOwningEntityIds?: ShareMetadataBehaviour\n }\n }\n ): Promise<T | undefined> {\n if (!Object.keys(delegatesShareInfo).length) {\n throw new Error('Must specify at least a delegate')\n }\n let defaultSecretIds: string[] | undefined\n if (autoShareSecretIds) {\n const availableSecretIds = await this.secretIdsOf(entity)\n if (availableSecretIds.length) {\n defaultSecretIds = availableSecretIds\n } else {\n defaultSecretIds = [this.primitives.randomUuid()]\n }\n }\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let updatedEntity = undefined\n for (const [delegateId, requests] of Object.entries(delegatesShareInfo)) {\n let shareSecretIds: string[] = autoShareSecretIds ? defaultSecretIds! : requests.shareSecretIds ?? []\n let actualShareEncryptionKeys: string[] = []\n if (requests.shareEncryptionKey !== ShareMetadataBehaviour.NEVER) {\n if (!availableEncryptionKeys.length && requests.shareEncryptionKey === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no encryption keys or the current data owner can't access any encryption keys.`)\n }\n actualShareEncryptionKeys = availableEncryptionKeys\n }\n let actualShareOwningEntityIds: string[] = []\n if (requests.shareOwningEntityIds !== ShareMetadataBehaviour.NEVER) {\n if (!availableOwningEntityIds.length && requests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids.`)\n }\n actualShareOwningEntityIds = availableOwningEntityIds\n }\n updatedEntity =\n (await this.entityWithExtendedEncryptedMetadata(\n updatedEntity ?? entity,\n delegateId,\n shareSecretIds,\n actualShareEncryptionKeys,\n actualShareOwningEntityIds\n )) ?? updatedEntity\n }\n return updatedEntity\n }\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param delegateId id of the delegate to share data with.\n * @param shareSecretIds secret ids to share.\n * @param shareEncryptionKeys encryption keys to share.\n * @param shareOwningEntityIds owning enttiy ids to share.\n * @param newTags tags to associate with the new encryption keys and metadata. Existing data won't be changed.\n * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.\n * @return an updated copy of the entity.\n */\n async entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newTags: string[] = []\n ): Promise<T | undefined> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithSharedEncryptedMetadata', arguments)\n async function checkInputAndGet(input: string[], inputName: string, validate: (x: string) => boolean | Promise<boolean>): Promise<string[]> {\n for (const x of input) {\n const validation = validate(x)\n if (validation !== true && validation !== false && !(await validation)) throw new Error(`Invalid input for ${inputName}.`)\n }\n return input\n }\n const secretIdsToShare = await checkInputAndGet(shareSecretIds, 'secretIds', (x) => this.validateSecretId(x))\n const encryptionKeysToShare = await checkInputAndGet(shareEncryptionKeys, 'encryptionKeys', (x) => this.validateEncryptionKey(x))\n const owningEntityIdsToShare = await checkInputAndGet(shareOwningEntityIds, 'owningEntityIds', (x) => this.validateOwningEntityId(x))\n const deduplicateInfoSecretIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.delegations ?? {},\n secretIdsToShare,\n (x) => this.validateSecretId(x)\n )\n const deduplicateInfoEncryptionKeys = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.encryptionKeys ?? {},\n encryptionKeysToShare,\n (x) => this.validateEncryptionKey(x)\n )\n const deduplicateInfoOwningEntityIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.cryptedForeignKeys ?? {},\n owningEntityIdsToShare,\n (x) => this.validateOwningEntityId(x)\n )\n /*TODO\n * Temporary hack since secret id is necessary to create a delegation for access control: if there is no delegation existing from me to the\n * delegate and there is no new secret id to be created create a new random id.\n */\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (deduplicateInfoSecretIds.missingEntries.length === 0 && !deduplicateInfoSecretIds.deduplicatedDelegations.some((d) => d.owner === selfId)) {\n deduplicateInfoSecretIds.missingEntries.push(this.primitives.randomUuid())\n }\n if (\n deduplicateInfoSecretIds.missingEntries.length === 0 &&\n deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&\n deduplicateInfoOwningEntityIds.missingEntries.length === 0\n )\n return undefined\n const { updatedEntity, keysForDelegates } = await this.loadEncryptionKeysForDelegates(entity, [delegateId])\n return this.createOrUpdateEntityDelegations(\n updatedEntity,\n delegateId,\n deduplicateInfoSecretIds.deduplicatedDelegations,\n deduplicateInfoEncryptionKeys.deduplicatedDelegations,\n deduplicateInfoOwningEntityIds.deduplicatedDelegations,\n deduplicateInfoSecretIds.missingEntries,\n deduplicateInfoEncryptionKeys.missingEntries,\n deduplicateInfoOwningEntityIds.missingEntries,\n newTags,\n keysForDelegates\n )\n }\n\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to encrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to use for encryption only keys associated to tags which pass the filter.\n * @return the encrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n async encryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf((await this.ensureEncryptionKeysInitialised(entity)) ?? entity, dataOwnerId, tagsFilter)\n if (keys.length === 0)\n throw new Error(\n `Could not extract any encryption keys of entity ${entity} for data owner ${\n dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n }.`\n )\n return this.primitives.AES.encryptWithRawKey(keys[0], content)\n }\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @param tagsFilter allows to use for decryption only keys associated to tags which pass the filter.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n async tryDecryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> = () => Promise.resolve(true),\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const keys = await this.encryptionKeysOf(entity, dataOwnerId, tagsFilter)\n for (const key of keys) {\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(key, content)\n if (await validator(decrypted)) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n /* ignore */\n }\n }\n return { data: content, wasDecrypted: false }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Decrypts the content of an encrypted entity.\n */\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n ownerId: string | undefined,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n const encryptionKeys = await this.importAllValidKeys(await this.encryptionKeysOf(entity, ownerId))\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries using the provided keys to decrypt some json.\n */\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n const text = ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted)\n return JSON.parse(text)\n } catch (e) {}\n }\n return undefined\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field\n * which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n dataOwnerId: string | undefined,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity)\n const encryptionKey = await this.tryImportFirstValidKey(await this.encryptionKeysOf(entity, dataOwnerId), entity.id!)\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n entityWithInitialisedEncryptionKeys ?? entity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n 'entity'\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n /**\n * @internal This method is for internal use only and may be changed without notice.\n * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of\n * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities\n * which were previously not encrypted.\n */\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T | undefined> {\n if (Object.keys(entity.encryptionKeys ?? {}).length > 0) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * If entity was using delegations as legacy encryption keys we will essentially revoke the access to the encrypted data for all other data\n * owners. This however should not be a problem as this form of legacy entities should not exist anymore, and it should be present only in the\n * databases of hcps without collaborators.\n */\n return await this.entityWithExtendedEncryptedMetadata(\n entity,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n [],\n [ua2hex(this.primitives.randomBytes(16))],\n []\n )\n }\n\n /**\n * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does\n * not consider exchange keys for parents).\n * Note that the retrieved exchange keys are decrypted using the private keys available on the device, and results may vary from other devices.\n * @param dataOwnerId id of a data owner, he should be part of the current data owner hierarchy.\n * @param delegations a delegation-like object containing the encrypted key\n * @param includeFromDelegations if true also considers delegation from the provided data owner (or parents) to look for values. This allows to\n * decrypt delegations associated to exchange keys recovered after a giveAccessBack request.\n * @param validateDecrypted validates the decrypted result, to drop decryption results with wrong key that still gave a valid checksum.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the key which could be decrypted using only keys available on the current device and delegations from/to the provided data owner. May\n * contain duplicates.\n */\n private async extractFromDelegationsForDataOwner(\n dataOwnerId: string,\n delegations: { [delegateId: string]: Delegation[] },\n includeFromDelegations: boolean,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const delegationsWithOwner = includeFromDelegations\n ? Object.entries(delegations).flatMap(([delegateId, delegations]) =>\n dataOwnerId === delegateId\n ? this.populateDelegatedTo(delegateId, delegations)\n : this.populateDelegatedTo(\n delegateId,\n delegations.filter((d) => d.owner === dataOwnerId)\n )\n )\n : delegations[dataOwnerId] ?? []\n const res = []\n for (const delegation of delegationsWithOwner) {\n if (await tagsFilter(delegation.tags ?? [])) {\n const decrypted = await this.tryDecryptDelegation(delegation, (k) => validateDecrypted(k))\n if (decrypted) res.push(decrypted)\n }\n }\n return res\n }\n\n // Ensures that the delegatedTo field of delegations has the appropriate values, else returns a copy of the delegations with the appropriate value.\n private populateDelegatedTo(delegateId: string, delegations: Delegation[]): Delegation[] {\n return delegations.map((d) => (d.delegatedTo === delegateId ? d : { ...d, delegatedTo: delegateId }))\n }\n\n private async extractedHierarchyFromDelegation(\n delegations: { [delegateId: string]: Delegation[] },\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n return Promise.all(\n canDecryptOwnerIds.map(async (ownerId) => {\n const extracted = this.deduplicate(\n await this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n return { ownerId, extracted }\n })\n )\n }\n\n /**\n * @internal This method should be private but is currently public/internal to allow to continue supporting legacy methods\n */\n async extractMergedHierarchyFromDelegationAndOwner(\n delegations: { [delegateId: string]: Delegation[] },\n dataOwnerId: string | undefined,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const extractedByOwner = await Promise.all(\n // Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.\n [...hierarchy].reverse().map((ownerId) =>\n this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n )\n return this.deduplicate(extractedByOwner.flatMap((x) => x))\n }\n\n private async tryDecryptDelegation(\n delegation: Delegation,\n validateDecrypted: (result: string) => boolean | Promise<boolean>\n ): Promise<string | undefined> {\n const exchangeKeys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegation.owner!, delegation.delegatedTo!)\n for (const key of exchangeKeys) {\n try {\n // Format of encrypted key for any delegation should be entityId:key, but with the merging of entities the entityId might not match the\n // current id. As a checksum we are only verifying that the decrypted bytes can be represented as a string with exactly one ':'.\n // Additionally, we also have a validator that is specific for each type of delegation content (encryption key, secret id, ...)\n const decrypted = ua2string(await this.primitives.AES.decrypt(key, hex2ua(delegation.key!)))\n const decryptedSplit = decrypted.split(':')\n if (decryptedSplit.length === 2) {\n const validation = validateDecrypted(decryptedSplit[1])\n if (validation === true || (validation !== false && (await validation))) return decryptedSplit[1]\n } else {\n console.warn(\"Error in the decrypted delegation: content should contain exactly 1 ':', the delegation is ignored.\")\n }\n } catch (e) {\n // Do nothing: the delegation uses another exchange key owner->delegator\n }\n }\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(keys, entityId)\n if (!res) throw new Error(`Could not find any valid key for entity ${entityId}.`)\n return res\n }\n\n private async tryImportFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string } | undefined> {\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) return { key: imported, raw: key }\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importAllValidKeys(keys: string[]): Promise<{ key: CryptoKey; raw: string }[]> {\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n private async validateEncryptionKey(key: string): Promise<boolean> {\n return !!(await this.tryImportKey(key))\n }\n\n private validateSecretId(key: string): boolean {\n return !!key\n }\n\n private validateOwningEntityId(key: string): boolean {\n return !!key\n }\n\n private async createEncryptionKeyDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n encryptionKey: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!(await this.validateEncryptionKey(encryptionKey))) throw new Error(`Invalid encryption key ${encryptionKey}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, encryptionKey, newTags)\n }\n\n private async createSecretIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n secretId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateSecretId(secretId)) throw new Error(`Invalid secret id ${secretId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, secretId, newTags)\n }\n\n private async createOwningEntityIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n owningEntityId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateOwningEntityId(owningEntityId)) throw new Error(`Invalid owning id ${owningEntityId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, owningEntityId, newTags)\n }\n\n private async createDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n content: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (entityId.includes(':')) throw new Error(\"Ids for encrypted entities are not allowed to contain ':'\")\n if (content.includes(':')) throw new Error(\"Content of delegations can not contain ':'\")\n return {\n delegatedTo: delegateId,\n owner: await this.dataOwnerApi.getCurrentDataOwnerId(),\n key: ua2hex(await this.primitives.AES.encrypt(exchangeKey, string2ua(entityId + ':' + content))),\n tags: newTags,\n }\n }\n\n private async loadEncryptionKeysForDelegates<T extends EncryptedEntity>(\n entity: T,\n delegates: string[]\n ): Promise<{ updatedEntity: T; keysForDelegates: { [delegateId: string]: CryptoKey[] } }> {\n const { updatedDelegator, keysForDelegates } = await delegates.reduce(\n async (acc, delegateId) => {\n const awaitedAcc = await acc\n const currUpdateResult = await this.exchangeKeysManager.getOrCreateEncryptionExchangeKeysTo(delegateId)\n return {\n updatedDelegator: currUpdateResult.updatedDelegator ?? awaitedAcc.updatedDelegator,\n keysForDelegates: {\n ...awaitedAcc.keysForDelegates,\n [delegateId]: currUpdateResult.keys,\n },\n }\n },\n Promise.resolve({\n updatedDelegator: undefined as CryptoActorStubWithType | undefined,\n keysForDelegates: {} as { [delegateId: string]: CryptoKey[] },\n })\n )\n const updatedEntity =\n entity.id === updatedDelegator?.stub?.id\n ? {\n ...entity,\n rev: updatedDelegator!.stub.rev,\n hcPartyKeys: updatedDelegator!.stub.hcPartyKeys,\n aesExchangeKeys: updatedDelegator!.stub.aesExchangeKeys,\n }\n : entity\n return { updatedEntity, keysForDelegates }\n }\n\n private async createOrUpdateEntityDelegations<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n existingSecretIds: Delegation[],\n existingEncryptionKeys: Delegation[],\n existingOwningEntityIds: Delegation[],\n newSecretIds: string[],\n newEncryptionKeys: string[],\n newOwningEntityIds: string[],\n newTags: string[],\n keysForDelegates: { [delegateId: string]: CryptoKey[] }\n ): Promise<T> {\n const entityCopy = _.cloneDeep(entity)\n if (newSecretIds.length === 0 && newEncryptionKeys.length === 0 && newOwningEntityIds.length === 0) return entityCopy\n const chosenKey = keysForDelegates[delegateId][0]\n const updatedSecretIds = [\n ...existingSecretIds,\n ...(await Promise.all(newSecretIds.map((x) => this.createSecretIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedEncryptionKeys = [\n ...existingEncryptionKeys,\n ...(await Promise.all(newEncryptionKeys.map((x) => this.createEncryptionKeyDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedOwningEntityIds = [\n ...existingOwningEntityIds,\n ...(await Promise.all(newOwningEntityIds.map((x) => this.createOwningEntityIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n if (updatedSecretIds.length > 0) {\n entityCopy.delegations = {\n ...(entity.delegations ?? {}),\n [delegateId]: updatedSecretIds,\n }\n }\n if (updatedEncryptionKeys.length > 0) {\n entityCopy.encryptionKeys = {\n ...(entity.encryptionKeys ?? {}),\n [delegateId]: updatedEncryptionKeys,\n }\n }\n if (updatedOwningEntityIds.length > 0) {\n entityCopy.cryptedForeignKeys = {\n ...(entity.cryptedForeignKeys ?? {}),\n [delegateId]: updatedOwningEntityIds,\n }\n }\n return entityCopy\n }\n\n /**\n * De-duplicates all currently accessible delegations, by removing any delegations created by the current data owner which have duplicated content,\n * and checks if any of the required entries are currently available to the delegate through the existing delegations.\n * @param delegateId id of the delegate.\n * @param allDelegations delegations of the entity.\n * @param requiredEntries potentially new entries that the delegate needs to be able to access from the delegations.\n * @param validateDecrypted validator for decrypted delegation content\n * @return the deduplicated delegations\n */\n private async deduplicateDelegationsAndFilterRequiredEntries(\n delegateId: string,\n allDelegations: { [delegateId: string]: Delegation[] },\n requiredEntries: string[],\n validateDecrypted: (x: string) => boolean | Promise<boolean>\n ): Promise<{\n deduplicatedDelegations: Delegation[]\n missingEntries: string[]\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const delegationsToDelegate = allDelegations[delegateId] ?? []\n const decryptedDelegations = await Promise.all(\n delegationsToDelegate.map(async (d) => ({\n delegation: d,\n content: d.owner === selfId ? await this.tryDecryptDelegation(d, (x) => validateDecrypted(x)) : undefined,\n }))\n )\n const deduplicatedDelegations: Delegation[] = []\n const deduplicatedContent = new Map<string, string[][]>()\n decryptedDelegations.forEach(({ delegation, content }) => {\n if (content === undefined) {\n // Keep all delegations we could not decrypt or from other data owners\n deduplicatedDelegations.push(delegation)\n } else {\n const deduplicatedTags = deduplicatedContent.get(content)\n if (!deduplicatedTags) {\n deduplicatedContent.set(content, [delegation.tags ?? []])\n deduplicatedDelegations.push(delegation)\n } else if (!deduplicatedTags.some((t) => arrayEquals(t, delegation.tags ?? []))) {\n deduplicatedTags.push(delegation.tags ?? [])\n deduplicatedDelegations.push(delegation)\n }\n }\n })\n const delegationsFromDelegateToSelf = (allDelegations[selfId] ?? []).filter((d) => d.owner === delegateId)\n const decryptedDelegationsFromDelegate = new Set(\n await Promise.all(delegationsFromDelegateToSelf.map((d) => this.tryDecryptDelegation(d, (x) => validateDecrypted(x)))).then((dels) =>\n dels.flatMap((x) => (x ? [x] : []))\n )\n )\n return {\n deduplicatedDelegations,\n missingEntries: requiredEntries.filter((entry) => !(deduplicatedContent.has(entry) || decryptedDelegationsFromDelegate.has(entry))),\n }\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n _.each(argsArray, (arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (existingMetadata.length > 0) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"KeyManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/KeyManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAiC;AAGjC,mCAAsE;AAoBtE,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAA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aACF;YACD,OAAO,UAAU,CAAA;QACnB,CAAC;KAAA;IAEO,qBAAqB,CAAI,GAAyC;QACxE,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IACnF,CAAC;IAEO,cAAc,CAAC,QAAuC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AA5XD,gCA4XC","sourcesContent":["import { DataOwner, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { fingerprintToPublicKeysMapOf, loadPublicKeys } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class KeyManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly baseExchangeKeyManager: BaseExchangeKeysManager,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey> }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair }) => ({ pair })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey?.slice(-32)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwner): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from(this.dataOwnerApi.getHexPublicKeysOf(dataOwner)).filter((key) => {\n const fp = key.slice(-32)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = (await this.dataOwnerApi.getCurrentDataOwnerHierarchy()).map(({ dataOwner, type }) => {\n if (dataOwner.publicKey == '') {\n if (Object.entries(dataOwner.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${dataOwner.id} has \"\" as public key but has non-empty hcPartyKeys`)\n delete dataOwner.publicKey\n }\n return {\n dataOwner,\n type,\n } as DataOwnerWithType\n })\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {\n const availableKeys = await this.loadAndRecoverKeysFor(dowt)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dowt.dataOwner)\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(key.slice(-32)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(x.slice(-32) in verifiedKeysMap) && !(availableKeys?.[x.slice(-32)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (const keyData of keysData) {\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp],\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(keyData.dowt, this.plainKeysByFingerprint(keysWithExternallyRecovered))\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair())\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const publicKeyFingerprint = publicKeyHex.slice(-32)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n const verifiedPublicKeysMap = await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const { updatedDelegator } = await this.baseExchangeKeyManager.createOrUpdateEncryptedExchangeKeyTo(\n selfDataOwner.dataOwner.id!,\n keyPair,\n await loadPublicKeys(\n this.primitives.RSA,\n Array.from(this.dataOwnerApi.getHexPublicKeysOf(selfDataOwner.dataOwner)).filter((x) => verifiedPublicKeysMap[x.slice(-32)])\n )\n )\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf: updatedDelegator }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: string[]\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n return await pubKeysFingerprints.reduce(async (acc, currentFingerprint) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair('jwk', storedKeypair.pair.privateKey, 'jwk', storedKeypair.pair.publicKey)\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(dataOwner: DataOwnerWithType): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const selfPublicKeys = this.dataOwnerApi.getHexPublicKeysOf(dataOwner.dataOwner)\n const pubKeysFingerprints = Array.from(selfPublicKeys).map((x) => x.slice(-32))\n const loadedKeys = pubKeysFingerprints.length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (loadedKeysFingerprints.length !== pubKeysFingerprints.length && loadedKeysFingerprints.length > 0) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint(loadedKeys))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k.slice(-32), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}