@icure/api 8.0.8 → 8.0.9

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 (256) hide show
  1. package/icc-api/model/models.d.ts +1 -0
  2. package/icc-api/model/models.js +1 -0
  3. package/icc-api/model/models.js.map +1 -1
  4. package/icc-x-api/crypto/ExchangeDataManager.js +3 -2
  5. package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -1
  6. package/icc-x-api/crypto/KeyRecovery.js +5 -4
  7. package/icc-x-api/crypto/KeyRecovery.js.map +1 -1
  8. package/icc-x-api/crypto/RSA.d.ts +4 -1
  9. package/icc-x-api/crypto/RSA.js +6 -1
  10. package/icc-x-api/crypto/RSA.js.map +1 -1
  11. package/icc-x-api/crypto/SecureDelegationsManager.js +2 -1
  12. package/icc-x-api/crypto/SecureDelegationsManager.js.map +1 -1
  13. package/icc-x-api/crypto/TransferKeysManager.js +4 -3
  14. package/icc-x-api/crypto/TransferKeysManager.js.map +1 -1
  15. package/icc-x-api/crypto/UserEncryptionKeysManager.js +2 -1
  16. package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
  17. package/icc-x-api/crypto/utils.d.ts +1 -4
  18. package/icc-x-api/crypto/utils.js +6 -8
  19. package/icc-x-api/crypto/utils.js.map +1 -1
  20. package/icc-x-api/icc-accesslog-x-api.js +16 -14
  21. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  22. package/icc-x-api/icc-calendar-item-x-api.d.ts +2 -2
  23. package/icc-x-api/icc-calendar-item-x-api.js +17 -17
  24. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  25. package/icc-x-api/icc-classification-x-api.js +12 -11
  26. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  27. package/icc-x-api/icc-contact-x-api.d.ts +2 -2
  28. package/icc-x-api/icc-contact-x-api.js +23 -20
  29. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  30. package/icc-x-api/icc-document-x-api.js +17 -16
  31. package/icc-x-api/icc-document-x-api.js.map +1 -1
  32. package/icc-x-api/icc-form-x-api.js +13 -12
  33. package/icc-x-api/icc-form-x-api.js.map +1 -1
  34. package/icc-x-api/icc-helement-x-api.js +18 -16
  35. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  36. package/icc-x-api/icc-invoice-x-api.js +12 -11
  37. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  38. package/icc-x-api/icc-maintenance-task-x-api.js +11 -11
  39. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  40. package/icc-x-api/icc-message-x-api.js +14 -14
  41. package/icc-x-api/icc-message-x-api.js.map +1 -1
  42. package/icc-x-api/icc-patient-x-api.js +28 -27
  43. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  44. package/icc-x-api/icc-receipt-x-api.js +11 -10
  45. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  46. package/icc-x-api/icc-recovery-x-api.js +3 -2
  47. package/icc-x-api/icc-recovery-x-api.js.map +1 -1
  48. package/icc-x-api/icc-time-table-x-api.js +9 -8
  49. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  50. package/icc-x-api/icc-topic-x-api.js +13 -13
  51. package/icc-x-api/icc-topic-x-api.js.map +1 -1
  52. package/icc-x-api/utils/EntityWithDelegationTypeName.d.ts +17 -1
  53. package/icc-x-api/utils/EntityWithDelegationTypeName.js +33 -15
  54. package/icc-x-api/utils/EntityWithDelegationTypeName.js.map +1 -1
  55. package/package.json +1 -1
  56. package/test/icc-api/api/IccAnonymousAccessApi.d.ts +1 -0
  57. package/test/icc-api/api/IccAnonymousAccessApi.js +58 -0
  58. package/test/icc-api/api/IccAnonymousAccessApi.js.map +1 -0
  59. package/test/icc-api/api/IccDocumentApi.d.ts +1 -0
  60. package/test/icc-api/api/IccDocumentApi.js +208 -0
  61. package/test/icc-api/api/IccDocumentApi.js.map +1 -0
  62. package/test/icc-api/api/IccGroupApi.d.ts +1 -0
  63. package/test/icc-api/api/IccGroupApi.js +50 -0
  64. package/test/icc-api/api/IccGroupApi.js.map +1 -0
  65. package/test/icc-api/api/IccRecoveryDataApi.d.ts +1 -0
  66. package/test/icc-api/api/IccRecoveryDataApi.js +95 -0
  67. package/test/icc-api/api/IccRecoveryDataApi.js.map +1 -0
  68. package/test/icc-api/api/IccRoleApi.d.ts +1 -0
  69. package/test/icc-api/api/IccRoleApi.js +34 -0
  70. package/test/icc-api/api/IccRoleApi.js.map +1 -0
  71. package/test/icc-api/api/IccUserApi.d.ts +1 -0
  72. package/test/icc-api/api/IccUserApi.js +96 -0
  73. package/test/icc-api/api/IccUserApi.js.map +1 -0
  74. package/test/icc-api/e2e/IccCalendarItemApi.d.ts +1 -0
  75. package/test/icc-api/e2e/IccCalendarItemApi.js +46 -0
  76. package/test/icc-api/e2e/IccCalendarItemApi.js.map +1 -0
  77. package/test/icc-api/model/modelHelpersTest.d.ts +1 -0
  78. package/test/icc-api/model/modelHelpersTest.js +45 -0
  79. package/test/icc-api/model/modelHelpersTest.js.map +1 -0
  80. package/test/icc-x-api/auth/group-switch-test.d.ts +1 -0
  81. package/test/icc-x-api/auth/group-switch-test.js +81 -0
  82. package/test/icc-x-api/auth/group-switch-test.js.map +1 -0
  83. package/test/icc-x-api/auth/jwt-concurrency-test.d.ts +2 -0
  84. package/test/icc-x-api/auth/jwt-concurrency-test.js +113 -0
  85. package/test/icc-x-api/auth/jwt-concurrency-test.js.map +1 -0
  86. package/test/icc-x-api/auth/smart-auth-provider-test.d.ts +1 -0
  87. package/test/icc-x-api/auth/smart-auth-provider-test.js +224 -0
  88. package/test/icc-x-api/auth/smart-auth-provider-test.js.map +1 -0
  89. package/test/icc-x-api/autofix-anonymity-test.d.ts +1 -0
  90. package/test/icc-x-api/autofix-anonymity-test.js +108 -0
  91. package/test/icc-x-api/autofix-anonymity-test.js.map +1 -0
  92. package/test/icc-x-api/confidential-entities-test.d.ts +1 -0
  93. package/test/icc-x-api/confidential-entities-test.js +110 -0
  94. package/test/icc-x-api/confidential-entities-test.js.map +1 -0
  95. package/test/icc-x-api/crud/comprehensive-crud-test.d.ts +1 -0
  96. package/test/icc-x-api/crud/comprehensive-crud-test.js +276 -0
  97. package/test/icc-x-api/crud/comprehensive-crud-test.js.map +1 -0
  98. package/test/icc-x-api/crud/entities-crud-test-interface.d.ts +16 -0
  99. package/test/icc-x-api/crud/entities-crud-test-interface.js +422 -0
  100. package/test/icc-x-api/crud/entities-crud-test-interface.js.map +1 -0
  101. package/test/icc-x-api/crypto/anonymous-delegations-test.d.ts +1 -0
  102. package/test/icc-x-api/crypto/anonymous-delegations-test.js +588 -0
  103. package/test/icc-x-api/crypto/anonymous-delegations-test.js.map +1 -0
  104. package/test/icc-x-api/crypto/concurrency.d.ts +1 -0
  105. package/test/icc-x-api/crypto/concurrency.js +35 -0
  106. package/test/icc-x-api/crypto/concurrency.js.map +1 -0
  107. package/test/icc-x-api/crypto/crypto-utils.d.ts +1 -0
  108. package/test/icc-x-api/crypto/crypto-utils.js +80 -0
  109. package/test/icc-x-api/crypto/crypto-utils.js.map +1 -0
  110. package/test/icc-x-api/crypto/cryptoTest.d.ts +2 -0
  111. package/test/icc-x-api/crypto/cryptoTest.js +302 -0
  112. package/test/icc-x-api/crypto/cryptoTest.js.map +1 -0
  113. package/test/icc-x-api/crypto/delegate-ci-to-patient-with-missing-keys-test.d.ts +1 -0
  114. package/test/icc-x-api/crypto/delegate-ci-to-patient-with-missing-keys-test.js +166 -0
  115. package/test/icc-x-api/crypto/delegate-ci-to-patient-with-missing-keys-test.js.map +1 -0
  116. package/test/icc-x-api/crypto/exchange-data-manager-test.d.ts +1 -0
  117. package/test/icc-x-api/crypto/exchange-data-manager-test.js +690 -0
  118. package/test/icc-x-api/crypto/exchange-data-manager-test.js.map +1 -0
  119. package/test/icc-x-api/crypto/full-crypto-test.d.ts +1 -0
  120. package/test/icc-x-api/crypto/full-crypto-test.js +457 -0
  121. package/test/icc-x-api/crypto/full-crypto-test.js.map +1 -0
  122. package/test/icc-x-api/crypto/secure-delegations-manager-test.d.ts +1 -0
  123. package/test/icc-x-api/crypto/secure-delegations-manager-test.js +266 -0
  124. package/test/icc-x-api/crypto/secure-delegations-manager-test.js.map +1 -0
  125. package/test/icc-x-api/crypto/secure-delegations-metadata-decryptor-test.d.ts +1 -0
  126. package/test/icc-x-api/crypto/secure-delegations-metadata-decryptor-test.js +393 -0
  127. package/test/icc-x-api/crypto/secure-delegations-metadata-decryptor-test.js.map +1 -0
  128. package/test/icc-x-api/crypto/security-metadata-decryptor-chain-test.d.ts +1 -0
  129. package/test/icc-x-api/crypto/security-metadata-decryptor-chain-test.js +213 -0
  130. package/test/icc-x-api/crypto/security-metadata-decryptor-chain-test.js.map +1 -0
  131. package/test/icc-x-api/crypto/shamir.d.ts +2 -0
  132. package/test/icc-x-api/crypto/shamir.js +166 -0
  133. package/test/icc-x-api/crypto/shamir.js.map +1 -0
  134. package/test/icc-x-api/crypto/share-to-newly-created-patient-from-hcp.d.ts +1 -0
  135. package/test/icc-x-api/crypto/share-to-newly-created-patient-from-hcp.js +71 -0
  136. package/test/icc-x-api/crypto/share-to-newly-created-patient-from-hcp.js.map +1 -0
  137. package/test/icc-x-api/crypto/signature-keys-manager-test.d.ts +1 -0
  138. package/test/icc-x-api/crypto/signature-keys-manager-test.js +44 -0
  139. package/test/icc-x-api/crypto/signature-keys-manager-test.js.map +1 -0
  140. package/test/icc-x-api/crypto/user-encryption-keys-manager-test.d.ts +1 -0
  141. package/test/icc-x-api/crypto/user-encryption-keys-manager-test.js +246 -0
  142. package/test/icc-x-api/crypto/user-encryption-keys-manager-test.js.map +1 -0
  143. package/test/icc-x-api/entity-with-attachments-api-test.d.ts +1 -0
  144. package/test/icc-x-api/entity-with-attachments-api-test.js +142 -0
  145. package/test/icc-x-api/entity-with-attachments-api-test.js.map +1 -0
  146. package/test/icc-x-api/filters/filters.d.ts +1 -0
  147. package/test/icc-x-api/filters/filters.js +49 -0
  148. package/test/icc-x-api/filters/filters.js.map +1 -0
  149. package/test/icc-x-api/icc-accesslog-x-api.d.ts +1 -0
  150. package/test/icc-x-api/icc-accesslog-x-api.js +106 -0
  151. package/test/icc-x-api/icc-accesslog-x-api.js.map +1 -0
  152. package/test/icc-x-api/icc-auth-api.d.ts +1 -0
  153. package/test/icc-x-api/icc-auth-api.js +47 -0
  154. package/test/icc-x-api/icc-auth-api.js.map +1 -0
  155. package/test/icc-x-api/icc-calendar-item-x-api.d.ts +1 -0
  156. package/test/icc-x-api/icc-calendar-item-x-api.js +150 -0
  157. package/test/icc-x-api/icc-calendar-item-x-api.js.map +1 -0
  158. package/test/icc-x-api/icc-contact-x-api.d.ts +1 -0
  159. package/test/icc-x-api/icc-contact-x-api.js +279 -0
  160. package/test/icc-x-api/icc-contact-x-api.js.map +1 -0
  161. package/test/icc-x-api/icc-form-x-api.d.ts +1 -0
  162. package/test/icc-x-api/icc-form-x-api.js +98 -0
  163. package/test/icc-x-api/icc-form-x-api.js.map +1 -0
  164. package/test/icc-x-api/icc-helement-x-api-test.d.ts +1 -0
  165. package/test/icc-x-api/icc-helement-x-api-test.js +153 -0
  166. package/test/icc-x-api/icc-helement-x-api-test.js.map +1 -0
  167. package/test/icc-x-api/icc-invoice-x-api.d.ts +1 -0
  168. package/test/icc-x-api/icc-invoice-x-api.js +99 -0
  169. package/test/icc-x-api/icc-invoice-x-api.js.map +1 -0
  170. package/test/icc-x-api/icc-maintenance-task-x-api-test.d.ts +1 -0
  171. package/test/icc-x-api/icc-maintenance-task-x-api-test.js +221 -0
  172. package/test/icc-x-api/icc-maintenance-task-x-api-test.js.map +1 -0
  173. package/test/icc-x-api/icc-message-x-api.d.ts +1 -0
  174. package/test/icc-x-api/icc-message-x-api.js +328 -0
  175. package/test/icc-x-api/icc-message-x-api.js.map +1 -0
  176. package/test/icc-x-api/icc-patient-x-api-test.d.ts +1 -0
  177. package/test/icc-x-api/icc-patient-x-api-test.js +158 -0
  178. package/test/icc-x-api/icc-patient-x-api-test.js.map +1 -0
  179. package/test/icc-x-api/icc-recovery-x-api.d.ts +1 -0
  180. package/test/icc-x-api/icc-recovery-x-api.js +170 -0
  181. package/test/icc-x-api/icc-recovery-x-api.js.map +1 -0
  182. package/test/icc-x-api/icc-time-table-x-api.d.ts +1 -0
  183. package/test/icc-x-api/icc-time-table-x-api.js +100 -0
  184. package/test/icc-x-api/icc-time-table-x-api.js.map +1 -0
  185. package/test/icc-x-api/icc-topic-x-api.d.ts +1 -0
  186. package/test/icc-x-api/icc-topic-x-api.js +269 -0
  187. package/test/icc-x-api/icc-topic-x-api.js.map +1 -0
  188. package/test/icc-x-api/icc-user-x-api-test.d.ts +1 -0
  189. package/test/icc-x-api/icc-user-x-api-test.js +99 -0
  190. package/test/icc-x-api/icc-user-x-api-test.js.map +1 -0
  191. package/test/icc-x-api/patient-user.d.ts +2 -0
  192. package/test/icc-x-api/patient-user.js +104 -0
  193. package/test/icc-x-api/patient-user.js.map +1 -0
  194. package/test/icc-x-api/storage/storage.d.ts +1 -0
  195. package/test/icc-x-api/storage/storage.js +48 -0
  196. package/test/icc-x-api/storage/storage.js.map +1 -0
  197. package/test/icc-x-api/test-api-no-parent.d.ts +1 -0
  198. package/test/icc-x-api/test-api-no-parent.js +79 -0
  199. package/test/icc-x-api/test-api-no-parent.js.map +1 -0
  200. package/test/icc-x-api/test-legacy-data-support.d.ts +1 -0
  201. package/test/icc-x-api/test-legacy-data-support.js +376 -0
  202. package/test/icc-x-api/test-legacy-data-support.js.map +1 -0
  203. package/test/icc-x-api/utils/graph-test.d.ts +1 -0
  204. package/test/icc-x-api/utils/graph-test.js +54 -0
  205. package/test/icc-x-api/utils/graph-test.js.map +1 -0
  206. package/test/icc-x-api/utils/lru-temporised-async-cache-test.d.ts +1 -0
  207. package/test/icc-x-api/utils/lru-temporised-async-cache-test.js +364 -0
  208. package/test/icc-x-api/utils/lru-temporised-async-cache-test.js.map +1 -0
  209. package/test/support/CSM-185.d.ts +1 -0
  210. package/test/support/CSM-185.js +124 -0
  211. package/test/support/CSM-185.js.map +1 -0
  212. package/test/support/CSM-243.d.ts +1 -0
  213. package/test/support/CSM-243.js +120 -0
  214. package/test/support/CSM-243.js.map +1 -0
  215. package/test/support/CSM-87.d.ts +0 -0
  216. package/test/support/CSM-87.js +21 -0
  217. package/test/support/CSM-87.js.map +1 -0
  218. package/test/support/CSM-93.d.ts +1 -0
  219. package/test/support/CSM-93.js +112 -0
  220. package/test/support/CSM-93.js.map +1 -0
  221. package/test/utils/FakeDataOwnerApi.d.ts +32 -0
  222. package/test/utils/FakeDataOwnerApi.js +136 -0
  223. package/test/utils/FakeDataOwnerApi.js.map +1 -0
  224. package/test/utils/FakeEncryptionKeysManager.d.ts +35 -0
  225. package/test/utils/FakeEncryptionKeysManager.js +87 -0
  226. package/test/utils/FakeEncryptionKeysManager.js.map +1 -0
  227. package/test/utils/FakeExchangeDataApi.d.ts +30 -0
  228. package/test/utils/FakeExchangeDataApi.js +74 -0
  229. package/test/utils/FakeExchangeDataApi.js.map +1 -0
  230. package/test/utils/FakeExchangeDataManager.d.ts +40 -0
  231. package/test/utils/FakeExchangeDataManager.js +89 -0
  232. package/test/utils/FakeExchangeDataManager.js.map +1 -0
  233. package/test/utils/FakeExchangeDataMapManager.d.ts +12 -0
  234. package/test/utils/FakeExchangeDataMapManager.js +38 -0
  235. package/test/utils/FakeExchangeDataMapManager.js.map +1 -0
  236. package/test/utils/FakeGenericApi.d.ts +16 -0
  237. package/test/utils/FakeGenericApi.js +65 -0
  238. package/test/utils/FakeGenericApi.js.map +1 -0
  239. package/test/utils/FakeSignatureKeysManager.d.ts +16 -0
  240. package/test/utils/FakeSignatureKeysManager.js +54 -0
  241. package/test/utils/FakeSignatureKeysManager.js.map +1 -0
  242. package/test/utils/TestApi.d.ts +3 -0
  243. package/test/utils/TestApi.js +30 -0
  244. package/test/utils/TestApi.js.map +1 -0
  245. package/test/utils/TestCollectionUtils.d.ts +1 -0
  246. package/test/utils/TestCollectionUtils.js +109 -0
  247. package/test/utils/TestCollectionUtils.js.map +1 -0
  248. package/test/utils/TestCryptoStrategies.d.ts +42 -0
  249. package/test/utils/TestCryptoStrategies.js +80 -0
  250. package/test/utils/TestCryptoStrategies.js.map +1 -0
  251. package/test/utils/TestStorage.d.ts +23 -0
  252. package/test/utils/TestStorage.js +61 -0
  253. package/test/utils/TestStorage.js.map +1 -0
  254. package/test/utils/test_utils.d.ts +76 -0
  255. package/test/utils/test_utils.js +419 -0
  256. package/test/utils/test_utils.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"file":"RSA.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/RSA.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAA4C;AAS5C,MAAa,QAAQ;IA2BnB,YAAY,SAAiB,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAE,EAAa;QA1BvI,iCAAiC;QACjC,qBAAqB;QACrB,sBAAsB;QACtB,cAAS,GAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,CAAA;QACrC,mDAAmD;QACnD,oBAAe,GAAQ;YACrB,IAAI,EAAE,UAAU;YAChB,aAAa,EAAE,IAAI;YACnB,cAAc,EAAE,IAAI,UAAU,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;YAClD,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;SACxB,CAAA;QACD,8BAAyB,GAAQ;YAC/B,IAAI,EAAE,UAAU;YAChB,aAAa,EAAE,IAAI;YACnB,cAAc,EAAE,IAAI,UAAU,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;YAClD,IAAI,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;SAC1B,CAAA;QACgB,kCAA6B,GAAG;YAC/C,IAAI,EAAE,SAAS;YACf,aAAa,EAAE,IAAI;YACnB,cAAc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EAAC,IAAI,CAAC,CAAC,CAAA;gBAC3E,MAAM,aAAa,GAAG,IAAA,eAAO,EAAC,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,IAAI,UAAU,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;gBACpG,OAAO,aAAa,KAAK,IAAI,CAAA;aAC9B;YAAC,OAAO,CAAC,EAAE;gBACV,OAAO,KAAK,CAAA;aACb;QACH,CAAC;KAAA;IAED;;;;;OAKG;IACG,IAAI,CAAC,UAAqB,EAAE,IAAiB;;YACjD,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,EAAE,EAAE,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;QAC7F,CAAC;KAAA;IAED;;;;;;OAMG;IACG,eAAe,CAAC,SAAoB,EAAE,SAAsB,EAAE,IAAiB;;YACnF,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;QACzG,CAAC;KAAA;CACF;AA5OD,4BA4OC;AAEY,QAAA,GAAG,GAAG,IAAI,QAAQ,EAAE,CAAA","sourcesContent":["import { ua2utf8, utf8_2ua } from '../utils'\n\n/**\n * Represents an RSA KeyPair in a generic format.\n */\nexport type KeyPair<T> = { publicKey: T; privateKey: T }\n\nexport type ShaVersion = 'sha-1' | 'sha-256'\n\nexport class RSAUtils {\n /********* RSA Config **********/\n //TODO bigger modulus\n //TODO PSS for signing\n rsaParams: any = { name: 'RSA-OAEP' }\n // RSA params for 'import' and 'generate' function.\n rsaHashedParams: any = {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'sha-1' },\n }\n rsaWithSha256HashedParams: any = {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'SHA-256' },\n }\n private readonly signatureKeysGenerationParams = {\n name: 'RSA-PSS',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'SHA-256' },\n }\n\n private crypto: Crypto\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n /**\n * Generates a key pair for encryption/decryption of data.\n * @param shaVersion the version of the SHA algorithm to use.\n */\n generateKeyPair(shaVersion: ShaVersion): Promise<KeyPair<CryptoKey>> {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const rsaParams = this.paramsForCreationOrImport(shaVersion)\n\n return new Promise<KeyPair<CryptoKey>>((resolve, reject) => {\n this.crypto.subtle.generateKey(rsaParams, extractable, keyUsages).then(resolve, reject)\n })\n }\n\n /**\n * Generates a key pair for signing data and signature verification.\n */\n async generateSignatureKeyPair(): Promise<KeyPair<CryptoKey>> {\n return await this.crypto.subtle.generateKey(this.signatureKeysGenerationParams, true, ['sign', 'verify'])\n }\n\n /**\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param keyPair is {publicKey: CryptoKey, privateKey: CryptoKey}\n * @param privKeyFormat will be 'pkcs8' or 'jwk'\n * @param pubKeyFormat will be 'spki' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'jwk', pubKeyFormat: 'jwk'): Promise<KeyPair<JsonWebKey>>\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'pkcs8', pubKeyFormat: 'spki'): Promise<KeyPair<ArrayBuffer>>\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: string, pubKeyFormat: string): Promise<KeyPair<JsonWebKey | ArrayBuffer>> {\n const pubPromise = this.crypto.subtle.exportKey(pubKeyFormat as any, keyPair.publicKey)\n const privPromise = this.crypto.subtle.exportKey(privKeyFormat as any, keyPair.privateKey)\n\n return Promise.all([pubPromise, privPromise]).then(function (results) {\n return {\n publicKey: results[0],\n privateKey: results[1],\n }\n })\n }\n\n /**\n * Format:\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param cryptoKey public or private\n * @param format either 'jwk' or 'spki' or 'pkcs8'\n * @returns {Promise|*} will be RSA key (public or private)\n */\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'spki'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'pkcs8'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: string): Promise<JsonWebKey | ArrayBuffer> {\n return new Promise((resolve: (value: JsonWebKey | ArrayBuffer) => any, reject) => {\n this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param publicKey (CryptoKey)\n * @param plainData (Uint8Array)\n */\n encrypt(publicKey: CryptoKey, plainData: Uint8Array): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject) => {\n this.crypto.subtle.encrypt(this.rsaParams, publicKey, plainData.buffer ? plainData.buffer : plainData).then(resolve, reject) //Node prefers arrayBuffer\n })\n }\n\n /**\n *\n * @param privateKey (CryptoKey)\n * @param encryptedData (Uint8Array)\n */\n decrypt(privateKey: CryptoKey, encryptedData: Uint8Array): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject) => {\n this.crypto.subtle.decrypt(this.rsaParams, privateKey, encryptedData).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param format 'jwk', 'spki', or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param keyUsages Array of usages. For example, ['encrypt'] for public key.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importKey(format: string, keydata: JsonWebKey | ArrayBuffer, keyUsages: KeyUsage[], hashAlgorithm: ShaVersion): Promise<CryptoKey> {\n const extractable = true\n return new Promise((resolve: (value: CryptoKey) => any, reject) => {\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n this.crypto.subtle.importKey(format as any, keydata as any, rsaParams, extractable, keyUsages).then(resolve, reject)\n })\n }\n\n importSignatureKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n const extractable = true\n return this.crypto.subtle.importKey(format as any, keydata as any, this.signatureKeysGenerationParams, extractable, ['sign'])\n }\n\n importVerificationKey(format: 'jwk' | 'spki', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n const extractable = true\n return this.crypto.subtle.importKey(format as any, keydata as any, this.signatureKeysGenerationParams, extractable, ['verify'])\n }\n\n private paramsForCreationOrImport(shaVersion: ShaVersion) {\n if (shaVersion === 'sha-1') {\n return this.rsaHashedParams\n } else if (shaVersion === 'sha-256') {\n return this.rsaWithSha256HashedParams\n } else {\n throw new Error('Unexpected error, invalid SHA version')\n }\n }\n\n /**\n *\n * @param format 'jwk' or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importPrivateKey(format: string, keydata: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<CryptoKey> {\n const extractable = true\n return new Promise((resolve: (value: CryptoKey) => any, reject) => {\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n this.crypto.subtle.importKey(format as any, keydata as any, rsaParams, extractable, ['decrypt']).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param privateKeyFormat 'jwk' or 'pkcs8'\n * @param privateKeydata should be the key data based on the format.\n * @param publicKeyFormat 'jwk' or 'spki'\n * @param publicKeyData should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {Promise|*}\n */\n importKeyPair(\n privateKeyFormat: string,\n privateKeydata: JsonWebKey | ArrayBuffer,\n publicKeyFormat: string,\n publicKeyData: JsonWebKey | ArrayBuffer,\n hashAlgorithm: ShaVersion\n ): Promise<KeyPair<CryptoKey>> {\n const extractable = true\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n const privPromise = this.crypto.subtle.importKey(privateKeyFormat as any, privateKeydata as any, rsaParams, extractable, ['decrypt'])\n const pubPromise = this.crypto.subtle.importKey(publicKeyFormat as any, publicKeyData as any, rsaParams, extractable, ['encrypt'])\n\n return Promise.all([pubPromise, privPromise]).then(function (results) {\n return {\n publicKey: results[0],\n privateKey: results[1],\n }\n })\n }\n\n /**\n * Tries to encrypt then decrypt data using a keypair. If both operations succeed without throwing an error and the decrypted data matches the\n * original data returns true, else false.\n * @param keyPair a key pair.\n * @return if the key pair could be successfully used to encrypt then decrypt data.\n */\n async checkKeyPairValidity(keyPair: KeyPair<CryptoKey>): Promise<boolean> {\n try {\n const text = 'shibboleth'\n const encryptedText = await this.encrypt(keyPair.publicKey, utf8_2ua(text))\n const decryptedText = ua2utf8(await this.decrypt(keyPair.privateKey, new Uint8Array(encryptedText)))\n return decryptedText === text\n } catch (e) {\n return false\n }\n }\n\n /**\n * Generates a signature for some data. The signature algorithm used is RSA-PSS with SHA-256.\n * @param privateKey private key to use for signature\n * @param data the data to sign\n * @return the signature.\n */\n async sign(privateKey: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer> {\n return await this.crypto.subtle.sign({ name: 'RSA-PSS', saltLength: 32 }, privateKey, data)\n }\n\n /**\n * Verifies if a signature matches the data. The signature algorithm used is RSA-PSS with sha-256.\n * @param publicKey public key to use for signature verification.\n * @param signature the signature to verify\n * @param data the data that was signed\n * @return if the signature matches the data and key.\n */\n async verifySignature(publicKey: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean> {\n return await this.crypto.subtle.verify({ name: 'RSA-PSS', saltLength: 32 }, publicKey, signature, data)\n }\n}\n\nexport const RSA = new RSAUtils()\n"]}
