@icure/api 8.2.3 → 8.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/icc-api/api/IccAuthApi.js +1 -1
  2. package/icc-api/api/IccAuthApi.js.map +1 -1
  3. package/icc-api/api/IccDocumentApi.js.map +1 -1
  4. package/icc-api/api/IccFormApi.js.map +1 -1
  5. package/icc-api/api/IccReceiptApi.js.map +1 -1
  6. package/icc-api/api/IccRestApiPath.js +1 -2
  7. package/icc-api/api/IccRestApiPath.js.map +1 -1
  8. package/icc-api/api/XHR.js +17 -8
  9. package/icc-api/api/XHR.js.map +1 -1
  10. package/icc-api/model/Address.js +1 -1
  11. package/icc-api/model/Address.js.map +1 -1
  12. package/icc-api/model/Amp.js +1 -1
  13. package/icc-api/model/Amp.js.map +1 -1
  14. package/icc-api/model/AmpComponent.js +1 -1
  15. package/icc-api/model/AmpComponent.js.map +1 -1
  16. package/icc-api/model/Ampp.js +1 -1
  17. package/icc-api/model/Ampp.js.map +1 -1
  18. package/icc-api/model/AmppComponent.js +1 -1
  19. package/icc-api/model/AmppComponent.js.map +1 -1
  20. package/icc-api/model/CareTeamMember.js +1 -1
  21. package/icc-api/model/CareTeamMember.js.map +1 -1
  22. package/icc-api/model/CareTeamMembership.js +1 -1
  23. package/icc-api/model/CareTeamMembership.js.map +1 -1
  24. package/icc-api/model/Code.js +1 -1
  25. package/icc-api/model/Code.js.map +1 -1
  26. package/icc-api/model/Contact.js.map +1 -1
  27. package/icc-api/model/Content.js.map +1 -1
  28. package/icc-api/model/DataOwnerTypeEnum.js +1 -1
  29. package/icc-api/model/DataOwnerTypeEnum.js.map +1 -1
  30. package/icc-api/model/DataOwnerWithType.js +1 -1
  31. package/icc-api/model/DataOwnerWithType.js.map +1 -1
  32. package/icc-api/model/DatabaseSynchronization.js +1 -1
  33. package/icc-api/model/DatabaseSynchronization.js.map +1 -1
  34. package/icc-api/model/Dmpp.js +1 -1
  35. package/icc-api/model/Dmpp.js.map +1 -1
  36. package/icc-api/model/Document.js +1 -1
  37. package/icc-api/model/Document.js.map +1 -1
  38. package/icc-api/model/DocumentTemplate.d.ts +1 -1
  39. package/icc-api/model/DocumentTemplate.js +1 -1
  40. package/icc-api/model/DocumentTemplate.js.map +1 -1
  41. package/icc-api/model/Editor.js +1 -1
  42. package/icc-api/model/Editor.js.map +1 -1
  43. package/icc-api/model/EfactInvoice.js +1 -1
  44. package/icc-api/model/EfactInvoice.js.map +1 -1
  45. package/icc-api/model/EmailOrSmsMessage.js +1 -1
  46. package/icc-api/model/EmailOrSmsMessage.js.map +1 -1
  47. package/icc-api/model/FlatRateTarification.js +1 -1
  48. package/icc-api/model/FlatRateTarification.js.map +1 -1
  49. package/icc-api/model/Formula.js +1 -1
  50. package/icc-api/model/Formula.js.map +1 -1
  51. package/icc-api/model/FrontEndMigration.js +1 -1
  52. package/icc-api/model/FrontEndMigration.js.map +1 -1
  53. package/icc-api/model/HealthElement.js +1 -1
  54. package/icc-api/model/HealthElement.js.map +1 -1
  55. package/icc-api/model/HealthcareParty.js +1 -1
  56. package/icc-api/model/HealthcareParty.js.map +1 -1
  57. package/icc-api/model/HealthcarePartyHistoryStatus.js +1 -1
  58. package/icc-api/model/HealthcarePartyHistoryStatus.js.map +1 -1
  59. package/icc-api/model/Ingredient.js +1 -1
  60. package/icc-api/model/Ingredient.js.map +1 -1
  61. package/icc-api/model/Invoice.js +1 -1
  62. package/icc-api/model/Invoice.js.map +1 -1
  63. package/icc-api/model/InvoiceItem.js +1 -1
  64. package/icc-api/model/InvoiceItem.js.map +1 -1
  65. package/icc-api/model/InvoicingCode.js +1 -1
  66. package/icc-api/model/InvoicingCode.js.map +1 -1
  67. package/icc-api/model/MaintenanceTask.js +1 -1
  68. package/icc-api/model/MaintenanceTask.js.map +1 -1
  69. package/icc-api/model/Measure.js.map +1 -1
  70. package/icc-api/model/MedicalHouseContract.js +1 -1
  71. package/icc-api/model/MedicalHouseContract.js.map +1 -1
  72. package/icc-api/model/ModelHelper.js +9 -10
  73. package/icc-api/model/ModelHelper.js.map +1 -1
  74. package/icc-api/model/Partnership.js +1 -1
  75. package/icc-api/model/Partnership.js.map +1 -1
  76. package/icc-api/model/Patient.js +1 -1
  77. package/icc-api/model/Patient.js.map +1 -1
  78. package/icc-api/model/PatientByHcPartyGenderEducationProfession.js +1 -1
  79. package/icc-api/model/PatientByHcPartyGenderEducationProfession.js.map +1 -1
  80. package/icc-api/model/PatientHealthCareParty.js +1 -1
  81. package/icc-api/model/PatientHealthCareParty.js.map +1 -1
  82. package/icc-api/model/Payment.js +1 -1
  83. package/icc-api/model/Payment.js.map +1 -1
  84. package/icc-api/model/PermissionCriterion.js +1 -1
  85. package/icc-api/model/PermissionCriterion.js.map +1 -1
  86. package/icc-api/model/PermissionItem.js +1 -1
  87. package/icc-api/model/PermissionItem.js.map +1 -1
  88. package/icc-api/model/PersonName.js +1 -1
  89. package/icc-api/model/PersonName.js.map +1 -1
  90. package/icc-api/model/PropertyTypeStub.js +1 -1
  91. package/icc-api/model/PropertyTypeStub.js.map +1 -1
  92. package/icc-api/model/Reimbursement.js +1 -1
  93. package/icc-api/model/Reimbursement.js.map +1 -1
  94. package/icc-api/model/RoleSourceEnum.js +1 -1
  95. package/icc-api/model/RoleSourceEnum.js.map +1 -1
  96. package/icc-api/model/SecureDelegation.js +1 -1
  97. package/icc-api/model/SecureDelegation.js.map +1 -1
  98. package/icc-api/model/Service.js.map +1 -1
  99. package/icc-api/model/StandardSubstance.js +1 -1
  100. package/icc-api/model/StandardSubstance.js.map +1 -1
  101. package/icc-api/model/SumehrValidity.js +1 -1
  102. package/icc-api/model/SumehrValidity.js.map +1 -1
  103. package/icc-api/model/Tarification.js +1 -1
  104. package/icc-api/model/Tarification.js.map +1 -1
  105. package/icc-api/model/Telecom.js +1 -1
  106. package/icc-api/model/Telecom.js.map +1 -1
  107. package/icc-api/model/Topic.js +1 -1
  108. package/icc-api/model/Topic.js.map +1 -1
  109. package/icc-api/model/TypedValueObject.js +1 -1
  110. package/icc-api/model/TypedValueObject.js.map +1 -1
  111. package/icc-api/model/User.js +1 -1
  112. package/icc-api/model/User.js.map +1 -1
  113. package/icc-api/model/UserTypeEnum.js +1 -1
  114. package/icc-api/model/UserTypeEnum.js.map +1 -1
  115. package/icc-api/model/VirtualIngredient.js +1 -1
  116. package/icc-api/model/VirtualIngredient.js.map +1 -1
  117. package/icc-api/model/internal/RecoveryData.js +1 -1
  118. package/icc-api/model/internal/RecoveryData.js.map +1 -1
  119. package/icc-api/model/requests/EntityBulkShareResult.js.map +1 -1
  120. package/icc-api/model/requests/EntityShareOrMetadataUpdateRequest.js.map +1 -1
  121. package/icc-api/model/requests/EntityShareRequest.js +1 -1
  122. package/icc-api/model/requests/EntityShareRequest.js.map +1 -1
  123. package/icc-api/model/requests/EntitySharedMetadataUpdateRequest.js +1 -1
  124. package/icc-api/model/requests/EntitySharedMetadataUpdateRequest.js.map +1 -1
  125. package/icc-x-api/auth/AuthenticationProvider.js.map +1 -1
  126. package/icc-x-api/auth/BasicAuthService.js.map +1 -1
  127. package/icc-x-api/auth/EnsembleAuthService.js.map +1 -1
  128. package/icc-x-api/auth/JwtAuthService.js.map +1 -1
  129. package/icc-x-api/auth/JwtBridgedAuthService.d.ts +1 -1
  130. package/icc-x-api/auth/JwtBridgedAuthService.js +1 -1
  131. package/icc-x-api/auth/JwtBridgedAuthService.js.map +1 -1
  132. package/icc-x-api/auth/JwtUtils.js +3 -4
  133. package/icc-x-api/auth/JwtUtils.js.map +1 -1
  134. package/icc-x-api/auth/NoAuthService.js.map +1 -1
  135. package/icc-x-api/auth/SmartAuthProvider.d.ts +1 -1
  136. package/icc-x-api/auth/SmartAuthProvider.js +1 -1
  137. package/icc-x-api/auth/SmartAuthProvider.js.map +1 -1
  138. package/icc-x-api/crypto/AES.js.map +1 -1
  139. package/icc-x-api/crypto/AccessControlKeysHeadersProvider.js.map +1 -1
  140. package/icc-x-api/crypto/AccessControlSecretUtils.js.map +1 -1
  141. package/icc-x-api/crypto/BaseExchangeDataManager.js +10 -10
  142. package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -1
  143. package/icc-x-api/crypto/BaseExchangeKeysManager.js +4 -4
  144. package/icc-x-api/crypto/BaseExchangeKeysManager.js.map +1 -1
  145. package/icc-x-api/crypto/CryptoStrategies.d.ts +5 -7
  146. package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
  147. package/icc-x-api/crypto/DelegationsDeAnonymization.js +1 -1
  148. package/icc-x-api/crypto/DelegationsDeAnonymization.js.map +1 -1
  149. package/icc-x-api/crypto/ExchangeDataManager.js +7 -8
  150. package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -1
  151. package/icc-x-api/crypto/ExchangeDataMapManager.js.map +1 -1
  152. package/icc-x-api/crypto/ExchangeKeysManager.js +1 -1
  153. package/icc-x-api/crypto/ExchangeKeysManager.js.map +1 -1
  154. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +11 -10
  155. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
  156. package/icc-x-api/crypto/HMACUtils.js.map +1 -1
  157. package/icc-x-api/crypto/KeyRecovery.js +5 -5
  158. package/icc-x-api/crypto/KeyRecovery.js.map +1 -1
  159. package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js +3 -3
  160. package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js.map +1 -1
  161. package/icc-x-api/crypto/RSA.js +4 -4
  162. package/icc-x-api/crypto/RSA.js.map +1 -1
  163. package/icc-x-api/crypto/RecoveryDataEncryption.js +1 -1
  164. package/icc-x-api/crypto/RecoveryDataEncryption.js.map +1 -1
  165. package/icc-x-api/crypto/SecretIdUseOption.js +1 -1
  166. package/icc-x-api/crypto/SecretIdUseOption.js.map +1 -1
  167. package/icc-x-api/crypto/SecureDelegationsEncryption.js +4 -4
  168. package/icc-x-api/crypto/SecureDelegationsEncryption.js.map +1 -1
  169. package/icc-x-api/crypto/SecureDelegationsManager.js +1 -1
  170. package/icc-x-api/crypto/SecureDelegationsManager.js.map +1 -1
  171. package/icc-x-api/crypto/SecurityMetadataDecryptor.d.ts +1 -1
  172. package/icc-x-api/crypto/SecurityMetadataDecryptor.js +9 -9
  173. package/icc-x-api/crypto/SecurityMetadataDecryptor.js.map +1 -1
  174. package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
  175. package/icc-x-api/crypto/ShareMetadataBehaviour.js +1 -1
  176. package/icc-x-api/crypto/ShareMetadataBehaviour.js.map +1 -1
  177. package/icc-x-api/crypto/TransferKeysManager.js +1 -1
  178. package/icc-x-api/crypto/TransferKeysManager.js.map +1 -1
  179. package/icc-x-api/crypto/UserEncryptionKeysManager.js +2 -2
  180. package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
  181. package/icc-x-api/crypto/shamir.d.ts +2 -2
  182. package/icc-x-api/crypto/shamir.js +4 -4
  183. package/icc-x-api/crypto/shamir.js.map +1 -1
  184. package/icc-x-api/crypto/utils.js +14 -15
  185. package/icc-x-api/crypto/utils.js.map +1 -1
  186. package/icc-x-api/icc-accesslog-x-api.js +10 -10
  187. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  188. package/icc-x-api/icc-bekmehr-x-api.js.map +1 -1
  189. package/icc-x-api/icc-calendar-item-x-api.js +7 -7
  190. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  191. package/icc-x-api/icc-classification-x-api.js +5 -5
  192. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  193. package/icc-x-api/icc-code-x-api.js.map +1 -1
  194. package/icc-x-api/icc-contact-x-api.js +12 -12
  195. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  196. package/icc-x-api/icc-data-owner-x-api.js.map +1 -1
  197. package/icc-x-api/icc-device-x-api.js +2 -2
  198. package/icc-x-api/icc-device-x-api.js.map +1 -1
  199. package/icc-x-api/icc-doctemplate-x-api.js.map +1 -1
  200. package/icc-x-api/icc-document-x-api.js +15 -15
  201. package/icc-x-api/icc-document-x-api.js.map +1 -1
  202. package/icc-x-api/icc-form-x-api.js +7 -7
  203. package/icc-x-api/icc-form-x-api.js.map +1 -1
  204. package/icc-x-api/icc-hcparty-x-api.js +4 -4
  205. package/icc-x-api/icc-hcparty-x-api.js.map +1 -1
  206. package/icc-x-api/icc-helement-x-api.js +10 -10
  207. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  208. package/icc-x-api/icc-icure-maintenance-x-api.js.map +1 -1
  209. package/icc-x-api/icc-invoice-x-api.js +7 -7
  210. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  211. package/icc-x-api/icc-maintenance-task-x-api.js +7 -7
  212. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  213. package/icc-x-api/icc-message-x-api.js +8 -8
  214. package/icc-x-api/icc-message-x-api.js.map +1 -1
  215. package/icc-x-api/icc-patient-x-api.js +11 -11
  216. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  217. package/icc-x-api/icc-receipt-x-api.js +10 -10
  218. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  219. package/icc-x-api/icc-recovery-x-api.js +4 -4
  220. package/icc-x-api/icc-recovery-x-api.js.map +1 -1
  221. package/icc-x-api/icc-time-table-x-api.js +5 -5
  222. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  223. package/icc-x-api/icc-topic-x-api.js +9 -9
  224. package/icc-x-api/icc-topic-x-api.js.map +1 -1
  225. package/icc-x-api/icc-user-x-api.js +4 -4
  226. package/icc-x-api/icc-user-x-api.js.map +1 -1
  227. package/icc-x-api/index.js +22 -22
  228. package/icc-x-api/index.js.map +1 -1
  229. package/icc-x-api/maintenance/KeyPairUpdateRequest.js +2 -2
  230. package/icc-x-api/maintenance/KeyPairUpdateRequest.js.map +1 -1
  231. package/icc-x-api/storage/IcureStorageFacade.js +1 -1
  232. package/icc-x-api/storage/IcureStorageFacade.js.map +1 -1
  233. package/icc-x-api/storage/LocalStorageImpl.js +1 -1
  234. package/icc-x-api/storage/LocalStorageImpl.js.map +1 -1
  235. package/icc-x-api/utils/EntityWithDelegationTypeName.js +4 -4
  236. package/icc-x-api/utils/EntityWithDelegationTypeName.js.map +1 -1
  237. package/icc-x-api/utils/asn1-packer.js +2 -3
  238. package/icc-x-api/utils/asn1-packer.js.map +1 -1
  239. package/icc-x-api/utils/asn1-parser.js +1 -2
  240. package/icc-x-api/utils/asn1-parser.js.map +1 -1
  241. package/icc-x-api/utils/binary-utils.js +11 -11
  242. package/icc-x-api/utils/binary-utils.js.map +1 -1
  243. package/icc-x-api/utils/code-util.js +1 -2
  244. package/icc-x-api/utils/code-util.js.map +1 -1
  245. package/icc-x-api/utils/collection-utils.js +5 -6
  246. package/icc-x-api/utils/collection-utils.js.map +1 -1
  247. package/icc-x-api/utils/crypto-utils.d.ts +1 -1
  248. package/icc-x-api/utils/crypto-utils.js +17 -18
  249. package/icc-x-api/utils/crypto-utils.js.map +1 -1
  250. package/icc-x-api/utils/formatting-util.js +21 -21
  251. package/icc-x-api/utils/formatting-util.js.map +1 -1
  252. package/icc-x-api/utils/functional-util.js +3 -4
  253. package/icc-x-api/utils/functional-util.js.map +1 -1
  254. package/icc-x-api/utils/graph-utils.js +3 -4
  255. package/icc-x-api/utils/graph-utils.js.map +1 -1
  256. package/icc-x-api/utils/hcp-util.js +4 -4
  257. package/icc-x-api/utils/hcp-util.js.map +1 -1
  258. package/icc-x-api/utils/insurability-util.js +6 -7
  259. package/icc-x-api/utils/insurability-util.js.map +1 -1
  260. package/icc-x-api/utils/lru-temporised-async-cache.js.map +1 -1
  261. package/icc-x-api/utils/net-utils.js +3 -4
  262. package/icc-x-api/utils/net-utils.js.map +1 -1
  263. package/icc-x-api/utils/person-util.js +3 -4
  264. package/icc-x-api/utils/person-util.js.map +1 -1
  265. package/icc-x-api/utils/proxy-utils.js.map +1 -1
  266. package/icc-x-api/utils/simple-lru-cache.js.map +1 -1
  267. package/icc-x-api/utils/uuid-encoder.js +2 -2
  268. package/icc-x-api/utils/uuid-encoder.js.map +1 -1
  269. package/icc-x-api/utils/websocket.d.ts +0 -1
  270. package/icc-x-api/utils/websocket.js +3 -3
  271. package/icc-x-api/utils/websocket.js.map +1 -1
  272. package/package.json +3 -3
  273. package/test/icc-api/api/IccAgendaApi.js.map +1 -1
  274. package/test/icc-api/api/IccCalendarItemApi.js.map +1 -1
  275. package/test/icc-api/api/IccCalendarItemTypeApi.js +2 -2
  276. package/test/icc-api/api/IccCalendarItemTypeApi.js.map +1 -1
  277. package/test/icc-api/api/IccDocumentApi.js.map +1 -1
  278. package/test/icc-api/api/IccKeywordApi.js.map +1 -1
  279. package/test/icc-api/api/IccMedicalLocationApi.js.map +1 -1
  280. package/test/icc-api/api/IccPlaceApi.js.map +1 -1
  281. package/test/icc-api/api/IccUserApi.js +6 -6
  282. package/test/icc-x-api/auth/group-switch-test.js.map +1 -1
  283. package/test/icc-x-api/auth/jwt-concurrency-test.js +1 -2
  284. package/test/icc-x-api/auth/jwt-concurrency-test.js.map +1 -1
  285. package/test/icc-x-api/auth/jwt-provider-test.js.map +1 -1
  286. package/test/icc-x-api/auth/smart-auth-provider-test.js.map +1 -1
  287. package/test/icc-x-api/autofix-anonymity-test.js.map +1 -1
  288. package/test/icc-x-api/confidential-entities-test.js +1 -1
  289. package/test/icc-x-api/confidential-entities-test.js.map +1 -1
  290. package/test/icc-x-api/crud/comprehensive-crud-test.js.map +1 -1
  291. package/test/icc-x-api/crud/entities-crud-test-interface.js +24 -24
  292. package/test/icc-x-api/crud/entities-crud-test-interface.js.map +1 -1
  293. package/test/icc-x-api/crypto/anonymous-delegations-test.js +2 -2
  294. package/test/icc-x-api/crypto/anonymous-delegations-test.js.map +1 -1
  295. package/test/icc-x-api/crypto/cryptoTest.js.map +1 -1
  296. package/test/icc-x-api/crypto/delegate-ci-to-patient-with-missing-keys-test.js.map +1 -1
  297. package/test/icc-x-api/crypto/exchange-data-manager-test.js +4 -4
  298. package/test/icc-x-api/crypto/exchange-data-manager-test.js.map +1 -1
  299. package/test/icc-x-api/crypto/full-crypto-test.js +5 -5
  300. package/test/icc-x-api/crypto/full-crypto-test.js.map +1 -1
  301. package/test/icc-x-api/crypto/legacy-metadata-migration-test.js +7 -7
  302. package/test/icc-x-api/crypto/legacy-metadata-migration-test.js.map +1 -1
  303. package/test/icc-x-api/crypto/secure-delegations-manager-test.js +2 -2
  304. package/test/icc-x-api/crypto/secure-delegations-manager-test.js.map +1 -1
  305. package/test/icc-x-api/crypto/shamir.js.map +1 -1
  306. package/test/icc-x-api/crypto/soft-deleted-data-owners.js +3 -3
  307. package/test/icc-x-api/crypto/soft-deleted-data-owners.js.map +1 -1
  308. package/test/icc-x-api/entity-with-attachments-api-test.js +2 -2
  309. package/test/icc-x-api/entity-with-attachments-api-test.js.map +1 -1
  310. package/test/icc-x-api/icc-maintenance-task-x-api-test.js +4 -4
  311. package/test/icc-x-api/icc-message-x-api.js +1 -1
  312. package/test/icc-x-api/icc-message-x-api.js.map +1 -1
  313. package/test/icc-x-api/icc-patient-x-api-test.js.map +1 -1
  314. package/test/icc-x-api/icc-recovery-x-api.js.map +1 -1
  315. package/test/icc-x-api/icc-topic-x-api.js.map +1 -1
  316. package/test/icc-x-api/icc-user-x-api-test.js.map +1 -1
  317. package/test/icc-x-api/patient-user.js.map +1 -1
  318. package/test/icc-x-api/test-legacy-data-support.js.map +1 -1
  319. package/test/icc-x-api/utils/graph-test.js.map +1 -1
  320. package/test/icc-x-api/utils/lru-temporised-async-cache-test.js.map +1 -1
  321. package/test/support/CSM-243.js +2 -2
  322. package/test/support/CSM-243.js.map +1 -1
  323. package/test/support/CSM-93.js +1 -1
  324. package/test/support/CSM-93.js.map +1 -1
  325. package/test/utils/FakeDataOwnerApi.js.map +1 -1
  326. package/test/utils/FakeEncryptionKeysManager.js +2 -2
  327. package/test/utils/FakeEncryptionKeysManager.js.map +1 -1
  328. package/test/utils/FakeExchangeDataApi.js.map +1 -1
  329. package/test/utils/FakeExchangeDataManager.js.map +1 -1
  330. package/test/utils/FakeGenericApi.js.map +1 -1
  331. package/test/utils/TestApi.js +2 -2
  332. package/test/utils/TestApi.js.map +1 -1
  333. package/test/utils/TestCryptoStrategies.js.map +1 -1
  334. package/test/utils/TestStorage.js +2 -2
  335. package/test/utils/TestStorage.js.map +1 -1
  336. package/test/utils/test_utils.js +22 -22
  337. package/test/utils/test_utils.js.map +1 -1
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getGroupOfJwt = exports.decodeJwtClaims = exports.isJwtInvalidOrExpired = void 0;
3
+ exports.isJwtInvalidOrExpired = isJwtInvalidOrExpired;
4
+ exports.decodeJwtClaims = decodeJwtClaims;
5
+ exports.getGroupOfJwt = getGroupOfJwt;
4
6
  const utils_1 = require("../utils");
