@icure/api 7.1.13 → 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 (337) hide show
  1. package/icc-api/api/IccAccesslogApi.d.ts +23 -1
  2. package/icc-api/api/IccAccesslogApi.js +154 -84
  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 +28 -5
  26. package/icc-api/api/IccFormApi.js +328 -222
  27. package/icc-api/api/IccFormApi.js.map +1 -1
  28. package/icc-api/api/IccGroupApi.d.ts +40 -7
  29. package/icc-api/api/IccGroupApi.js +91 -16
  30. package/icc-api/api/IccGroupApi.js.map +1 -1
  31. package/icc-api/api/IccHelementApi.d.ts +21 -1
  32. package/icc-api/api/IccHelementApi.js +207 -137
  33. package/icc-api/api/IccHelementApi.js.map +1 -1
  34. package/icc-api/api/IccInvoiceApi.d.ts +21 -1
  35. package/icc-api/api/IccInvoiceApi.js +404 -298
  36. package/icc-api/api/IccInvoiceApi.js.map +1 -1
  37. package/icc-api/api/IccMaintenanceTaskApi.d.ts +12 -1
  38. package/icc-api/api/IccMaintenanceTaskApi.js +79 -43
  39. package/icc-api/api/IccMaintenanceTaskApi.js.map +1 -1
  40. package/icc-api/api/IccMessageApi.d.ts +12 -1
  41. package/icc-api/api/IccMessageApi.js +257 -191
  42. package/icc-api/api/IccMessageApi.js.map +1 -1
  43. package/icc-api/api/IccPatientApi.d.ts +12 -1
  44. package/icc-api/api/IccPatientApi.js +447 -351
  45. package/icc-api/api/IccPatientApi.js.map +1 -1
  46. package/icc-api/api/IccReceiptApi.d.ts +22 -8
  47. package/icc-api/api/IccReceiptApi.js +121 -64
  48. package/icc-api/api/IccReceiptApi.js.map +1 -1
  49. package/icc-api/api/IccRestApiPath.js +1 -1
  50. package/icc-api/api/IccRestApiPath.js.map +1 -1
  51. package/icc-api/api/IccTimeTableApi.d.ts +12 -1
  52. package/icc-api/api/IccTimeTableApi.js +86 -48
  53. package/icc-api/api/IccTimeTableApi.js.map +1 -1
  54. package/icc-api/api/XHR.js +1 -1
  55. package/icc-api/api/XHR.js.map +1 -1
  56. package/icc-api/index.d.ts +1 -0
  57. package/icc-api/index.js +1 -0
  58. package/icc-api/index.js.map +1 -1
  59. package/icc-api/model/AccessLog.d.ts +4 -0
  60. package/icc-api/model/AccessLog.js +1 -0
  61. package/icc-api/model/AccessLog.js.map +1 -1
  62. package/icc-api/model/Article.d.ts +4 -0
  63. package/icc-api/model/Article.js +1 -0
  64. package/icc-api/model/Article.js.map +1 -1
  65. package/icc-api/model/CalendarItem.d.ts +6 -1
  66. package/icc-api/model/CalendarItem.js +1 -0
  67. package/icc-api/model/CalendarItem.js.map +1 -1
  68. package/icc-api/model/Classification.d.ts +4 -0
  69. package/icc-api/model/Classification.js +1 -0
  70. package/icc-api/model/Classification.js.map +1 -1
  71. package/icc-api/model/ClassificationTemplate.d.ts +2 -0
  72. package/icc-api/model/ClassificationTemplate.js.map +1 -1
  73. package/icc-api/model/Contact.d.ts +4 -0
  74. package/icc-api/model/Contact.js +1 -0
  75. package/icc-api/model/Contact.js.map +1 -1
  76. package/icc-api/model/Device.d.ts +4 -4
  77. package/icc-api/model/Device.js.map +1 -1
  78. package/icc-api/model/Document.d.ts +4 -0
  79. package/icc-api/model/Document.js +1 -0
  80. package/icc-api/model/Document.js.map +1 -1
  81. package/icc-api/model/ExchangeData.d.ts +61 -0
  82. package/icc-api/model/ExchangeData.js +12 -0
  83. package/icc-api/model/ExchangeData.js.map +1 -0
  84. package/icc-api/model/ExchangeDataMap.d.ts +21 -0
  85. package/icc-api/model/ExchangeDataMap.js +10 -0
  86. package/icc-api/model/ExchangeDataMap.js.map +1 -0
  87. package/icc-api/model/ExchangeDataMapCreationBatch.d.ts +13 -0
  88. package/icc-api/model/ExchangeDataMapCreationBatch.js +10 -0
  89. package/icc-api/model/ExchangeDataMapCreationBatch.js.map +1 -0
  90. package/icc-api/model/Form.d.ts +4 -0
  91. package/icc-api/model/Form.js +1 -0
  92. package/icc-api/model/Form.js.map +1 -1
  93. package/icc-api/model/FormTemplate.d.ts +2 -1
  94. package/icc-api/model/FormTemplate.js +2 -1
  95. package/icc-api/model/FormTemplate.js.map +1 -1
  96. package/icc-api/model/Group.d.ts +7 -0
  97. package/icc-api/model/Group.js.map +1 -1
  98. package/icc-api/model/GroupDatabasesInfo.d.ts +1 -0
  99. package/icc-api/model/GroupDatabasesInfo.js.map +1 -1
  100. package/icc-api/model/HealthElement.d.ts +4 -0
  101. package/icc-api/model/HealthElement.js +1 -0
  102. package/icc-api/model/HealthElement.js.map +1 -1
  103. package/icc-api/model/HealthcareParty.d.ts +2 -2
  104. package/icc-api/model/HealthcareParty.js.map +1 -1
  105. package/icc-api/model/IcureStub.d.ts +2 -0
  106. package/icc-api/model/IcureStub.js.map +1 -1
  107. package/icc-api/model/Invoice.d.ts +4 -0
  108. package/icc-api/model/Invoice.js +1 -0
  109. package/icc-api/model/Invoice.js.map +1 -1
  110. package/icc-api/model/MaintenanceTask.d.ts +4 -0
  111. package/icc-api/model/MaintenanceTask.js +1 -0
  112. package/icc-api/model/MaintenanceTask.js.map +1 -1
  113. package/icc-api/model/Message.d.ts +4 -0
  114. package/icc-api/model/Message.js +1 -0
  115. package/icc-api/model/Message.js.map +1 -1
  116. package/icc-api/model/OperationToken.d.ts +18 -0
  117. package/icc-api/model/OperationToken.js +21 -0
  118. package/icc-api/model/OperationToken.js.map +1 -0
  119. package/icc-api/model/PaginatedListExchangeData.d.ts +9 -0
  120. package/icc-api/model/PaginatedListExchangeData.js +10 -0
  121. package/icc-api/model/PaginatedListExchangeData.js.map +1 -0
  122. package/icc-api/model/Patient.d.ts +6 -2
  123. package/icc-api/model/Patient.js +1 -0
  124. package/icc-api/model/Patient.js.map +1 -1
  125. package/icc-api/model/PatientByHcPartyGenderEducationProfession.d.ts +31 -0
  126. package/icc-api/model/PatientByHcPartyGenderEducationProfession.js +32 -0
  127. package/icc-api/model/PatientByHcPartyGenderEducationProfession.js.map +1 -0
  128. package/icc-api/model/Receipt.d.ts +4 -0
  129. package/icc-api/model/Receipt.js +1 -0
  130. package/icc-api/model/Receipt.js.map +1 -1
  131. package/icc-api/model/SecureDelegation.d.ts +52 -0
  132. package/icc-api/model/SecureDelegation.js +16 -0
  133. package/icc-api/model/SecureDelegation.js.map +1 -0
  134. package/icc-api/model/SecurityMetadata.d.ts +33 -0
  135. package/icc-api/model/SecurityMetadata.js +13 -0
  136. package/icc-api/model/SecurityMetadata.js.map +1 -0
  137. package/icc-api/model/Service.d.ts +2 -0
  138. package/icc-api/model/Service.js.map +1 -1
  139. package/icc-api/model/TimeTable.d.ts +4 -0
  140. package/icc-api/model/TimeTable.js +1 -0
  141. package/icc-api/model/TimeTable.js.map +1 -1
  142. package/icc-api/model/models.d.ts +20 -39
  143. package/icc-api/model/models.js +15 -37
  144. package/icc-api/model/models.js.map +1 -1
  145. package/icc-api/model/requests/EntityBulkShareResult.d.ts +28 -0
  146. package/icc-api/model/requests/EntityBulkShareResult.js +16 -0
  147. package/icc-api/model/requests/EntityBulkShareResult.js.map +1 -0
  148. package/icc-api/model/requests/EntityShareOrMetadataUpdateRequest.d.ts +10 -0
  149. package/icc-api/model/requests/EntityShareOrMetadataUpdateRequest.js +17 -0
  150. package/icc-api/model/requests/EntityShareOrMetadataUpdateRequest.js.map +1 -0
  151. package/icc-api/model/requests/EntityShareRequest.d.ts +110 -0
  152. package/icc-api/model/requests/EntityShareRequest.js +63 -0
  153. package/icc-api/model/requests/EntityShareRequest.js.map +1 -0
  154. package/icc-api/model/requests/EntitySharedMetadataUpdateRequest.d.ts +54 -0
  155. package/icc-api/model/requests/EntitySharedMetadataUpdateRequest.js +24 -0
  156. package/icc-api/model/requests/EntitySharedMetadataUpdateRequest.js.map +1 -0
  157. package/icc-api/model/requests/MinimalEntityBulkShareResult.d.ts +23 -0
  158. package/icc-api/model/requests/MinimalEntityBulkShareResult.js +13 -0
  159. package/icc-api/model/requests/MinimalEntityBulkShareResult.js.map +1 -0
  160. package/icc-api/model/requests/RejectedShareOrMetadataUpdateRequest.d.ts +21 -0
  161. package/icc-api/model/requests/RejectedShareOrMetadataUpdateRequest.js +14 -0
  162. package/icc-api/model/requests/RejectedShareOrMetadataUpdateRequest.js.map +1 -0
  163. package/icc-x-api/basexapi/EncryptedEntityXApi.d.ts +3 -2
  164. package/icc-x-api/basexapi/EncryptedEntityXApi.js.map +1 -1
  165. package/icc-x-api/crypto/AES.js +1 -1
  166. package/icc-x-api/crypto/AES.js.map +1 -1
  167. package/icc-x-api/crypto/AccessControlKeysHeadersProvider.d.ts +16 -0
  168. package/icc-x-api/crypto/AccessControlKeysHeadersProvider.js +41 -0
  169. package/icc-x-api/crypto/AccessControlKeysHeadersProvider.js.map +1 -0
  170. package/icc-x-api/crypto/AccessControlSecretUtils.d.ts +42 -0
  171. package/icc-x-api/crypto/AccessControlSecretUtils.js +86 -0
  172. package/icc-x-api/crypto/AccessControlSecretUtils.js.map +1 -0
  173. package/icc-x-api/crypto/BaseExchangeDataManager.d.ts +146 -0
  174. package/icc-x-api/crypto/BaseExchangeDataManager.js +342 -0
  175. package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -0
  176. package/icc-x-api/crypto/BaseExchangeKeysManager.d.ts +0 -18
  177. package/icc-x-api/crypto/BaseExchangeKeysManager.js +11 -85
  178. package/icc-x-api/crypto/BaseExchangeKeysManager.js.map +1 -1
  179. package/icc-x-api/crypto/ConfidentialEntities.d.ts +26 -16
  180. package/icc-x-api/crypto/ConfidentialEntities.js +30 -17
  181. package/icc-x-api/crypto/ConfidentialEntities.js.map +1 -1
  182. package/icc-x-api/crypto/CryptoStrategies.d.ts +8 -1
  183. package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
  184. package/icc-x-api/crypto/ExchangeDataManager.d.ts +95 -0
  185. package/icc-x-api/crypto/ExchangeDataManager.js +493 -0
  186. package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -0
  187. package/icc-x-api/crypto/ExchangeDataMapManager.d.ts +32 -0
  188. package/icc-x-api/crypto/ExchangeDataMapManager.js +70 -0
  189. package/icc-x-api/crypto/ExchangeDataMapManager.js.map +1 -0
  190. package/icc-x-api/crypto/ExchangeKeysManager.d.ts +4 -16
  191. package/icc-x-api/crypto/ExchangeKeysManager.js +4 -62
  192. package/icc-x-api/crypto/ExchangeKeysManager.js.map +1 -1
  193. package/icc-x-api/crypto/ExtendedApisUtils.d.ts +336 -0
  194. package/icc-x-api/crypto/ExtendedApisUtils.js +3 -0
  195. package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -0
  196. package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +181 -0
  197. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +562 -0
  198. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -0
  199. package/icc-x-api/crypto/KeyRecovery.d.ts +5 -2
  200. package/icc-x-api/crypto/KeyRecovery.js +59 -29
  201. package/icc-x-api/crypto/KeyRecovery.js.map +1 -1
  202. package/icc-x-api/crypto/LegacyCryptoStrategies.d.ts +7 -2
  203. package/icc-x-api/crypto/LegacyCryptoStrategies.js +8 -1
  204. package/icc-x-api/crypto/LegacyCryptoStrategies.js.map +1 -1
  205. package/icc-x-api/crypto/LegacyDelegationSecurityMetadataDecryptor.d.ts +39 -0
  206. package/icc-x-api/crypto/LegacyDelegationSecurityMetadataDecryptor.js +150 -0
  207. package/icc-x-api/crypto/LegacyDelegationSecurityMetadataDecryptor.js.map +1 -0
  208. package/icc-x-api/crypto/RSA.d.ts +34 -8
  209. package/icc-x-api/crypto/RSA.js +80 -13
  210. package/icc-x-api/crypto/RSA.js.map +1 -1
  211. package/icc-x-api/crypto/SecureDelegationsEncryption.d.ts +54 -0
  212. package/icc-x-api/crypto/SecureDelegationsEncryption.js +178 -0
  213. package/icc-x-api/crypto/SecureDelegationsEncryption.js.map +1 -0
  214. package/icc-x-api/crypto/SecureDelegationsManager.d.ts +66 -0
  215. package/icc-x-api/crypto/SecureDelegationsManager.js +261 -0
  216. package/icc-x-api/crypto/SecureDelegationsManager.js.map +1 -0
  217. package/icc-x-api/crypto/SecureDelegationsSecurityMetadataDecryptor.d.ts +37 -0
  218. package/icc-x-api/crypto/SecureDelegationsSecurityMetadataDecryptor.js +294 -0
  219. package/icc-x-api/crypto/SecureDelegationsSecurityMetadataDecryptor.js.map +1 -0
  220. package/icc-x-api/crypto/SecurityMetadataDecryptor.d.ts +114 -0
  221. package/icc-x-api/crypto/SecurityMetadataDecryptor.js +98 -0
  222. package/icc-x-api/crypto/SecurityMetadataDecryptor.js.map +1 -0
  223. package/icc-x-api/crypto/ShamirKeysManager.d.ts +5 -5
  224. package/icc-x-api/crypto/ShamirKeysManager.js +6 -9
  225. package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
  226. package/icc-x-api/crypto/TransferKeysManager.d.ts +8 -6
  227. package/icc-x-api/crypto/TransferKeysManager.js +75 -52
  228. package/icc-x-api/crypto/TransferKeysManager.js.map +1 -1
  229. package/icc-x-api/crypto/{KeyManager.d.ts → UserEncryptionKeysManager.d.ts} +4 -6
  230. package/icc-x-api/crypto/{KeyManager.js → UserEncryptionKeysManager.js} +43 -23
  231. package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -0
  232. package/icc-x-api/crypto/UserSignatureKeysManager.d.ts +26 -0
  233. package/icc-x-api/crypto/UserSignatureKeysManager.js +74 -0
  234. package/icc-x-api/crypto/UserSignatureKeysManager.js.map +1 -0
  235. package/icc-x-api/crypto/utils.d.ts +61 -11
  236. package/icc-x-api/crypto/utils.js +113 -44
  237. package/icc-x-api/crypto/utils.js.map +1 -1
  238. package/icc-x-api/filters/filters.js.map +1 -1
  239. package/icc-x-api/icc-accesslog-x-api.d.ts +46 -11
  240. package/icc-x-api/icc-accesslog-x-api.js +75 -42
  241. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  242. package/icc-x-api/icc-calendar-item-x-api.d.ts +50 -14
  243. package/icc-x-api/icc-calendar-item-x-api.js +99 -49
  244. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  245. package/icc-x-api/icc-classification-x-api.d.ts +44 -9
  246. package/icc-x-api/icc-classification-x-api.js +56 -31
  247. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  248. package/icc-x-api/icc-contact-x-api.d.ts +56 -32
  249. package/icc-x-api/icc-contact-x-api.js +95 -64
  250. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  251. package/icc-x-api/icc-crypto-x-api.d.ts +28 -334
  252. package/icc-x-api/icc-crypto-x-api.js +41 -765
  253. package/icc-x-api/icc-crypto-x-api.js.map +1 -1
  254. package/icc-x-api/icc-data-owner-x-api.d.ts +20 -8
  255. package/icc-x-api/icc-data-owner-x-api.js +31 -10
  256. package/icc-x-api/icc-data-owner-x-api.js.map +1 -1
  257. package/icc-x-api/icc-document-x-api.d.ts +48 -11
  258. package/icc-x-api/icc-document-x-api.js +111 -64
  259. package/icc-x-api/icc-document-x-api.js.map +1 -1
  260. package/icc-x-api/icc-form-x-api.d.ts +45 -10
  261. package/icc-x-api/icc-form-x-api.js +65 -35
  262. package/icc-x-api/icc-form-x-api.js.map +1 -1
  263. package/icc-x-api/icc-hcparty-x-api.d.ts +2 -2
  264. package/icc-x-api/icc-hcparty-x-api.js +3 -3
  265. package/icc-x-api/icc-hcparty-x-api.js.map +1 -1
  266. package/icc-x-api/icc-helement-x-api.d.ts +55 -18
  267. package/icc-x-api/icc-helement-x-api.js +76 -41
  268. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  269. package/icc-x-api/icc-icure-maintenance-x-api.d.ts +7 -2
  270. package/icc-x-api/icc-icure-maintenance-x-api.js +38 -27
  271. package/icc-x-api/icc-icure-maintenance-x-api.js.map +1 -1
  272. package/icc-x-api/icc-invoice-x-api.d.ts +50 -15
  273. package/icc-x-api/icc-invoice-x-api.js +63 -33
  274. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  275. package/icc-x-api/icc-maintenance-task-x-api.d.ts +53 -21
  276. package/icc-x-api/icc-maintenance-task-x-api.js +72 -35
  277. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  278. package/icc-x-api/icc-message-x-api.d.ts +53 -15
  279. package/icc-x-api/icc-message-x-api.js +65 -36
  280. package/icc-x-api/icc-message-x-api.js.map +1 -1
  281. package/icc-x-api/icc-patient-x-api.d.ts +84 -29
  282. package/icc-x-api/icc-patient-x-api.js +313 -378
  283. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  284. package/icc-x-api/icc-receipt-x-api.d.ts +44 -12
  285. package/icc-x-api/icc-receipt-x-api.js +67 -35
  286. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  287. package/icc-x-api/icc-time-table-x-api.d.ts +43 -12
  288. package/icc-x-api/icc-time-table-x-api.js +56 -26
  289. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  290. package/icc-x-api/icc-user-x-api.d.ts +2 -2
  291. package/icc-x-api/icc-user-x-api.js +3 -3
  292. package/icc-x-api/icc-user-x-api.js.map +1 -1
  293. package/icc-x-api/index.d.ts +4 -2
  294. package/icc-x-api/index.js +154 -135
  295. package/icc-x-api/index.js.map +1 -1
  296. package/icc-x-api/storage/DefaultStorageEntryKeysFactory.d.ts +2 -0
  297. package/icc-x-api/storage/DefaultStorageEntryKeysFactory.js +9 -2
  298. package/icc-x-api/storage/DefaultStorageEntryKeysFactory.js.map +1 -1
  299. package/icc-x-api/storage/IcureStorageFacade.d.ts +23 -2
  300. package/icc-x-api/storage/IcureStorageFacade.js +36 -2
  301. package/icc-x-api/storage/IcureStorageFacade.js.map +1 -1
  302. package/icc-x-api/storage/KeyStorageFacade.d.ts +12 -0
  303. package/icc-x-api/storage/KeyStorageFacade.js.map +1 -1
  304. package/icc-x-api/storage/KeyStorageImpl.d.ts +2 -0
  305. package/icc-x-api/storage/KeyStorageImpl.js +10 -0
  306. package/icc-x-api/storage/KeyStorageImpl.js.map +1 -1
  307. package/icc-x-api/storage/StorageEntryKeysFactory.d.ts +14 -1
  308. package/icc-x-api/storage/StorageEntryKeysFactory.js.map +1 -1
  309. package/icc-x-api/utils/EntityWithDelegationTypeName.d.ts +32 -0
  310. package/icc-x-api/utils/EntityWithDelegationTypeName.js +75 -0
  311. package/icc-x-api/utils/EntityWithDelegationTypeName.js.map +1 -0
  312. package/icc-x-api/utils/ShareResult.d.ts +74 -0
  313. package/icc-x-api/utils/ShareResult.js +61 -0
  314. package/icc-x-api/utils/ShareResult.js.map +1 -0
  315. package/icc-x-api/utils/binary-utils.d.ts +1 -0
  316. package/icc-x-api/utils/binary-utils.js +8 -1
  317. package/icc-x-api/utils/binary-utils.js.map +1 -1
  318. package/icc-x-api/utils/collection-utils.d.ts +5 -0
  319. package/icc-x-api/utils/collection-utils.js +26 -1
  320. package/icc-x-api/utils/collection-utils.js.map +1 -1
  321. package/icc-x-api/utils/crypto-utils.d.ts +4 -3
  322. package/icc-x-api/utils/crypto-utils.js +5 -4
  323. package/icc-x-api/utils/crypto-utils.js.map +1 -1
  324. package/icc-x-api/utils/lru-temporised-async-cache.d.ts +26 -3
  325. package/icc-x-api/utils/lru-temporised-async-cache.js +75 -15
  326. package/icc-x-api/utils/lru-temporised-async-cache.js.map +1 -1
  327. package/icc-x-api/utils/websocket.d.ts +10 -10
  328. package/icc-x-api/utils/websocket.js +18 -9
  329. package/icc-x-api/utils/websocket.js.map +1 -1
  330. package/index.d.ts +1 -1
  331. package/index.js +3 -1
  332. package/index.js.map +1 -1
  333. package/package.json +2 -3
  334. package/icc-x-api/crypto/EntitiesEncryption.d.ts +0 -275
  335. package/icc-x-api/crypto/EntitiesEncryption.js +0 -734
  336. package/icc-x-api/crypto/EntitiesEncryption.js.map +0 -1
  337. package/icc-x-api/crypto/KeyManager.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseExchangeDataManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeDataManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,mEAA+D;AAE/D,+CAA2C;AAC3C,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAE9B,oCAA6E;AAC7E,4BAA2B;AAC3B,mCAA4D;AAE5D;;;;GAIG;AACH,MAAa,uBAAuB;IAClC,YACW,GAAuB,EACf,YAA8B,EAC9B,UAA4B,EAC5B,gCAAyC;QAHjD,QAAG,GAAH,GAAG,CAAoB;QACf,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,eAAU,GAAV,UAAU,CAAkB;QAC5B,qCAAgC,GAAhC,gCAAgC,CAAS;IACzD,CAAC;IAEJ;;;;;;OAMG;IACG,8CAA8C;;;YAClD,IAAI,CAAC,IAAI,CAAC,gCAAgC;gBAAE,OAAO,SAAS,C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C,CAAC,CAAC,CAAA;aAClI;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;IAEa,gBAAgB,CAC5B,OAAoB,EACpB,IAAiD;;YAEjD,MAAM,GAAG,GAA6C,EAAE,CAAA;YACxD,KAAK,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;gBAC5C,GAAG,CAAC,EAAE,CAAC,GAAG,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;aAC/E;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;CACF;AArXD,0DAqXC","sourcesContent":["import { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ExchangeData } from '../../icc-api/model/ExchangeData'\nimport { IccExchangeDataApi } from '../../icc-api/api/IccExchangeDataApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport XHRError = XHR.XHRError\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { b64_2ua, hex2ua, ua2b64, ua2hex, ua2utf8, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { fingerprintV1toV2, fingerprintIsV1 } from './utils'\n\n/**\n * @internal this class is intended for internal use only and may be modified without notice\n * Functions to create and get exchange data.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeDataManager {\n constructor(\n readonly api: IccExchangeDataApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly primitives: CryptoPrimitives,\n private readonly selfRequiresAnonymousDelegations: boolean\n ) {}\n\n /**\n * Get all the exchange data where the current data owner is the delegator or the delegate. However, some data owners, generally HCPs, may have a\n * prohibitively high amount of exchange data. If the crypto strategies specify that the current data owner requires anonymous delegation this\n * method returns all the exchange data found for the data owner, else the method returns undefined.\n * @return all the exchange data for the current data owner or undefined if the crypto strategies don't allow to retrieve all data for the current\n * data owner.\n */\n async getAllExchangeDataForCurrentDataOwnerIfAllowed(): Promise<ExchangeData[] | undefined> {\n if (!this.selfRequiresAnonymousDelegations) return undefined\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n let latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, undefined, 1000)\n const allRetrieved = latestResult.rows ?? []\n while (latestResult.nextKeyPair?.startKeyDocId) {\n latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, latestResult.nextKeyPair.startKeyDocId, 1000)\n if (latestResult.rows) allRetrieved.push(...latestResult.rows)\n }\n return allRetrieved\n }\n\n /**\n * Get all exchange data for the provided delegator-delegate pair.\n * @param delegatorId id of a delegator data owner.\n * @param delegateId id of a delegate data owner.\n * @return all exchange data for the provided delegator-delegate pair.\n */\n async getExchangeDataByDelegatorDelegatePair(delegatorId: string, delegateId: string): Promise<ExchangeData[]> {\n return await this.api.getExchangeDataByDelegatorDelegate(delegatorId, delegateId)\n }\n\n /**\n * Get the exchange data with the provided id.\n * @param exchangeDataId id of the exchange data.\n * @return the exchange data with the provided id or undefined if no exchange data with such id could be found.\n */\n async getExchangeDataById(exchangeDataId: string): Promise<ExchangeData | undefined> {\n return await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && e.statusCode === 404) {\n return undefined\n } else throw e\n })\n }\n\n /**\n * Filters exchange data returning only the instances that could be verified using their signature and the provided verification\n * keys.\n * Note that all exchange data created by data owners other than the current data owner (including members of his hierarchy)\n * will always be unverified.\n * @param exchangeData the exchange data to verify.\n * @param getVerificationKey function to retrieve keys to use for verification by fingerprint.\n * @return the exchange data which could be verified given his signature and the available verification keys.\n * @throws if any of the provided exchange data has been created by a data owner other than the current data owner.\n */\n async filterVerifiedExchangeData(\n exchangeData: ExchangeData[],\n getVerificationKey: (publicKeyFingerprint: string) => Promise<CryptoKey | undefined>\n ): Promise<ExchangeData[]> {\n const verified: ExchangeData[] = []\n for (const ed of exchangeData) {\n if (await this.verifyExchangeData(ed, (x) => getVerificationKey(x))) verified.push(ed)\n }\n return verified\n }\n\n /**\n * Verifies the authenticity of the exchange data by checking the signature.\n * Note that all exchange data created by data owners other than the current data owner (including members of his hierarchy)\n * will always be unverified.\n * @param exchangeData the exchange data to verify.\n * @param getVerificationKey function to retrieve keys to use for verification by fingerprint.\n * @return the exchange data which could be verified given his signature and the available verification keys.\n * @throws if any of the provided exchange data has been created by a data owner other than the current data owner.\n */\n async verifyExchangeData(\n exchangeData: ExchangeData,\n getVerificationKey: (publicKeyFingerprint: string) => Promise<CryptoKey | undefined>\n ): Promise<boolean> {\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (exchangeData.delegator !== dataOwnerId) return false\n const signatureData = await this.bytesToSign(exchangeData)\n for (const [fp, signature] of Object.entries(exchangeData.signature)) {\n const verificationKey = await getVerificationKey(fp.slice(-32))\n if (verificationKey && (await this.primitives.RSA.verifySignature(verificationKey, b64_2ua(signature), signatureData))) return true\n }\n return false\n }\n\n /**\n * Extracts and decrypts the access control secret from the provided exchange data.\n * These need to be hashed together with the entity class and confidentiality level in order to get the actual access control key\n * which will be sent to the server.\n * @param exchangeData the exchange data from which to extract access control secrets.\n * @param decryptionKeys rsa key pairs to use for decryption of the access control secret.\n * @return an object composed of:\n * - successfulDecryptions: array of all successfully decrypted access control keys\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptAccessControlSecret(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: string[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.accessControlSecret,\n (d) => this.importAccessControlSecret(new Uint8Array(d))\n )\n }\n\n /**\n * Extract and decrypts the exchange keys from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptExchangeKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.exchangeKey,\n (d) => this.importExchangeKey(new Uint8Array(d))\n )\n }\n\n private async tryDecryptExchangeData<T>(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n encryptedDataSelector: (data: ExchangeData) => { [keyPairFingerprint: string]: string },\n unmarshalDecrypted: (decrypted: ArrayBuffer) => Promise<T>\n ): Promise<{\n successfulDecryptions: T[]\n failedDecryptions: ExchangeData[]\n }> {\n const successfulDecryptions: T[] = []\n const failedDecryptions: ExchangeData[] = []\n for (const ed of exchangeData) {\n try {\n const decrypted = await this.tryDecrypt(encryptedDataSelector(ed), decryptionKeys)\n if (decrypted) {\n successfulDecryptions.push(await unmarshalDecrypted(decrypted))\n } else {\n failedDecryptions.push(ed)\n }\n } catch (e) {\n failedDecryptions.push(ed)\n }\n }\n return { successfulDecryptions, failedDecryptions }\n }\n\n private async tryDecrypt(\n encryptedData: { [keyPairFingerprintV2: string]: string },\n decryptionKeys: { [publicKeyFingerprintV1: string]: KeyPair<CryptoKey> }\n ): Promise<ArrayBuffer | undefined> {\n const decryptionKeysWithV2Fp = Object.keys(decryptionKeys).reduce((prev, fp) => {\n return {\n ...prev,\n [fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp]: decryptionKeys[fp],\n }\n }, {} as { [publicKeyFingerprint: string]: KeyPair<CryptoKey> })\n for (const [fp, encrypted] of Object.entries(encryptedData)) {\n try {\n const key = decryptionKeysWithV2Fp[fp]?.privateKey\n if (key) return hex2ua(ua2utf8(await this.primitives.RSA.decrypt(key, b64_2ua(encrypted))))\n } catch (e) {\n // Try with another key\n }\n }\n }\n\n /**\n * Creates exchange data from the current data owner to the provided delegate, uploading the newly created exchange data to the cloud.\n * This assumes that the keys have been verified.\n * @param delegateId id of the delegate for the new exchange data.\n * @param signatureKeys private keys to use for signing the created data.\n * @param encryptionKeys public keys to use for the encryption of the exchange data (from delegator and delegate).\n * @param optionalAttributes optional precalculated attributes for the creation of data\n * @return the newly created exchange data, and its decrypted exchange key and access control secret.\n */\n async createExchangeData(\n delegateId: string,\n signatureKeys: { [keyPairFingerprint: string]: CryptoKey },\n encryptionKeys: { [keyPairFingerprint: string]: CryptoKey },\n optionalAttributes: {\n id?: string\n } = {}\n ): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }> {\n if (!Object.keys(signatureKeys).length || !Object.keys(encryptionKeys).length) {\n throw new Error('Must specify at least one signature key and ')\n }\n const exchangeKey = await this.generateExchangeKey()\n const accessControlSecret = await this.generateAccessControlSecret()\n const encryptedExchangeKey = await this.encryptDataWithKeys(exchangeKey.rawBytes, encryptionKeys)\n const encryptedAccessControlSecret = await this.encryptDataWithKeys(accessControlSecret.rawBytes, encryptionKeys)\n const baseExchangeData = {\n id: optionalAttributes.id ?? this.primitives.randomUuid(),\n delegator: await this.dataOwnerApi.getCurrentDataOwnerId(),\n delegate: delegateId,\n exchangeKey: encryptedExchangeKey,\n accessControlSecret: encryptedAccessControlSecret,\n }\n const signature = await this.signDataWithKeys(await this.bytesToSign(baseExchangeData), signatureKeys)\n const exchangeData = new ExchangeData({ ...baseExchangeData, signature })\n return {\n exchangeData: await this.api.createExchangeData(exchangeData),\n exchangeKey: exchangeKey.key,\n accessControlSecret: accessControlSecret.secret,\n }\n }\n\n /**\n * Updates existing exchange data and uploads it to the cloud in order to share it also with additional public keys, useful for example in cases\n * where one of the data owners involved in the exchange data has lost one of his keys.\n * If the content of the exchange data could not be decrypted using the provided keys the method will not update anything and will return undefined.\n * This method assumes that the new encryption keys have been verified.\n * If the current data owner is also the delegator of the provided exchange data and at least one of the verification keys can be used to\n * validate the current exchange data then the signature will be updated using the signature keys.\n * Instead, if the current data owner is not the delegator of the provided exchange data, or the exchange data could not be verified using\n * the provided verification keys then the updated exchange data will become unverified, and won't ever be verifiable again.\n * @param exchangeData exchange data to update.\n * @param decryptionKeys keys to use to extract the content of the exchange data which will be shared with the new keys.\n * @param signatureKeys keys to use for the new signature of the updated exchange data.\n * @param newEncryptionKeys new keys to add to the exchange data.\n * @param getVerificationKey function to retrieve keys to use for verification by fingerprint.\n * @return the updated exchange data, and its decrypted exchange key and access control secret, or undefined if the exchange data content could not\n * be decrypted and the exchange data could not be updated.\n */\n async tryUpdateExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n newEncryptionKeys: { [keyPairFingerprint: string]: CryptoKey },\n signatureKeys: { [keyPairFingerprint: string]: CryptoKey },\n getVerificationKey: (publicKeyFingerprint: string) => Promise<CryptoKey | undefined>\n ): Promise<\n | {\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }\n | undefined\n > {\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret) return undefined\n const exchangeKey = await this.importExchangeKey(new Uint8Array(rawExchangeKey))\n const accessControlSecret = await this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret))\n const existingExchangeKeyEntries = new Set(Object.keys(exchangeData.exchangeKey))\n const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret))\n const missingEntries = Object.keys(newEncryptionKeys).filter((fp) => !existingAcsEntries.has(fp) || !existingExchangeKeyEntries.has(fp))\n if (!missingEntries.length) return { exchangeData, exchangeKey, accessControlSecret }\n const encryptionKeysForMissingEntries = missingEntries.reduce((obj, fp) => {\n obj[fp] = newEncryptionKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n const isVerified = exchangeData.delegator == dataOwnerId && (await this.verifyExchangeData(exchangeData, (fp) => getVerificationKey(fp)))\n const updatedExchangeData = _.cloneDeep(exchangeData)\n updatedExchangeData.exchangeKey = {\n ...exchangeData.exchangeKey,\n ...(await this.encryptDataWithKeys(rawExchangeKey, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.accessControlSecret = {\n ...exchangeData.accessControlSecret,\n ...(await this.encryptDataWithKeys(rawAccessControlSecret, encryptionKeysForMissingEntries)),\n }\n if (isVerified) {\n const newDataToSign = await this.bytesToSign(updatedExchangeData)\n updatedExchangeData.signature = await this.signDataWithKeys(newDataToSign, signatureKeys)\n }\n return { exchangeData: await this.api.modifyExchangeData(new ExchangeData(updatedExchangeData)), exchangeKey, accessControlSecret }\n }\n\n // Gets a byte representation of the parts of exchange data which should be included in the signature.\n // Equivalent json representations of the exchange data should provide the same bytes (even if the order of entries\n // is different).\n private async bytesToSign(exchangeData: {\n delegate: string\n delegator: string\n exchangeKey: { [k: string]: string }\n accessControlSecret: { [k: string]: string }\n }): Promise<ArrayBuffer> {\n function sortObject(obj: { [k: string]: string }): [string, string][] {\n return Object.keys(obj)\n .sort()\n .reduce((sorted, key) => {\n return [...sorted, [key, obj[key]]]\n }, [] as [string, string][])\n }\n const signObject = [\n ['delegator', exchangeData.delegator],\n ['delegate', exchangeData.delegate],\n ['exchangeKey', sortObject(exchangeData.exchangeKey)],\n ['accessControlSecret', sortObject(exchangeData.accessControlSecret)],\n ]\n const signJson = JSON.stringify(signObject)\n return this.primitives.sha256(utf8_2ua(signJson))\n }\n\n // Generates a new exchange key\n private async generateExchangeKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = await this.primitives.randomBytes(32)\n return {\n key: await this.importExchangeKey(rawBytes),\n rawBytes,\n }\n }\n\n private async importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.AES.importKey('raw', decryptedBytes)\n }\n\n // Generates a new access control secret\n private async generateAccessControlSecret(): Promise<{\n secret: string // the imported secret\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = await this.primitives.randomBytes(16)\n return {\n secret: await this.importAccessControlSecret(rawBytes),\n rawBytes,\n }\n }\n\n private importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string> {\n return Promise.resolve(ua2hex(decryptedBytes))\n }\n\n private async encryptDataWithKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprintV1: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprintV2: string]: string }> {\n const res: { [keyPairFingerprintV2: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp] = ua2b64(await this.primitives.RSA.encrypt(key, utf8_2ua(ua2hex(rawData))))\n }\n return res\n }\n\n private async signDataWithKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprint: string]: string }> {\n const res: { [keyPairFingerprint: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fp] = ua2b64(await this.primitives.RSA.sign(key, new Uint8Array(rawData)))\n }\n return res\n }\n}\n"]}
@@ -2,7 +2,6 @@ import { KeyPair } from './RSA';
2
2
  import { IccDataOwnerXApi } from '../icc-data-owner-x-api';
3
3
  import { CryptoPrimitives } from './CryptoPrimitives';
4
4
  import { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../../icc-api';
5
- import { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub';
6
5
  import { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum';
7
6
  /**
8
7
  * @internal This class is meant only for internal use and may be changed without notice.
@@ -17,21 +16,6 @@ export declare class BaseExchangeKeysManager {
17
16
  private readonly patientBaseApi;
18
17
  private readonly deviceBaseApi;
19
18
  constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, hcpartyBaseApi: IccHcpartyApi, patientBaseApi: IccPatientApi, deviceBaseApi: IccDeviceApi);
20
- /**
21
- * Creates a new exchange key from the current data owner to a delegate, or updates an existing one allowing additional public keys to access it.
22
- * @param delegateId the delegate data owner id.
23
- * @param delegatorMainKeyPair main key pair for the delegator. The private key will be used for the decryption of the existing key in case of
24
- * update, and the public key will be used as entry key of the aesExchangeKey map
25
- * @param additionalPublicKeys all public keys of key pairs other than {@link delegatorMainKeyPair} that need to have access to the exchange key.
26
- * Can be a mix of crypto keys and full hex-encoded spki format (no fingerprints).
27
- * @return the exchange key for the delegator-delegate-delegatorKey triple (new or existing) and the updated delegator.
28
- */
29
- createOrUpdateEncryptedExchangeKeyTo(delegateId: string, delegatorMainKeyPair: KeyPair<CryptoKey>, additionalPublicKeys: {
30
- [keyFingerprint: string]: CryptoKey;
31
- }): Promise<{
32
- updatedDelegator: CryptoActorStubWithType;
33
- key: CryptoKey;
34
- }>;
35
19
  /**
36
20
  * Updates the aes exchange keys between the current data owner and another data owner to allow the other data owner to access the exchange key
37
21
  * using his new public key. Note that this will make existing exchange keys from the other data owner to the current data owner invalid for
@@ -118,7 +102,5 @@ export declare class BaseExchangeKeysManager {
118
102
  */
119
103
  private tryDecryptExchangeKeyWith;
120
104
  private updateLegacyExchangeKeys;
121
- private updateExchangeKeys;
122
105
  private combineLegacyHcpKeysWithAesExchangeKeys;
123
- private fixAesExchangeKeyEntriesToFingerprints;
124
106
  }
@@ -11,8 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.BaseExchangeKeysManager = void 0;
13
13
  const utils_1 = require("../utils");
14
- const CryptoActorStub_1 = require("../../icc-api/model/CryptoActorStub");
15
- const DataOwnerTypeEnum_1 = require("../../icc-api/model/DataOwnerTypeEnum");
14
+ const utils_2 = require("./utils");
16
15
  /**
17
16
  * @internal This class is meant only for internal use and may be changed without notice.
18
17
  * Functions to create and get exchange keys.
@@ -27,65 +26,6 @@ class BaseExchangeKeysManager {
27
26
  this.patientBaseApi = patientBaseApi;
28
27
  this.deviceBaseApi = deviceBaseApi;
29
28
  }
30
- /**
31
- * Creates a new exchange key from the current data owner to a delegate, or updates an existing one allowing additional public keys to access it.
32
- * @param delegateId the delegate data owner id.
33
- * @param delegatorMainKeyPair main key pair for the delegator. The private key will be used for the decryption of the existing key in case of
34
- * update, and the public key will be used as entry key of the aesExchangeKey map
35
- * @param additionalPublicKeys all public keys of key pairs other than {@link delegatorMainKeyPair} that need to have access to the exchange key.
36
- * Can be a mix of crypto keys and full hex-encoded spki format (no fingerprints).
37
- * @return the exchange key for the delegator-delegate-delegatorKey triple (new or existing) and the updated delegator.
38
- */
39
- createOrUpdateEncryptedExchangeKeyTo(delegateId, delegatorMainKeyPair, additionalPublicKeys) {
40
- return __awaiter(this, void 0, void 0, function* () {
41
- const delegatorId = yield this.dataOwnerApi.getCurrentDataOwnerId();
42
- return yield (0, utils_1.notConcurrent)(this.generateKeyConcurrencyMap, delegatorId, () => __awaiter(this, void 0, void 0, function* () {
43
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
44
- const delegator = CryptoActorStub_1.CryptoActorStubWithType.fromDataOwner(yield this.dataOwnerApi.getCurrentDataOwner());
45
- const delegate = delegatorId === delegateId ? delegator : yield this.dataOwnerApi.getCryptoActorStub(delegateId);
46
- const mainDelegatorKeyPairPubHex = (0, utils_1.ua2hex)(yield this.primitives.RSA.exportKey(delegatorMainKeyPair.publicKey, 'spki'));
47
- let exchangeKey = undefined;
48
- const existingExchangeKey = (_d = (_c = (_b = (_a = delegator.stub.aesExchangeKeys) === null || _a === void 0 ? void 0 : _a[mainDelegatorKeyPairPubHex]) === null || _b === void 0 ? void 0 : _b[delegateId]) === null || _c === void 0 ? void 0 : _c[mainDelegatorKeyPairPubHex.slice(-32)]) !== null && _d !== void 0 ? _d : (mainDelegatorKeyPairPubHex === delegator.stub.publicKey ? (_f = (_e = delegator.stub.hcPartyKeys) === null || _e === void 0 ? void 0 : _e[delegateId]) === null || _f === void 0 ? void 0 : _f[0] : undefined);
49
- if (existingExchangeKey) {
50
- exchangeKey = yield this.tryDecryptExchangeKeyWith(existingExchangeKey, delegatorMainKeyPair, undefined);
51
- if (!exchangeKey)
52
- throw new Error(`Failed to decrypt existing exchange key for update of ${mainDelegatorKeyPairPubHex.slice(-32)}@${delegatorId}->${delegateId}`);
53
- const existingAesExchangeKey = (_h = (_g = delegator.stub.aesExchangeKeys) === null || _g === void 0 ? void 0 : _g[mainDelegatorKeyPairPubHex]) === null || _h === void 0 ? void 0 : _h[delegateId];
54
- if (existingAesExchangeKey) {
55
- const existingPublicKeysSet = new Set(existingExchangeKey);
56
- if (Object.keys(additionalPublicKeys).every((fp) => existingPublicKeysSet.has(fp)))
57
- return {
58
- updatedDelegator: delegator,
59
- key: exchangeKey.key,
60
- };
61
- }
62
- }
63
- const allPublicKeys = Object.assign(Object.assign({}, additionalPublicKeys), { [mainDelegatorKeyPairPubHex.slice(-32)]: delegatorMainKeyPair.publicKey });
64
- const encryptedKeyInfo = yield this.encryptExchangeKey(exchangeKey, allPublicKeys);
65
- let updatedDelegatorPublicKey;
66
- if (delegator.stub.publicKey == '') {
67
- if (Object.entries((_j = delegator.stub.hcPartyKeys) !== null && _j !== void 0 ? _j : {}).length > 0)
68
- throw new Error(`Data owner ${delegator.stub.id} has "" as public key but has non-empty hcPartyKeys`);
69
- updatedDelegatorPublicKey = mainDelegatorKeyPairPubHex;
70
- }
71
- else {
72
- updatedDelegatorPublicKey = (_k = delegator.stub.publicKey) !== null && _k !== void 0 ? _k : mainDelegatorKeyPairPubHex;
73
- }
74
- const updatedStub = Object.assign(Object.assign({}, delegator.stub), { aesExchangeKeys: yield this.updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyInfo.encryptedExchangeKey), publicKey: updatedDelegatorPublicKey });
75
- if (delegator.stub.publicKey === mainDelegatorKeyPairPubHex) {
76
- updatedStub.hcPartyKeys = this.updateLegacyExchangeKeys(delegator, delegate, encryptedKeyInfo.encryptedExchangeKey);
77
- }
78
- const updatedDelegator = yield this.dataOwnerApi.modifyCryptoActorStub({
79
- type: delegator.type,
80
- stub: updatedStub,
81
- });
82
- return {
83
- key: encryptedKeyInfo.exchangeKey,
84
- updatedDelegator,
85
- };
86
- }));
87
- });
88
- }
89
29
  /**
90
30
  * Updates the aes exchange keys between the current data owner and another data owner to allow the other data owner to access the exchange key
91
31
  * using his new public key. Note that this will make existing exchange keys from the other data owner to the current data owner invalid for
@@ -97,9 +37,13 @@ class BaseExchangeKeysManager {
97
37
  giveAccessBackTo(otherDataOwner, newDataOwnerPublicKey, keyPairsByFingerprint) {
98
38
  return __awaiter(this, void 0, void 0, function* () {
99
39
  const selfId = yield this.dataOwnerApi.getCurrentDataOwnerId();
100
- const newPublicKey = yield this.primitives.RSA.importKey('spki', (0, utils_1.hex2ua)(newDataOwnerPublicKey), ['encrypt']);
101
- yield this.extendForGiveAccessBackTo(selfId, otherDataOwner, newDataOwnerPublicKey.slice(-32), newPublicKey, keyPairsByFingerprint);
102
- yield this.extendForGiveAccessBackTo(otherDataOwner, selfId, newDataOwnerPublicKey.slice(-32), newPublicKey, keyPairsByFingerprint);
40
+ const other = yield this.dataOwnerApi.getCryptoActorStub(otherDataOwner);
41
+ const newKeyHashVersion = (0, utils_2.getShaVersionForKey)(other.stub, newDataOwnerPublicKey);
42
+ if (!newKeyHashVersion)
43
+ throw new Error(`Public key not found for data owner ${otherDataOwner}`);
44
+ const newPublicKey = yield this.primitives.RSA.importKey('spki', (0, utils_1.hex2ua)(newDataOwnerPublicKey), ['encrypt'], newKeyHashVersion);
45
+ yield this.extendForGiveAccessBackTo(selfId, otherDataOwner, (0, utils_2.fingerprintV1)(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint);
46
+ yield this.extendForGiveAccessBackTo(otherDataOwner, selfId, (0, utils_2.fingerprintV1)(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint);
103
47
  });
104
48
  }
105
49
  /**
@@ -138,13 +82,11 @@ class BaseExchangeKeysManager {
138
82
  if (otherOwnerTypes.length === 0)
139
83
  throw new Error('otherOwnerTypes must not be empty!');
140
84
  const keysToOwner = yield Promise.all([
141
- otherOwnerTypes.find((x) => x === DataOwnerTypeEnum_1.DataOwnerTypeEnum.Hcp)
142
- ? this.hcpartyBaseApi.getAesExchangeKeysForDelegate(dataOwnerId).catch(() => { })
143
- : Promise.resolve({}),
144
- otherOwnerTypes.find((x) => x === DataOwnerTypeEnum_1.DataOwnerTypeEnum.Patient)
85
+ otherOwnerTypes.find((x) => x === 'hcp') ? this.hcpartyBaseApi.getAesExchangeKeysForDelegate(dataOwnerId).catch(() => { }) : Promise.resolve({}),
86
+ otherOwnerTypes.find((x) => x === 'patient')
145
87
  ? this.patientBaseApi.getPatientAesExchangeKeysForDelegate(dataOwnerId).catch(() => { })
146
88
  : Promise.resolve({}),
147
- otherOwnerTypes.find((x) => x === DataOwnerTypeEnum_1.DataOwnerTypeEnum.Device)
89
+ otherOwnerTypes.find((x) => x === 'device')
148
90
  ? this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(dataOwnerId).catch(() => { })
149
91
  : Promise.resolve({}),
150
92
  ]).then(([a, b, c]) => (Object.assign(Object.assign(Object.assign({}, a), b), c)));
@@ -315,13 +257,6 @@ class BaseExchangeKeysManager {
315
257
  else
316
258
  return delegator.stub.hcPartyKeys;
317
259
  }
318
- updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyMap) {
319
- var _a, _b, _c;
320
- return __awaiter(this, void 0, void 0, function* () {
321
- const combinedAesExchangeKeys = yield this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub);
322
- return this.fixAesExchangeKeyEntriesToFingerprints(Object.assign(Object.assign({}, combinedAesExchangeKeys), { [mainDelegatorKeyPairPubHex]: Object.assign(Object.assign({}, ((_a = combinedAesExchangeKeys[mainDelegatorKeyPairPubHex]) !== null && _a !== void 0 ? _a : {})), { [delegate.stub.id]: Object.assign(Object.assign({}, ((_c = (_b = combinedAesExchangeKeys[mainDelegatorKeyPairPubHex]) === null || _b === void 0 ? void 0 : _b[delegate.stub.id]) !== null && _c !== void 0 ? _c : {})), encryptedKeyMap) }) }));
323
- });
324
- }
325
260
  // Copy all legacy hcp exchange keys into the new aes exchange keys
326
261
  combineLegacyHcpKeysWithAesExchangeKeys(owner, delegate) {
327
262
  var _a, _b, _c, _d, _e;
@@ -352,15 +287,6 @@ class BaseExchangeKeysManager {
352
287
  return (_e = owner.aesExchangeKeys) !== null && _e !== void 0 ? _e : {};
353
288
  });
354
289
  }
355
- fixAesExchangeKeyEntriesToFingerprints(aesExchangeKeys) {
356
- return Object.fromEntries(Object.entries(aesExchangeKeys).map(([delegatorPubKey, allDelegates]) => [
357
- delegatorPubKey,
358
- Object.fromEntries(Object.entries(allDelegates).map(([delegateId, keyEntries]) => [
359
- delegateId,
360
- Object.fromEntries(Object.entries(keyEntries).map(([publicKey, encryptedValue]) => [publicKey.slice(-32), encryptedValue])),
361
- ])),
362
- ]));
363
- }
364
290
  }
365
291
  exports.BaseExchangeKeysManager = BaseExchangeKeysManager;
366
292
  //# sourceMappingURL=BaseExchangeKeysManager.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseExchangeKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,oCAAwD;AAIxD,yEAA8F;AAC9F,6EAAyE;AAEzE;;;;GAIG;AACH,MAAa,uBAAuB;IAQlC,YACE,UAA4B,EAC5B,YAA8B,EAC9B,cAA6B,EAC7B,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F,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,MAAA,MAAA,MAAA,gBAAgB,CAAC,KAAK,CAAC,0CAAE,SAAS,0CAAE,KAAK,CAAC,CAAC,EAAE,CAAC,mCAAI,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;wBAC5H,OAAO,GAAG,CAAA;oBACZ,CAAC,EAAE,EAAiE,CAAC,IAClE,CAAC,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAC,EACjC;aACF;;gBAAM,OAAO,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAA;;KAC1C;IAEO,sCAAsC,CAAC,eAE9C;QACC,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,eAAe,EAAE,YAAY,CAAC,EAAE,EAAE,CAAC;YACvE,eAAe;YACf,MAAM,CAAC,WAAW,CAChB,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,UAAU,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC;gBAC7D,UAAU;gBACV,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,EAAE,cAAc,CAAC,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC;aAC5H,CAAC,CACH;SACF,CAAC,CACH,CAAA;IACH,CAAC;CACF;AA1aD,0DA0aC","sourcesContent":["import { KeyPair } from './RSA'\nimport { hex2ua, notConcurrent, ua2hex } from '../utils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../../icc-api'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * Functions to create and get exchange keys.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeKeysManager {\n private readonly generateKeyConcurrencyMap: { [key: string]: PromiseLike<any> } = {}\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly hcpartyBaseApi: IccHcpartyApi\n private readonly patientBaseApi: IccPatientApi\n private readonly deviceBaseApi: IccDeviceApi\n\n constructor(\n primitives: CryptoPrimitives,\n dataOwnerApi: IccDataOwnerXApi,\n hcpartyBaseApi: IccHcpartyApi,\n patientBaseApi: IccPatientApi,\n deviceBaseApi: IccDeviceApi\n ) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.hcpartyBaseApi = hcpartyBaseApi\n this.patientBaseApi = patientBaseApi\n this.deviceBaseApi = deviceBaseApi\n }\n\n /**\n * Creates a new exchange key from the current data owner to a delegate, or updates an existing one allowing additional public keys to access it.\n * @param delegateId the delegate data owner id.\n * @param delegatorMainKeyPair main key pair for the delegator. The private key will be used for the decryption of the existing key in case of\n * update, and the public key will be used as entry key of the aesExchangeKey map\n * @param additionalPublicKeys all public keys of key pairs other than {@link delegatorMainKeyPair} that need to have access to the exchange key.\n * Can be a mix of crypto keys and full hex-encoded spki format (no fingerprints).\n * @return the exchange key for the delegator-delegate-delegatorKey triple (new or existing) and the updated delegator.\n */\n async createOrUpdateEncryptedExchangeKeyTo(\n delegateId: string,\n delegatorMainKeyPair: KeyPair<CryptoKey>,\n additionalPublicKeys: { [keyFingerprint: string]: CryptoKey }\n ): Promise<{\n updatedDelegator: CryptoActorStubWithType\n key: CryptoKey\n }> {\n const delegatorId = await this.dataOwnerApi.getCurrentDataOwnerId()\n return await notConcurrent(this.generateKeyConcurrencyMap, delegatorId, async () => {\n const delegator = CryptoActorStubWithType.fromDataOwner(await this.dataOwnerApi.getCurrentDataOwner())\n const delegate = delegatorId === delegateId ? delegator : await this.dataOwnerApi.getCryptoActorStub(delegateId)\n const mainDelegatorKeyPairPubHex = ua2hex(await this.primitives.RSA.exportKey(delegatorMainKeyPair.publicKey, 'spki'))\n let exchangeKey: { raw: string; key: CryptoKey } | undefined = undefined\n const existingExchangeKey =\n delegator.stub.aesExchangeKeys?.[mainDelegatorKeyPairPubHex]?.[delegateId]?.[mainDelegatorKeyPairPubHex.slice(-32)] ??\n (mainDelegatorKeyPairPubHex === delegator.stub.publicKey ? delegator.stub.hcPartyKeys?.[delegateId]?.[0] : undefined)\n if (existingExchangeKey) {\n exchangeKey = await this.tryDecryptExchangeKeyWith(existingExchangeKey, delegatorMainKeyPair, undefined)\n if (!exchangeKey)\n throw new Error(\n `Failed to decrypt existing exchange key for update of ${mainDelegatorKeyPairPubHex.slice(-32)}@${delegatorId}->${delegateId}`\n )\n const existingAesExchangeKey = delegator.stub.aesExchangeKeys?.[mainDelegatorKeyPairPubHex]?.[delegateId]\n if (existingAesExchangeKey) {\n const existingPublicKeysSet = new Set(existingExchangeKey)\n if (Object.keys(additionalPublicKeys).every((fp) => existingPublicKeysSet.has(fp)))\n return {\n updatedDelegator: delegator,\n key: exchangeKey.key,\n }\n }\n }\n const allPublicKeys = {\n ...additionalPublicKeys,\n [mainDelegatorKeyPairPubHex.slice(-32)]: delegatorMainKeyPair.publicKey,\n }\n const encryptedKeyInfo = await this.encryptExchangeKey(exchangeKey, allPublicKeys)\n let updatedDelegatorPublicKey: string\n if (delegator.stub.publicKey == '') {\n if (Object.entries(delegator.stub.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${delegator.stub.id} has \"\" as public key but has non-empty hcPartyKeys`)\n updatedDelegatorPublicKey = mainDelegatorKeyPairPubHex\n } else {\n updatedDelegatorPublicKey = delegator.stub.publicKey ?? mainDelegatorKeyPairPubHex\n }\n const updatedStub: CryptoActorStub = {\n ...delegator.stub,\n aesExchangeKeys: await this.updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyInfo.encryptedExchangeKey),\n publicKey: updatedDelegatorPublicKey,\n }\n if (delegator.stub.publicKey === mainDelegatorKeyPairPubHex) {\n updatedStub.hcPartyKeys = this.updateLegacyExchangeKeys(delegator, delegate, encryptedKeyInfo.encryptedExchangeKey)\n }\n const updatedDelegator = await this.dataOwnerApi.modifyCryptoActorStub({\n type: delegator.type,\n stub: updatedStub,\n })\n return {\n key: encryptedKeyInfo.exchangeKey,\n updatedDelegator,\n }\n })\n }\n\n /**\n * Updates the aes exchange keys between the current data owner and another data owner to allow the other data owner to access the exchange key\n * using his new public key. Note that this will make existing exchange keys from the other data owner to the current data owner invalid for\n * encryption.\n * @param otherDataOwner the other data owner.\n * @param newDataOwnerPublicKey a new public key of the other data owner.\n * @param keyPairsByFingerprint all available key pairs to use for the decryption of existing aes exchange keys.\n */\n async giveAccessBackTo(\n otherDataOwner: string,\n newDataOwnerPublicKey: string,\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const newPublicKey = await this.primitives.RSA.importKey('spki', hex2ua(newDataOwnerPublicKey), ['encrypt'])\n await this.extendForGiveAccessBackTo(selfId, otherDataOwner, newDataOwnerPublicKey.slice(-32), newPublicKey, keyPairsByFingerprint)\n await this.extendForGiveAccessBackTo(otherDataOwner, selfId, newDataOwnerPublicKey.slice(-32), newPublicKey, keyPairsByFingerprint)\n }\n\n /**\n * Get the encrypted exchange keys for a delegator-delegate pair.\n * @param delegatorId id of the delegator data owner.\n * @param delegateId id of the delegate data owner.\n * @return an array of exchange keys from the delegator to delegate where each key is encrypted with one or more public keys.\n */\n async getEncryptedExchangeKeysFor(delegatorId: string, delegateId: string): Promise<{ [publicKeyFingerprint: string]: string }[]> {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const res: { [publicKeyFingerprint: string]: string }[] = Object.values(delegator.stub.aesExchangeKeys ?? {}).flatMap((delegateToKey) => {\n const encryptedKeyForDelegate = delegateToKey[delegateId]\n if (encryptedKeyForDelegate) {\n return [encryptedKeyForDelegate]\n } else {\n return []\n }\n })\n const legacyDelegation = delegator.stub.hcPartyKeys?.[delegateId]?.[1]\n if (legacyDelegation) res.push({ '': legacyDelegation })\n return res\n }\n\n /**\n * Get all exchange keys where the provided data owner is involved either as the delegator or as the delegate.\n * @param dataOwnerId id of a data owner.\n * @param otherOwnerTypes only exchange keys between the current data owner and data owners of this type will be included in the result.\n * @return all exchange keys involving the provided data owner. Note that there may be an overlap between some keys to and from the data owner.\n */\n async getAllExchangeKeysWith(\n dataOwnerId: string,\n otherOwnerTypes: DataOwnerTypeEnum[]\n ): Promise<{\n keysToOwner: { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }\n keysFromOwner: { [delegatorFp: string]: { [delegateId: string]: { [entryFp: string]: string } } }\n }> {\n if (otherOwnerTypes.length === 0) throw new Error('otherOwnerTypes must not be empty!')\n const keysToOwner = await Promise.all([\n otherOwnerTypes.find((x) => x === DataOwnerTypeEnum.Hcp)\n ? this.hcpartyBaseApi.getAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes.find((x) => x === DataOwnerTypeEnum.Patient)\n ? this.patientBaseApi.getPatientAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes.find((x) => x === DataOwnerTypeEnum.Device)\n ? this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n ]).then(([a, b, c]) => ({ ...a, ...b, ...c } as { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }))\n const dataOwner = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n const allOwnerKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(dataOwner.stub, undefined)\n const filteredDelegates = new Set(\n await Array.from(new Set(Object.values(allOwnerKeys).flatMap((x) => Object.keys(x)))).reduce(async (acc, ownerId) => {\n const awaitedAcc = await acc\n if (ownerId === dataOwnerId) {\n return [...awaitedAcc, ownerId]\n } else {\n const dataOwnerType: DataOwnerTypeEnum = (await this.dataOwnerApi.getCryptoActorStub(ownerId)).type\n if (otherOwnerTypes.some((x) => x === dataOwnerType)) {\n return [...awaitedAcc, ownerId]\n } else return awaitedAcc\n }\n }, Promise.resolve([] as string[]))\n )\n const keysFromOwner = Object.fromEntries(\n Object.entries(allOwnerKeys)\n .map(([delegatorPubKey, delegateToKeys]) => [\n delegatorPubKey,\n Object.fromEntries(\n Object.entries(delegateToKeys).filter(([delegateId]) => filteredDelegates.has(delegateId)) as [string, { [k: string]: string }][]\n ),\n ])\n .filter(([, x]) => Object.keys(x).length > 0) as [string, { [k: string]: { [k: string]: string } }][]\n )\n return { keysToOwner, keysFromOwner }\n }\n\n /**\n * Attempts to decrypt many exchange keys using any of the provided key pairs.\n * @param encryptedExchangeKeys an array of exchange keys where each key is encrypted with one or more public keys.\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return an array all successfully decrypted exchange keys and an array containing all exchange keys which could not be decrypted.\n */\n async tryDecryptExchangeKeys(\n encryptedExchangeKeys: { [publicKeyFingerprint: string]: string }[],\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n }> {\n const raws = new Set<string>()\n const res: {\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n } = { successfulDecryptions: [], failedDecryptions: [] }\n for (const encryptedExchangeKey of encryptedExchangeKeys) {\n const decrypted = await this.tryDecryptExchangeKey(encryptedExchangeKey, keyPairsByFingerprint)\n if (decrypted !== undefined && !raws.has(decrypted.raw)) {\n raws.add(decrypted.raw)\n res.successfulDecryptions.push(decrypted.key)\n } else {\n res.failedDecryptions.push(encryptedExchangeKey)\n }\n }\n return res\n }\n\n private async extendForGiveAccessBackTo(\n delegatorId: string,\n delegateId: string,\n newPublicKeyFp: string,\n newPublicKey: CryptoKey,\n decryptionKeyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n await notConcurrent(this.generateKeyConcurrencyMap, delegatorId, async () => {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n let didUpdateSomeKey = false\n const combinedKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub)\n const updatedExchangeKeys: { [delegatorKey: string]: { [delegateId: string]: { [keyFp: string]: string } } } = {}\n const newEncryptionKeys = { [newPublicKeyFp]: newPublicKey }\n for (const [currDelegatorKey, currDelegatesToKeys] of Object.entries(combinedKeys)) {\n const updatedDelegatesToKeys: { [delegateId: string]: { [keyFp: string]: string } } = {}\n for (const [currDelegateId, currEncryptedKey] of Object.entries(currDelegatesToKeys)) {\n if (delegateId !== currDelegateId || newPublicKeyFp in currEncryptedKey) {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n } else {\n const decrypted = await this.tryDecryptExchangeKey(currEncryptedKey, decryptionKeyPairsByFingerprint)\n if (decrypted) {\n didUpdateSomeKey = true\n updatedDelegatesToKeys[currDelegateId] = {\n ...currEncryptedKey,\n ...(await this.encryptExchangeKey(decrypted, newEncryptionKeys)).encryptedExchangeKey,\n }\n } else {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n }\n }\n }\n updatedExchangeKeys[currDelegatorKey] = updatedDelegatesToKeys\n }\n if (didUpdateSomeKey) {\n await this.dataOwnerApi.modifyCryptoActorStub({\n type: delegator.type,\n stub: {\n ...delegator.stub,\n aesExchangeKeys: updatedExchangeKeys,\n },\n })\n }\n })\n }\n\n /**\n * Attempts to decrypt an exchange key using any of the provided key pairs.\n * @param encryptedExchangeKey an encrypted exchange key, in the form publicKeyXyzFingerprint -> hex(exchangeKeyEncryptedByPrivateKeyXyz).\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided keys.\n */\n private async tryDecryptExchangeKey(\n encryptedExchangeKey: { [publicKeyFingerprint: string]: string },\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n for (const [entryKey, encrypted] of Object.entries(encryptedExchangeKey)) {\n // Due to bugs in past version the entry may actually contain the full public key instead of just the fingerprint.\n const fp = entryKey.slice(-32)\n const keyPair = keyPairsByFingerprint[fp]\n if (keyPair !== undefined) {\n const res = await this.tryDecryptExchangeKeyWith(encrypted, keyPair, fp)\n if (res !== undefined) return res\n }\n }\n const defaultEncryptedKey = encryptedExchangeKey['']\n if (defaultEncryptedKey !== undefined) {\n for (const keyPair of Object.values(keyPairsByFingerprint)) {\n // disable error logging, we are not sure keyPair is the correct key\n const res = await this.tryDecryptExchangeKeyWith(defaultEncryptedKey, keyPair, undefined)\n if (res !== undefined) return res\n }\n }\n return undefined\n }\n\n /**\n * Creates an encrypted exchange key for the provided public keys.\n * @param exchangeKey the exchange key in raw and imported format. If undefined a new key will be automatically created.\n * @param publicKeys additional public keys that will have access to the exchange key in spki format, hex-encoded.\n * @return the exchangeKey and an object with the exchange key encrypted with each of the provided public keys, hex-encoded, by fingerprint.\n */\n private async encryptExchangeKey(\n exchangeKey: { raw: string; key: CryptoKey } | undefined,\n publicKeys: { [keyFingerprint: string]: CryptoKey }\n ): Promise<{\n exchangeKey: CryptoKey\n encryptedExchangeKey: { [pubKeyFp: string]: string }\n }> {\n const exchangeKeyCrypto = exchangeKey?.key ?? (await this.primitives.AES.generateCryptoKey(false))\n const exchangeKeyBytes = exchangeKey !== undefined ? hex2ua(exchangeKey.raw) : await this.primitives.AES.exportKey(exchangeKeyCrypto, 'raw')\n const encryptedExchangeKey = await Object.entries(publicKeys).reduce(\n async (acc, [currKeyFp, currKey]) => ({\n ...(await acc),\n [currKeyFp]: ua2hex(await this.primitives.RSA.encrypt(currKey, new Uint8Array(exchangeKeyBytes))),\n }),\n Promise.resolve({} as { [pubKeyFp: string]: string })\n )\n return { exchangeKey: exchangeKeyCrypto, encryptedExchangeKey }\n }\n\n /**\n * Attempts to decrypt an exchange key using the provided key pairs.\n * If you are confident that the provided {@link keyPair} was used to encrypt {@link encryptedByOneKey} you should also provide {@link keyPairFp},\n * so that if the decryption fail an error will be logged to console before returning undefined.\n * @param encryptedByOneKey an exchange key which may be encrypted with {@link keyPair}.\n * @param keyPair an rsa key pair.\n * @param keyPairFp the fingerprint of the provided key pair or undefined to disable logging of error if the decryption failed.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided key.\n */\n private async tryDecryptExchangeKeyWith(\n encryptedByOneKey: string,\n keyPair: KeyPair<CryptoKey>,\n keyPairFp: string | undefined // if undefined will not log errors, when we are not sure the key to be used is the provided key.\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n try {\n const decrypted = await this.primitives.RSA.decrypt(keyPair.privateKey, hex2ua(encryptedByOneKey))\n return { raw: ua2hex(decrypted), key: await this.primitives.AES.importKey('raw', decrypted) }\n } catch (e) {\n if (keyPairFp) {\n console.error(`Failed to decrypt or import exchange key ${encryptedByOneKey} using key with fingerprint ${keyPairFp}.`, e)\n }\n }\n }\n\n private updateLegacyExchangeKeys(\n delegator: CryptoActorStubWithType,\n delegate: CryptoActorStubWithType,\n encryptedKeyMap: { [fp: string]: string }\n ): { [delegateId: string]: string[] } | undefined {\n const legacyEncryptedKeyDelegator = delegator.stub.publicKey ? encryptedKeyMap[delegator.stub.publicKey] : undefined\n const legacyEncryptedKeyDelegate = delegate.stub.publicKey ? encryptedKeyMap[delegate.stub.publicKey] : undefined\n if (legacyEncryptedKeyDelegator && legacyEncryptedKeyDelegate) {\n return {\n ...(delegator.stub.hcPartyKeys ?? {}),\n [delegate.stub.id!]: [legacyEncryptedKeyDelegator, legacyEncryptedKeyDelegate],\n }\n } else return delegator.stub.hcPartyKeys\n }\n\n private async updateExchangeKeys(\n delegator: CryptoActorStubWithType,\n delegate: CryptoActorStubWithType,\n mainDelegatorKeyPairPubHex: string,\n encryptedKeyMap: { [fp: string]: string }\n ): Promise<{ [ownerPublicKey: string]: { [delegateId: string]: { [fingerprint: string]: string } } }> {\n const combinedAesExchangeKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub)\n return this.fixAesExchangeKeyEntriesToFingerprints({\n ...combinedAesExchangeKeys,\n [mainDelegatorKeyPairPubHex]: {\n ...(combinedAesExchangeKeys[mainDelegatorKeyPairPubHex] ?? {}),\n [delegate.stub.id!]: {\n ...(combinedAesExchangeKeys[mainDelegatorKeyPairPubHex]?.[delegate.stub.id!] ?? {}),\n ...encryptedKeyMap,\n },\n },\n })\n }\n\n // Copy all legacy hcp exchange keys into the new aes exchange keys\n private async combineLegacyHcpKeysWithAesExchangeKeys(\n owner: CryptoActorStub,\n delegate: CryptoActorStub | undefined\n ): Promise<{ [ownerPublicKey: string]: { [delegateId: string]: { [fingerprint: string]: string } } }> {\n const ownerLegacyPublicKey = owner.publicKey\n if (ownerLegacyPublicKey && !(owner.aesExchangeKeys ?? {})[ownerLegacyPublicKey]) {\n /*\n * This condition would technically prevent new updates to the hcPartyKeys to be migrated to the aes exchange keys, but since I can only update\n * data for self data owner and parent entities this is not an issue, because I will always be using the new api from now on and I won't have\n * a situation where the legacy keys are updated but the aes exchange keys are not.\n */\n const unknownDataOwnerCounterPartIds = Object.keys(owner.hcPartyKeys ?? {}).filter((x) => x !== owner.id && x !== delegate?.id)\n const counterPartsById = [\n owner,\n ...(delegate ? [delegate] : []),\n ...(await Promise.all(unknownDataOwnerCounterPartIds.map(async (cpid) => (await this.dataOwnerApi.getCryptoActorStub(cpid)).stub))),\n ].reduce((acc, dataOwner) => {\n acc[dataOwner.id!] = dataOwner\n return acc\n }, {} as { [id: string]: CryptoActorStub })\n return {\n [ownerLegacyPublicKey]: Object.entries(owner.hcPartyKeys ?? {}).reduce((acc, [hcpId, keys]) => {\n acc[hcpId] = { [ownerLegacyPublicKey.slice(-32)]: keys[0], [counterPartsById[hcpId]?.publicKey?.slice(-32) ?? '']: keys[1] }\n return acc\n }, {} as { [delegateId: string]: { [fingerprint: string]: string } }),\n ...(owner.aesExchangeKeys ?? {}),\n }\n } else return owner.aesExchangeKeys ?? {}\n }\n\n private fixAesExchangeKeyEntriesToFingerprints(aesExchangeKeys: {\n [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } }\n }): { [delegatorPubKey: string]: { [delegateId: string]: { [pubKeyFp: string]: string } } } {\n return Object.fromEntries(\n Object.entries(aesExchangeKeys).map(([delegatorPubKey, allDelegates]) => [\n delegatorPubKey,\n Object.fromEntries(\n Object.entries(allDelegates).map(([delegateId, keyEntries]) => [\n delegateId,\n Object.fromEntries(Object.entries(keyEntries).map(([publicKey, encryptedValue]) => [publicKey.slice(-32), encryptedValue])),\n ])\n ),\n ])\n )\n }\n}\n"]}
1
+ {"version":3,"file":"BaseExchangeKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,oCAAwD;AAIxD,mCAA4D;AAI5D;;;;GAIG;AACH,MAAa,uBAAuB;IAQlC,YACE,UAA4B,EAC5B,YAA8B,EAC9B,cAA6B,EAC7B,cAA6B,EAC7B,aAA2B;QAZZ,8BAAyB,GAAwC,EAAE,CAAA;QAclF,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,cAAc,GAAG,cAAc,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CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,EAAE;;wBAC5F,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,MAAA,MAAA,MAAA,gBAAgB,CAAC,KAAK,CAAC,0CAAE,SAAS,0CAAE,KAAK,CAAC,CAAC,EAAE,CAAC,mCAAI,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;wBAC5H,OAAO,GAAG,CAAA;oBACZ,CAAC,EAAE,EAAiE,CAAC,IAClE,CAAC,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAC,EACjC;aACF;;gBAAM,OAAO,MAAA,KAAK,CAAC,eAAe,mCAAI,EAAE,CAAA;;KAC1C;CACF;AA9TD,0DA8TC","sourcesContent":["import { KeyPair } from './RSA'\nimport { hex2ua, notConcurrent, ua2hex } from '../utils'\nimport { DataOwner, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../../icc-api'\nimport { fingerprintV1, getShaVersionForKey } from './utils'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\n\n/**\n * @internal This class is meant only for internal use and may be changed without notice.\n * Functions to create and get exchange keys.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeKeysManager {\n private readonly generateKeyConcurrencyMap: { [key: string]: PromiseLike<any> } = {}\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly hcpartyBaseApi: IccHcpartyApi\n private readonly patientBaseApi: IccPatientApi\n private readonly deviceBaseApi: IccDeviceApi\n\n constructor(\n primitives: CryptoPrimitives,\n dataOwnerApi: IccDataOwnerXApi,\n hcpartyBaseApi: IccHcpartyApi,\n patientBaseApi: IccPatientApi,\n deviceBaseApi: IccDeviceApi\n ) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.hcpartyBaseApi = hcpartyBaseApi\n this.patientBaseApi = patientBaseApi\n this.deviceBaseApi = deviceBaseApi\n }\n\n /**\n * Updates the aes exchange keys between the current data owner and another data owner to allow the other data owner to access the exchange key\n * using his new public key. Note that this will make existing exchange keys from the other data owner to the current data owner invalid for\n * encryption.\n * @param otherDataOwner the other data owner.\n * @param newDataOwnerPublicKey a new public key of the other data owner.\n * @param keyPairsByFingerprint all available key pairs to use for the decryption of existing aes exchange keys.\n */\n async giveAccessBackTo(\n otherDataOwner: string,\n newDataOwnerPublicKey: string,\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\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 newPublicKey = await this.primitives.RSA.importKey('spki', hex2ua(newDataOwnerPublicKey), ['encrypt'], newKeyHashVersion)\n await this.extendForGiveAccessBackTo(selfId, otherDataOwner, fingerprintV1(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint)\n await this.extendForGiveAccessBackTo(otherDataOwner, selfId, fingerprintV1(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint)\n }\n\n /**\n * Get the encrypted exchange keys for a delegator-delegate pair.\n * @param delegatorId id of the delegator data owner.\n * @param delegateId id of the delegate data owner.\n * @return an array of exchange keys from the delegator to delegate where each key is encrypted with one or more public keys.\n */\n async getEncryptedExchangeKeysFor(delegatorId: string, delegateId: string): Promise<{ [publicKeyFingerprint: string]: string }[]> {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const res: { [publicKeyFingerprint: string]: string }[] = Object.values(delegator.stub.aesExchangeKeys ?? {}).flatMap((delegateToKey) => {\n const encryptedKeyForDelegate = delegateToKey[delegateId]\n if (encryptedKeyForDelegate) {\n return [encryptedKeyForDelegate]\n } else {\n return []\n }\n })\n const legacyDelegation = delegator.stub.hcPartyKeys?.[delegateId]?.[1]\n if (legacyDelegation) res.push({ '': legacyDelegation })\n return res\n }\n\n /**\n * Get all exchange keys where the provided data owner is involved either as the delegator or as the delegate.\n * @param dataOwnerId id of a data owner.\n * @param otherOwnerTypes only exchange keys between the current data owner and data owners of this type will be included in the result.\n * @return all exchange keys involving the provided data owner. Note that there may be an overlap between some keys to and from the data owner.\n */\n async getAllExchangeKeysWith(\n dataOwnerId: string,\n otherOwnerTypes: DataOwnerTypeEnum[]\n ): Promise<{\n keysToOwner: { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }\n keysFromOwner: { [delegatorFp: string]: { [delegateId: string]: { [entryFp: string]: string } } }\n }> {\n if (otherOwnerTypes.length === 0) throw new Error('otherOwnerTypes must not be empty!')\n const keysToOwner = await Promise.all([\n otherOwnerTypes.find((x) => x === 'hcp') ? this.hcpartyBaseApi.getAesExchangeKeysForDelegate(dataOwnerId).catch(() => {}) : Promise.resolve({}),\n otherOwnerTypes.find((x) => x === 'patient')\n ? this.patientBaseApi.getPatientAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n otherOwnerTypes.find((x) => x === 'device')\n ? this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(dataOwnerId).catch(() => {})\n : Promise.resolve({}),\n ]).then(([a, b, c]) => ({ ...a, ...b, ...c } as { [delegatorId: string]: { [delegatorFp: string]: { [entryFp: string]: string } } }))\n const dataOwner = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n const allOwnerKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(dataOwner.stub, undefined)\n const filteredDelegates = new Set(\n await Array.from(new Set(Object.values(allOwnerKeys).flatMap((x) => Object.keys(x)))).reduce(async (acc, ownerId) => {\n const awaitedAcc = await acc\n if (ownerId === dataOwnerId) {\n return [...awaitedAcc, ownerId]\n } else {\n const dataOwnerType: DataOwnerTypeEnum = (await this.dataOwnerApi.getCryptoActorStub(ownerId)).type\n if (otherOwnerTypes.some((x) => x === dataOwnerType)) {\n return [...awaitedAcc, ownerId]\n } else return awaitedAcc\n }\n }, Promise.resolve([] as string[]))\n )\n const keysFromOwner = Object.fromEntries(\n Object.entries(allOwnerKeys)\n .map(([delegatorPubKey, delegateToKeys]) => [\n delegatorPubKey,\n Object.fromEntries(\n Object.entries(delegateToKeys).filter(([delegateId]) => filteredDelegates.has(delegateId)) as [string, { [k: string]: string }][]\n ),\n ])\n .filter(([, x]) => Object.keys(x).length > 0) as [string, { [k: string]: { [k: string]: string } }][]\n )\n return { keysToOwner, keysFromOwner }\n }\n\n /**\n * Attempts to decrypt many exchange keys using any of the provided key pairs.\n * @param encryptedExchangeKeys an array of exchange keys where each key is encrypted with one or more public keys.\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return an array all successfully decrypted exchange keys and an array containing all exchange keys which could not be decrypted.\n */\n async tryDecryptExchangeKeys(\n encryptedExchangeKeys: { [publicKeyFingerprint: string]: string }[],\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n }> {\n const raws = new Set<string>()\n const res: {\n successfulDecryptions: CryptoKey[]\n failedDecryptions: { [publicKeyFingerprint: string]: string }[]\n } = { successfulDecryptions: [], failedDecryptions: [] }\n for (const encryptedExchangeKey of encryptedExchangeKeys) {\n const decrypted = await this.tryDecryptExchangeKey(encryptedExchangeKey, keyPairsByFingerprint)\n if (decrypted !== undefined && !raws.has(decrypted.raw)) {\n raws.add(decrypted.raw)\n res.successfulDecryptions.push(decrypted.key)\n } else {\n res.failedDecryptions.push(encryptedExchangeKey)\n }\n }\n return res\n }\n\n private async extendForGiveAccessBackTo(\n delegatorId: string,\n delegateId: string,\n newPublicKeyFp: string,\n newPublicKey: CryptoKey,\n decryptionKeyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ) {\n await notConcurrent(this.generateKeyConcurrencyMap, delegatorId, async () => {\n const delegator = await this.dataOwnerApi.getCryptoActorStub(delegatorId)\n const delegate = await this.dataOwnerApi.getCryptoActorStub(delegateId)\n let didUpdateSomeKey = false\n const combinedKeys = await this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub)\n const updatedExchangeKeys: { [delegatorKey: string]: { [delegateId: string]: { [keyFp: string]: string } } } = {}\n const newEncryptionKeys = { [newPublicKeyFp]: newPublicKey }\n for (const [currDelegatorKey, currDelegatesToKeys] of Object.entries(combinedKeys)) {\n const updatedDelegatesToKeys: { [delegateId: string]: { [keyFp: string]: string } } = {}\n for (const [currDelegateId, currEncryptedKey] of Object.entries(currDelegatesToKeys)) {\n if (delegateId !== currDelegateId || newPublicKeyFp in currEncryptedKey) {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n } else {\n const decrypted = await this.tryDecryptExchangeKey(currEncryptedKey, decryptionKeyPairsByFingerprint)\n if (decrypted) {\n didUpdateSomeKey = true\n updatedDelegatesToKeys[currDelegateId] = {\n ...currEncryptedKey,\n ...(await this.encryptExchangeKey(decrypted, newEncryptionKeys)).encryptedExchangeKey,\n }\n } else {\n updatedDelegatesToKeys[currDelegateId] = currEncryptedKey\n }\n }\n }\n updatedExchangeKeys[currDelegatorKey] = updatedDelegatesToKeys\n }\n if (didUpdateSomeKey) {\n await this.dataOwnerApi.modifyCryptoActorStub({\n type: delegator.type,\n stub: {\n ...delegator.stub,\n aesExchangeKeys: updatedExchangeKeys,\n },\n })\n }\n })\n }\n\n /**\n * Attempts to decrypt an exchange key using any of the provided key pairs.\n * @param encryptedExchangeKey an encrypted exchange key, in the form publicKeyXyzFingerprint -> hex(exchangeKeyEncryptedByPrivateKeyXyz).\n * @param keyPairsByFingerprint rsa key pairs to use for decryption.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided keys.\n */\n private async tryDecryptExchangeKey(\n encryptedExchangeKey: { [publicKeyFingerprint: string]: string },\n keyPairsByFingerprint: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n for (const [entryKey, encrypted] of Object.entries(encryptedExchangeKey)) {\n // Due to bugs in past version the entry may actually contain the full public key instead of just the fingerprint.\n const fp = entryKey.slice(-32)\n const keyPair = keyPairsByFingerprint[fp]\n if (keyPair !== undefined) {\n const res = await this.tryDecryptExchangeKeyWith(encrypted, keyPair, fp)\n if (res !== undefined) return res\n }\n }\n const defaultEncryptedKey = encryptedExchangeKey['']\n if (defaultEncryptedKey !== undefined) {\n for (const keyPair of Object.values(keyPairsByFingerprint)) {\n // disable error logging, we are not sure keyPair is the correct key\n const res = await this.tryDecryptExchangeKeyWith(defaultEncryptedKey, keyPair, undefined)\n if (res !== undefined) return res\n }\n }\n return undefined\n }\n\n /**\n * Creates an encrypted exchange key for the provided public keys.\n * @param exchangeKey the exchange key in raw and imported format. If undefined a new key will be automatically created.\n * @param publicKeys additional public keys that will have access to the exchange key in spki format, hex-encoded.\n * @return the exchangeKey and an object with the exchange key encrypted with each of the provided public keys, hex-encoded, by fingerprint.\n */\n private async encryptExchangeKey(\n exchangeKey: { raw: string; key: CryptoKey } | undefined,\n publicKeys: { [keyFingerprint: string]: CryptoKey }\n ): Promise<{\n exchangeKey: CryptoKey\n encryptedExchangeKey: { [pubKeyFp: string]: string }\n }> {\n const exchangeKeyCrypto = exchangeKey?.key ?? (await this.primitives.AES.generateCryptoKey(false))\n const exchangeKeyBytes = exchangeKey !== undefined ? hex2ua(exchangeKey.raw) : await this.primitives.AES.exportKey(exchangeKeyCrypto, 'raw')\n const encryptedExchangeKey = await Object.entries(publicKeys).reduce(\n async (acc, [currKeyFp, currKey]) => ({\n ...(await acc),\n [currKeyFp]: ua2hex(await this.primitives.RSA.encrypt(currKey, new Uint8Array(exchangeKeyBytes))),\n }),\n Promise.resolve({} as { [pubKeyFp: string]: string })\n )\n return { exchangeKey: exchangeKeyCrypto, encryptedExchangeKey }\n }\n\n /**\n * Attempts to decrypt an exchange key using the provided key pairs.\n * If you are confident that the provided {@link keyPair} was used to encrypt {@link encryptedByOneKey} you should also provide {@link keyPairFp},\n * so that if the decryption fail an error will be logged to console before returning undefined.\n * @param encryptedByOneKey an exchange key which may be encrypted with {@link keyPair}.\n * @param keyPair an rsa key pair.\n * @param keyPairFp the fingerprint of the provided key pair or undefined to disable logging of error if the decryption failed.\n * @return the decrypted exchange key, in raw and key format (to allow deduplication), or undefined if the key could not be decrypted using the\n * provided key.\n */\n private async tryDecryptExchangeKeyWith(\n encryptedByOneKey: string,\n keyPair: KeyPair<CryptoKey>,\n keyPairFp: string | undefined // if undefined will not log errors, when we are not sure the key to be used is the provided key.\n ): Promise<{ raw: string; key: CryptoKey } | undefined> {\n try {\n const decrypted = await this.primitives.RSA.decrypt(keyPair.privateKey, hex2ua(encryptedByOneKey))\n return { raw: ua2hex(decrypted), key: await this.primitives.AES.importKey('raw', decrypted) }\n } catch (e) {\n if (keyPairFp) {\n console.error(`Failed to decrypt or import exchange key ${encryptedByOneKey} using key with fingerprint ${keyPairFp}.`, e)\n }\n }\n }\n\n private updateLegacyExchangeKeys(\n delegator: CryptoActorStubWithType,\n delegate: CryptoActorStubWithType,\n encryptedKeyMap: { [fp: string]: string }\n ): { [delegateId: string]: string[] } | undefined {\n const legacyEncryptedKeyDelegator = delegator.stub.publicKey ? encryptedKeyMap[delegator.stub.publicKey] : undefined\n const legacyEncryptedKeyDelegate = delegate.stub.publicKey ? encryptedKeyMap[delegate.stub.publicKey] : undefined\n if (legacyEncryptedKeyDelegator && legacyEncryptedKeyDelegate) {\n return {\n ...(delegator.stub.hcPartyKeys ?? {}),\n [delegate.stub.id!]: [legacyEncryptedKeyDelegator, legacyEncryptedKeyDelegate],\n }\n } else return delegator.stub.hcPartyKeys\n }\n\n // Copy all legacy hcp exchange keys into the new aes exchange keys\n private async combineLegacyHcpKeysWithAesExchangeKeys(\n owner: CryptoActorStub,\n delegate: CryptoActorStub | undefined\n ): Promise<{ [ownerPublicKey: string]: { [delegateId: string]: { [fingerprint: string]: string } } }> {\n const ownerLegacyPublicKey = owner.publicKey\n if (ownerLegacyPublicKey && !(owner.aesExchangeKeys ?? {})[ownerLegacyPublicKey]) {\n /*\n * This condition would technically prevent new updates to the hcPartyKeys to be migrated to the aes exchange keys, but since I can only update\n * data for self data owner and parent entities this is not an issue, because I will always be using the new api from now on and I won't have\n * a situation where the legacy keys are updated but the aes exchange keys are not.\n */\n const unknownDataOwnerCounterPartIds = Object.keys(owner.hcPartyKeys ?? {}).filter((x) => x !== owner.id && x !== delegate?.id)\n const counterPartsById = [\n owner,\n ...(delegate ? [delegate] : []),\n ...(await Promise.all(unknownDataOwnerCounterPartIds.map(async (cpid) => (await this.dataOwnerApi.getCryptoActorStub(cpid)).stub))),\n ].reduce((acc, dataOwner) => {\n acc[dataOwner.id!] = dataOwner\n return acc\n }, {} as { [id: string]: CryptoActorStub })\n return {\n [ownerLegacyPublicKey]: Object.entries(owner.hcPartyKeys ?? {}).reduce((acc, [hcpId, keys]) => {\n acc[hcpId] = { [ownerLegacyPublicKey.slice(-32)]: keys[0], [counterPartsById[hcpId]?.publicKey?.slice(-32) ?? '']: keys[1] }\n return acc\n }, {} as { [delegateId: string]: { [fingerprint: string]: string } }),\n ...(owner.aesExchangeKeys ?? {}),\n }\n } else return owner.aesExchangeKeys ?? {}\n }\n}\n"]}
@@ -1,8 +1,12 @@
1
1
  import { EncryptedEntity } from '../../icc-api/model/models';
2
- import { EntitiesEncryption } from './EntitiesEncryption';
2
+ import { ExtendedApisUtils } from './ExtendedApisUtils';
3
3
  import { CryptoPrimitives } from './CryptoPrimitives';
4
4
  import { IccDataOwnerXApi } from '../icc-data-owner-x-api';
5
+ import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName';
6
+ import { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest';
7
+ import { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult';
5
8
  /**
9
+ * @internal this class is intended for internal use only and may be changed without notice.
6
10
  * This class helps to create confidential medical data in systems where multiple hcps share data with each other using parent hcps: while normally
7
11
  * the hcps would share all data with other hcps part of the same "family" (e.g. an hospital) there are situations where the medical data is
8
12
  * confidential and should only be known by the doctor which created the data. In these situations it is also important that the secret foreign key
@@ -13,17 +17,23 @@ export declare class ConfidentialEntities {
13
17
  private readonly entitiesEncryption;
14
18
  private readonly primitives;
15
19
  private readonly dataOwnerApi;
16
- constructor(entitiesEncryption: EntitiesEncryption, primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi);
20
+ constructor(entitiesEncryption: ExtendedApisUtils, primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi);
17
21
  /**
18
22
  * Ensures that the current data owner has access to a confidential secret id for the provided entity: this is an id that is known to the data owner
19
23
  * but is not known by any of his parents. If there is currently no confidential secret id for this entity the method returns a copy of the entity
20
24
  * with a new confidential secret id for the current data owner (the entity in the database won't be updated), else this method returns undefined.
21
25
  * New confidential secret ids will have an appropriate tag, but existing confidential secret ids may not necessarily have it.
22
26
  * @param entity an entity which needs to have a confidential secret id for the current data owner
23
- * @return undefined if the entity already had a confidential secret id for the current user, or the updated entity with the new confidential secret
24
- * id.
27
+ * @param entityType the type of the entity
28
+ * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).
29
+ * @return undefined if the entity already had a confidential secret id for the current user, or the updated AND SAVED entity with the new
30
+ * confidential secret id.
25
31
  */
26
- entityWithInitialisedConfidentialSecretId<T extends EncryptedEntity>(entity: T): Promise<T | undefined>;
32
+ initialiseConfidentialSecretId<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName, doRequestBulkShareOrUpdate: (request: {
33
+ [entityId: string]: {
34
+ [requestId: string]: EntityShareOrMetadataUpdateRequest;
35
+ };
36
+ }) => Promise<EntityBulkShareResult<T>[]>): Promise<T | undefined>;
27
37
  /**
28
38
  * Get an existing confidential secret id of the provided entity for the provided data owner (current data owner by default). A confidential secret
29
39
  * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.
@@ -31,15 +41,7 @@ export declare class ConfidentialEntities {
31
41
  * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.
32
42
  * @return the confidential secret id or undefined if there is no confidential secret id for the provided data owner.
33
43
  */
34
- getConfidentialSecretId(entity: EncryptedEntity, dataOwnerId?: string): Promise<string | undefined>;
35
- /**
36
- * Gets a secret id known by the topmost parent of the current data owner hierarchy. If there is multiple secret ids shared with the topmost parent
37
- * there is no guarantee on which one will be chosen.
38
- * @param entity an entity.
39
- * @return a secret id known by the topmost parent of the current data owner hierarchy, or undefined if there is no secret id currently available
40
- * for the topmost parent.
41
- */
42
- getAnySecretIdSharedWithParents(entity: EncryptedEntity): Promise<string | undefined>;
44
+ getConfidentialSecretId(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string | undefined>;
43
45
  /**
44
46
  * Get all existing confidential secret ids of the provided entity for the provided data owner (current data owner by default). A confidential secret
45
47
  * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.
@@ -47,12 +49,20 @@ export declare class ConfidentialEntities {
47
49
  * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.
48
50
  * @return the confidential secret ids for the data owner (may be empty).
49
51
  */
50
- getConfidentialSecretIds(entity: EncryptedEntity, dataOwnerId?: string): Promise<string[]>;
52
+ getConfidentialSecretIds(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]>;
53
+ /**
54
+ * Gets a secret id known by the topmost parent of the current data owner hierarchy. If there is multiple secret ids shared with the topmost parent
55
+ * there is no guarantee on which one will be chosen.
56
+ * @param entity an entity.
57
+ * @return a secret id known by the topmost parent of the current data owner hierarchy, or undefined if there is no secret id currently available
58
+ * for the topmost parent.
59
+ */
60
+ getAnySecretIdSharedWithParents(entity: EncryptedEntityWithType): Promise<string | undefined>;
51
61
  /**
52
62
  * Gets all secret ids known by the topmost parent of the current data owner hierarchy (or all secret ids known by the current data owner if he is
53
63
  * not part of any data owner hierarchy).
54
64
  * @param entity an entity.
55
65
  * @return all secret ids known by the topmost parent of the current data owner hierarchy, may be empty.
56
66
  */
57
- getSecretIdsSharedWithParents(entity: EncryptedEntity): Promise<string[]>;
67
+ getSecretIdsSharedWithParents(entity: EncryptedEntityWithType): Promise<string[]>;
58
68
  }
@@ -10,7 +10,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.ConfidentialEntities = void 0;
13
+ const ShareMetadataBehaviour_1 = require("./ShareMetadataBehaviour");
14
+ const EntityShareRequest_1 = require("../../icc-api/model/requests/EntityShareRequest");
15
+ var RequestedPermissionEnum = EntityShareRequest_1.EntityShareRequest.RequestedPermissionEnum;
13
16
  /**
17
+ * @internal this class is intended for internal use only and may be changed without notice.
14
18
  * This class helps to create confidential medical data in systems where multiple hcps share data with each other using parent hcps: while normally
15
19
  * the hcps would share all data with other hcps part of the same "family" (e.g. an hospital) there are situations where the medical data is
16
20
  * confidential and should only be known by the doctor which created the data. In these situations it is also important that the secret foreign key
@@ -29,15 +33,24 @@ class ConfidentialEntities {
29
33
  * with a new confidential secret id for the current data owner (the entity in the database won't be updated), else this method returns undefined.
30
34
  * New confidential secret ids will have an appropriate tag, but existing confidential secret ids may not necessarily have it.
31
35
  * @param entity an entity which needs to have a confidential secret id for the current data owner
32
- * @return undefined if the entity already had a confidential secret id for the current user, or the updated entity with the new confidential secret
33
- * id.
36
+ * @param entityType the type of the entity
37
+ * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).
38
+ * @return undefined if the entity already had a confidential secret id for the current user, or the updated AND SAVED entity with the new
39
+ * confidential secret id.
34
40
  */
35
- entityWithInitialisedConfidentialSecretId(entity) {
41
+ initialiseConfidentialSecretId(entity, entityType, doRequestBulkShareOrUpdate) {
36
42
  return __awaiter(this, void 0, void 0, function* () {
37
- if (yield this.getConfidentialSecretId(entity))
43
+ if (yield this.getConfidentialSecretId({ entity, type: entityType }))
38
44
  return undefined;
39
45
  const confidentialSecretId = this.primitives.randomUuid();
40
- return yield this.entitiesEncryption.entityWithExtendedEncryptedMetadata(entity, yield this.dataOwnerApi.getCurrentDataOwnerId(), [confidentialSecretId], [], [], ['confidential']);
46
+ return (yield this.entitiesEncryption.simpleShareOrUpdateEncryptedEntityMetadata({ entity, type: entityType }, false, {
47
+ [yield this.dataOwnerApi.getCurrentDataOwnerId()]: {
48
+ shareEncryptionKeys: ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER,
49
+ shareOwningEntityIds: ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER,
50
+ shareSecretIds: [confidentialSecretId],
51
+ requestedPermissions: RequestedPermissionEnum.MAX_WRITE,
52
+ },
53
+ }, (request) => doRequestBulkShareOrUpdate(request))).updatedEntityOrThrow;
41
54
  });
42
55
  }
43
56
  /**
@@ -52,18 +65,6 @@ class ConfidentialEntities {
52
65
  return this.getConfidentialSecretIds(entity, dataOwnerId).then((x) => x[0]);
53
66
  });
54
67
  }
55
- /**
56
- * Gets a secret id known by the topmost parent of the current data owner hierarchy. If there is multiple secret ids shared with the topmost parent
57
- * there is no guarantee on which one will be chosen.
58
- * @param entity an entity.
59
- * @return a secret id known by the topmost parent of the current data owner hierarchy, or undefined if there is no secret id currently available
60
- * for the topmost parent.
61
- */
62
- getAnySecretIdSharedWithParents(entity) {
63
- return __awaiter(this, void 0, void 0, function* () {
64
- return (yield this.getSecretIdsSharedWithParents(entity))[0];
65
- });
66
- }
67
68
  /**
68
69
  * Get all existing confidential secret ids of the provided entity for the provided data owner (current data owner by default). A confidential secret
69
70
  * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.
@@ -83,6 +84,18 @@ class ConfidentialEntities {
83
84
  return keysForDataOwner.extracted.filter((k) => !hierarchySecretIds.some((x) => x.ownerId !== chosenDataOwnerId && x.extracted.includes(k)));
84
85
  });
85
86
  }
87
+ /**
88
+ * Gets a secret id known by the topmost parent of the current data owner hierarchy. If there is multiple secret ids shared with the topmost parent
89
+ * there is no guarantee on which one will be chosen.
90
+ * @param entity an entity.
91
+ * @return a secret id known by the topmost parent of the current data owner hierarchy, or undefined if there is no secret id currently available
92
+ * for the topmost parent.
93
+ */
94
+ getAnySecretIdSharedWithParents(entity) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ return (yield this.getSecretIdsSharedWithParents(entity))[0];
97
+ });
98
+ }
86
99
  /**
87
100
  * Gets all secret ids known by the topmost parent of the current data owner hierarchy (or all secret ids known by the current data owner if he is
88
101
  * not part of any data owner hierarchy).