1
+ {"version":3,"file":"RSA.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/RSA.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAA4C;AAO5C,IAAY,UAGX;AAHD,WAAY,UAAU;IACpB,4BAAc,CAAA;IACd,gCAAkB,CAAA;AACpB,CAAC,EAHW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAGrB;AAED,MAAa,QAAQ;IA2BnB,YAAY,SAAiB,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAE,EAAa;QA1BvI,iCAAiC;QACjC,qBAAqB;QACrB,sBAAsB;QACtB,cAAS,GAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,CAAA;QACrC,mDAAmD;QACnD,oBAAe,GAAQ;YACrB,IAAI,EAAE,UAAU;YAChB,aAAa,EAAE,IAAI;YACnB,cAAc,EAAE,IAAI,UAAU,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;YAClD,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;SACxB,CAAA;QACD,8BAAyB,GAAQ;YAC/B,IAAI,EAAE,UAAU;YAChB,aAAa,EAAE,IAAI;YACnB,cAAc,EAAE,IAAI,UAAU,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;YAClD,IAAI,EAAE,EAAE,IAAI,EA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G,YAAY,CAAA;gBACzB,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,IAAA,gBAAQ,EAAC,IAAI,CAAC,CAAC,CAAA;gBAC3E,MAAM,aAAa,GAAG,IAAA,eAAO,EAAC,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,IAAI,UAAU,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;gBACpG,OAAO,aAAa,KAAK,IAAI,CAAA;aAC9B;YAAC,OAAO,CAAC,EAAE;gBACV,OAAO,KAAK,CAAA;aACb;QACH,CAAC;KAAA;IAED;;;;;OAKG;IACG,IAAI,CAAC,UAAqB,EAAE,IAAiB;;YACjD,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,EAAE,EAAE,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;QAC7F,CAAC;KAAA;IAED;;;;;;OAMG;IACG,eAAe,CAAC,SAAoB,EAAE,SAAsB,EAAE,IAAiB;;YACnF,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;QACzG,CAAC;KAAA;CACF;AA5OD,4BA4OC;AAEY,QAAA,GAAG,GAAG,IAAI,QAAQ,EAAE,CAAA","sourcesContent":["import { ua2utf8, utf8_2ua } from '../utils'\n\n/**\n * Represents an RSA KeyPair in a generic format.\n */\nexport type KeyPair<T> = { publicKey: T; privateKey: T }\n\nexport enum ShaVersion {\n Sha1 = 'sha-1',\n Sha256 = 'sha-256',\n}\n\nexport class RSAUtils {\n /********* RSA Config **********/\n //TODO bigger modulus\n //TODO PSS for signing\n rsaParams: any = { name: 'RSA-OAEP' }\n // RSA params for 'import' and 'generate' function.\n rsaHashedParams: any = {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'sha-1' },\n }\n rsaWithSha256HashedParams: any = {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'SHA-256' },\n }\n private readonly signatureKeysGenerationParams = {\n name: 'RSA-PSS',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'SHA-256' },\n }\n\n private crypto: Crypto\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n /**\n * Generates a key pair for encryption/decryption of data.\n * @param shaVersion the version of the SHA algorithm to use.\n */\n generateKeyPair(shaVersion: ShaVersion): Promise<KeyPair<CryptoKey>> {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const rsaParams = this.paramsForCreationOrImport(shaVersion)\n\n return new Promise<KeyPair<CryptoKey>>((resolve, reject) => {\n this.crypto.subtle.generateKey(rsaParams, extractable, keyUsages).then(resolve, reject)\n })\n }\n\n /**\n * Generates a key pair for signing data and signature verification.\n */\n async generateSignatureKeyPair(): Promise<KeyPair<CryptoKey>> {\n return await this.crypto.subtle.generateKey(this.signatureKeysGenerationParams, true, ['sign', 'verify'])\n }\n\n /**\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param keyPair is {publicKey: CryptoKey, privateKey: CryptoKey}\n * @param privKeyFormat will be 'pkcs8' or 'jwk'\n * @param pubKeyFormat will be 'spki' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'jwk', pubKeyFormat: 'jwk'): Promise<KeyPair<JsonWebKey>>\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'pkcs8', pubKeyFormat: 'spki'): Promise<KeyPair<ArrayBuffer>>\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: string, pubKeyFormat: string): Promise<KeyPair<JsonWebKey | ArrayBuffer>> {\n const pubPromise = this.crypto.subtle.exportKey(pubKeyFormat as any, keyPair.publicKey)\n const privPromise = this.crypto.subtle.exportKey(privKeyFormat as any, keyPair.privateKey)\n\n return Promise.all([pubPromise, privPromise]).then(function (results) {\n return {\n publicKey: results[0],\n privateKey: results[1],\n }\n })\n }\n\n /**\n * Format:\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param cryptoKey public or private\n * @param format either 'jwk' or 'spki' or 'pkcs8'\n * @returns {Promise|*} will be RSA key (public or private)\n */\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'spki'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'pkcs8'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: string): Promise<JsonWebKey | ArrayBuffer> {\n return new Promise((resolve: (value: JsonWebKey | ArrayBuffer) => any, reject) => {\n this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param publicKey (CryptoKey)\n * @param plainData (Uint8Array)\n */\n encrypt(publicKey: CryptoKey, plainData: Uint8Array): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject) => {\n this.crypto.subtle.encrypt(this.rsaParams, publicKey, plainData.buffer ? plainData.buffer : plainData).then(resolve, reject) //Node prefers arrayBuffer\n })\n }\n\n /**\n *\n * @param privateKey (CryptoKey)\n * @param encryptedData (Uint8Array)\n */\n decrypt(privateKey: CryptoKey, encryptedData: Uint8Array): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject) => {\n this.crypto.subtle.decrypt(this.rsaParams, privateKey, encryptedData).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param format 'jwk', 'spki', or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param keyUsages Array of usages. For example, ['encrypt'] for public key.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importKey(format: string, keydata: JsonWebKey | ArrayBuffer, keyUsages: KeyUsage[], hashAlgorithm: ShaVersion): Promise<CryptoKey> {\n const extractable = true\n return new Promise((resolve: (value: CryptoKey) => any, reject) => {\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n this.crypto.subtle.importKey(format as any, keydata as any, rsaParams, extractable, keyUsages).then(resolve, reject)\n })\n }\n\n importSignatureKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n const extractable = true\n return this.crypto.subtle.importKey(format as any, keydata as any, this.signatureKeysGenerationParams, extractable, ['sign'])\n }\n\n importVerificationKey(format: 'jwk' | 'spki', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n const extractable = true\n return this.crypto.subtle.importKey(format as any, keydata as any, this.signatureKeysGenerationParams, extractable, ['verify'])\n }\n\n private paramsForCreationOrImport(shaVersion: ShaVersion) {\n if (shaVersion === 'sha-1') {\n return this.rsaHashedParams\n } else if (shaVersion === 'sha-256') {\n return this.rsaWithSha256HashedParams\n } else {\n throw new Error('Unexpected error, invalid SHA version')\n }\n }\n\n /**\n *\n * @param format 'jwk' or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importPrivateKey(format: string, keydata: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<CryptoKey> {\n const extractable = true\n return new Promise((resolve: (value: CryptoKey) => any, reject) => {\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n this.crypto.subtle.importKey(format as any, keydata as any, rsaParams, extractable, ['decrypt']).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param privateKeyFormat 'jwk' or 'pkcs8'\n * @param privateKeydata should be the key data based on the format.\n * @param publicKeyFormat 'jwk' or 'spki'\n * @param publicKeyData should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {Promise|*}\n */\n importKeyPair(\n privateKeyFormat: string,\n privateKeydata: JsonWebKey | ArrayBuffer,\n publicKeyFormat: string,\n publicKeyData: JsonWebKey | ArrayBuffer,\n hashAlgorithm: ShaVersion\n ): Promise<KeyPair<CryptoKey>> {\n const extractable = true\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n const privPromise = this.crypto.subtle.importKey(privateKeyFormat as any, privateKeydata as any, rsaParams, extractable, ['decrypt'])\n const pubPromise = this.crypto.subtle.importKey(publicKeyFormat as any, publicKeyData as any, rsaParams, extractable, ['encrypt'])\n\n return Promise.all([pubPromise, privPromise]).then(function (results) {\n return {\n publicKey: results[0],\n privateKey: results[1],\n }\n })\n }\n\n /**\n * Tries to encrypt then decrypt data using a keypair. If both operations succeed without throwing an error and the decrypted data matches the\n * original data returns true, else false.\n * @param keyPair a key pair.\n * @return if the key pair could be successfully used to encrypt then decrypt data.\n */\n async checkKeyPairValidity(keyPair: KeyPair<CryptoKey>): Promise<boolean> {\n try {\n const text = 'shibboleth'\n const encryptedText = await this.encrypt(keyPair.publicKey, utf8_2ua(text))\n const decryptedText = ua2utf8(await this.decrypt(keyPair.privateKey, new Uint8Array(encryptedText)))\n return decryptedText === text\n } catch (e) {\n return false\n }\n }\n\n /**\n * Generates a signature for some data. The signature algorithm used is RSA-PSS with SHA-256.\n * @param privateKey private key to use for signature\n * @param data the data to sign\n * @return the signature.\n */\n async sign(privateKey: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer> {\n return await this.crypto.subtle.sign({ name: 'RSA-PSS', saltLength: 32 }, privateKey, data)\n }\n\n /**\n * Verifies if a signature matches the data. The signature algorithm used is RSA-PSS with sha-256.\n * @param publicKey public key to use for signature verification.\n * @param signature the signature to verify\n * @param data the data that was signed\n * @return if the signature matches the data and key.\n */\n async verifySignature(publicKey: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean> {\n return await this.crypto.subtle.verify({ name: 'RSA-PSS', saltLength: 32 }, publicKey, signature, data)\n }\n}\n\nexport const RSA = new RSAUtils()\n"]}
@@ -19,6 +19,7 @@ const EntitySharedMetadataUpdateRequest_1 = require("../../icc-api/model/request
19
19
  var EntryUpdateTypeEnum = EntitySharedMetadataUpdateRequest_1.EntitySharedMetadataUpdateRequest.EntryUpdateTypeEnum;
20
20
  var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
21
21
  const SecurityMetadata_1 = require("../../icc-api/model/SecurityMetadata");
22
+ const RSA_1 = require("./RSA");
22
23
  class SecureDelegationsManager {
23
24
  constructor(exchangeDataManager, exchangeDataMapManager, secureDelegationsEncryption, accessControlSecretUtils, userKeys, primitives, dataOwnerApi, cryptoStrategies, selfNeedsAnonymousDelegations) {
24
25
  this.exchangeDataManager = exchangeDataManager;
@@ -198,7 +199,7 @@ class SecureDelegationsManager {
198
199
  const delegateVerifiedKeys = {};
199
200
  for (const keyHex of [...delegateInfo.availablePublicKeysHexWithSha1, ...delegateInfo.availablePublicKeysHexWithSha256]) {
200
201
  const currFp = (0, utils_1.fingerprintV2)(keyHex);
201
- const shaVersion = delegateInfo.availablePublicKeysHexWithSha1.includes(keyHex) ? 'sha-1' : 'sha-256';
202
+ const shaVersion = delegateInfo.availablePublicKeysHexWithSha1.includes(keyHex) ? RSA_1.ShaVersion.Sha1 : RSA_1.ShaVersion.Sha256;
202
203
  if (fingerprintsOfVerifiedExchangeData.has(currFp)) {
203
204
  delegateVerifiedKeys[currFp] = yield this.primitives.RSA.importKey('spki', (0, utils_2.hex2ua)(keyHex), ['encrypt'], shaVersion);
204
205
  }
@@ -1 +1 @@
1
- {"version":3,"file":"SecureDelegationsManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/SecureDelegationsManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wFAAoF;AAKpF,oFAA6E;AAC7E,mCAA2F;AAK3F,oCAAyC;AAIzC,2EAAuE;AACvE,sHAAkH;AAClH,IAAO,mBAAmB,GAAG,qEAAiC,CAAC,mBAAmB,CAAA;AAClF,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACzD,2EAAuE;AAGvE,MAAa,wBAAwB;IACnC,YACmB,mBAAwC,EACxC,sBAA8C,EAC9C,2BAAwD,EACxD,wBAAkD,EAClD,QAAmC,EACnC,UAA4B,EAC5B,YAA8B,EAC9B,gBAAkC,EAClC,6BAAsC;QARtC,wBAAmB,GAAnB,mBAAmB,CAAqB;QACxC,2BAAsB,GAAtB,sBAAsB,CAAwB;QAC9C,gCAA2B,GAA3B,2BAA2B,CAA6B;QACxD,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,aAAQ,GAAR,QAAQ,CAA2B;QACnC,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,kCAA6B,GAA7B,6BAA6B,CAAS;QAGxC,uBAAkB,GAO/B,IAAI,oDAAuB,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;IATvD,CAAC;IAWJ;;;;;;;;;;OAUG;IACG,sCAAsC,CAC1C,MAA2C,EAC3C,UAAwC,EACxC,SAAmB,EACnB,eAAyB,EACzB,cAAwB,EACxB,eAA2E;;YAE3E,MAAM,cAAc,GAA4B,EAAE,MAAM,EAAE,IAAI,EAAE,UA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rG,MAAM,yBAAyB,GAAG,uBAAuB,CAAC,CAAC,CAAC,CAAA;QAC5D,MAAM,yBAAyB,GAAG,MAAA,gBAAgB,CAAC,iBAAiB,0CAAG,yBAAyB,CAAC,CAAA;QACjG,OAAO,CACL,MAAA,gBAAgB,CAAC,CAAC,CAAC,mCACnB,CAAC,CAAC,CAAC,yBAAyB,IAAI,CAAC,CAAC,yBAAyB;YACzD,CAAC,CAAC,EAAE,YAAY,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,yBAAyB,EAAE;YAC1F,CAAC,CAAC,SAAS,CAAC,CACf,CAAA;IACH,CAAC;CACF;AAjaD,4DAiaC","sourcesContent":["import { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { fingerprintV2, hexPublicKeysWithSha1Of, hexPublicKeysWithSha256Of } from './utils'\nimport { ExchangeDataManager } from './ExchangeDataManager'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { SecureDelegationsEncryption } from './SecureDelegationsEncryption'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { hex2ua, ua2hex } from '../utils'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { EntitySharedMetadataUpdateRequest } from '../../icc-api/model/requests/EntitySharedMetadataUpdateRequest'\nimport EntryUpdateTypeEnum = EntitySharedMetadataUpdateRequest.EntryUpdateTypeEnum\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { SecurityMetadata } from '../../icc-api/model/SecurityMetadata'\nimport { ExchangeDataMapManager } from './ExchangeDataMapManager'\n\nexport class SecureDelegationsManager {\n constructor(\n private readonly exchangeDataManager: ExchangeDataManager,\n private readonly exchangeDataMapManager: ExchangeDataMapManager,\n private readonly secureDelegationsEncryption: SecureDelegationsEncryption,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n private readonly userKeys: UserEncryptionKeysManager,\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly cryptoStrategies: CryptoStrategies,\n private readonly selfNeedsAnonymousDelegations: boolean\n ) {}\n\n private readonly dataOwnerInfoCache: LruTemporisedAsyncCache<\n string,\n {\n requiresAnonymousDelegations: boolean\n availablePublicKeysHexWithSha1: string[]\n availablePublicKeysHexWithSha256: string[]\n }\n > = new LruTemporisedAsyncCache(100, () => 30 * 60 * 1000)\n\n /**\n * Note: this method does not save the updated entity.\n * @param entity an entity, must already have secret foreign keys initialised.\n * @param entityType the type of the entity\n * @param secretIds the initial secret ids to include and share with the auto-delegations\n * @param owningEntityIds the initial owning entity ids to include and share with the auto-delegations\n * @param encryptionKeys the initial encryption keys to include and share with the auto-delegations\n * @param autoDelegations the data owners which will initially have access to the entity in addition to the current data owner and the access level\n * they will have on the entity.\n * @return the entity with the security metadata initialised for the provided parameters.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T & { secretForeignKeys: string[] },\n entityType: EntityWithDelegationTypeName,\n secretIds: string[],\n owningEntityIds: string[],\n encryptionKeys: string[],\n autoDelegations: { [delegateId: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<T> {\n const entityWithType: EncryptedEntityWithType = { entity, type: entityType }\n const rootDelegationInfo = await this.makeSecureDelegationInfo(\n entityWithType,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n secretIds,\n encryptionKeys,\n owningEntityIds,\n AccessLevelEnum.WRITE,\n undefined\n )\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const otherDelegationsInfo: {\n canonicalDelegationKey: string\n canonicalAccessControlKey: string\n delegation: SecureDelegation\n delegationKeyEquivalences: { [p: string]: string }\n encryptedExchangeDataId: { [fp: string]: string } | undefined\n }[] = []\n for (const [delegateId, permissions] of Object.entries(autoDelegations)) {\n if (delegateId !== selfId) {\n otherDelegationsInfo.push(\n await this.makeSecureDelegationInfo(\n entityWithType,\n delegateId,\n secretIds,\n encryptionKeys,\n owningEntityIds,\n permissions,\n rootDelegationInfo.canonicalDelegationKey\n )\n )\n }\n }\n const secureDelegations = Object.fromEntries(\n [rootDelegationInfo, ...otherDelegationsInfo].map(({ canonicalDelegationKey, delegation }) => [canonicalDelegationKey, delegation])\n )\n const keysEquivalences = {\n ...rootDelegationInfo.delegationKeyEquivalences,\n }\n for (const { delegationKeyEquivalences: otherKeyEquivalences } of otherDelegationsInfo) {\n Object.assign(keysEquivalences, otherKeyEquivalences)\n }\n const newExchangeDataMaps = Object.fromEntries(\n otherDelegationsInfo\n .filter(({ encryptedExchangeDataId }) => !!encryptedExchangeDataId)\n .map(({ canonicalAccessControlKey, encryptedExchangeDataId }) => [canonicalAccessControlKey, encryptedExchangeDataId!])\n )\n await this.exchangeDataMapManager.createExchangeDataMaps(newExchangeDataMaps)\n return {\n ...entity,\n securityMetadata: new SecurityMetadata({ secureDelegations, keysEquivalences }),\n }\n }\n\n /**\n * Make a request for sharing an entity with a delegate or to update existing shared metadata by adding additional secretIds, encryptionKeys or\n * owningEntityIds if there is already some metadata shared between the current data owner and the delegate. In case there is already a delegation\n * for the delegate, and it already contains all the provided metadata, this method returns undefined, since there is no need to make any request to\n * share the provided data.\n * @param entityWithType an entity with type\n * @param delegateId the id of the delegate\n * @param shareSecretIds the secret ids to share\n * @param shareEncryptionKeys the encryption keys to share\n * @param shareOwningEntityIds the owning entity ids to share\n * @param newDelegationPermissions the permissions to grant to the delegate in case a new delegation needs to be created. If this method creates an\n * update request instead of a share request, this parameter is ignored.\n * @return the request to share the entity, or the request to update the shared metadata for the entity, or undefined if there is no need to update\n * the entity to allow the delegate to access the provided data.\n */\n async makeShareOrUpdateRequestParams(\n entityWithType: EncryptedEntityWithType,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newDelegationPermissions: EntityShareRequest.RequestedPermissionInternal\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n const exchangeDataInfo = await this.exchangeDataManager.getOrCreateEncryptionDataTo(\n delegateId,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? [],\n false\n )\n const accessControlHashes = await this.accessControlSecretUtils.secureDelegationKeysFor(\n exchangeDataInfo.accessControlSecret,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? []\n )\n const existingSecureDelegation = this.getExistingCanonicalKeyAndSecureDelegation(entityWithType.entity, accessControlHashes)\n if (existingSecureDelegation) {\n const updateParams = await this.makeUpdateRequestParams(\n existingSecureDelegation.canonicalKey,\n existingSecureDelegation.secureDelegation,\n exchangeDataInfo,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds\n )\n return updateParams ? { update: updateParams } : undefined\n } else {\n const accessControlKeys = (\n await this.accessControlSecretUtils.accessControlKeysFor(\n exchangeDataInfo.accessControlSecret,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? []\n )\n ).map((x) => ua2hex(x))\n return {\n share: await this.makeShareRequestParams(\n exchangeDataInfo,\n accessControlKeys,\n delegateId,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds,\n newDelegationPermissions\n ),\n }\n }\n }\n\n private async makeUpdateRequestParams(\n canonicalKey: string,\n existingDelegation: SecureDelegation,\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[]\n ): Promise<EntitySharedMetadataUpdateRequest | undefined> {\n const existingSecretIds = new Set(await this.secureDelegationsEncryption.decryptSecretIds(existingDelegation, exchangeDataInfo.exchangeKey))\n const existingEncryptionKeys = new Set(\n await this.secureDelegationsEncryption.decryptEncryptionKeys(existingDelegation, exchangeDataInfo.exchangeKey)\n )\n const existingOwningEntityIds = new Set(\n await this.secureDelegationsEncryption.decryptOwningEntityIds(existingDelegation, exchangeDataInfo.exchangeKey)\n )\n const newSecretIds = shareSecretIds.filter((id) => !existingSecretIds.has(id))\n const newEncryptionKeys = shareEncryptionKeys.filter((key) => !existingEncryptionKeys.has(key))\n const newOwningEntityIds = shareOwningEntityIds.filter((id) => !existingOwningEntityIds.has(id))\n if (newSecretIds.length || newEncryptionKeys.length || newOwningEntityIds.length) {\n const encryptedNewSecretIds = await this.secureDelegationsEncryption.encryptSecretIds(newSecretIds, exchangeDataInfo.exchangeKey)\n const encryptedNewEncryptionKeys = await this.secureDelegationsEncryption.encryptEncryptionKeys(newEncryptionKeys, exchangeDataInfo.exchangeKey)\n const encryptedNewOwningEntityIds = await this.secureDelegationsEncryption.encryptOwningEntityIds(\n newOwningEntityIds,\n exchangeDataInfo.exchangeKey\n )\n return new EntitySharedMetadataUpdateRequest({\n metadataAccessControlHash: canonicalKey,\n secretIds: Object.fromEntries(encryptedNewSecretIds.map((id) => [id, EntryUpdateTypeEnum.CREATE])),\n encryptionKeys: Object.fromEntries(encryptedNewEncryptionKeys.map((key) => [key, EntryUpdateTypeEnum.CREATE])),\n owningEntityIds: Object.fromEntries(encryptedNewOwningEntityIds.map((id) => [id, EntryUpdateTypeEnum.CREATE])),\n })\n } else return undefined\n }\n\n private async makeShareRequestParams(\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n accessControlKeys: string[],\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newDelegationPermissions: EntityShareRequest.RequestedPermissionInternal\n ): Promise<EntityShareRequest> {\n return new EntityShareRequest({\n ...(await this.makeSecureDelegationEncryptedData(exchangeDataInfo, delegateId, shareSecretIds, shareEncryptionKeys, shareOwningEntityIds)),\n requestedPermissions: newDelegationPermissions,\n accessControlKeys,\n })\n }\n\n private async makeSecureDelegationInfo(\n entity: EncryptedEntityWithType,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n permissions: AccessLevelEnum,\n parentDelegationKey: string | undefined\n ): Promise<{\n canonicalDelegationKey: string\n canonicalAccessControlKey: string\n delegation: SecureDelegation\n encryptedExchangeDataId: { [fp: string]: string } | undefined\n delegationKeyEquivalences: { [alias: string]: string }\n }> {\n // Be wary of explicit delegator and explicit delegate\n const exchangeDataInfo = await this.exchangeDataManager.getOrCreateEncryptionDataTo(\n delegateId,\n entity.type,\n entity.entity.secretForeignKeys ?? [],\n false\n )\n const accessControlHashes = await this.accessControlSecretUtils.secureDelegationKeysFor(\n exchangeDataInfo.accessControlSecret,\n entity.type,\n entity.entity.secretForeignKeys ?? []\n )\n const accessControlKeys = (\n await this.accessControlSecretUtils.accessControlKeysFor(\n exchangeDataInfo.accessControlSecret,\n entity.type,\n entity.entity.secretForeignKeys ?? []\n )\n ).map((x) => ua2hex(x))\n const accessControlKeysToHashes = accessControlKeys\n .map((key, index) => {\n return [key, accessControlHashes[index]]\n })\n .sort((a, b) => a[1].localeCompare(b[1]))\n\n const canonicalKey = accessControlKeysToHashes[0][1]\n const keyEquivalences = Object.fromEntries(accessControlKeysToHashes.slice(1).map((hash) => [hash[1], canonicalKey]))\n const encryptedDelegationInfo = await this.makeSecureDelegationEncryptedData(\n exchangeDataInfo,\n delegateId,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds\n )\n const delegation = new SecureDelegation({\n delegator: encryptedDelegationInfo?.explicitDelegator,\n delegate: encryptedDelegationInfo?.explicitDelegate,\n secretIds: encryptedDelegationInfo?.secretIds,\n encryptionKeys: encryptedDelegationInfo?.encryptionKeys,\n owningEntityIds: encryptedDelegationInfo?.owningEntityIds,\n parentDelegations: parentDelegationKey ? [parentDelegationKey] : undefined,\n exchangeDataId: encryptedDelegationInfo?.exchangeDataId,\n encryptedExchangeDataId: encryptedDelegationInfo?.encryptedExchangeDataId,\n permissions: permissions,\n })\n return {\n canonicalDelegationKey: canonicalKey,\n canonicalAccessControlKey: accessControlKeysToHashes[0][0],\n delegation,\n encryptedExchangeDataId: encryptedDelegationInfo?.encryptedExchangeDataId,\n delegationKeyEquivalences: keyEquivalences,\n }\n }\n\n private async makeSecureDelegationEncryptedData(\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[]\n ): Promise<{\n explicitDelegator?: string\n explicitDelegate?: string\n secretIds?: string[]\n encryptionKeys?: string[]\n owningEntityIds?: string[]\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string } // TODO if secure delegation info, check cache before calculating\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const exchangeDataIdInfo =\n delegateId === selfId\n ? this.makeExchangeDataIdInfoForSelf(selfId, exchangeDataInfo.exchangeData)\n : await this.makeExchangeDataIdInfoForDelegate(selfId, delegateId, exchangeDataInfo.exchangeData)\n const encryptedSecretIds = await this.secureDelegationsEncryption.encryptSecretIds(shareSecretIds, exchangeDataInfo.exchangeKey)\n const encryptedEncryptionKeys = await this.secureDelegationsEncryption.encryptEncryptionKeys(shareEncryptionKeys, exchangeDataInfo.exchangeKey)\n const encryptedOwningEntityIds = await this.secureDelegationsEncryption.encryptOwningEntityIds(shareOwningEntityIds, exchangeDataInfo.exchangeKey)\n return {\n ...exchangeDataIdInfo,\n secretIds: encryptedSecretIds,\n encryptionKeys: encryptedEncryptionKeys,\n owningEntityIds: encryptedOwningEntityIds,\n }\n }\n\n private async makeExchangeDataIdInfoForDelegate(\n selfId: string,\n delegateId: string,\n exchangeData: ExchangeData\n ): Promise<{\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string }\n explicitDelegator?: string\n explicitDelegate?: string\n }> {\n const delegateInfo = await this.getDataOwnerInfo(delegateId)\n if (!delegateInfo.requiresAnonymousDelegations && !this.selfNeedsAnonymousDelegations) {\n return {\n explicitDelegator: selfId,\n explicitDelegate: delegateId,\n exchangeDataId: exchangeData.id,\n }\n } else if (delegateInfo.requiresAnonymousDelegations && !this.selfNeedsAnonymousDelegations) {\n return {\n explicitDelegator: selfId,\n encryptedExchangeDataId: await this.secureDelegationsEncryption.encryptExchangeDataId(\n exchangeData.id!,\n Object.fromEntries(this.userKeys.getSelfVerifiedKeys().map((keyInfo) => [keyInfo.fingerprint, keyInfo.pair.publicKey]))\n ),\n }\n } else if (!delegateInfo.requiresAnonymousDelegations && this.selfNeedsAnonymousDelegations) {\n /**\n * Important: this requires that the exchange data signature also validates the authenticity of the public keys included in there.\n */\n const fingerprintsOfVerifiedExchangeData = new Set(Object.keys(exchangeData.exchangeKey))\n const delegateVerifiedKeys: { [fp: string]: CryptoKey } = {}\n for (const keyHex of [...delegateInfo.availablePublicKeysHexWithSha1, ...delegateInfo.availablePublicKeysHexWithSha256]) {\n const currFp = fingerprintV2(keyHex)\n const shaVersion = delegateInfo.availablePublicKeysHexWithSha1.includes(keyHex) ? 'sha-1' : 'sha-256'\n if (fingerprintsOfVerifiedExchangeData.has(currFp)) {\n delegateVerifiedKeys[currFp] = await this.primitives.RSA.importKey('spki', hex2ua(keyHex), ['encrypt'], shaVersion)\n }\n }\n if (!Object.keys(delegateVerifiedKeys).length)\n throw new Error('Illegal state: could not find any verified key for delegate in verified exchange data.')\n return {\n explicitDelegate: delegateId,\n encryptedExchangeDataId: await this.secureDelegationsEncryption.encryptExchangeDataId(exchangeData.id!, delegateVerifiedKeys),\n }\n } else return {}\n }\n\n private makeExchangeDataIdInfoForSelf(\n selfId: string,\n exchangeData: ExchangeData\n ): {\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string }\n explicitDelegator?: string\n explicitDelegate?: string\n } {\n if (this.selfNeedsAnonymousDelegations) {\n return {}\n } else {\n return {\n exchangeDataId: exchangeData.id,\n explicitDelegator: selfId,\n explicitDelegate: selfId,\n }\n }\n }\n\n private async getDataOwnerInfo(dataOwnerId: string) {\n return this.dataOwnerInfoCache.get(dataOwnerId, async () => {\n const dataOwnerWithType = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n return {\n item: {\n requiresAnonymousDelegations: this.cryptoStrategies.dataOwnerRequiresAnonymousDelegation(dataOwnerWithType),\n availablePublicKeysHexWithSha1: Array.from(hexPublicKeysWithSha1Of(dataOwnerWithType.stub)),\n availablePublicKeysHexWithSha256: Array.from(hexPublicKeysWithSha256Of(dataOwnerWithType.stub)),\n },\n }\n })\n }\n\n private getExistingCanonicalKeyAndSecureDelegation(\n entity: EncryptedEntityStub | EncryptedEntity,\n hashes: string[]\n ): { canonicalKey: string; secureDelegation: SecureDelegation } | undefined {\n const securityMetadata = entity.securityMetadata ?? {}\n const canonicalByEquivalences = Array.from(new Set(hashes.flatMap((hash) => securityMetadata.keysEquivalences?.[hash] ?? [])))\n const directRetrievals = hashes.flatMap((hash) => {\n const retrievedMetadata = securityMetadata.secureDelegations?.[hash]\n return retrievedMetadata ? { canonicalKey: hash, secureDelegation: retrievedMetadata } : []\n })\n if (\n directRetrievals.length > 1 ||\n canonicalByEquivalences.length > 1 ||\n (!!canonicalByEquivalences[0] && !!directRetrievals[0]?.canonicalKey && canonicalByEquivalences[0] !== directRetrievals[0]?.canonicalKey)\n )\n throw new Error('Illegal state: multiple secure delegations matching equivalent hashes of entity.')\n const canonicalFromEquivalences = canonicalByEquivalences[0]\n const retrievedFromEquivalences = securityMetadata.secureDelegations?.[canonicalFromEquivalences]\n return (\n directRetrievals[0] ??\n (!!canonicalFromEquivalences && !!retrievedFromEquivalences\n ? { canonicalKey: canonicalFromEquivalences, secureDelegation: retrievedFromEquivalences }\n : undefined)\n )\n }\n}\n"]}
1
+ {"version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,gBAAgB,CAAC,iBAAiB,0CAAG,yBAAyB,CAAC,CAAA;QACjG,OAAO,CACL,MAAA,gBAAgB,CAAC,CAAC,CAAC,mCACnB,CAAC,CAAC,CAAC,yBAAyB,IAAI,CAAC,CAAC,yBAAyB;YACzD,CAAC,CAAC,EAAE,YAAY,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,yBAAyB,EAAE;YAC1F,CAAC,CAAC,SAAS,CAAC,CACf,CAAA;IACH,CAAC;CACF;AAjaD,4DAiaC","sourcesContent":["import { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { fingerprintV2, hexPublicKeysWithSha1Of, hexPublicKeysWithSha256Of } from './utils'\nimport { ExchangeDataManager } from './ExchangeDataManager'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { SecureDelegationsEncryption } from './SecureDelegationsEncryption'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { hex2ua, ua2hex } from '../utils'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { EntitySharedMetadataUpdateRequest } from '../../icc-api/model/requests/EntitySharedMetadataUpdateRequest'\nimport EntryUpdateTypeEnum = EntitySharedMetadataUpdateRequest.EntryUpdateTypeEnum\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { SecurityMetadata } from '../../icc-api/model/SecurityMetadata'\nimport { ExchangeDataMapManager } from './ExchangeDataMapManager'\nimport { ShaVersion } from './RSA'\n\nexport class SecureDelegationsManager {\n constructor(\n private readonly exchangeDataManager: ExchangeDataManager,\n private readonly exchangeDataMapManager: ExchangeDataMapManager,\n private readonly secureDelegationsEncryption: SecureDelegationsEncryption,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n private readonly userKeys: UserEncryptionKeysManager,\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly cryptoStrategies: CryptoStrategies,\n private readonly selfNeedsAnonymousDelegations: boolean\n ) {}\n\n private readonly dataOwnerInfoCache: LruTemporisedAsyncCache<\n string,\n {\n requiresAnonymousDelegations: boolean\n availablePublicKeysHexWithSha1: string[]\n availablePublicKeysHexWithSha256: string[]\n }\n > = new LruTemporisedAsyncCache(100, () => 30 * 60 * 1000)\n\n /**\n * Note: this method does not save the updated entity.\n * @param entity an entity, must already have secret foreign keys initialised.\n * @param entityType the type of the entity\n * @param secretIds the initial secret ids to include and share with the auto-delegations\n * @param owningEntityIds the initial owning entity ids to include and share with the auto-delegations\n * @param encryptionKeys the initial encryption keys to include and share with the auto-delegations\n * @param autoDelegations the data owners which will initially have access to the entity in addition to the current data owner and the access level\n * they will have on the entity.\n * @return the entity with the security metadata initialised for the provided parameters.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T & { secretForeignKeys: string[] },\n entityType: EntityWithDelegationTypeName,\n secretIds: string[],\n owningEntityIds: string[],\n encryptionKeys: string[],\n autoDelegations: { [delegateId: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<T> {\n const entityWithType: EncryptedEntityWithType = { entity, type: entityType }\n const rootDelegationInfo = await this.makeSecureDelegationInfo(\n entityWithType,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n secretIds,\n encryptionKeys,\n owningEntityIds,\n AccessLevelEnum.WRITE,\n undefined\n )\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const otherDelegationsInfo: {\n canonicalDelegationKey: string\n canonicalAccessControlKey: string\n delegation: SecureDelegation\n delegationKeyEquivalences: { [p: string]: string }\n encryptedExchangeDataId: { [fp: string]: string } | undefined\n }[] = []\n for (const [delegateId, permissions] of Object.entries(autoDelegations)) {\n if (delegateId !== selfId) {\n otherDelegationsInfo.push(\n await this.makeSecureDelegationInfo(\n entityWithType,\n delegateId,\n secretIds,\n encryptionKeys,\n owningEntityIds,\n permissions,\n rootDelegationInfo.canonicalDelegationKey\n )\n )\n }\n }\n const secureDelegations = Object.fromEntries(\n [rootDelegationInfo, ...otherDelegationsInfo].map(({ canonicalDelegationKey, delegation }) => [canonicalDelegationKey, delegation])\n )\n const keysEquivalences = {\n ...rootDelegationInfo.delegationKeyEquivalences,\n }\n for (const { delegationKeyEquivalences: otherKeyEquivalences } of otherDelegationsInfo) {\n Object.assign(keysEquivalences, otherKeyEquivalences)\n }\n const newExchangeDataMaps = Object.fromEntries(\n otherDelegationsInfo\n .filter(({ encryptedExchangeDataId }) => !!encryptedExchangeDataId)\n .map(({ canonicalAccessControlKey, encryptedExchangeDataId }) => [canonicalAccessControlKey, encryptedExchangeDataId!])\n )\n await this.exchangeDataMapManager.createExchangeDataMaps(newExchangeDataMaps)\n return {\n ...entity,\n securityMetadata: new SecurityMetadata({ secureDelegations, keysEquivalences }),\n }\n }\n\n /**\n * Make a request for sharing an entity with a delegate or to update existing shared metadata by adding additional secretIds, encryptionKeys or\n * owningEntityIds if there is already some metadata shared between the current data owner and the delegate. In case there is already a delegation\n * for the delegate, and it already contains all the provided metadata, this method returns undefined, since there is no need to make any request to\n * share the provided data.\n * @param entityWithType an entity with type\n * @param delegateId the id of the delegate\n * @param shareSecretIds the secret ids to share\n * @param shareEncryptionKeys the encryption keys to share\n * @param shareOwningEntityIds the owning entity ids to share\n * @param newDelegationPermissions the permissions to grant to the delegate in case a new delegation needs to be created. If this method creates an\n * update request instead of a share request, this parameter is ignored.\n * @return the request to share the entity, or the request to update the shared metadata for the entity, or undefined if there is no need to update\n * the entity to allow the delegate to access the provided data.\n */\n async makeShareOrUpdateRequestParams(\n entityWithType: EncryptedEntityWithType,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newDelegationPermissions: EntityShareRequest.RequestedPermissionInternal\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n const exchangeDataInfo = await this.exchangeDataManager.getOrCreateEncryptionDataTo(\n delegateId,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? [],\n false\n )\n const accessControlHashes = await this.accessControlSecretUtils.secureDelegationKeysFor(\n exchangeDataInfo.accessControlSecret,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? []\n )\n const existingSecureDelegation = this.getExistingCanonicalKeyAndSecureDelegation(entityWithType.entity, accessControlHashes)\n if (existingSecureDelegation) {\n const updateParams = await this.makeUpdateRequestParams(\n existingSecureDelegation.canonicalKey,\n existingSecureDelegation.secureDelegation,\n exchangeDataInfo,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds\n )\n return updateParams ? { update: updateParams } : undefined\n } else {\n const accessControlKeys = (\n await this.accessControlSecretUtils.accessControlKeysFor(\n exchangeDataInfo.accessControlSecret,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? []\n )\n ).map((x) => ua2hex(x))\n return {\n share: await this.makeShareRequestParams(\n exchangeDataInfo,\n accessControlKeys,\n delegateId,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds,\n newDelegationPermissions\n ),\n }\n }\n }\n\n private async makeUpdateRequestParams(\n canonicalKey: string,\n existingDelegation: SecureDelegation,\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[]\n ): Promise<EntitySharedMetadataUpdateRequest | undefined> {\n const existingSecretIds = new Set(await this.secureDelegationsEncryption.decryptSecretIds(existingDelegation, exchangeDataInfo.exchangeKey))\n const existingEncryptionKeys = new Set(\n await this.secureDelegationsEncryption.decryptEncryptionKeys(existingDelegation, exchangeDataInfo.exchangeKey)\n )\n const existingOwningEntityIds = new Set(\n await this.secureDelegationsEncryption.decryptOwningEntityIds(existingDelegation, exchangeDataInfo.exchangeKey)\n )\n const newSecretIds = shareSecretIds.filter((id) => !existingSecretIds.has(id))\n const newEncryptionKeys = shareEncryptionKeys.filter((key) => !existingEncryptionKeys.has(key))\n const newOwningEntityIds = shareOwningEntityIds.filter((id) => !existingOwningEntityIds.has(id))\n if (newSecretIds.length || newEncryptionKeys.length || newOwningEntityIds.length) {\n const encryptedNewSecretIds = await this.secureDelegationsEncryption.encryptSecretIds(newSecretIds, exchangeDataInfo.exchangeKey)\n const encryptedNewEncryptionKeys = await this.secureDelegationsEncryption.encryptEncryptionKeys(newEncryptionKeys, exchangeDataInfo.exchangeKey)\n const encryptedNewOwningEntityIds = await this.secureDelegationsEncryption.encryptOwningEntityIds(\n newOwningEntityIds,\n exchangeDataInfo.exchangeKey\n )\n return new EntitySharedMetadataUpdateRequest({\n metadataAccessControlHash: canonicalKey,\n secretIds: Object.fromEntries(encryptedNewSecretIds.map((id) => [id, EntryUpdateTypeEnum.CREATE])),\n encryptionKeys: Object.fromEntries(encryptedNewEncryptionKeys.map((key) => [key, EntryUpdateTypeEnum.CREATE])),\n owningEntityIds: Object.fromEntries(encryptedNewOwningEntityIds.map((id) => [id, EntryUpdateTypeEnum.CREATE])),\n })\n } else return undefined\n }\n\n private async makeShareRequestParams(\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n accessControlKeys: string[],\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newDelegationPermissions: EntityShareRequest.RequestedPermissionInternal\n ): Promise<EntityShareRequest> {\n return new EntityShareRequest({\n ...(await this.makeSecureDelegationEncryptedData(exchangeDataInfo, delegateId, shareSecretIds, shareEncryptionKeys, shareOwningEntityIds)),\n requestedPermissions: newDelegationPermissions,\n accessControlKeys,\n })\n }\n\n private async makeSecureDelegationInfo(\n entity: EncryptedEntityWithType,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n permissions: AccessLevelEnum,\n parentDelegationKey: string | undefined\n ): Promise<{\n canonicalDelegationKey: string\n canonicalAccessControlKey: string\n delegation: SecureDelegation\n encryptedExchangeDataId: { [fp: string]: string } | undefined\n delegationKeyEquivalences: { [alias: string]: string }\n }> {\n // Be wary of explicit delegator and explicit delegate\n const exchangeDataInfo = await this.exchangeDataManager.getOrCreateEncryptionDataTo(\n delegateId,\n entity.type,\n entity.entity.secretForeignKeys ?? [],\n false\n )\n const accessControlHashes = await this.accessControlSecretUtils.secureDelegationKeysFor(\n exchangeDataInfo.accessControlSecret,\n entity.type,\n entity.entity.secretForeignKeys ?? []\n )\n const accessControlKeys = (\n await this.accessControlSecretUtils.accessControlKeysFor(\n exchangeDataInfo.accessControlSecret,\n entity.type,\n entity.entity.secretForeignKeys ?? []\n )\n ).map((x) => ua2hex(x))\n const accessControlKeysToHashes = accessControlKeys\n .map((key, index) => {\n return [key, accessControlHashes[index]]\n })\n .sort((a, b) => a[1].localeCompare(b[1]))\n\n const canonicalKey = accessControlKeysToHashes[0][1]\n const keyEquivalences = Object.fromEntries(accessControlKeysToHashes.slice(1).map((hash) => [hash[1], canonicalKey]))\n const encryptedDelegationInfo = await this.makeSecureDelegationEncryptedData(\n exchangeDataInfo,\n delegateId,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds\n )\n const delegation = new SecureDelegation({\n delegator: encryptedDelegationInfo?.explicitDelegator,\n delegate: encryptedDelegationInfo?.explicitDelegate,\n secretIds: encryptedDelegationInfo?.secretIds,\n encryptionKeys: encryptedDelegationInfo?.encryptionKeys,\n owningEntityIds: encryptedDelegationInfo?.owningEntityIds,\n parentDelegations: parentDelegationKey ? [parentDelegationKey] : undefined,\n exchangeDataId: encryptedDelegationInfo?.exchangeDataId,\n encryptedExchangeDataId: encryptedDelegationInfo?.encryptedExchangeDataId,\n permissions: permissions,\n })\n return {\n canonicalDelegationKey: canonicalKey,\n canonicalAccessControlKey: accessControlKeysToHashes[0][0],\n delegation,\n encryptedExchangeDataId: encryptedDelegationInfo?.encryptedExchangeDataId,\n delegationKeyEquivalences: keyEquivalences,\n }\n }\n\n private async makeSecureDelegationEncryptedData(\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[]\n ): Promise<{\n explicitDelegator?: string\n explicitDelegate?: string\n secretIds?: string[]\n encryptionKeys?: string[]\n owningEntityIds?: string[]\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string } // TODO if secure delegation info, check cache before calculating\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const exchangeDataIdInfo =\n delegateId === selfId\n ? this.makeExchangeDataIdInfoForSelf(selfId, exchangeDataInfo.exchangeData)\n : await this.makeExchangeDataIdInfoForDelegate(selfId, delegateId, exchangeDataInfo.exchangeData)\n const encryptedSecretIds = await this.secureDelegationsEncryption.encryptSecretIds(shareSecretIds, exchangeDataInfo.exchangeKey)\n const encryptedEncryptionKeys = await this.secureDelegationsEncryption.encryptEncryptionKeys(shareEncryptionKeys, exchangeDataInfo.exchangeKey)\n const encryptedOwningEntityIds = await this.secureDelegationsEncryption.encryptOwningEntityIds(shareOwningEntityIds, exchangeDataInfo.exchangeKey)\n return {\n ...exchangeDataIdInfo,\n secretIds: encryptedSecretIds,\n encryptionKeys: encryptedEncryptionKeys,\n owningEntityIds: encryptedOwningEntityIds,\n }\n }\n\n private async makeExchangeDataIdInfoForDelegate(\n selfId: string,\n delegateId: string,\n exchangeData: ExchangeData\n ): Promise<{\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string }\n explicitDelegator?: string\n explicitDelegate?: string\n }> {\n const delegateInfo = await this.getDataOwnerInfo(delegateId)\n if (!delegateInfo.requiresAnonymousDelegations && !this.selfNeedsAnonymousDelegations) {\n return {\n explicitDelegator: selfId,\n explicitDelegate: delegateId,\n exchangeDataId: exchangeData.id,\n }\n } else if (delegateInfo.requiresAnonymousDelegations && !this.selfNeedsAnonymousDelegations) {\n return {\n explicitDelegator: selfId,\n encryptedExchangeDataId: await this.secureDelegationsEncryption.encryptExchangeDataId(\n exchangeData.id!,\n Object.fromEntries(this.userKeys.getSelfVerifiedKeys().map((keyInfo) => [keyInfo.fingerprint, keyInfo.pair.publicKey]))\n ),\n }\n } else if (!delegateInfo.requiresAnonymousDelegations && this.selfNeedsAnonymousDelegations) {\n /**\n * Important: this requires that the exchange data signature also validates the authenticity of the public keys included in there.\n */\n const fingerprintsOfVerifiedExchangeData = new Set(Object.keys(exchangeData.exchangeKey))\n const delegateVerifiedKeys: { [fp: string]: CryptoKey } = {}\n for (const keyHex of [...delegateInfo.availablePublicKeysHexWithSha1, ...delegateInfo.availablePublicKeysHexWithSha256]) {\n const currFp = fingerprintV2(keyHex)\n const shaVersion = delegateInfo.availablePublicKeysHexWithSha1.includes(keyHex) ? ShaVersion.Sha1 : ShaVersion.Sha256\n if (fingerprintsOfVerifiedExchangeData.has(currFp)) {\n delegateVerifiedKeys[currFp] = await this.primitives.RSA.importKey('spki', hex2ua(keyHex), ['encrypt'], shaVersion)\n }\n }\n if (!Object.keys(delegateVerifiedKeys).length)\n throw new Error('Illegal state: could not find any verified key for delegate in verified exchange data.')\n return {\n explicitDelegate: delegateId,\n encryptedExchangeDataId: await this.secureDelegationsEncryption.encryptExchangeDataId(exchangeData.id!, delegateVerifiedKeys),\n }\n } else return {}\n }\n\n private makeExchangeDataIdInfoForSelf(\n selfId: string,\n exchangeData: ExchangeData\n ): {\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string }\n explicitDelegator?: string\n explicitDelegate?: string\n } {\n if (this.selfNeedsAnonymousDelegations) {\n return {}\n } else {\n return {\n exchangeDataId: exchangeData.id,\n explicitDelegator: selfId,\n explicitDelegate: selfId,\n }\n }\n }\n\n private async getDataOwnerInfo(dataOwnerId: string) {\n return this.dataOwnerInfoCache.get(dataOwnerId, async () => {\n const dataOwnerWithType = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n return {\n item: {\n requiresAnonymousDelegations: this.cryptoStrategies.dataOwnerRequiresAnonymousDelegation(dataOwnerWithType),\n availablePublicKeysHexWithSha1: Array.from(hexPublicKeysWithSha1Of(dataOwnerWithType.stub)),\n availablePublicKeysHexWithSha256: Array.from(hexPublicKeysWithSha256Of(dataOwnerWithType.stub)),\n },\n }\n })\n }\n\n private getExistingCanonicalKeyAndSecureDelegation(\n entity: EncryptedEntityStub | EncryptedEntity,\n hashes: string[]\n ): { canonicalKey: string; secureDelegation: SecureDelegation } | undefined {\n const securityMetadata = entity.securityMetadata ?? {}\n const canonicalByEquivalences = Array.from(new Set(hashes.flatMap((hash) => securityMetadata.keysEquivalences?.[hash] ?? [])))\n const directRetrievals = hashes.flatMap((hash) => {\n const retrievedMetadata = securityMetadata.secureDelegations?.[hash]\n return retrievedMetadata ? { canonicalKey: hash, secureDelegation: retrievedMetadata } : []\n })\n if (\n directRetrievals.length > 1 ||\n canonicalByEquivalences.length > 1 ||\n (!!canonicalByEquivalences[0] && !!directRetrievals[0]?.canonicalKey && canonicalByEquivalences[0] !== directRetrievals[0]?.canonicalKey)\n )\n throw new Error('Illegal state: multiple secure delegations matching equivalent hashes of entity.')\n const canonicalFromEquivalences = canonicalByEquivalences[0]\n const retrievedFromEquivalences = securityMetadata.secureDelegations?.[canonicalFromEquivalences]\n return (\n directRetrievals[0] ??\n (!!canonicalFromEquivalences && !!retrievedFromEquivalences\n ? { canonicalKey: canonicalFromEquivalences, secureDelegation: retrievedFromEquivalences }\n : undefined)\n )\n }\n}\n"]}
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.TransferKeysManager = void 0;
13
+ const RSA_1 = require("./RSA");
13
14
  const utils_1 = require("../utils");
14
15
  const graph_utils_1 = require("../utils/graph-utils");
15
16
  const utils_2 = require("./utils");
@@ -40,8 +41,8 @@ class TransferKeysManager {
40
41
  if (!newEdgesByTarget.length)
41
42
  return;
42
43
  const selfId = self.stub.id;
43
- const fpToPublicKey = (0, utils_2.fingerprintToPublicKeysMapOf)(self.stub, 'sha-1');
44
- const fpToPublicKeyWithSha256 = (0, utils_2.fingerprintToPublicKeysMapOf)(self.stub, 'sha-256');
44
+ const fpToPublicKey = (0, utils_2.fingerprintToPublicKeysMapOf)(self.stub, RSA_1.ShaVersion.Sha1);
45
+ const fpToPublicKeyWithSha256 = (0, utils_2.fingerprintToPublicKeysMapOf)(self.stub, RSA_1.ShaVersion.Sha256);
45
46
  const signatureKeyPair = yield this.userSignatureKeysManager.getOrCreateSignatureKeyPair();
46
47
  const verifiedFps = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint));
47
48
  const allVerifiedSourcesAndTarget = Array.from(new Set(newEdgesByTarget.flatMap((x) =>
@@ -49,7 +50,7 @@ class TransferKeysManager {
49
50
  verifiedFps.has(x.targetFp) ? [x.targetFp, ...x.sources] : x.sources)));
50
51
  const newExchangeKeyPublicKeys = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKey[fp]).filter((key) => !!key);
51
52
  const newExchangeKeyPublicKeysWithSha256 = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKeyWithSha256[fp]).filter((key) => !!key);
52
- const createdExchangeData = yield this.baseExchangeDataManager.createExchangeData(selfId, { [signatureKeyPair.fingerprint]: signatureKeyPair.keyPair.privateKey }, Object.assign(Object.assign({}, (yield (0, utils_2.loadPublicKeys)(this.primitives.RSA, newExchangeKeyPublicKeys, 'sha-1'))), (yield (0, utils_2.loadPublicKeys)(this.primitives.RSA, newExchangeKeyPublicKeysWithSha256, 'sha-256'))));
53
+ const createdExchangeData = yield this.baseExchangeDataManager.createExchangeData(selfId, { [signatureKeyPair.fingerprint]: signatureKeyPair.keyPair.privateKey }, Object.assign(Object.assign({}, (yield (0, utils_2.loadPublicKeys)(this.primitives.RSA, newExchangeKeyPublicKeys, RSA_1.ShaVersion.Sha1))), (yield (0, utils_2.loadPublicKeys)(this.primitives.RSA, newExchangeKeyPublicKeysWithSha256, RSA_1.ShaVersion.Sha256))));
53
54
  let updatedTransferKeys = (_a = self.stub.transferKeys) !== null && _a !== void 0 ? _a : {};
54
55
  for (const newEdges of newEdgesByTarget) {
55
56
  const encryptedTransferKey = yield this.encryptTransferKey(newEdges.target, createdExchangeData.exchangeKey);
@@ -1 +1 @@
1
- {"version":3,"file":"TransferKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/TransferKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAiC;AAEjC,sDAA+E;AAC/E,mCAAgJ;AAOhJ;;;GAGG;AACH,MAAa,mBAAmB;IAC9B,YACmB,UAA4B,EAC5B,uBAAgD,EAChD,YAA8B,EAC9B,qBAAgD,EAChD,wBAAkD,EAClD,YAAgC;QALhC,eAAU,GAAV,UAAU,CAAkB;QAC5B,4BAAuB,GAAvB,uBAAuB,CAAyB;QAChD,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,0BAAqB,GAArB,qBAAqB,CAA2B;QAChD,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,iBAAY,GAAZ,YAAY,CAAoB;IAChD,CAAC;IAEJ;;;;;;OAMG;IACG,kBAAkB,CAAC,IAA6B;;;YACpD,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,+BAA+B,CAAC,IAAI,CAAC,CAAA;YACzE,IAAI,CAAC,gBAAgB,CAAC,MAAM;gBAAE,OAAM;YACpC,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,EAAG,CAAA;YAC5B,MAAM,aAAa,GAAG,IAAA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mBAAmB,CAAC,MAAM,IAAI,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAA;gBACxH,kJAAkJ;gBAClJ,OAAO;gBACP,MAAM,2BAA2B,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE;oBACxE,MAAM,GAAG,GAAG,KAAK,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAA;oBAC9G,IAAI,CAAC,GAAG;wBAAE,MAAM,IAAI,KAAK,CAAC,kFAAkF,CAAC,CAAA;oBAC7G,OAAO,GAAG,CAAA;gBACZ,CAAC,CAAC,CAAA;gBACF,GAAG,CAAC,IAAI,CAAC;oBACP,OAAO,EAAE,2BAA2B;oBACpC,MAAM,EAAE,SAAS;oBACjB,QAAQ,EAAE,WAAW;iBACtB,CAAC,CAAA;aACH;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;CACF;AA5ID,kDA4IC","sourcesContent":["import { KeyPair } from './RSA'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ua2hex } from '../utils'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { reachSetsAcyclic, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { fingerprintToPublicKeysMapOf, fingerprintV1, loadPublicKeys, transferKeysFpGraphOf, fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeDataManager } from './BaseExchangeDataManager'\nimport { UserSignatureKeysManager } from './UserSignatureKeysManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is intended only for internal use and may be changed without notice.\n * Allows to create new transfer keys.\n */\nexport class TransferKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly baseExchangeDataManager: BaseExchangeDataManager,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly userSignatureKeysManager: UserSignatureKeysManager,\n private readonly icureStorage: IcureStorageFacade\n ) {}\n\n /**\n * Analyses the transfer keys graph and creates new transfer keys which allow to improve data accessibility from other devices.\n * For security reasons transfer keys will only be created between keys verified by the user, but this will be done ignoring any existing edges from\n * unverified keys to verified keys.\n * @param self the current data owner.\n * @return the updated data owner.\n */\n async updateTransferKeys(self: CryptoActorStubWithType): Promise<void> {\n const newEdgesByTarget = await this.getNewVerifiedTransferKeysEdges(self)\n if (!newEdgesByTarget.length) return\n const selfId = self.stub.id!\n const fpToPublicKey = fingerprintToPublicKeysMapOf(self.stub, 'sha-1')\n const fpToPublicKeyWithSha256 = fingerprintToPublicKeysMapOf(self.stub, 'sha-256')\n const signatureKeyPair = await this.userSignatureKeysManager.getOrCreateSignatureKeyPair()\n const verifiedFps = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n const allVerifiedSourcesAndTarget = Array.from(\n new Set(\n newEdgesByTarget.flatMap((x) =>\n // Sources are guaranteed to be verified, but target may not be\n verifiedFps.has(x.targetFp) ? [x.targetFp, ...x.sources] : x.sources\n )\n )\n )\n const newExchangeKeyPublicKeys = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKey[fp]).filter((key) => !!key)\n const newExchangeKeyPublicKeysWithSha256 = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKeyWithSha256[fp]).filter((key) => !!key)\n const createdExchangeData = await this.baseExchangeDataManager.createExchangeData(\n selfId,\n { [signatureKeyPair.fingerprint]: signatureKeyPair.keyPair.privateKey },\n {\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeys, 'sha-1')),\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeysWithSha256, 'sha-256')),\n }\n )\n let updatedTransferKeys = self.stub.transferKeys ?? {}\n for (const newEdges of newEdgesByTarget) {\n const encryptedTransferKey = await this.encryptTransferKey(newEdges.target, createdExchangeData.exchangeKey)\n updatedTransferKeys = newEdges.sources.reduce((acc, candidateFp) => {\n const existingKeys = { ...(acc[candidateFp] ?? {}) }\n existingKeys[newEdges.targetFp] = encryptedTransferKey\n acc[candidateFp] = existingKeys\n return acc\n }, updatedTransferKeys)\n }\n await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...self.stub,\n transferKeys: updatedTransferKeys,\n },\n type: self.type,\n })\n }\n\n // encrypts a transfer key in pkcs8 format using an exchange key, returns the hex representation\n private async encryptTransferKey(transferKey: KeyPair<CryptoKey>, exchangeKey: CryptoKey): Promise<string> {\n const exportedKey = await this.primitives.RSA.exportKey(transferKey.privateKey, 'pkcs8')\n return ua2hex(await this.primitives.AES.encrypt(exchangeKey, exportedKey))\n }\n\n // all public keys would go to the stored keys -> no need for specifying the key.\n // Result only includes the acyclic label, not the full group\n private transferKeysCandidatesFp(keyToFp: string, graph: StronglyConnectedGraph): string[] {\n return Object.entries(reachSetsAcyclic(graph.acyclicGraph))\n .filter(([from, reachable]) => from != keyToFp && !reachable.has(keyToFp))\n .map((x) => x[0])\n }\n\n private async transferTargetKeys(\n keyManager: UserEncryptionKeysManager,\n graph: StronglyConnectedGraph\n ): Promise<{ fingerprint: string; pair: KeyPair<CryptoKey> }[]> {\n const availableGroups = new Set(Object.keys(keyManager.getDecryptionKeys()).map((x) => graph.originalLabelToAcyclicLabel[x] ?? x))\n const groupsReachableFromAvailable = new Set(\n Object.entries(graph.acyclicGraph).flatMap(([source, reachables]) => (availableGroups.has(source) ? Array.from(reachables) : []))\n )\n const targetCandidates = Array.from(availableGroups).filter((x) => !groupsReachableFromAvailable.has(x))\n const verifiedFps = new Set(keyManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n return targetCandidates.map((candidateFp) => {\n const candidateGroup = graph.acyclicLabelToGroup[candidateFp] ?? [candidateFp] // May not be part of transfer keys graph yet\n const bestCandidateOfGroup = candidateGroup.find((x) => verifiedFps.has(x)) ?? candidateFp\n return { fingerprint: bestCandidateOfGroup, pair: keyManager.getKeyPairForFingerprint(bestCandidateOfGroup)!.pair }\n })\n }\n\n // Decides the best edges considering the verified public keys.\n private async getNewVerifiedTransferKeysEdges(self: CryptoActorStubWithType): Promise<\n {\n sources: string[]\n target: KeyPair<CryptoKey>\n targetFp: string\n }[]\n > {\n const verifiedKeysFpSet = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(self.stub.id!)).forEach(([key, verified]) => {\n if (verified) verifiedKeysFpSet.add(fingerprintV1(key))\n })\n if (verifiedKeysFpSet.size == 0) return []\n const graph = transferKeysFpGraphOf(self.stub)\n // 1. Choose keys available in this device which should be reachable from all other verified keys\n const targetKeys = await this.transferTargetKeys(this.encryptionKeysManager, graph)\n const res = []\n for (const { fingerprint: targetKeyFp, pair: targetKey } of targetKeys) {\n // 2. Find groups which can't reach the existing target keys\n const candidatesFp = this.transferKeysCandidatesFp(targetKeyFp, graph)\n // 3. Keep only groups which contain at least a verified candidate\n const verifiedGroupCandidates = candidatesFp.filter((candidate) =>\n graph.acyclicLabelToGroup[candidate].some((candidateGroupMember) => verifiedKeysFpSet.has(candidateGroupMember))\n )\n const verifiedCandidatesSet = new Set(verifiedGroupCandidates)\n if (verifiedCandidatesSet.size == 0) continue\n // 4. Drop all candidates which can already reach another candidate group: it is sufficient to create a transfer key from that group.\n const reachSets = reachSetsAcyclic(graph.acyclicGraph)\n const optimizedCandidates = verifiedGroupCandidates.filter((candidate) =>\n Array.from(reachSets[candidate]).every((reachableNode) => !verifiedCandidatesSet.has(reachableNode))\n )\n if (optimizedCandidates.length == 0) throw new Error('Check failed: at least one candidate should survive optimization')\n // 5. Transfer keys could also be faked: to make sure we are not giving access to unauthorised people we remap the candidates to a verified public\n // keys\n const verifiedOptimizedCandidates = optimizedCandidates.map((candidate) => {\n const res = graph.acyclicLabelToGroup[candidate].find((groupMemberFp) => verifiedKeysFpSet.has(groupMemberFp))\n if (!res) throw new Error('Check failed: optimized candidates groups should have at least a verified member')\n return res\n })\n res.push({\n sources: verifiedOptimizedCandidates,\n target: targetKey,\n targetFp: targetKeyFp,\n })\n }\n return res\n }\n}\n"]}
1
+ {"version":3,"file":"TransferKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/TransferKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,+BAA2C;AAE3C,oCAAiC;AAEjC,sDAA+E;AAC/E,mCAAgJ;AAOhJ;;;GAGG;AACH,MAAa,mBAAmB;IAC9B,YACmB,UAA4B,EAC5B,uBAAgD,EAChD,YAA8B,EAC9B,qBAAgD,EAChD,wBAAkD,EAClD,YAAgC;QALhC,eAAU,GAAV,UAAU,CAAkB;QAC5B,4BAAuB,GAAvB,uBAAuB,CAAyB;QAChD,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,0BAAqB,GAArB,qBAAqB,CAA2B;QAChD,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,iBAAY,GAAZ,YAAY,CAAoB;IAChD,CAAC;IAEJ;;;;;;OAMG;IACG,kBAAkB,CAAC,IAA6B;;;YACpD,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,+BAA+B,CAAC,IAAI,CAAC,CAAA;YACzE,IAAI,CAAC,gBAAgB,CAAC,MAAM;gBAAE,OAAM;YACpC,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,EAAG,CAAA;YAC5B,MAAM,aAAa,GAAG,IAAA,oCAA4B,EAAC,IAAI,CAAC,IAAI,EAAE,gBAAU,CAAC,IAAI,CAAC,CAAA;YAC9E,MAAM,uBAAuB,GAAG,IAAA,oCAA4B,EAAC,IAAI,CAAC,IAAI,EAAE,gBAAU,CAAC,MAAM,CAAC,CAAA;YAC1F,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,wBAAwB,CA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S,EAAE,EAAE;oBACxE,MAAM,GAAG,GAAG,KAAK,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAA;oBAC9G,IAAI,CAAC,GAAG;wBAAE,MAAM,IAAI,KAAK,CAAC,kFAAkF,CAAC,CAAA;oBAC7G,OAAO,GAAG,CAAA;gBACZ,CAAC,CAAC,CAAA;gBACF,GAAG,CAAC,IAAI,CAAC;oBACP,OAAO,EAAE,2BAA2B;oBACpC,MAAM,EAAE,SAAS;oBACjB,QAAQ,EAAE,WAAW;iBACtB,CAAC,CAAA;aACH;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;CACF;AA5ID,kDA4IC","sourcesContent":["import { KeyPair, ShaVersion } from './RSA'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ua2hex } from '../utils'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { reachSetsAcyclic, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { fingerprintToPublicKeysMapOf, fingerprintV1, loadPublicKeys, transferKeysFpGraphOf, fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeDataManager } from './BaseExchangeDataManager'\nimport { UserSignatureKeysManager } from './UserSignatureKeysManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is intended only for internal use and may be changed without notice.\n * Allows to create new transfer keys.\n */\nexport class TransferKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly baseExchangeDataManager: BaseExchangeDataManager,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly userSignatureKeysManager: UserSignatureKeysManager,\n private readonly icureStorage: IcureStorageFacade\n ) {}\n\n /**\n * Analyses the transfer keys graph and creates new transfer keys which allow to improve data accessibility from other devices.\n * For security reasons transfer keys will only be created between keys verified by the user, but this will be done ignoring any existing edges from\n * unverified keys to verified keys.\n * @param self the current data owner.\n * @return the updated data owner.\n */\n async updateTransferKeys(self: CryptoActorStubWithType): Promise<void> {\n const newEdgesByTarget = await this.getNewVerifiedTransferKeysEdges(self)\n if (!newEdgesByTarget.length) return\n const selfId = self.stub.id!\n const fpToPublicKey = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha1)\n const fpToPublicKeyWithSha256 = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha256)\n const signatureKeyPair = await this.userSignatureKeysManager.getOrCreateSignatureKeyPair()\n const verifiedFps = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n const allVerifiedSourcesAndTarget = Array.from(\n new Set(\n newEdgesByTarget.flatMap((x) =>\n // Sources are guaranteed to be verified, but target may not be\n verifiedFps.has(x.targetFp) ? [x.targetFp, ...x.sources] : x.sources\n )\n )\n )\n const newExchangeKeyPublicKeys = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKey[fp]).filter((key) => !!key)\n const newExchangeKeyPublicKeysWithSha256 = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKeyWithSha256[fp]).filter((key) => !!key)\n const createdExchangeData = await this.baseExchangeDataManager.createExchangeData(\n selfId,\n { [signatureKeyPair.fingerprint]: signatureKeyPair.keyPair.privateKey },\n {\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeys, ShaVersion.Sha1)),\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeysWithSha256, ShaVersion.Sha256)),\n }\n )\n let updatedTransferKeys = self.stub.transferKeys ?? {}\n for (const newEdges of newEdgesByTarget) {\n const encryptedTransferKey = await this.encryptTransferKey(newEdges.target, createdExchangeData.exchangeKey)\n updatedTransferKeys = newEdges.sources.reduce((acc, candidateFp) => {\n const existingKeys = { ...(acc[candidateFp] ?? {}) }\n existingKeys[newEdges.targetFp] = encryptedTransferKey\n acc[candidateFp] = existingKeys\n return acc\n }, updatedTransferKeys)\n }\n await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...self.stub,\n transferKeys: updatedTransferKeys,\n },\n type: self.type,\n })\n }\n\n // encrypts a transfer key in pkcs8 format using an exchange key, returns the hex representation\n private async encryptTransferKey(transferKey: KeyPair<CryptoKey>, exchangeKey: CryptoKey): Promise<string> {\n const exportedKey = await this.primitives.RSA.exportKey(transferKey.privateKey, 'pkcs8')\n return ua2hex(await this.primitives.AES.encrypt(exchangeKey, exportedKey))\n }\n\n // all public keys would go to the stored keys -> no need for specifying the key.\n // Result only includes the acyclic label, not the full group\n private transferKeysCandidatesFp(keyToFp: string, graph: StronglyConnectedGraph): string[] {\n return Object.entries(reachSetsAcyclic(graph.acyclicGraph))\n .filter(([from, reachable]) => from != keyToFp && !reachable.has(keyToFp))\n .map((x) => x[0])\n }\n\n private async transferTargetKeys(\n keyManager: UserEncryptionKeysManager,\n graph: StronglyConnectedGraph\n ): Promise<{ fingerprint: string; pair: KeyPair<CryptoKey> }[]> {\n const availableGroups = new Set(Object.keys(keyManager.getDecryptionKeys()).map((x) => graph.originalLabelToAcyclicLabel[x] ?? x))\n const groupsReachableFromAvailable = new Set(\n Object.entries(graph.acyclicGraph).flatMap(([source, reachables]) => (availableGroups.has(source) ? Array.from(reachables) : []))\n )\n const targetCandidates = Array.from(availableGroups).filter((x) => !groupsReachableFromAvailable.has(x))\n const verifiedFps = new Set(keyManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n return targetCandidates.map((candidateFp) => {\n const candidateGroup = graph.acyclicLabelToGroup[candidateFp] ?? [candidateFp] // May not be part of transfer keys graph yet\n const bestCandidateOfGroup = candidateGroup.find((x) => verifiedFps.has(x)) ?? candidateFp\n return { fingerprint: bestCandidateOfGroup, pair: keyManager.getKeyPairForFingerprint(bestCandidateOfGroup)!.pair }\n })\n }\n\n // Decides the best edges considering the verified public keys.\n private async getNewVerifiedTransferKeysEdges(self: CryptoActorStubWithType): Promise<\n {\n sources: string[]\n target: KeyPair<CryptoKey>\n targetFp: string\n }[]\n > {\n const verifiedKeysFpSet = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(self.stub.id!)).forEach(([key, verified]) => {\n if (verified) verifiedKeysFpSet.add(fingerprintV1(key))\n })\n if (verifiedKeysFpSet.size == 0) return []\n const graph = transferKeysFpGraphOf(self.stub)\n // 1. Choose keys available in this device which should be reachable from all other verified keys\n const targetKeys = await this.transferTargetKeys(this.encryptionKeysManager, graph)\n const res = []\n for (const { fingerprint: targetKeyFp, pair: targetKey } of targetKeys) {\n // 2. Find groups which can't reach the existing target keys\n const candidatesFp = this.transferKeysCandidatesFp(targetKeyFp, graph)\n // 3. Keep only groups which contain at least a verified candidate\n const verifiedGroupCandidates = candidatesFp.filter((candidate) =>\n graph.acyclicLabelToGroup[candidate].some((candidateGroupMember) => verifiedKeysFpSet.has(candidateGroupMember))\n )\n const verifiedCandidatesSet = new Set(verifiedGroupCandidates)\n if (verifiedCandidatesSet.size == 0) continue\n // 4. Drop all candidates which can already reach another candidate group: it is sufficient to create a transfer key from that group.\n const reachSets = reachSetsAcyclic(graph.acyclicGraph)\n const optimizedCandidates = verifiedGroupCandidates.filter((candidate) =>\n Array.from(reachSets[candidate]).every((reachableNode) => !verifiedCandidatesSet.has(reachableNode))\n )\n if (optimizedCandidates.length == 0) throw new Error('Check failed: at least one candidate should survive optimization')\n // 5. Transfer keys could also be faked: to make sure we are not giving access to unauthorised people we remap the candidates to a verified public\n // keys\n const verifiedOptimizedCandidates = optimizedCandidates.map((candidate) => {\n const res = graph.acyclicLabelToGroup[candidate].find((groupMemberFp) => verifiedKeysFpSet.has(groupMemberFp))\n if (!res) throw new Error('Check failed: optimized candidates groups should have at least a verified member')\n return res\n })\n res.push({\n sources: verifiedOptimizedCandidates,\n target: targetKey,\n targetFp: targetKeyFp,\n })\n }\n return res\n }\n}\n"]}
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.UserEncryptionKeysManager = void 0;
13
+ const RSA_1 = require("./RSA");
13
14
  const utils_1 = require("../utils");
14
15
  const utils_2 = require("./utils");
15
16
  const CryptoActorStub_1 = require("../../icc-api/model/CryptoActorStub");
@@ -264,7 +265,7 @@ class UserEncryptionKeysManager {
264
265
  createAndSaveNewKeyPair(importedKeyPair, selfDataOwner) {
265
266
  var _a;
266
267
  return __awaiter(this, void 0, void 0, function* () {
267
- const keyPair = importedKeyPair !== null && importedKeyPair !== void 0 ? importedKeyPair : (yield this.primitives.RSA.generateKeyPair('sha-256'));
268
+ const keyPair = importedKeyPair !== null && importedKeyPair !== void 0 ? importedKeyPair : (yield this.primitives.RSA.generateKeyPair(RSA_1.ShaVersion.Sha256));
268
269
  const publicKeyHex = (0, utils_1.ua2hex)(yield this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'));
269
270
  const jwKey = yield this.primitives.RSA.exportKey(keyPair.publicKey, 'jwk');
270
271
  if (jwKey.alg !== 'RSA-OAEP-256') {
@@ -1 +1 @@
1
- {"version":3,"file":"UserEncryptionKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/UserEncryptionKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAiC;AAEjC,mCAAqE;AAKrE,yEAA8F;AAiB9F,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAAC,CAAC,MAAM,CACN,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAG,CAAC,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE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AAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AApZD,8DAoZC","sourcesContent":["import { DataOwner, DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair, ShaVersion } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { fingerprintToPublicKeysMapOf, fingerprintV1 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { BaseExchangeKeysManager } from './BaseExchangeKeysManager'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class UserEncryptionKeysManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean,\n private readonly keypairRecoverer: KeyPairRecoverer\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives, this.keypairRecoverer),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey?.slice(-32)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwnerOrStub): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner),\n ]).filter((key) => {\n const fp = fingerprintV1(key)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = (await this.dataOwnerApi.getCurrentDataOwnerHierarchy()).map(({ dataOwner, type }) => {\n if (dataOwner.publicKey == '') {\n if (Object.entries(dataOwner.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${dataOwner.id} has \"\" as public key but has non-empty hcPartyKeys`)\n delete dataOwner.publicKey\n }\n return {\n dataOwner,\n type,\n } as DataOwnerWithType\n })\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {\n const availableKeys = await this.loadAndRecoverKeysFor(dowt)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = new Set([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dowt.dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dowt.dataOwner),\n ])\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(key.slice(-32)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(fingerprintV1(x) in verifiedKeysMap) && !(availableKeys?.[fingerprintV1(x)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (const keyData of keysData) {\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp],\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(keyData.dowt, this.plainKeysByFingerprint(keysWithExternallyRecovered))\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair('sha-256'))\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const jwKey = await this.primitives.RSA.exportKey(keyPair.publicKey, 'jwk')\n if (jwKey.alg !== 'RSA-OAEP-256') {\n throw new Error('Only keys generated with SHA-256 are currently supported')\n }\n const publicKeyFingerprint = fingerprintV1(publicKeyHex)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const updatedSelf = await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...CryptoActorStub.fromDataOwner(selfDataOwner.dataOwner),\n publicKeysForOaepWithSha256: [...(selfDataOwner.dataOwner.publicKeysForOaepWithSha256 ?? []), publicKeyHex],\n },\n type: selfDataOwner.type,\n })\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: { [key: string]: string[] }\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprintsWithVersion = Object.entries(pubKeysFingerprints).flatMap(([shaVersion, fps]) => {\n return fps.map((fp) => [shaVersion, fp] as [ShaVersion, string])\n })\n return await pubKeysFingerprintsWithVersion.reduce(async (acc, [shaVersion, currentFingerprint]) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (!!storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair(\n 'jwk',\n storedKeypair.pair.privateKey,\n 'jwk',\n storedKeypair.pair.publicKey,\n shaVersion\n )\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(dataOwner: DataOwnerWithType): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprints = {\n 'sha-1': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n 'sha-256': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n }\n const loadedKeys =\n pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (\n loadedKeysFingerprints.length !== pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length &&\n loadedKeysFingerprints.length > 0\n ) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint(loadedKeys))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [fingerprintV1(k), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}
1
+ {"version":3,"file":"UserEncryptionKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/UserEncryptionKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+BAA2C;AAC3C,oCAAiC;AAEjC,mCAAuC;AAKvC,yEAA8F;AAgB9F,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAAC,CAAC,MAAM,CACN,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAG,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AQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AApZD,8DAoZC","sourcesContent":["import { DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair, ShaVersion } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { fingerprintV1 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class UserEncryptionKeysManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean,\n private readonly keypairRecoverer: KeyPairRecoverer\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives, this.keypairRecoverer),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey?.slice(-32)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwnerOrStub): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner),\n ]).filter((key) => {\n const fp = fingerprintV1(key)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = (await this.dataOwnerApi.getCurrentDataOwnerHierarchy()).map(({ dataOwner, type }) => {\n if (dataOwner.publicKey == '') {\n if (Object.entries(dataOwner.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${dataOwner.id} has \"\" as public key but has non-empty hcPartyKeys`)\n delete dataOwner.publicKey\n }\n return {\n dataOwner,\n type,\n } as DataOwnerWithType\n })\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {\n const availableKeys = await this.loadAndRecoverKeysFor(dowt)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = new Set([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dowt.dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dowt.dataOwner),\n ])\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(key.slice(-32)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(fingerprintV1(x) in verifiedKeysMap) && !(availableKeys?.[fingerprintV1(x)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (const keyData of keysData) {\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp],\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(keyData.dowt, this.plainKeysByFingerprint(keysWithExternallyRecovered))\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair(ShaVersion.Sha256))\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const jwKey = await this.primitives.RSA.exportKey(keyPair.publicKey, 'jwk')\n if (jwKey.alg !== 'RSA-OAEP-256') {\n throw new Error('Only keys generated with SHA-256 are currently supported')\n }\n const publicKeyFingerprint = fingerprintV1(publicKeyHex)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const updatedSelf = await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...CryptoActorStub.fromDataOwner(selfDataOwner.dataOwner),\n publicKeysForOaepWithSha256: [...(selfDataOwner.dataOwner.publicKeysForOaepWithSha256 ?? []), publicKeyHex],\n },\n type: selfDataOwner.type,\n })\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: { [key: string]: string[] }\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprintsWithVersion = Object.entries(pubKeysFingerprints).flatMap(([shaVersion, fps]) => {\n return fps.map((fp) => [shaVersion, fp] as [ShaVersion, string])\n })\n return await pubKeysFingerprintsWithVersion.reduce(async (acc, [shaVersion, currentFingerprint]) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (!!storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair(\n 'jwk',\n storedKeypair.pair.privateKey,\n 'jwk',\n storedKeypair.pair.publicKey,\n shaVersion\n )\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(dataOwner: DataOwnerWithType): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprints = {\n 'sha-1': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n 'sha-256': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n }\n const loadedKeys =\n pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (\n loadedKeysFingerprints.length !== pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length &&\n loadedKeysFingerprints.length > 0\n ) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint(loadedKeys))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [fingerprintV1(k), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}