5
7
  /**
6
8
  * @internal this function is for internal use only and may be changed without notice
@@ -16,7 +18,6 @@ function isJwtInvalidOrExpired(jwt) {
16
18
  return true;
17
19
  }
18
20
  }
19
- exports.isJwtInvalidOrExpired = isJwtInvalidOrExpired;
20
21
  /**
21
22
  * @internal this function is for internal use only and may be changed without notice
22
23
  * Get the claims of the jwt.
@@ -27,7 +28,6 @@ function decodeJwtClaims(jwt) {
27
28
  throw new Error('Invalid JWT: should be 3 parts');
28
29
  return JSON.parse((0, utils_1.a2b)(parts[1]));
29
30
  }
30
- exports.decodeJwtClaims = decodeJwtClaims;
31
31
  /**
32
32
  * @internal this function is for internal use only and may be changed without notice
33
33
  * Get the group of the jwt.
@@ -35,5 +35,4 @@ exports.decodeJwtClaims = decodeJwtClaims;
35
35
  function getGroupOfJwt(jwt) {
36
36
  return decodeJwtClaims(jwt)['g'];
37
37
  }
38
- exports.getGroupOfJwt = getGroupOfJwt;
39
38
  //# sourceMappingURL=JwtUtils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"JwtUtils.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtUtils.ts"],"names":[],"mappings":";;;AAAA,oCAA8B;AAE9B;;;GAGG;AACH,SAAgB,qBAAqB,CAAC,GAAW;IAC/C,IAAI;QACF,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,CAAC,CAAA;QACnC,mGAAmG;QACnG,OAAO,CAAC,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;KACzE;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,IAAI,CAAA;KACZ;AACH,CAAC;AARD,sDAQC;AAED;;;GAGG;AACH,SAAgB,eAAe,CAAC,GAAW;IACzC,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC5B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;IACzE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAA,WAAG,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAClC,CAAC;AAJD,0CAIC;AAED;;;GAGG;AACH,SAAgB,aAAa,CAAC,GAAW;IACvC,OAAO,eAAe,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAA;AAClC,CAAC;AAFD,sCAEC","sourcesContent":["import { a2b } from '../utils'\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Returns true if the jwt is invalid or expired, false otherwise.\n */\nexport function isJwtInvalidOrExpired(jwt: string): boolean {\n try {\n const claims = decodeJwtClaims(jwt)\n // Using the 'exp' string is safe to use as it is part of the JWT RFC and cannot be modified by us.\n return !('exp' in claims) || claims['exp'] * 1000 < new Date().getTime()\n } catch (e) {\n return true\n }\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Get the claims of the jwt.\n */\nexport function decodeJwtClaims(jwt: string): any {\n const parts = jwt.split('.')\n if (parts.length !== 3) throw new Error('Invalid JWT: should be 3 parts')\n return JSON.parse(a2b(parts[1]))\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Get the group of the jwt.\n */\nexport function getGroupOfJwt(jwt: string): string {\n return decodeJwtClaims(jwt)['g']\n}\n"]}
1
+ {"version":3,"file":"JwtUtils.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtUtils.ts"],"names":[],"mappings":";;AAMA,sDAQC;AAMD,0CAIC;AAMD,sCAEC;AAhCD,oCAA8B;AAE9B;;;GAGG;AACH,SAAgB,qBAAqB,CAAC,GAAW;IAC/C,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,CAAC,CAAA;QACnC,mGAAmG;QACnG,OAAO,CAAC,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;IAC1E,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,SAAgB,eAAe,CAAC,GAAW;IACzC,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC5B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;IACzE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAA,WAAG,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAClC,CAAC;AAED;;;GAGG;AACH,SAAgB,aAAa,CAAC,GAAW;IACvC,OAAO,eAAe,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAA;AAClC,CAAC","sourcesContent":["import { a2b } from '../utils'\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Returns true if the jwt is invalid or expired, false otherwise.\n */\nexport function isJwtInvalidOrExpired(jwt: string): boolean {\n try {\n const claims = decodeJwtClaims(jwt)\n // Using the 'exp' string is safe to use as it is part of the JWT RFC and cannot be modified by us.\n return !('exp' in claims) || claims['exp'] * 1000 < new Date().getTime()\n } catch (e) {\n return true\n }\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Get the claims of the jwt.\n */\nexport function decodeJwtClaims(jwt: string): any {\n const parts = jwt.split('.')\n if (parts.length !== 3) throw new Error('Invalid JWT: should be 3 parts')\n return JSON.parse(a2b(parts[1]))\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Get the group of the jwt.\n */\nexport function getGroupOfJwt(jwt: string): string {\n return decodeJwtClaims(jwt)['g']\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"NoAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/NoAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,MAAa,aAAa;IAA1B;QACU,UAAK,GAAiB,IAAI,CAAA;IAYpC,CAAC;IAVO,cAAc;;YAClB,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE;gBAChB,MAAM,IAAI,CAAC,KAAK,CAAA;aACjB;YACD,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;QAC5B,CAAC;KAAA;IAED,gBAAgB,CAAC,KAAY;QAC3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;CACF;AAbD,sCAaC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport Header = XHR.Header\n\nexport class NoAuthService implements AuthService {\n private error: Error | null = null\n\n async getAuthHeaders(): Promise<Array<Header>> {\n if (!!this.error) {\n throw this.error\n }\n return Promise.resolve([])\n }\n\n invalidateHeader(error: Error): void {\n this.error = error\n }\n}\n"]}
1
+ {"version":3,"file":"NoAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/NoAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,MAAa,aAAa;IAA1B;QACU,UAAK,GAAiB,IAAI,CAAA;IAYpC,CAAC;IAVO,cAAc;;YAClB,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;gBACjB,MAAM,IAAI,CAAC,KAAK,CAAA;YAClB,CAAC;YACD,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;QAC5B,CAAC;KAAA;IAED,gBAAgB,CAAC,KAAY;QAC3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;CACF;AAbD,sCAaC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport Header = XHR.Header\n\nexport class NoAuthService implements AuthService {\n private error: Error | null = null\n\n async getAuthHeaders(): Promise<Array<Header>> {\n if (!!this.error) {\n throw this.error\n }\n return Promise.resolve([])\n }\n\n invalidateHeader(error: Error): void {\n this.error = error\n }\n}\n"]}
@@ -60,7 +60,7 @@ export declare enum AuthSecretType {
60
60
  /**
61
61
  * Password chosen by the user.
62
62
  */
63
- PASSWORD = "PASSWORD",
63
+ PASSWORD = "PASSWORD",// pragma: allowlist secret
64
64
  /**
65
65
  * Time based one time password provided by authenticator applications, generated on the basis of a timestamp and a shared secret between the iCure
66
66
  * server and the authenticator application.
@@ -48,7 +48,7 @@ var AuthSecretType;
48
48
  * Not yet in use.
49
49
  */
50
50
  // DIGITAL_ID = 'DIGITAL_ID',
51
- })(AuthSecretType = exports.AuthSecretType || (exports.AuthSecretType = {}));
51
+ })(AuthSecretType || (exports.AuthSecretType = AuthSecretType = {}));
52
52
  // Here starts internal entities that should not be used directly.
53
53
  /**
54
54
  * @internal this class is meant for internal use only and may be changed without notice. The SmartAuthProvider will be initialised automatically
@@ -1 +1 @@
1
- {"version":3,"file":"SmartAuthProvider.js","sourceRoot":"","sources":["../../../icc-x-api/auth/SmartAuthProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,2CAA2D;AAC3D,+CAA2C;AAC3C,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAC9B,yCAAmE;AAoDnE;;GAEG;AACH,IAAY,c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I,CAAC,YAAY,GAAG,EAAE,EAAE,EAAE,qBAAqB,CAAC,uCAAuC,EAAE,iBAAiB,EAAE,KAAK,EAAE,CAAA;gBACnH,MAAK;YACP,KAAK,qBAAqB,CAAC,0CAA0C;gBACnE,IAAI,CAAC,YAAY,GAAG,EAAE,EAAE,EAAE,qBAAqB,CAAC,cAAc,EAAE,KAAK,EAAE,KAAK,EAAE,CAAA;gBAC9E,MAAK;YACP;gBACE,MAAM,IAAI,KAAK,CAAC,oDAAoD,IAAI,CAAC,YAAY,CAAC,EAAE,GAAG,CAAC,CAAA;SAC/F;IACH,CAAC;CACF","sourcesContent":["import { AuthenticationProvider } from './AuthenticationProvider'\nimport { UserGroup } from '../../icc-api/model/UserGroup'\nimport { AuthService } from './AuthService'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { XHR } from '../../icc-api/api/XHR'\nimport XHRError = XHR.XHRError\nimport { decodeJwtClaims, isJwtInvalidOrExpired } from './JwtUtils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\n\n/**\n * Needed by a {@link SmartAuthProvider} to get the secrets (password, token, etc.) for authentication to the iCure SDK as needed.\n */\nexport interface AuthSecretProvider {\n /**\n * Provides a secret for authentication to the iCure SDK.\n *\n * ## Accepted secrets\n *\n * The method will be provided with an array of the secrets types that are acceptable (`acceptedSecrets`). Usually this array will contain multiple\n * elements, but this depends on the group configuration, the user (if he has 2fa setup or not), or the operation being performed. For groups using\n * default configurations and for patients without 2fa enabled for example the array will always contain the {@link AuthSecretType.PASSWORD} element.\n * Usually the array contain also the {@link AuthSecretType.LONG_LIVED_TOKEN} element, but if the user is attempting to perform a sensitive operations\n * such as changing his password the default group configuration does not allow for the user to authenticate using a JWT obtained from a long-lived\n * token for this operation, meaning the array will not contain the {@link AuthSecretType.LONG_LIVED_TOKEN} element.\n *\n * Regardless of the number of elements in the array only one secret of the accepted types is sufficient for the operation to succeed.\n *\n * ## TWO_FACTOR_AUTHENTICATION_TOKEN secret type\n *\n * The {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN} secret type is only used when the user has 2fa enabled. In this case the SDK will call\n * this method twice, once containing the {@link AuthSecretType.PASSWORD} element in the `acceptedSecrets` array, and if the provided secret is a\n * valid password the SDK will immediately call this method again, this time containing the {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN}\n * instead of the {@link AuthSecretType.PASSWORD} element.\n *\n * Any future call to this method from the same provider instance will not contain the {@link AuthSecretType.PASSWORD} element anymore, as it is\n * cached, but it may contain the {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN} element instead.\n *\n * Note that the 2fa token is not needed for logging in through a long-lived or short-lived token, it is only used in combination with a password.\n * If the user is using 2fa, and you get in input as `acceptedSecrets` an array `[PASSWORD, LONG_LIVED_TOKEN, SHORT_LIVED_TOKEN]`, and you pass to\n * authenticate a long-lived token, the SDK will not call this method again to ask for the 2fa token.\n *\n * @param acceptedSecrets the types of secrets that are acceptable for the operation being performed.\n * @param previousAttempts the secrets that were previously attempted by the SDK for this operation. This array will be empty the first time this\n * method is called for a given operation, but it may contain multiple elements if the SDK has already called this method multiple times because the\n * previously returned secrets were not valid. The first element is the first secret that was attempted, and the last element is the most recently\n * attempted.\n * @param isUpgradeRequest specifies if the secret was requested to upgrade an existing and valid jwt.\n * @return a promise that resolves with the secret and the secret type to use for authentication. If the promise rejects then the ongoing SDK\n * operation will fail without being re-attempted.\n */\n getSecret(acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[], isUpgradeRequest: boolean): Promise<AuthSecretDetails>\n}\n\n// We may want to add some onSuccess callback in future or similar\nexport type AuthSecretDetails =\n | { value: string; secretType: Exclude<AuthSecretType, AuthSecretType.EXTERNAL_AUTHENTICATION> }\n | { value: string; secretType: AuthSecretType.EXTERNAL_AUTHENTICATION; oauthType: OAuthThirdParty }\n\n/**\n * Represents a type of secret that can be used for authentication with iCure.\n */\nexport enum AuthSecretType {\n /**\n * Password chosen by the user.\n */\n PASSWORD = 'PASSWORD', // pragma: allowlist secret\n /**\n * Time based one time password provided by authenticator applications, generated on the basis of a timestamp and a shared secret between the iCure\n * server and the authenticator application.\n */\n TWO_FACTOR_AUTHENTICATION_TOKEN = 'TWO_FACTOR_AUTHENTICATION_TOKEN',\n /**\n * A short-lived iCure token, an internal authentication token that lasts 5 minutes or less. Unlike passwords these tokens usually are generated by\n * some component of iCure, and are not chosen by the user.\n */\n SHORT_LIVED_TOKEN = 'SHORT_LIVED_TOKEN',\n /**\n * A long-lived iCure token, an internal authentication token that lasts longer than 5 minutes. Unlike passwords these tokens usually are generated\n * by some component of iCure, and are not chosen by the user.\n */\n LONG_LIVED_TOKEN = 'LONG_LIVED_TOKEN',\n /**\n * A token provided by an external authentication provider (e.g. Oauth/Google).\n * Not yet in use.\n */\n EXTERNAL_AUTHENTICATION = 'EXTERNAL_AUTHENTICATION',\n /**\n * A special case of external authentication where the provider is a digital identity provider.\n * Not yet in use.\n */\n // DIGITAL_ID = 'DIGITAL_ID',\n}\n\n// Here starts internal entities that should not be used directly.\n\n/**\n * @internal this class is meant for internal use only and may be changed without notice. The SmartAuthProvider will be initialised automatically\n * by the iCure api depending on the authentication options you provide.\n *\n * An authentication provider that automatically requests secrets for authentication as needed.\n *\n * This authentication provider can be initialised already with some secrets or tokens, and the provider will cache them and use them as needed for\n * as long as they remain valid. If at any point however the provider needs an updated secret or a secret of a different kind it will automatically\n * request this to the {@link SmartAuthProvider} to get the secret.\n *\n * An advantage of using this provider over others is that in case all the cached tokens and secrets were to expire while performing a request,\n * instead of having the request fail the provider will ask for new secrets from the {@link SmartAuthProvider} and the request will automatically\n * be retried with the new secret. Additionally, the provider may request updated secrets also for performing some sensitive operations (e.g. changing\n * password of the user) even if the cached tokens and/or did not expire. This could be the case for example if the cached secret is a long-lived\n * token, but in order to change the password the user needs to provide his current password.\n *\n * Note that in this context the cache of secrets and token is in memory only, and is not persisted in any way. Different instances of this provider\n * will not share the same cache.\n *\n */\nexport class SmartAuthProvider implements AuthenticationProvider {\n /**\n * Initialises a {@link SmartAuthProvider}.\n * @param authApi an \"anonymous\" {@link IccAuthApi} to use for authentication.\n * @param login\n * @param secretProvider\n * @param props optional initialisation properties.\n */\n static initialise(\n authApi: IccAuthApi,\n login: string,\n secretProvider: AuthSecretProvider,\n props: {\n initialSecret?: { password: string } | { longToken: string } | { oauthToken: string; oauthType: OAuthThirdParty }\n initialAuthToken?: string\n initialRefreshToken?: string\n loginGroupId?: string\n debugLog?: boolean\n } = {}\n ): SmartAuthProvider {\n let initialSecret: CachedSecretType | undefined = undefined\n if (props.initialSecret) {\n if ('password' in props.initialSecret) {\n initialSecret = { value: props.initialSecret.password, type: ServerAuthenticationClass.PASSWORD }\n } else if ('longToken' in props.initialSecret) {\n initialSecret = { value: props.initialSecret.longToken, type: ServerAuthenticationClass.LONG_LIVED_TOKEN }\n } else {\n initialSecret = {\n value: props.initialSecret.oauthToken,\n type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION,\n oauthType: props.initialSecret.oauthType,\n }\n }\n }\n return new SmartAuthProvider(\n new TokenProvider(\n login,\n props.loginGroupId,\n initialSecret,\n props.initialAuthToken,\n props.initialRefreshToken,\n authApi,\n secretProvider,\n props.debugLog != undefined ? props.debugLog : true\n ),\n props.loginGroupId\n )\n }\n\n private constructor(private readonly tokenProvider: TokenProvider, private readonly groupId: string | undefined) {}\n\n getAuthService(): AuthService {\n return new SmartAuthService(this.tokenProvider)\n }\n\n async switchGroup(newGroupId: string, matches: Array<UserGroup>): Promise<AuthenticationProvider> {\n if (newGroupId == this.groupId) return Promise.resolve(this)\n if (!matches.find((match) => match.groupId == newGroupId)) throw new Error('New group id not found in matches.')\n const switchedProvider = await this.tokenProvider.switchedGroup(newGroupId)\n return new SmartAuthProvider(switchedProvider, this.groupId)\n }\n\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this.tokenProvider.getCachedTokensOrLoad()\n }\n}\n\nenum ServerAuthenticationClass {\n // DIGITAL_ID = 60,\n TWO_FACTOR_AUTHENTICATION = 50,\n SHORT_LIVED_TOKEN = 40,\n EXTERNAL_AUTHENTICATION = 30,\n PASSWORD = 20,\n LONG_LIVED_TOKEN = 10,\n}\n// Secrets lasting more than 5 minutes -> makes sense to reuse them to get an elevated security jwt\ntype LongLivedSecretType = ServerAuthenticationClass.LONG_LIVED_TOKEN | ServerAuthenticationClass.PASSWORD\ntype CachedSecretType =\n | { value: string; type: LongLivedSecretType | undefined }\n | { value: string; type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION; oauthType: OAuthThirdParty }\n// In some providers Oauth tokens may have short duration or may be usable only once. We only want to cache them if they are going to be reusable and\n// if they last more than 5 minutes.\nconst longLivedOAuthTokens = new Set([OAuthThirdParty.GOOGLE])\nclass TokenProvider {\n constructor(\n private login: string,\n private groupId: string | undefined,\n private currentLongLivedSecret: CachedSecretType | undefined,\n private cachedToken: string | undefined,\n private cachedRefreshToken: string | undefined,\n private readonly authApi: IccAuthApi,\n private readonly authSecretProvider: AuthSecretProvider,\n private readonly debugLog: boolean\n ) {}\n\n private debugCacheInfo(): String {\n return `\\n\\tcached bearer exp: ${this.cachedToken ? decodeJwtClaims(this.cachedToken)['exp'] : 'none'}\\n\\tcached refresh exp ${\n this.cachedRefreshToken ? decodeJwtClaims(this.cachedRefreshToken)['exp'] : 'none'\n }\\n\\tcached secret: ${this.currentLongLivedSecret?.value != undefined}\\n\\tcached secret type: ${this.currentLongLivedSecret?.type}`\n }\n\n async getCachedOrRefreshedOrNewToken(): Promise<{ token: string; type: RetrievedTokenType }> {\n if (!!this.cachedToken && !isJwtInvalidOrExpired(this.cachedToken)) {\n return { token: this.cachedToken, type: RetrievedTokenType.CACHED }\n } else if (!!this.cachedRefreshToken && !isJwtInvalidOrExpired(this.cachedRefreshToken)) {\n return this.refreshAndCacheToken(this.cachedRefreshToken)\n } else {\n return { token: await this.getAndCacheNewToken(undefined), type: RetrievedTokenType.NEW }\n }\n }\n\n async getCachedTokensOrLoad(): Promise<{ token: string; refreshToken: string }> {\n if (!this.cachedToken || !this.cachedRefreshToken) {\n await this.getAndCacheNewToken(undefined)\n }\n return { token: this.cachedToken!, refreshToken: this.cachedRefreshToken! }\n }\n\n async getNewTokenWithClass(minimumAuthenticationClass: number): Promise<string> {\n return await this.getAndCacheNewToken(minimumAuthenticationClass)\n }\n\n private async getAndCacheNewToken(minimumAuthenticationClassLevel: number | undefined): Promise<string> {\n const { token, refreshToken } = await this.getNewToken(minimumAuthenticationClassLevel ?? 0)\n this.cachedToken = token\n this.cachedRefreshToken = refreshToken\n return token\n }\n\n private async refreshAndCacheToken(refreshToken: string): Promise<{ token: string; type: RetrievedTokenType }> {\n if (this.debugLog) console.log(`Attempting to refresh bearer token ${this.debugCacheInfo()}`)\n return await this.authApi.refreshAuthenticationJWT(refreshToken).then(\n (authResult) => {\n if (!authResult.token) throw new Error('Internal error: refresh succeeded but no token was returned. Unsupported backend version?')\n this.cachedToken = authResult.token\n return { token: authResult.token, type: RetrievedTokenType.REFRESHED }\n },\n async () => ({ token: await this.getAndCacheNewToken(undefined), type: RetrievedTokenType.NEW })\n )\n }\n\n private async getNewToken(minimumAuthenticationClassLevel: number): Promise<{ token: string; refreshToken: string }> {\n if (this.debugLog) console.log(`Attempting to get new token for auth class ${minimumAuthenticationClassLevel} ${this.debugCacheInfo()}`)\n if (!!this.currentLongLivedSecret && (!this.currentLongLivedSecret.type || this.currentLongLivedSecret.type >= minimumAuthenticationClassLevel)) {\n if (this.debugLog) console.log('Using cached secret')\n const resultWithCachedSecret = await this.doGetTokenWithSecret(this.currentLongLivedSecret, minimumAuthenticationClassLevel)\n if ('success' in resultWithCachedSecret) {\n if (this.debugLog) console.log('New token using cached secret success')\n return resultWithCachedSecret.success\n } else if (\n resultWithCachedSecret.failure === DoGetTokenResultFailureReason.NEEDS_2FA &&\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION\n ) {\n if (this.debugLog) console.log('New token using cached secret requires 2fa')\n return this.askTotpAndGetToken(this.currentLongLivedSecret.value, minimumAuthenticationClassLevel)\n } else {\n if (this.debugLog) console.log('New token using cached secret failed')\n return this.askSecretAndGetToken(minimumAuthenticationClassLevel, true)\n }\n } else {\n if (this.debugLog) console.log('No cached credentials of correct auth class found')\n return this.askSecretAndGetToken(minimumAuthenticationClassLevel, true)\n }\n }\n\n private async askSecretAndGetToken(\n minimumAuthenticationClassLevel: number,\n passwordIsValidAs2fa: boolean\n ): Promise<{ token: string; refreshToken: string }> {\n const acceptedSecrets = [\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.LONG_LIVED_TOKEN ? [AuthSecretType.LONG_LIVED_TOKEN] : [],\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.SHORT_LIVED_TOKEN ? [AuthSecretType.SHORT_LIVED_TOKEN] : [],\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION &&\n (passwordIsValidAs2fa || minimumAuthenticationClassLevel <= ServerAuthenticationClass.PASSWORD)\n ? [AuthSecretType.PASSWORD]\n : [],\n ].flat()\n if (!acceptedSecrets.length)\n throw new Error('Internal error: no secret type is accepted for this request. Group may be misconfigured, or client may be outdated.')\n const attempts: AuthSecretDetails[] = []\n if (this.debugLog) console.log(`Asking for secret and getting token for auth class ${minimumAuthenticationClassLevel} ${this.debugCacheInfo()}`)\n while (true) {\n const secretDetails = await this.authSecretProvider.getSecret([...acceptedSecrets], attempts, minimumAuthenticationClassLevel > 0)\n if (!acceptedSecrets.includes(secretDetails.secretType))\n throw new Error(`Accepted secret types are ${JSON.stringify(acceptedSecrets)}, but got a secret of type ${secretDetails.secretType}.`)\n attempts.push(secretDetails)\n const result = await this.doGetTokenWithSecret(secretDetails, minimumAuthenticationClassLevel)\n if ('success' in result) {\n this.updateCachedSecret(secretDetails)\n return result.success\n } else if (result.failure == DoGetTokenResultFailureReason.NEEDS_2FA) {\n return this.askTotpAndGetToken(secretDetails.value, minimumAuthenticationClassLevel)\n } else if (secretDetails.value == AuthSecretType.PASSWORD && result.failure == DoGetTokenResultFailureReason.INVALID_AUTH_CLASS_LEVEL) {\n // If we tried a password, and it turns out that the user has 2fa not enabled next time we don't consider password valid\n return this.askSecretAndGetToken(minimumAuthenticationClassLevel, false)\n } // else retry\n }\n }\n\n private async askTotpAndGetToken(password: string, minimumAuthenticationClassLevel: number): Promise<{ token: string; refreshToken: string }> {\n if (minimumAuthenticationClassLevel > ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION)\n throw new Error(\n \"Internal error: asking for totp to login but minimumAuthenticationClassLevel is higher than TWO_FACTOR_AUTHENTICATION's level.\"\n )\n const attempts: AuthSecretDetails[] = []\n while (true) {\n const details = await this.authSecretProvider.getSecret([AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN], attempts, false)\n if (details.secretType != AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n throw new Error(`Was expecting a 2fa token but got a secret of type ${details.secretType}.`)\n attempts.push(details)\n const result = await this.doGetTokenWithSecret({ value: `${password}|${details.value}` }, minimumAuthenticationClassLevel)\n if ('success' in result) {\n this.updateCachedSecret({ value: password, secretType: AuthSecretType.PASSWORD })\n return result.success\n } else if (result.failure != DoGetTokenResultFailureReason.INVALID_2FA) {\n throw new Error(`Unexpected error while trying to login with (previously) valid password and 2fa token ${result.failure}.`)\n } // else retry\n }\n }\n\n private async doGetTokenWithSecret(\n secret: { value: string; oauthType?: OAuthThirdParty },\n minimumAuthenticationClassLevel: number\n ): Promise<DoGetTokenResult> {\n let authResultPromise: Promise<AuthenticationResponse>\n if ('oauthType' in secret && !!secret.oauthType) {\n authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value) // TODO add group id\n } else {\n authResultPromise = this.authApi.login({ username: this.login, password: secret.value }, this.groupId)\n }\n return authResultPromise.then(\n (authResult) => {\n const { token, refreshToken } = authResult\n if (!token || !refreshToken) throw new Error('Internal error: login succeeded but no token was returned. Unsupported backend version?')\n const claims = decodeJwtClaims(token)\n const authClassLevel = claims['tac']\n if (!authClassLevel || typeof authClassLevel !== 'number') {\n if (minimumAuthenticationClassLevel > 0) {\n throw new Error('Internal error: authClassLevel is not a number. Unsupported backend version?')\n } else return { success: { token, refreshToken } }\n }\n if (authClassLevel < minimumAuthenticationClassLevel) {\n return { failure: DoGetTokenResultFailureReason.INVALID_AUTH_CLASS_LEVEL }\n } else {\n return { success: { token, refreshToken } }\n }\n },\n (error) => {\n if (!(error instanceof XHRError)) throw error\n if (error.statusCode == 401 || error.statusCode == 412) {\n // Password is wrong (401) or unacceptable (e.g. too short, 412)\n return { failure: DoGetTokenResultFailureReason.INVALID_PW_OR_TOKEN }\n } else if (error.statusCode == 406) {\n // Password is correct, but 2fa token is not\n return { failure: DoGetTokenResultFailureReason.INVALID_2FA }\n } else if (error.statusCode == 417) {\n // Password is correct, but the user has 2fa enabled and no 2fa token was provided\n return { failure: DoGetTokenResultFailureReason.NEEDS_2FA }\n } else throw error\n }\n )\n }\n\n async switchedGroup(newGroupId: string): Promise<TokenProvider> {\n const groupSwitchedTokens = this.cachedRefreshToken\n ? await this.authApi.switchGroup(this.cachedRefreshToken, newGroupId).then(\n (response) => {\n if (!response.token || !response.refreshToken)\n throw new Error('Internal error: group switch succeeded but no token was returned. Unsupported backend version?')\n return { token: response.token, refreshToken: response.refreshToken }\n },\n () => ({ token: undefined, refreshToken: undefined })\n )\n : { token: undefined, refreshToken: undefined }\n return new TokenProvider(\n this.login,\n newGroupId,\n this.currentLongLivedSecret ? { value: this.currentLongLivedSecret.value, type: undefined } : undefined,\n groupSwitchedTokens.token,\n groupSwitchedTokens.refreshToken,\n this.authApi,\n this.authSecretProvider,\n this.debugLog\n )\n }\n\n private updateCachedSecret(details: AuthSecretDetails) {\n switch (details.secretType) {\n case AuthSecretType.PASSWORD:\n this.currentLongLivedSecret = { value: details.value, type: ServerAuthenticationClass.PASSWORD }\n break\n case AuthSecretType.LONG_LIVED_TOKEN:\n this.currentLongLivedSecret = { value: details.value, type: ServerAuthenticationClass.LONG_LIVED_TOKEN }\n break\n case AuthSecretType.EXTERNAL_AUTHENTICATION:\n if (longLivedOAuthTokens.has(details.oauthType)) {\n this.currentLongLivedSecret = {\n value: details.value,\n type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION,\n oauthType: details.oauthType,\n }\n }\n break\n }\n }\n}\ntype DoGetTokenResult = { success: { token: string; refreshToken: string } } | { failure: DoGetTokenResultFailureReason }\nenum DoGetTokenResultFailureReason {\n NEEDS_2FA,\n INVALID_2FA,\n INVALID_PW_OR_TOKEN,\n INVALID_AUTH_CLASS_LEVEL,\n}\nenum RetrievedTokenType {\n CACHED,\n REFRESHED,\n NEW,\n}\n\nenum SmartAuthServiceState {\n INITIAL,\n DONE_INITIAL,\n REATTEMPT,\n REATTEMPTED_WITH_NEW_UNBOUND_TOKEN,\n REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN,\n EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS,\n TERMINAL_ERROR,\n}\nclass SmartAuthService implements AuthService {\n private currentState:\n | { id: SmartAuthServiceState.INITIAL }\n | { id: SmartAuthServiceState.DONE_INITIAL; initialToken: string }\n | { id: SmartAuthServiceState.REATTEMPT; initialToken: string; initialError: Error }\n | { id: SmartAuthServiceState.REATTEMPTED_WITH_NEW_UNBOUND_TOKEN }\n | { id: SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN }\n | { id: SmartAuthServiceState.EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS; errorFromNewToken: Error }\n | { id: SmartAuthServiceState.TERMINAL_ERROR; error: Error } = { id: SmartAuthServiceState.INITIAL }\n\n constructor(private readonly tokenProvider: TokenProvider) {}\n\n async jwtGetter(): Promise<{ token: string; refreshToken: string | undefined }> {\n const token = await this.getAuthToken(undefined)\n return { token, refreshToken: undefined }\n }\n\n async getAuthHeaders(minimumAuthenticationClassLevel: number | undefined): Promise<Array<XHR.Header>> {\n return [new XHR.Header('Authorization', `Bearer ${await this.getAuthToken(minimumAuthenticationClassLevel)}`)]\n }\n\n private async getAuthToken(minimumAuthenticationClassLevel: number | undefined): Promise<string> {\n switch (this.currentState.id) {\n case SmartAuthServiceState.INITIAL:\n if (minimumAuthenticationClassLevel != undefined) {\n throw new Error('Illegal state: cannot ask for a specific auth class level at the first request attempt.')\n } else {\n const { token } = await this.tokenProvider.getCachedOrRefreshedOrNewToken()\n this.currentState = { id: SmartAuthServiceState.DONE_INITIAL, initialToken: token }\n return token\n }\n case SmartAuthServiceState.REATTEMPT:\n if (minimumAuthenticationClassLevel != undefined) {\n const token = await this.tokenProvider.getNewTokenWithClass(minimumAuthenticationClassLevel)\n this.currentState = { id: SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN }\n return token\n } else {\n const { token } = await this.tokenProvider.getCachedOrRefreshedOrNewToken()\n if (token == this.currentState.initialToken) throw this.currentState.initialError\n this.currentState = { id: SmartAuthServiceState.REATTEMPTED_WITH_NEW_UNBOUND_TOKEN }\n return token\n }\n case SmartAuthServiceState.EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS:\n if (minimumAuthenticationClassLevel != undefined) {\n const token = await this.tokenProvider.getNewTokenWithClass(minimumAuthenticationClassLevel)\n this.currentState = { id: SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN }\n return token\n } else throw this.currentState.errorFromNewToken\n case SmartAuthServiceState.TERMINAL_ERROR:\n throw this.currentState.error\n default:\n throw new Error(`Illegal state: cannot get token in state ${this.currentState.id}.`)\n }\n }\n\n invalidateHeader(error: Error): void {\n switch (this.currentState.id) {\n case SmartAuthServiceState.DONE_INITIAL:\n this.currentState = { id: SmartAuthServiceState.REATTEMPT, initialToken: this.currentState.initialToken, initialError: error }\n break\n case SmartAuthServiceState.REATTEMPTED_WITH_NEW_UNBOUND_TOKEN:\n this.currentState = { id: SmartAuthServiceState.EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS, errorFromNewToken: error }\n break\n case SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN:\n this.currentState = { id: SmartAuthServiceState.TERMINAL_ERROR, error: error }\n break\n default:\n throw new Error(`Illegal state: cannot invalidate header in state ${this.currentState.id}.`)\n }\n }\n}\n"]}
1
+ {"version":3,"file":"SmartAuthProvider.js","sourceRoot":"","sources":["../../../icc-x-api/auth/SmartAuthProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,2CAA2D;AAC3D,+CAA2C;AAC3C,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAC9B,yCAAmE;AAoDnE;;GAEG;AACH,IAAY,cA8BX;AA9BD,WAAY,cAAc;IACxB;;OAEG;IACH,uCAAqB,CAAA;IACrB;;;OAGG;IACH,qFAAmE,CAAA;IACnE;;;OAGG;IACH,yDAAuC,CAAA;IACvC;;;OAGG;IACH,uDAAqC,CAAA;IACrC;;;OAGG;IACH,qEAAmD,CAAA;IACnD;;;OAGG;IACH,6BAA6B;AAC/B,CAAC,EA9BW,cAAc,8BAAd,cAAc,QA8BzB;AAED,kEAAkE;AAElE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAa,iBAAiB;IAC5B;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CACf,OAAmB,EACnB,KAAa,EACb,cAAkC,EAClC,QAMI,EAAE;QAEN,IAAI,aAAa,GAAiC,SAAS,CAAA;QAC3D,IAAI,KAAK,CAAC,aAAa,EAAE,CAAC;YACxB,IAAI,UAAU,IAAI,KAAK,CAAC,aAAa,EAAE,CAAC;gBACtC,aAAa,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,EAAE,yBAAyB,CAAC,QAAQ,EAAE,CAAA;YACnG,CAAC;iBAAM,IAAI,WAAW,IAAI,KAAK,CAAC,aAAa,EAAE,CAAC;gBAC9C,aAAa,GAAG,E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AE,GAAG,CAAC,CAAA;QAChG,CAAC;IACH,CAAC;CACF","sourcesContent":["import { AuthenticationProvider } from './AuthenticationProvider'\nimport { UserGroup } from '../../icc-api/model/UserGroup'\nimport { AuthService } from './AuthService'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { XHR } from '../../icc-api/api/XHR'\nimport XHRError = XHR.XHRError\nimport { decodeJwtClaims, isJwtInvalidOrExpired } from './JwtUtils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\n\n/**\n * Needed by a {@link SmartAuthProvider} to get the secrets (password, token, etc.) for authentication to the iCure SDK as needed.\n */\nexport interface AuthSecretProvider {\n /**\n * Provides a secret for authentication to the iCure SDK.\n *\n * ## Accepted secrets\n *\n * The method will be provided with an array of the secrets types that are acceptable (`acceptedSecrets`). Usually this array will contain multiple\n * elements, but this depends on the group configuration, the user (if he has 2fa setup or not), or the operation being performed. For groups using\n * default configurations and for patients without 2fa enabled for example the array will always contain the {@link AuthSecretType.PASSWORD} element.\n * Usually the array contain also the {@link AuthSecretType.LONG_LIVED_TOKEN} element, but if the user is attempting to perform a sensitive operations\n * such as changing his password the default group configuration does not allow for the user to authenticate using a JWT obtained from a long-lived\n * token for this operation, meaning the array will not contain the {@link AuthSecretType.LONG_LIVED_TOKEN} element.\n *\n * Regardless of the number of elements in the array only one secret of the accepted types is sufficient for the operation to succeed.\n *\n * ## TWO_FACTOR_AUTHENTICATION_TOKEN secret type\n *\n * The {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN} secret type is only used when the user has 2fa enabled. In this case the SDK will call\n * this method twice, once containing the {@link AuthSecretType.PASSWORD} element in the `acceptedSecrets` array, and if the provided secret is a\n * valid password the SDK will immediately call this method again, this time containing the {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN}\n * instead of the {@link AuthSecretType.PASSWORD} element.\n *\n * Any future call to this method from the same provider instance will not contain the {@link AuthSecretType.PASSWORD} element anymore, as it is\n * cached, but it may contain the {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN} element instead.\n *\n * Note that the 2fa token is not needed for logging in through a long-lived or short-lived token, it is only used in combination with a password.\n * If the user is using 2fa, and you get in input as `acceptedSecrets` an array `[PASSWORD, LONG_LIVED_TOKEN, SHORT_LIVED_TOKEN]`, and you pass to\n * authenticate a long-lived token, the SDK will not call this method again to ask for the 2fa token.\n *\n * @param acceptedSecrets the types of secrets that are acceptable for the operation being performed.\n * @param previousAttempts the secrets that were previously attempted by the SDK for this operation. This array will be empty the first time this\n * method is called for a given operation, but it may contain multiple elements if the SDK has already called this method multiple times because the\n * previously returned secrets were not valid. The first element is the first secret that was attempted, and the last element is the most recently\n * attempted.\n * @param isUpgradeRequest specifies if the secret was requested to upgrade an existing and valid jwt.\n * @return a promise that resolves with the secret and the secret type to use for authentication. If the promise rejects then the ongoing SDK\n * operation will fail without being re-attempted.\n */\n getSecret(acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[], isUpgradeRequest: boolean): Promise<AuthSecretDetails>\n}\n\n// We may want to add some onSuccess callback in future or similar\nexport type AuthSecretDetails =\n | { value: string; secretType: Exclude<AuthSecretType, AuthSecretType.EXTERNAL_AUTHENTICATION> }\n | { value: string; secretType: AuthSecretType.EXTERNAL_AUTHENTICATION; oauthType: OAuthThirdParty }\n\n/**\n * Represents a type of secret that can be used for authentication with iCure.\n */\nexport enum AuthSecretType {\n /**\n * Password chosen by the user.\n */\n PASSWORD = 'PASSWORD', // pragma: allowlist secret\n /**\n * Time based one time password provided by authenticator applications, generated on the basis of a timestamp and a shared secret between the iCure\n * server and the authenticator application.\n */\n TWO_FACTOR_AUTHENTICATION_TOKEN = 'TWO_FACTOR_AUTHENTICATION_TOKEN',\n /**\n * A short-lived iCure token, an internal authentication token that lasts 5 minutes or less. Unlike passwords these tokens usually are generated by\n * some component of iCure, and are not chosen by the user.\n */\n SHORT_LIVED_TOKEN = 'SHORT_LIVED_TOKEN',\n /**\n * A long-lived iCure token, an internal authentication token that lasts longer than 5 minutes. Unlike passwords these tokens usually are generated\n * by some component of iCure, and are not chosen by the user.\n */\n LONG_LIVED_TOKEN = 'LONG_LIVED_TOKEN',\n /**\n * A token provided by an external authentication provider (e.g. Oauth/Google).\n * Not yet in use.\n */\n EXTERNAL_AUTHENTICATION = 'EXTERNAL_AUTHENTICATION',\n /**\n * A special case of external authentication where the provider is a digital identity provider.\n * Not yet in use.\n */\n // DIGITAL_ID = 'DIGITAL_ID',\n}\n\n// Here starts internal entities that should not be used directly.\n\n/**\n * @internal this class is meant for internal use only and may be changed without notice. The SmartAuthProvider will be initialised automatically\n * by the iCure api depending on the authentication options you provide.\n *\n * An authentication provider that automatically requests secrets for authentication as needed.\n *\n * This authentication provider can be initialised already with some secrets or tokens, and the provider will cache them and use them as needed for\n * as long as they remain valid. If at any point however the provider needs an updated secret or a secret of a different kind it will automatically\n * request this to the {@link SmartAuthProvider} to get the secret.\n *\n * An advantage of using this provider over others is that in case all the cached tokens and secrets were to expire while performing a request,\n * instead of having the request fail the provider will ask for new secrets from the {@link SmartAuthProvider} and the request will automatically\n * be retried with the new secret. Additionally, the provider may request updated secrets also for performing some sensitive operations (e.g. changing\n * password of the user) even if the cached tokens and/or did not expire. This could be the case for example if the cached secret is a long-lived\n * token, but in order to change the password the user needs to provide his current password.\n *\n * Note that in this context the cache of secrets and token is in memory only, and is not persisted in any way. Different instances of this provider\n * will not share the same cache.\n *\n */\nexport class SmartAuthProvider implements AuthenticationProvider {\n /**\n * Initialises a {@link SmartAuthProvider}.\n * @param authApi an \"anonymous\" {@link IccAuthApi} to use for authentication.\n * @param login\n * @param secretProvider\n * @param props optional initialisation properties.\n */\n static initialise(\n authApi: IccAuthApi,\n login: string,\n secretProvider: AuthSecretProvider,\n props: {\n initialSecret?: { password: string } | { longToken: string } | { oauthToken: string; oauthType: OAuthThirdParty }\n initialAuthToken?: string\n initialRefreshToken?: string\n loginGroupId?: string\n debugLog?: boolean\n } = {}\n ): SmartAuthProvider {\n let initialSecret: CachedSecretType | undefined = undefined\n if (props.initialSecret) {\n if ('password' in props.initialSecret) {\n initialSecret = { value: props.initialSecret.password, type: ServerAuthenticationClass.PASSWORD }\n } else if ('longToken' in props.initialSecret) {\n initialSecret = { value: props.initialSecret.longToken, type: ServerAuthenticationClass.LONG_LIVED_TOKEN }\n } else {\n initialSecret = {\n value: props.initialSecret.oauthToken,\n type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION,\n oauthType: props.initialSecret.oauthType,\n }\n }\n }\n return new SmartAuthProvider(\n new TokenProvider(\n login,\n props.loginGroupId,\n initialSecret,\n props.initialAuthToken,\n props.initialRefreshToken,\n authApi,\n secretProvider,\n props.debugLog != undefined ? props.debugLog : true\n ),\n props.loginGroupId\n )\n }\n\n private constructor(private readonly tokenProvider: TokenProvider, private readonly groupId: string | undefined) {}\n\n getAuthService(): AuthService {\n return new SmartAuthService(this.tokenProvider)\n }\n\n async switchGroup(newGroupId: string, matches: Array<UserGroup>): Promise<AuthenticationProvider> {\n if (newGroupId == this.groupId) return Promise.resolve(this)\n if (!matches.find((match) => match.groupId == newGroupId)) throw new Error('New group id not found in matches.')\n const switchedProvider = await this.tokenProvider.switchedGroup(newGroupId)\n return new SmartAuthProvider(switchedProvider, this.groupId)\n }\n\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this.tokenProvider.getCachedTokensOrLoad()\n }\n}\n\nenum ServerAuthenticationClass {\n // DIGITAL_ID = 60,\n TWO_FACTOR_AUTHENTICATION = 50,\n SHORT_LIVED_TOKEN = 40,\n EXTERNAL_AUTHENTICATION = 30,\n PASSWORD = 20,\n LONG_LIVED_TOKEN = 10,\n}\n// Secrets lasting more than 5 minutes -> makes sense to reuse them to get an elevated security jwt\ntype LongLivedSecretType = ServerAuthenticationClass.LONG_LIVED_TOKEN | ServerAuthenticationClass.PASSWORD\ntype CachedSecretType =\n | { value: string; type: LongLivedSecretType | undefined }\n | { value: string; type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION; oauthType: OAuthThirdParty }\n// In some providers Oauth tokens may have short duration or may be usable only once. We only want to cache them if they are going to be reusable and\n// if they last more than 5 minutes.\nconst longLivedOAuthTokens = new Set([OAuthThirdParty.GOOGLE])\nclass TokenProvider {\n constructor(\n private login: string,\n private groupId: string | undefined,\n private currentLongLivedSecret: CachedSecretType | undefined,\n private cachedToken: string | undefined,\n private cachedRefreshToken: string | undefined,\n private readonly authApi: IccAuthApi,\n private readonly authSecretProvider: AuthSecretProvider,\n private readonly debugLog: boolean\n ) {}\n\n private debugCacheInfo(): String {\n return `\\n\\tcached bearer exp: ${this.cachedToken ? decodeJwtClaims(this.cachedToken)['exp'] : 'none'}\\n\\tcached refresh exp ${\n this.cachedRefreshToken ? decodeJwtClaims(this.cachedRefreshToken)['exp'] : 'none'\n }\\n\\tcached secret: ${this.currentLongLivedSecret?.value != undefined}\\n\\tcached secret type: ${this.currentLongLivedSecret?.type}`\n }\n\n async getCachedOrRefreshedOrNewToken(): Promise<{ token: string; type: RetrievedTokenType }> {\n if (!!this.cachedToken && !isJwtInvalidOrExpired(this.cachedToken)) {\n return { token: this.cachedToken, type: RetrievedTokenType.CACHED }\n } else if (!!this.cachedRefreshToken && !isJwtInvalidOrExpired(this.cachedRefreshToken)) {\n return this.refreshAndCacheToken(this.cachedRefreshToken)\n } else {\n return { token: await this.getAndCacheNewToken(undefined), type: RetrievedTokenType.NEW }\n }\n }\n\n async getCachedTokensOrLoad(): Promise<{ token: string; refreshToken: string }> {\n if (!this.cachedToken || !this.cachedRefreshToken) {\n await this.getAndCacheNewToken(undefined)\n }\n return { token: this.cachedToken!, refreshToken: this.cachedRefreshToken! }\n }\n\n async getNewTokenWithClass(minimumAuthenticationClass: number): Promise<string> {\n return await this.getAndCacheNewToken(minimumAuthenticationClass)\n }\n\n private async getAndCacheNewToken(minimumAuthenticationClassLevel: number | undefined): Promise<string> {\n const { token, refreshToken } = await this.getNewToken(minimumAuthenticationClassLevel ?? 0)\n this.cachedToken = token\n this.cachedRefreshToken = refreshToken\n return token\n }\n\n private async refreshAndCacheToken(refreshToken: string): Promise<{ token: string; type: RetrievedTokenType }> {\n if (this.debugLog) console.log(`Attempting to refresh bearer token ${this.debugCacheInfo()}`)\n return await this.authApi.refreshAuthenticationJWT(refreshToken).then(\n (authResult) => {\n if (!authResult.token) throw new Error('Internal error: refresh succeeded but no token was returned. Unsupported backend version?')\n this.cachedToken = authResult.token\n return { token: authResult.token, type: RetrievedTokenType.REFRESHED }\n },\n async () => ({ token: await this.getAndCacheNewToken(undefined), type: RetrievedTokenType.NEW })\n )\n }\n\n private async getNewToken(minimumAuthenticationClassLevel: number): Promise<{ token: string; refreshToken: string }> {\n if (this.debugLog) console.log(`Attempting to get new token for auth class ${minimumAuthenticationClassLevel} ${this.debugCacheInfo()}`)\n if (!!this.currentLongLivedSecret && (!this.currentLongLivedSecret.type || this.currentLongLivedSecret.type >= minimumAuthenticationClassLevel)) {\n if (this.debugLog) console.log('Using cached secret')\n const resultWithCachedSecret = await this.doGetTokenWithSecret(this.currentLongLivedSecret, minimumAuthenticationClassLevel)\n if ('success' in resultWithCachedSecret) {\n if (this.debugLog) console.log('New token using cached secret success')\n return resultWithCachedSecret.success\n } else if (\n resultWithCachedSecret.failure === DoGetTokenResultFailureReason.NEEDS_2FA &&\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION\n ) {\n if (this.debugLog) console.log('New token using cached secret requires 2fa')\n return this.askTotpAndGetToken(this.currentLongLivedSecret.value, minimumAuthenticationClassLevel)\n } else {\n if (this.debugLog) console.log('New token using cached secret failed')\n return this.askSecretAndGetToken(minimumAuthenticationClassLevel, true)\n }\n } else {\n if (this.debugLog) console.log('No cached credentials of correct auth class found')\n return this.askSecretAndGetToken(minimumAuthenticationClassLevel, true)\n }\n }\n\n private async askSecretAndGetToken(\n minimumAuthenticationClassLevel: number,\n passwordIsValidAs2fa: boolean\n ): Promise<{ token: string; refreshToken: string }> {\n const acceptedSecrets = [\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.LONG_LIVED_TOKEN ? [AuthSecretType.LONG_LIVED_TOKEN] : [],\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.SHORT_LIVED_TOKEN ? [AuthSecretType.SHORT_LIVED_TOKEN] : [],\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION &&\n (passwordIsValidAs2fa || minimumAuthenticationClassLevel <= ServerAuthenticationClass.PASSWORD)\n ? [AuthSecretType.PASSWORD]\n : [],\n ].flat()\n if (!acceptedSecrets.length)\n throw new Error('Internal error: no secret type is accepted for this request. Group may be misconfigured, or client may be outdated.')\n const attempts: AuthSecretDetails[] = []\n if (this.debugLog) console.log(`Asking for secret and getting token for auth class ${minimumAuthenticationClassLevel} ${this.debugCacheInfo()}`)\n while (true) {\n const secretDetails = await this.authSecretProvider.getSecret([...acceptedSecrets], attempts, minimumAuthenticationClassLevel > 0)\n if (!acceptedSecrets.includes(secretDetails.secretType))\n throw new Error(`Accepted secret types are ${JSON.stringify(acceptedSecrets)}, but got a secret of type ${secretDetails.secretType}.`)\n attempts.push(secretDetails)\n const result = await this.doGetTokenWithSecret(secretDetails, minimumAuthenticationClassLevel)\n if ('success' in result) {\n this.updateCachedSecret(secretDetails)\n return result.success\n } else if (result.failure == DoGetTokenResultFailureReason.NEEDS_2FA) {\n return this.askTotpAndGetToken(secretDetails.value, minimumAuthenticationClassLevel)\n } else if (secretDetails.value == AuthSecretType.PASSWORD && result.failure == DoGetTokenResultFailureReason.INVALID_AUTH_CLASS_LEVEL) {\n // If we tried a password, and it turns out that the user has 2fa not enabled next time we don't consider password valid\n return this.askSecretAndGetToken(minimumAuthenticationClassLevel, false)\n } // else retry\n }\n }\n\n private async askTotpAndGetToken(password: string, minimumAuthenticationClassLevel: number): Promise<{ token: string; refreshToken: string }> {\n if (minimumAuthenticationClassLevel > ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION)\n throw new Error(\n \"Internal error: asking for totp to login but minimumAuthenticationClassLevel is higher than TWO_FACTOR_AUTHENTICATION's level.\"\n )\n const attempts: AuthSecretDetails[] = []\n while (true) {\n const details = await this.authSecretProvider.getSecret([AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN], attempts, false)\n if (details.secretType != AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n throw new Error(`Was expecting a 2fa token but got a secret of type ${details.secretType}.`)\n attempts.push(details)\n const result = await this.doGetTokenWithSecret({ value: `${password}|${details.value}` }, minimumAuthenticationClassLevel)\n if ('success' in result) {\n this.updateCachedSecret({ value: password, secretType: AuthSecretType.PASSWORD })\n return result.success\n } else if (result.failure != DoGetTokenResultFailureReason.INVALID_2FA) {\n throw new Error(`Unexpected error while trying to login with (previously) valid password and 2fa token ${result.failure}.`)\n } // else retry\n }\n }\n\n private async doGetTokenWithSecret(\n secret: { value: string; oauthType?: OAuthThirdParty },\n minimumAuthenticationClassLevel: number\n ): Promise<DoGetTokenResult> {\n let authResultPromise: Promise<AuthenticationResponse>\n if ('oauthType' in secret && !!secret.oauthType) {\n authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value) // TODO add group id\n } else {\n authResultPromise = this.authApi.login({ username: this.login, password: secret.value }, this.groupId)\n }\n return authResultPromise.then(\n (authResult) => {\n const { token, refreshToken } = authResult\n if (!token || !refreshToken) throw new Error('Internal error: login succeeded but no token was returned. Unsupported backend version?')\n const claims = decodeJwtClaims(token)\n const authClassLevel = claims['tac']\n if (!authClassLevel || typeof authClassLevel !== 'number') {\n if (minimumAuthenticationClassLevel > 0) {\n throw new Error('Internal error: authClassLevel is not a number. Unsupported backend version?')\n } else return { success: { token, refreshToken } }\n }\n if (authClassLevel < minimumAuthenticationClassLevel) {\n return { failure: DoGetTokenResultFailureReason.INVALID_AUTH_CLASS_LEVEL }\n } else {\n return { success: { token, refreshToken } }\n }\n },\n (error) => {\n if (!(error instanceof XHRError)) throw error\n if (error.statusCode == 401 || error.statusCode == 412) {\n // Password is wrong (401) or unacceptable (e.g. too short, 412)\n return { failure: DoGetTokenResultFailureReason.INVALID_PW_OR_TOKEN }\n } else if (error.statusCode == 406) {\n // Password is correct, but 2fa token is not\n return { failure: DoGetTokenResultFailureReason.INVALID_2FA }\n } else if (error.statusCode == 417) {\n // Password is correct, but the user has 2fa enabled and no 2fa token was provided\n return { failure: DoGetTokenResultFailureReason.NEEDS_2FA }\n } else throw error\n }\n )\n }\n\n async switchedGroup(newGroupId: string): Promise<TokenProvider> {\n const groupSwitchedTokens = this.cachedRefreshToken\n ? await this.authApi.switchGroup(this.cachedRefreshToken, newGroupId).then(\n (response) => {\n if (!response.token || !response.refreshToken)\n throw new Error('Internal error: group switch succeeded but no token was returned. Unsupported backend version?')\n return { token: response.token, refreshToken: response.refreshToken }\n },\n () => ({ token: undefined, refreshToken: undefined })\n )\n : { token: undefined, refreshToken: undefined }\n return new TokenProvider(\n this.login,\n newGroupId,\n this.currentLongLivedSecret ? { value: this.currentLongLivedSecret.value, type: undefined } : undefined,\n groupSwitchedTokens.token,\n groupSwitchedTokens.refreshToken,\n this.authApi,\n this.authSecretProvider,\n this.debugLog\n )\n }\n\n private updateCachedSecret(details: AuthSecretDetails) {\n switch (details.secretType) {\n case AuthSecretType.PASSWORD:\n this.currentLongLivedSecret = { value: details.value, type: ServerAuthenticationClass.PASSWORD }\n break\n case AuthSecretType.LONG_LIVED_TOKEN:\n this.currentLongLivedSecret = { value: details.value, type: ServerAuthenticationClass.LONG_LIVED_TOKEN }\n break\n case AuthSecretType.EXTERNAL_AUTHENTICATION:\n if (longLivedOAuthTokens.has(details.oauthType)) {\n this.currentLongLivedSecret = {\n value: details.value,\n type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION,\n oauthType: details.oauthType,\n }\n }\n break\n }\n }\n}\ntype DoGetTokenResult = { success: { token: string; refreshToken: string } } | { failure: DoGetTokenResultFailureReason }\nenum DoGetTokenResultFailureReason {\n NEEDS_2FA,\n INVALID_2FA,\n INVALID_PW_OR_TOKEN,\n INVALID_AUTH_CLASS_LEVEL,\n}\nenum RetrievedTokenType {\n CACHED,\n REFRESHED,\n NEW,\n}\n\nenum SmartAuthServiceState {\n INITIAL,\n DONE_INITIAL,\n REATTEMPT,\n REATTEMPTED_WITH_NEW_UNBOUND_TOKEN,\n REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN,\n EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS,\n TERMINAL_ERROR,\n}\nclass SmartAuthService implements AuthService {\n private currentState:\n | { id: SmartAuthServiceState.INITIAL }\n | { id: SmartAuthServiceState.DONE_INITIAL; initialToken: string }\n | { id: SmartAuthServiceState.REATTEMPT; initialToken: string; initialError: Error }\n | { id: SmartAuthServiceState.REATTEMPTED_WITH_NEW_UNBOUND_TOKEN }\n | { id: SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN }\n | { id: SmartAuthServiceState.EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS; errorFromNewToken: Error }\n | { id: SmartAuthServiceState.TERMINAL_ERROR; error: Error } = { id: SmartAuthServiceState.INITIAL }\n\n constructor(private readonly tokenProvider: TokenProvider) {}\n\n async jwtGetter(): Promise<{ token: string; refreshToken: string | undefined }> {\n const token = await this.getAuthToken(undefined)\n return { token, refreshToken: undefined }\n }\n\n async getAuthHeaders(minimumAuthenticationClassLevel: number | undefined): Promise<Array<XHR.Header>> {\n return [new XHR.Header('Authorization', `Bearer ${await this.getAuthToken(minimumAuthenticationClassLevel)}`)]\n }\n\n private async getAuthToken(minimumAuthenticationClassLevel: number | undefined): Promise<string> {\n switch (this.currentState.id) {\n case SmartAuthServiceState.INITIAL:\n if (minimumAuthenticationClassLevel != undefined) {\n throw new Error('Illegal state: cannot ask for a specific auth class level at the first request attempt.')\n } else {\n const { token } = await this.tokenProvider.getCachedOrRefreshedOrNewToken()\n this.currentState = { id: SmartAuthServiceState.DONE_INITIAL, initialToken: token }\n return token\n }\n case SmartAuthServiceState.REATTEMPT:\n if (minimumAuthenticationClassLevel != undefined) {\n const token = await this.tokenProvider.getNewTokenWithClass(minimumAuthenticationClassLevel)\n this.currentState = { id: SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN }\n return token\n } else {\n const { token } = await this.tokenProvider.getCachedOrRefreshedOrNewToken()\n if (token == this.currentState.initialToken) throw this.currentState.initialError\n this.currentState = { id: SmartAuthServiceState.REATTEMPTED_WITH_NEW_UNBOUND_TOKEN }\n return token\n }\n case SmartAuthServiceState.EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS:\n if (minimumAuthenticationClassLevel != undefined) {\n const token = await this.tokenProvider.getNewTokenWithClass(minimumAuthenticationClassLevel)\n this.currentState = { id: SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN }\n return token\n } else throw this.currentState.errorFromNewToken\n case SmartAuthServiceState.TERMINAL_ERROR:\n throw this.currentState.error\n default:\n throw new Error(`Illegal state: cannot get token in state ${this.currentState.id}.`)\n }\n }\n\n invalidateHeader(error: Error): void {\n switch (this.currentState.id) {\n case SmartAuthServiceState.DONE_INITIAL:\n this.currentState = { id: SmartAuthServiceState.REATTEMPT, initialToken: this.currentState.initialToken, initialError: error }\n break\n case SmartAuthServiceState.REATTEMPTED_WITH_NEW_UNBOUND_TOKEN:\n this.currentState = { id: SmartAuthServiceState.EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS, errorFromNewToken: error }\n break\n case SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN:\n this.currentState = { id: SmartAuthServiceState.TERMINAL_ERROR, error: error }\n break\n default:\n throw new Error(`Illegal state: cannot invalidate header in state ${this.currentState.id}.`)\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"AES.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AES.ts"],"names":[],"mappings":";;;;;;;;;;;;AAA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C,CAAA;QACrF,CAAC,CAAC,CAAA;IACJ,CAAC;IAED;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,MAAqB,EAAE,MAA6C;QAC5E,OAAO,IAAI,OAAO,CAAC,CAAC,OAAkC,EAAE,MAA4B,EAAE,EAAE;YACtF,MAAM,WAAW,GAAG,IAAI,CAAA;YACxB,MAAM,SAAS,GAAe,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;YACpD,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM;iBACtB,SAAS,CAAC,MAAa,EAAE,MAAa,EAAE,IAAI,CAAC,eAAe,EAAE,WAAW,EAAE,SAAS,CAAC;iBACrF,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACb,IAAI,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE;oBACpF,OAAO,CAAC,IAAI,CAAC,iBAAiB,IAAA,cAAM,EAAC,MAAM,CAAC,SAAS,CAAC,CAAA;iBACvD;gBACD,MAAM,GAAG,CAAA;YACX,CAAC,CAAC;iBACD,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC1B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAhMD,oCAgMC;AAEY,QAAA,GAAG,GAAG,IAAI,YAAY,EAAE,CAAA","sourcesContent":["import { appendBuffer, hex2ua, ua2hex } from '../utils'\n\nexport interface AESUtils {\n encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>\n\n decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>\n\n /**\n * @deprecated this method is not correct: in some cases decryption may not fail even if the wrong key is used: if the\n * first provided keys are wrong and the last one is correct the decryption will succeed for sure, but there is a small\n * chance that you will get garbage\n */\n decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n\n generateCryptoKey(toHex: true): Promise<string>\n\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey>\n\n generateIV(ivByteLength: number): Uint8Array\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey>\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey>\n}\n\nexport class AESUtilsImpl implements AESUtils {\n /********* AES Config **********/\n ivLength = 16\n aesAlgorithmEncryptName = 'AES-CBC'\n\n aesKeyGenParams: AesKeyGenParams = {\n name: 'AES-CBC',\n length: 256,\n }\n private crypto: Crypto\n private _debug: boolean = false\n\n set debug(value: boolean) {\n this._debug = value\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n async encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.encrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (plainData instanceof Uint8Array) {\n const buffer = plainData.buffer\n plainData = (buffer.byteLength > plainData.byteLength ? buffer.slice(0, plainData.byteLength) : buffer) as ArrayBuffer\n }\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: this.generateIV(this.ivLength),\n }\n this._debug && console.log(`encrypt ${ua2hex(plainData)} with ${rawKey}`)\n this.crypto.subtle\n .encrypt(\n {\n ...aesAlgorithmEncrypt,\n } /* some ill behaved implementations change the values in place */,\n cryptoKey,\n plainData\n )\n .then(\n (cipherData) => {\n this._debug && console.log(`cipherData: ${ua2hex(cipherData)}`)\n return resolve(appendBuffer(aesAlgorithmEncrypt.iv.buffer as ArrayBuffer, cipherData))\n },\n (err) => reject('AES encryption failed: ' + err)\n )\n })\n }\n\n async decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.decrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (!cryptoKey) {\n return reject('No crypto key provided for decryption')\n }\n const encryptedDataUint8 = encryptedData instanceof ArrayBuffer ? new Uint8Array(encryptedData) : encryptedData\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: encryptedDataUint8.subarray(0, this.ivLength),\n\n /*\n * IF THIS BIT OF CODE PRODUCES A DOMEXCEPTION CODE 0 ERROR, IT MIGHT BE RELATED TO THIS:\n *\n * NOTOK:\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[hcpartyId] && hcparty.hcPartyKeys[hcpartyId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + hcpartyId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[hcpartyId][1];\n *\n * SHOULD BE:\n * var delegatorId = patient.delegations[hcpartyId][0].owner;\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[delegatorId] && hcparty.hcPartyKeys[delegatorId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + delegatorId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[delegatorId][1];\n */\n }\n this._debug && console.log(`decrypt ${ua2hex(encryptedData)} with ${rawKey}`)\n this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length)).then(\n (decipheredData) => {\n this._debug && console.log(`decipheredData: ${ua2hex(decipheredData)}`)\n resolve(decipheredData)\n },\n (err) => {\n reject(new Error('AES decryption failed: ' + err))\n }\n )\n })\n }\n\n async decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer> {\n try {\n return this.decrypt(cryptoKeys[0], uint8Array)\n } catch (e) {\n if (cryptoKeys.length > 1) {\n return this.decryptSome(cryptoKeys.slice(1), uint8Array)\n } else {\n throw e\n }\n }\n }\n\n // generate an AES key\n // noinspection JSUnusedGlobalSymbols\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n generateCryptoKey(toHex: true): Promise<string>\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey> {\n return new Promise((resolve: (value: CryptoKey | string) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const cryptoKeyPromise: Promise<CryptoKey> = this.crypto.subtle.generateKey(this.aesKeyGenParams, extractable, keyUsages) as Promise<CryptoKey>\n return toHex === undefined || !toHex\n ? cryptoKeyPromise.then(resolve, reject)\n : cryptoKeyPromise.then((k) => this.exportKey(k, 'raw'), reject).then((raw) => resolve(ua2hex(raw)), reject)\n })\n }\n\n // noinspection JSMethodCanBeStatic\n generateIV(ivByteLength: number): Uint8Array {\n return new Uint8Array(this.crypto.getRandomValues(new Uint8Array(ivByteLength)))\n }\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey> {\n return new Promise((resolve: (value: ArrayBuffer | JsonWebKey) => any, reject: (reason: any) => any) => {\n return this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey> {\n return new Promise((resolve: (value: CryptoKey) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n return this.crypto.subtle\n .importKey(format as any, aesKey as any, this.aesKeyGenParams, extractable, keyUsages)\n .catch((err) => {\n if (format == 'raw' && (aesKey instanceof ArrayBuffer || ArrayBuffer.isView(aesKey))) {\n console.warn(`Import of key ${ua2hex(aesKey)} failed`)\n }\n throw err\n })\n .then(resolve, reject)\n })\n }\n}\n\nexport const AES = new AESUtilsImpl()\n"]}
1
+ {"version":3,"file":"AES.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AES.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAAuD;AAmEvD,MAAa,YAAY;IAYvB,IAAI,KAAK,CAAC,KAAc;QACtB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,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;QAfvI,iCAAiC;QACjC,aAAQ,GAAG,EAAE,CAAA;QACb,4BAAuB,GAAG,SAAS,CAAA;QAEnC,oBAAe,GAAoB;YACjC,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,GAAG;SACZ,CAAA;QAEO,WAAM,GAAY,KAAK,CAAA;QAO7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAEK,iBAAiB,CAAC,MAAc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M,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;oBACrF,OAAO,CAAC,IAAI,CAAC,iBAAiB,IAAA,cAAM,EAAC,MAAM,CAAC,SAAS,CAAC,CAAA;gBACxD,CAAC;gBACD,MAAM,GAAG,CAAA;YACX,CAAC,CAAC;iBACD,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC1B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAhMD,oCAgMC;AAEY,QAAA,GAAG,GAAG,IAAI,YAAY,EAAE,CAAA","sourcesContent":["import { appendBuffer, hex2ua, ua2hex } from '../utils'\n\nexport interface AESUtils {\n encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>\n\n decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>\n\n /**\n * @deprecated this method is not correct: in some cases decryption may not fail even if the wrong key is used: if the\n * first provided keys are wrong and the last one is correct the decryption will succeed for sure, but there is a small\n * chance that you will get garbage\n */\n decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n\n generateCryptoKey(toHex: true): Promise<string>\n\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey>\n\n generateIV(ivByteLength: number): Uint8Array\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey>\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey>\n}\n\nexport class AESUtilsImpl implements AESUtils {\n /********* AES Config **********/\n ivLength = 16\n aesAlgorithmEncryptName = 'AES-CBC'\n\n aesKeyGenParams: AesKeyGenParams = {\n name: 'AES-CBC',\n length: 256,\n }\n private crypto: Crypto\n private _debug: boolean = false\n\n set debug(value: boolean) {\n this._debug = value\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n async encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.encrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (plainData instanceof Uint8Array) {\n const buffer = plainData.buffer\n plainData = (buffer.byteLength > plainData.byteLength ? buffer.slice(0, plainData.byteLength) : buffer) as ArrayBuffer\n }\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: this.generateIV(this.ivLength),\n }\n this._debug && console.log(`encrypt ${ua2hex(plainData)} with ${rawKey}`)\n this.crypto.subtle\n .encrypt(\n {\n ...aesAlgorithmEncrypt,\n } /* some ill behaved implementations change the values in place */,\n cryptoKey,\n plainData\n )\n .then(\n (cipherData) => {\n this._debug && console.log(`cipherData: ${ua2hex(cipherData)}`)\n return resolve(appendBuffer(aesAlgorithmEncrypt.iv.buffer as ArrayBuffer, cipherData))\n },\n (err) => reject('AES encryption failed: ' + err)\n )\n })\n }\n\n async decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.decrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (!cryptoKey) {\n return reject('No crypto key provided for decryption')\n }\n const encryptedDataUint8 = encryptedData instanceof ArrayBuffer ? new Uint8Array(encryptedData) : encryptedData\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: encryptedDataUint8.subarray(0, this.ivLength),\n\n /*\n * IF THIS BIT OF CODE PRODUCES A DOMEXCEPTION CODE 0 ERROR, IT MIGHT BE RELATED TO THIS:\n *\n * NOTOK:\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[hcpartyId] && hcparty.hcPartyKeys[hcpartyId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + hcpartyId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[hcpartyId][1];\n *\n * SHOULD BE:\n * var delegatorId = patient.delegations[hcpartyId][0].owner;\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[delegatorId] && hcparty.hcPartyKeys[delegatorId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + delegatorId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[delegatorId][1];\n */\n }\n this._debug && console.log(`decrypt ${ua2hex(encryptedData)} with ${rawKey}`)\n this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length)).then(\n (decipheredData) => {\n this._debug && console.log(`decipheredData: ${ua2hex(decipheredData)}`)\n resolve(decipheredData)\n },\n (err) => {\n reject(new Error('AES decryption failed: ' + err))\n }\n )\n })\n }\n\n async decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer> {\n try {\n return this.decrypt(cryptoKeys[0], uint8Array)\n } catch (e) {\n if (cryptoKeys.length > 1) {\n return this.decryptSome(cryptoKeys.slice(1), uint8Array)\n } else {\n throw e\n }\n }\n }\n\n // generate an AES key\n // noinspection JSUnusedGlobalSymbols\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n generateCryptoKey(toHex: true): Promise<string>\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey> {\n return new Promise((resolve: (value: CryptoKey | string) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const cryptoKeyPromise: Promise<CryptoKey> = this.crypto.subtle.generateKey(this.aesKeyGenParams, extractable, keyUsages) as Promise<CryptoKey>\n return toHex === undefined || !toHex\n ? cryptoKeyPromise.then(resolve, reject)\n : cryptoKeyPromise.then((k) => this.exportKey(k, 'raw'), reject).then((raw) => resolve(ua2hex(raw)), reject)\n })\n }\n\n // noinspection JSMethodCanBeStatic\n generateIV(ivByteLength: number): Uint8Array {\n return new Uint8Array(this.crypto.getRandomValues(new Uint8Array(ivByteLength)))\n }\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey> {\n return new Promise((resolve: (value: ArrayBuffer | JsonWebKey) => any, reject: (reason: any) => any) => {\n return this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey> {\n return new Promise((resolve: (value: CryptoKey) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n return this.crypto.subtle\n .importKey(format as any, aesKey as any, this.aesKeyGenParams, extractable, keyUsages)\n .catch((err) => {\n if (format == 'raw' && (aesKey instanceof ArrayBuffer || ArrayBuffer.isView(aesKey))) {\n console.warn(`Import of key ${ua2hex(aesKey)} failed`)\n }\n throw err\n })\n .then(resolve, reject)\n })\n }\n}\n\nexport const AES = new AESUtilsImpl()\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"AccessControlKeysHeadersProvider.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AccessControlKeysHeadersProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAG9B,QAAA,0BAA0B,GAAG,2BAA2B,CAAA;AAErE;;GAEG;AACH,MAAa,gCAAgC;IAC3C,YAA6B,mBAAwC;QAAxC,wBAAmB,GAAnB,mBAAmB,CAAqB;IAAG,CAAC;IAEzE,iGAAiG;IACjG;;;;OAIG;IACG,2BAA2B,CAAC,cAA4B,EAAE,UAAwC;;YACtG,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,2BAA2B,CAAC,UAAU,CAAC,CAAA;YACrE,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;gBAAE,OAAO,CAAC,GAAG,cAAc,EAAE,GAAG,UAAU,CAAC,CAAA;;gBAC/D,OAAO,cAAc,CAAA;QAC5B,CAAC;KAAA;IAEK,2BAA2B,CAAC,UAAwC;;YACxE,MAAM,sBAAsB,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,yBAAyB,CAAC,UAAU,CAAC,CAAA;YACnG,IAAI,sBAAsB,EAAE;gBAC1B,OAAO,CAAC,IAAI,SAAG,CAAC,MAAM,CAAC,kCAA0B,EAAE,sBAAsB,CAAC,CAAC,CAAA;aAC5E;iBAAM;gBACL,OAAO,EAAE,CAAA;aACV;QACH,CAAC;KAAA;CACF;AAvBD,4EAuBC","sourcesContent":["import { ExchangeDataManager } from './ExchangeDataManager'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\n\nexport const ACCESS_CONTROL_KEYS_HEADER = 'Icure-Access-Control-Keys'\n\n/**\n * @internal this class is intended for internal use only and may be changed without notice.\n */\nexport class AccessControlKeysHeadersProvider {\n constructor(private readonly exchangeDataManager: ExchangeDataManager) {}\n\n // This will be enough only as long as we don't use the entities sfks in the access control keys.\n /**\n * Add the access control keys headers to the provided initial headers, allowing access control on users with anonymous delegations.\n * @param initialHeaders the initial headers\n * @param entityType the type of entity which the user is attempting to retrieve.\n */\n async addAccessControlKeysHeaders(initialHeaders: XHR.Header[], entityType: EntityWithDelegationTypeName): Promise<XHR.Header[]> {\n const newHeaders = await this.getAccessControlKeysHeaders(entityType)\n if (newHeaders.length > 0) return [...initialHeaders, ...newHeaders]\n else return initialHeaders\n }\n\n async getAccessControlKeysHeaders(entityType: EntityWithDelegationTypeName): Promise<XHR.Header[]> {\n const accessControlKeysValue = await this.exchangeDataManager.getAccessControlKeysValue(entityType)\n if (accessControlKeysValue) {\n return [new XHR.Header(ACCESS_CONTROL_KEYS_HEADER, accessControlKeysValue)]\n } else {\n return []\n }\n }\n}\n"]}
1
+ {"version":3,"file":"AccessControlKeysHeadersProvider.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AccessControlKeysHeadersProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAG9B,QAAA,0BAA0B,GAAG,2BAA2B,CAAA;AAErE;;GAEG;AACH,MAAa,gCAAgC;IAC3C,YAA6B,mBAAwC;QAAxC,wBAAmB,GAAnB,mBAAmB,CAAqB;IAAG,CAAC;IAEzE,iGAAiG;IACjG;;;;OAIG;IACG,2BAA2B,CAAC,cAA4B,EAAE,UAAwC;;YACtG,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,2BAA2B,CAAC,UAAU,CAAC,CAAA;YACrE,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;gBAAE,OAAO,CAAC,GAAG,cAAc,EAAE,GAAG,UAAU,CAAC,CAAA;;gBAC/D,OAAO,cAAc,CAAA;QAC5B,CAAC;KAAA;IAEK,2BAA2B,CAAC,UAAwC;;YACxE,MAAM,sBAAsB,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,yBAAyB,CAAC,UAAU,CAAC,CAAA;YACnG,IAAI,sBAAsB,EAAE,CAAC;gBAC3B,OAAO,CAAC,IAAI,SAAG,CAAC,MAAM,CAAC,kCAA0B,EAAE,sBAAsB,CAAC,CAAC,CAAA;YAC7E,CAAC;iBAAM,CAAC;gBACN,OAAO,EAAE,CAAA;YACX,CAAC;QACH,CAAC;KAAA;CACF;AAvBD,4EAuBC","sourcesContent":["import { ExchangeDataManager } from './ExchangeDataManager'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\n\nexport const ACCESS_CONTROL_KEYS_HEADER = 'Icure-Access-Control-Keys'\n\n/**\n * @internal this class is intended for internal use only and may be changed without notice.\n */\nexport class AccessControlKeysHeadersProvider {\n constructor(private readonly exchangeDataManager: ExchangeDataManager) {}\n\n // This will be enough only as long as we don't use the entities sfks in the access control keys.\n /**\n * Add the access control keys headers to the provided initial headers, allowing access control on users with anonymous delegations.\n * @param initialHeaders the initial headers\n * @param entityType the type of entity which the user is attempting to retrieve.\n */\n async addAccessControlKeysHeaders(initialHeaders: XHR.Header[], entityType: EntityWithDelegationTypeName): Promise<XHR.Header[]> {\n const newHeaders = await this.getAccessControlKeysHeaders(entityType)\n if (newHeaders.length > 0) return [...initialHeaders, ...newHeaders]\n else return initialHeaders\n }\n\n async getAccessControlKeysHeaders(entityType: EntityWithDelegationTypeName): Promise<XHR.Header[]> {\n const accessControlKeysValue = await this.exchangeDataManager.getAccessControlKeysValue(entityType)\n if (accessControlKeysValue) {\n return [new XHR.Header(ACCESS_CONTROL_KEYS_HEADER, accessControlKeysValue)]\n } else {\n return []\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"AccessControlSecretUtils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AccessControlSecretUtils.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,wFAAmH;AACnH,oCAAmD;AAEnD,MAAM,+BAA+B,GAAG,EAAE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AC,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAA;aACjE;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;IAEK,2BAA2B,CAAC,oBAA8B,EAAE,cAA4C;;YAC5G,MAAM,UAAU,GAAG,IAAI,UAAU,CAAC,oBAAoB,CAAC,MAAM,GAAG,IAAI,CAAC,2BAA2B,CAAC,CAAA;YACjG,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,oBAAoB,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBACpD,MAAM,mBAAmB,GAAG,oBAAoB,CAAC,CAAC,CAAC,CAAA;gBACnD,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,mBAAmB,EAAE,cAAc,CAAC,CAAA;gBAC/E,UAAU,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,2BAA2B,CAAC,CAAA;aAC1E;YACD,OAAO,IAAA,cAAM,EAAC,UAAU,CAAC,CAAA;QAC3B,CAAC;KAAA;CACF;AA5DD,4DA4DC","sourcesContent":["import { CryptoPrimitives } from './CryptoPrimitives'\nimport { EntityWithDelegationTypeName, entityWithDelegationTypeNames } from '../utils/EntityWithDelegationTypeName'\nimport { ua2b64, ua2hex, utf8_2ua } from '../utils'\n\nconst ACCESS_CONTROL_KEY_LENGTH_BYTES = 16\n\n/**\n * @internal this class is intended for internal use only and may be changed without notice.\n */\nexport class AccessControlSecretUtils {\n constructor(private readonly primitives: CryptoPrimitives) {}\n\n /**\n * Size of the access control keys returned by this class.\n */\n get accessControlKeyLengthBytes(): number {\n return ACCESS_CONTROL_KEY_LENGTH_BYTES\n }\n\n /**\n * Get the access control key to use for entities of the provided type and using the provided secret foreign key. The combination of secret foreign\n * keys and entity type ensures that unauthorised people will not be able to draw links between entities of different types of data or different\n * confidentiality levels.\n * These keys will be sent to the icure server for access control of data owners which require anonymous delegations.\n * @param accessControlSecret an access control secret\n * @param entityTypeName an entity type name\n */\n async accessControlKeyFor(accessControlSecret: string, entityTypeName: EntityWithDelegationTypeName): Promise<ArrayBuffer> {\n return (await this.primitives.sha256(utf8_2ua(accessControlSecret + entityTypeName))).slice(0, ACCESS_CONTROL_KEY_LENGTH_BYTES)\n }\n\n async allAccessControlKeyFor(accessControlSecret: string): Promise<ArrayBuffer[]> {\n const res: ArrayBuffer[] = []\n for (const entityTypeName of entityWithDelegationTypeNames) {\n res.push((await this.primitives.sha256(utf8_2ua(accessControlSecret + entityTypeName))).slice(0, ACCESS_CONTROL_KEY_LENGTH_BYTES))\n }\n return res\n }\n\n /**\n * Get value to use as key in secure delegations for entities of the provided type with the provided secret foreign key. The combination of secret\n * foreign keys and entity type ensures that unauthorised people will not be able to draw links between entities of different types of data or\n * different confidentiality levels.\n * These keys will be used in the secure delegations map of security metadata.\n * @param accessControlSecret an access control secret\n * @param entityTypeName an entity type name\n */\n async secureDelegationKeyFor(accessControlSecret: string, entityTypeName: EntityWithDelegationTypeName): Promise<string> {\n return ua2hex(await this.primitives.sha256(await this.accessControlKeyFor(accessControlSecret, entityTypeName)))\n }\n\n async allSecureDelegationKeysFor(accessControlSecret: string): Promise<string[]> {\n const accessControlKeys = await this.allAccessControlKeyFor(accessControlSecret)\n const res: string[] = []\n for (const accessControlKey of accessControlKeys) {\n res.push(ua2hex(await this.primitives.sha256(accessControlKey)))\n }\n return res\n }\n\n async getEncodedAccessControlKeys(accessControlSecrets: string[], entityTypeName: EntityWithDelegationTypeName): Promise<string> {\n const fullBuffer = new Uint8Array(accessControlSecrets.length * this.accessControlKeyLengthBytes)\n for (let i = 0; i < accessControlSecrets.length; i++) {\n const accessControlSecret = accessControlSecrets[i]\n const key = await this.accessControlKeyFor(accessControlSecret, entityTypeName)\n fullBuffer.set(new Uint8Array(key), i * this.accessControlKeyLengthBytes)\n }\n return ua2b64(fullBuffer)\n }\n}\n"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1D,MAAM,iBAAiB,GAAG,MAAM,IAAI,CAAC,sBAAsB,CAAC,mBAAmB,CAAC,CAAA;YAChF,MAAM,GAAG,GAAa,EAAE,CAAA;YACxB,KAAK,MAAM,gBAAgB,IAAI,iBAAiB,EAAE,CAAC;gBACjD,GAAG,CAAC,IAAI,CAAC,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAA;YAClE,CAAC;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;IAEK,2BAA2B,CAAC,oBAA8B,EAAE,cAA4C;;YAC5G,MAAM,UAAU,GAAG,IAAI,UAAU,CAAC,oBAAoB,CAAC,MAAM,GAAG,IAAI,CAAC,2BAA2B,CAAC,CAAA;YACjG,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,oBAAoB,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACrD,MAAM,mBAAmB,GAAG,oBAAoB,CAAC,CAAC,CAAC,CAAA;gBACnD,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,mBAAmB,EAAE,cAAc,CAAC,CAAA;gBAC/E,UAAU,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,2BAA2B,CAAC,CAAA;YAC3E,CAAC;YACD,OAAO,IAAA,cAAM,EAAC,UAAU,CAAC,CAAA;QAC3B,CAAC;KAAA;CACF;AA5DD,4DA4DC","sourcesContent":["import { CryptoPrimitives } from './CryptoPrimitives'\nimport { EntityWithDelegationTypeName, entityWithDelegationTypeNames } from '../utils/EntityWithDelegationTypeName'\nimport { ua2b64, ua2hex, utf8_2ua } from '../utils'\n\nconst ACCESS_CONTROL_KEY_LENGTH_BYTES = 16\n\n/**\n * @internal this class is intended for internal use only and may be changed without notice.\n */\nexport class AccessControlSecretUtils {\n constructor(private readonly primitives: CryptoPrimitives) {}\n\n /**\n * Size of the access control keys returned by this class.\n */\n get accessControlKeyLengthBytes(): number {\n return ACCESS_CONTROL_KEY_LENGTH_BYTES\n }\n\n /**\n * Get the access control key to use for entities of the provided type and using the provided secret foreign key. The combination of secret foreign\n * keys and entity type ensures that unauthorised people will not be able to draw links between entities of different types of data or different\n * confidentiality levels.\n * These keys will be sent to the icure server for access control of data owners which require anonymous delegations.\n * @param accessControlSecret an access control secret\n * @param entityTypeName an entity type name\n */\n async accessControlKeyFor(accessControlSecret: string, entityTypeName: EntityWithDelegationTypeName): Promise<ArrayBuffer> {\n return (await this.primitives.sha256(utf8_2ua(accessControlSecret + entityTypeName))).slice(0, ACCESS_CONTROL_KEY_LENGTH_BYTES)\n }\n\n async allAccessControlKeyFor(accessControlSecret: string): Promise<ArrayBuffer[]> {\n const res: ArrayBuffer[] = []\n for (const entityTypeName of entityWithDelegationTypeNames) {\n res.push((await this.primitives.sha256(utf8_2ua(accessControlSecret + entityTypeName))).slice(0, ACCESS_CONTROL_KEY_LENGTH_BYTES))\n }\n return res\n }\n\n /**\n * Get value to use as key in secure delegations for entities of the provided type with the provided secret foreign key. The combination of secret\n * foreign keys and entity type ensures that unauthorised people will not be able to draw links between entities of different types of data or\n * different confidentiality levels.\n * These keys will be used in the secure delegations map of security metadata.\n * @param accessControlSecret an access control secret\n * @param entityTypeName an entity type name\n */\n async secureDelegationKeyFor(accessControlSecret: string, entityTypeName: EntityWithDelegationTypeName): Promise<string> {\n return ua2hex(await this.primitives.sha256(await this.accessControlKeyFor(accessControlSecret, entityTypeName)))\n }\n\n async allSecureDelegationKeysFor(accessControlSecret: string): Promise<string[]> {\n const accessControlKeys = await this.allAccessControlKeyFor(accessControlSecret)\n const res: string[] = []\n for (const accessControlKey of accessControlKeys) {\n res.push(ua2hex(await this.primitives.sha256(accessControlKey)))\n }\n return res\n }\n\n async getEncodedAccessControlKeys(accessControlSecrets: string[], entityTypeName: EntityWithDelegationTypeName): Promise<string> {\n const fullBuffer = new Uint8Array(accessControlSecrets.length * this.accessControlKeyLengthBytes)\n for (let i = 0; i < accessControlSecrets.length; i++) {\n const accessControlSecret = accessControlSecrets[i]\n const key = await this.accessControlKeyFor(accessControlSecret, entityTypeName)\n fullBuffer.set(new Uint8Array(key), i * this.accessControlKeyLengthBytes)\n }\n return ua2b64(fullBuffer)\n }\n}\n"]}
@@ -37,8 +37,8 @@ class BaseExchangeDataManager {
37
37
  * data owner.
38
38
  */
39
39
  getAllExchangeDataForCurrentDataOwnerIfAllowed() {
40
- var _a, _b;
41
40
  return __awaiter(this, void 0, void 0, function* () {
41
+ var _a, _b;
42
42
  if (!this.selfRequiresAnonymousDelegations)
43
43
  return undefined;
44
44
  const dataOwnerId = yield this.dataOwnerApi.getCurrentDataOwnerId();
@@ -201,8 +201,8 @@ class BaseExchangeDataManager {
201
201
  });
202
202
  }
203
203
  tryDecrypt(encryptedData, decryptionKeys) {
204
- var _a;
205
204
  return __awaiter(this, void 0, void 0, function* () {
205
+ var _a;
206
206
  const decryptionKeysWithV2Fp = Object.keys(decryptionKeys).reduce((prev, fp) => {
207
207
  return Object.assign(Object.assign({}, prev), { [(0, utils_2.fingerprintIsV1)(fp) ? (0, utils_2.fingerprintV1toV2)(fp) : fp]: decryptionKeys[fp] });
208
208
  }, {});
@@ -227,9 +227,9 @@ class BaseExchangeDataManager {
227
227
  * @param optionalAttributes optional precalculated attributes for the creation of data
228
228
  * @return the newly created exchange data, and its decrypted exchange key and access control secret.
229
229
  */
230
- createExchangeData(delegateId, signatureKeys, encryptionKeys, optionalAttributes = {}) {
231
- var _a;
232
- return __awaiter(this, void 0, void 0, function* () {
230
+ createExchangeData(delegateId_1, signatureKeys_1, encryptionKeys_1) {
231
+ return __awaiter(this, arguments, void 0, function* (delegateId, signatureKeys, encryptionKeys, optionalAttributes = {}) {
232
+ var _a;
233
233
  if (!Object.keys(encryptionKeys).length) {
234
234
  throw new Error('Must specify at least one encryption key ');
235
235
  }
@@ -307,9 +307,9 @@ class BaseExchangeDataManager {
307
307
  /**
308
308
  * Same as [tryUpdateExchangeData] but the decrypted content is already provided.
309
309
  */
310
- updateExchangeDataWithRawDecryptedContent({ exchangeData, newEncryptionKeys, rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey, newDelegatorSignatureKeys, }) {
311
- var _a;
312
- return __awaiter(this, void 0, void 0, function* () {
310
+ updateExchangeDataWithRawDecryptedContent(_a) {
311
+ return __awaiter(this, arguments, void 0, function* ({ exchangeData, newEncryptionKeys, rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey, newDelegatorSignatureKeys, }) {
312
+ var _b;
313
313
  const self = yield this.dataOwnerApi.getCurrentDataOwnerId();
314
314
  const exchangeKey = yield this.importExchangeKey(new Uint8Array(rawExchangeKey));
315
315
  const accessControlSecret = yield this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret));
@@ -318,7 +318,7 @@ class BaseExchangeDataManager {
318
318
  const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret));
319
319
  const existingSharedSignatureKeyEntries = new Set(Object.keys(exchangeData.sharedSignatureKey));
320
320
  const missingEntries = Object.keys(newEncryptionKeys).filter((fp) => !existingAcsEntries.has(fp) || !existingExchangeKeyEntries.has(fp) || !existingSharedSignatureKeyEntries.has(fp));
321
- const existingDelegatorSignatureEntries = new Set(Object.keys((_a = exchangeData.delegatorSignature) !== null && _a !== void 0 ? _a : {}));
321
+ const existingDelegatorSignatureEntries = new Set(Object.keys((_b = exchangeData.delegatorSignature) !== null && _b !== void 0 ? _b : {}));
322
322
  const missingDelegatorSignatureEntries = exchangeData.delegator == self ? Object.keys(newDelegatorSignatureKeys).filter((fp) => !existingDelegatorSignatureEntries.has(fp)) : [];
323
323
  if (!missingEntries.length && !missingDelegatorSignatureEntries.length)
324
324
  return { exchangeData, exchangeKey, accessControlSecret };
@@ -457,8 +457,8 @@ class BaseExchangeDataManager {
457
457
  });
458
458
  }
459
459
  verifyDelegatorSignature(exchangeData, decryptedSharedSignatureKey, verificationKeys) {
460
- var _a;
461
460
  return __awaiter(this, void 0, void 0, function* () {
461
+ var _a;
462
462
  const delegatorSignatureData = yield this.bytesToSignForDelegatorSignature({
463
463
  sharedSignatureKey: decryptedSharedSignatureKey,
464
464
  });