@icure/api 7.0.0-beta.3 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/icc-api/api/IccAccesslogApi.js +2 -1
  2. package/icc-api/api/IccAccesslogApi.js.map +1 -1
  3. package/icc-api/api/IccAgendaApi.js +2 -1
  4. package/icc-api/api/IccAgendaApi.js.map +1 -1
  5. package/icc-api/api/IccAnonymousAccessApi.js +2 -1
  6. package/icc-api/api/IccAnonymousAccessApi.js.map +1 -1
  7. package/icc-api/api/IccApplicationsettingsApi.js +2 -1
  8. package/icc-api/api/IccApplicationsettingsApi.js.map +1 -1
  9. package/icc-api/api/IccArticleApi.js +2 -1
  10. package/icc-api/api/IccArticleApi.js.map +1 -1
  11. package/icc-api/api/IccAuthApi.d.ts +23 -0
  12. package/icc-api/api/IccAuthApi.js +59 -2
  13. package/icc-api/api/IccAuthApi.js.map +1 -1
  14. package/icc-api/api/IccBeefactApi.js +2 -1
  15. package/icc-api/api/IccBeefactApi.js.map +1 -1
  16. package/icc-api/api/IccBekmehrApi.js +2 -1
  17. package/icc-api/api/IccBekmehrApi.js.map +1 -1
  18. package/icc-api/api/IccBeresultexportApi.js +2 -1
  19. package/icc-api/api/IccBeresultexportApi.js.map +1 -1
  20. package/icc-api/api/IccBeresultimportApi.js +2 -1
  21. package/icc-api/api/IccBeresultimportApi.js.map +1 -1
  22. package/icc-api/api/IccBesamv2Api.d.ts +6 -0
  23. package/icc-api/api/IccBesamv2Api.js +15 -1
  24. package/icc-api/api/IccBesamv2Api.js.map +1 -1
  25. package/icc-api/api/IccCalendarItemApi.js +2 -1
  26. package/icc-api/api/IccCalendarItemApi.js.map +1 -1
  27. package/icc-api/api/IccCalendarItemTypeApi.js +2 -1
  28. package/icc-api/api/IccCalendarItemTypeApi.js.map +1 -1
  29. package/icc-api/api/IccClassificationApi.js +2 -1
  30. package/icc-api/api/IccClassificationApi.js.map +1 -1
  31. package/icc-api/api/IccClassificationTemplateApi.js +2 -1
  32. package/icc-api/api/IccClassificationTemplateApi.js.map +1 -1
  33. package/icc-api/api/IccCodeApi.js +2 -1
  34. package/icc-api/api/IccCodeApi.js.map +1 -1
  35. package/icc-api/api/IccContactApi.d.ts +6 -0
  36. package/icc-api/api/IccContactApi.js +26 -1
  37. package/icc-api/api/IccContactApi.js.map +1 -1
  38. package/icc-api/api/IccDataownerApi.js +2 -1
  39. package/icc-api/api/IccDataownerApi.js.map +1 -1
  40. package/icc-api/api/IccDeviceApi.js +2 -1
  41. package/icc-api/api/IccDeviceApi.js.map +1 -1
  42. package/icc-api/api/IccDoctemplateApi.js +2 -1
  43. package/icc-api/api/IccDoctemplateApi.js.map +1 -1
  44. package/icc-api/api/IccDocumentApi.d.ts +6 -4
  45. package/icc-api/api/IccDocumentApi.js +10 -6
  46. package/icc-api/api/IccDocumentApi.js.map +1 -1
  47. package/icc-api/api/IccDocumentTemplateApi.js +2 -1
  48. package/icc-api/api/IccDocumentTemplateApi.js.map +1 -1
  49. package/icc-api/api/IccEntityrefApi.js +2 -1
  50. package/icc-api/api/IccEntityrefApi.js.map +1 -1
  51. package/icc-api/api/IccEntitytemplateApi.js +2 -1
  52. package/icc-api/api/IccEntitytemplateApi.js.map +1 -1
  53. package/icc-api/api/IccFormApi.js +2 -1
  54. package/icc-api/api/IccFormApi.js.map +1 -1
  55. package/icc-api/api/IccFrontendmigrationApi.js +2 -1
  56. package/icc-api/api/IccFrontendmigrationApi.js.map +1 -1
  57. package/icc-api/api/IccGroupApi.d.ts +6 -0
  58. package/icc-api/api/IccGroupApi.js +15 -1
  59. package/icc-api/api/IccGroupApi.js.map +1 -1
  60. package/icc-api/api/IccHcpartyApi.js +2 -1
  61. package/icc-api/api/IccHcpartyApi.js.map +1 -1
  62. package/icc-api/api/IccHelementApi.js +2 -1
  63. package/icc-api/api/IccHelementApi.js.map +1 -1
  64. package/icc-api/api/IccIcureApi.js +2 -1
  65. package/icc-api/api/IccIcureApi.js.map +1 -1
  66. package/icc-api/api/IccInsuranceApi.js +2 -1
  67. package/icc-api/api/IccInsuranceApi.js.map +1 -1
  68. package/icc-api/api/IccInvoiceApi.js +2 -1
  69. package/icc-api/api/IccInvoiceApi.js.map +1 -1
  70. package/icc-api/api/IccKeywordApi.js +2 -1
  71. package/icc-api/api/IccKeywordApi.js.map +1 -1
  72. package/icc-api/api/IccMaintenanceTaskApi.js +2 -1
  73. package/icc-api/api/IccMaintenanceTaskApi.js.map +1 -1
  74. package/icc-api/api/IccMedexApi.js +2 -1
  75. package/icc-api/api/IccMedexApi.js.map +1 -1
  76. package/icc-api/api/IccMedicallocationApi.js +2 -1
  77. package/icc-api/api/IccMedicallocationApi.js.map +1 -1
  78. package/icc-api/api/IccMessageApi.js +2 -1
  79. package/icc-api/api/IccMessageApi.js.map +1 -1
  80. package/icc-api/api/IccPatientApi.js +2 -1
  81. package/icc-api/api/IccPatientApi.js.map +1 -1
  82. package/icc-api/api/IccPermissionApi.js +2 -1
  83. package/icc-api/api/IccPermissionApi.js.map +1 -1
  84. package/icc-api/api/IccPlaceApi.js +2 -1
  85. package/icc-api/api/IccPlaceApi.js.map +1 -1
  86. package/icc-api/api/IccPubsubApi.js +2 -1
  87. package/icc-api/api/IccPubsubApi.js.map +1 -1
  88. package/icc-api/api/IccReceiptApi.js +2 -1
  89. package/icc-api/api/IccReceiptApi.js.map +1 -1
  90. package/icc-api/api/IccReplicationApi.js +2 -1
  91. package/icc-api/api/IccReplicationApi.js.map +1 -1
  92. package/icc-api/api/IccRestApiPath.d.ts +1 -0
  93. package/icc-api/api/IccRestApiPath.js +10 -0
  94. package/icc-api/api/IccRestApiPath.js.map +1 -0
  95. package/icc-api/api/IccTarificationApi.js +2 -1
  96. package/icc-api/api/IccTarificationApi.js.map +1 -1
  97. package/icc-api/api/IccTimeTableApi.js +2 -1
  98. package/icc-api/api/IccTimeTableApi.js.map +1 -1
  99. package/icc-api/api/IccTmpApi.js +2 -1
  100. package/icc-api/api/IccTmpApi.js.map +1 -1
  101. package/icc-api/api/IccUserApi.js +2 -1
  102. package/icc-api/api/IccUserApi.js.map +1 -1
  103. package/icc-api/index.d.ts +0 -1
  104. package/icc-api/index.js +0 -1
  105. package/icc-api/index.js.map +1 -1
  106. package/icc-api/model/Address.d.ts +6 -0
  107. package/icc-api/model/Address.js.map +1 -1
  108. package/icc-api/model/Annotation.d.ts +18 -0
  109. package/icc-api/model/Annotation.js.map +1 -1
  110. package/icc-api/model/AuthenticationToken.d.ts +1 -0
  111. package/icc-api/model/AuthenticationToken.js.map +1 -1
  112. package/icc-api/model/Content.js +1 -1
  113. package/icc-api/model/Content.js.map +1 -1
  114. package/icc-api/model/CryptoActorStub.d.ts +5 -0
  115. package/icc-api/model/CryptoActorStub.js +1 -0
  116. package/icc-api/model/CryptoActorStub.js.map +1 -1
  117. package/icc-api/model/Delegation.d.ts +3 -0
  118. package/icc-api/model/Delegation.js.map +1 -1
  119. package/icc-api/model/FlatRateTarification.d.ts +4 -1
  120. package/icc-api/model/FlatRateTarification.js +3 -0
  121. package/icc-api/model/FlatRateTarification.js.map +1 -1
  122. package/icc-api/model/HealthElement.d.ts +6 -0
  123. package/icc-api/model/HealthElement.js.map +1 -1
  124. package/icc-api/model/HealthcareParty.js +1 -1
  125. package/icc-api/model/HealthcareParty.js.map +1 -1
  126. package/icc-api/model/ISO639_1.d.ts +8 -0
  127. package/icc-api/model/ISO639_1.js +3 -0
  128. package/icc-api/model/ISO639_1.js.map +1 -0
  129. package/icc-api/model/Patient.d.ts +7 -0
  130. package/icc-api/model/Patient.js +1 -1
  131. package/icc-api/model/Patient.js.map +1 -1
  132. package/icc-api/model/UserGroup.d.ts +1 -0
  133. package/icc-api/model/UserGroup.js.map +1 -1
  134. package/icc-api/model/models.d.ts +1 -0
  135. package/icc-api/model/models.js.map +1 -1
  136. package/icc-x-api/auth/AuthenticationProvider.d.ts +67 -6
  137. package/icc-x-api/auth/AuthenticationProvider.js +100 -7
  138. package/icc-x-api/auth/AuthenticationProvider.js.map +1 -1
  139. package/icc-x-api/auth/EnsembleAuthService.d.ts +7 -2
  140. package/icc-x-api/auth/EnsembleAuthService.js +9 -0
  141. package/icc-x-api/auth/EnsembleAuthService.js.map +1 -1
  142. package/icc-x-api/auth/JwtAuthService.d.ts +10 -5
  143. package/icc-x-api/auth/JwtAuthService.js +22 -26
  144. package/icc-x-api/auth/JwtAuthService.js.map +1 -1
  145. package/icc-x-api/auth/JwtBridgedAuthService.d.ts +27 -0
  146. package/icc-x-api/auth/JwtBridgedAuthService.js +131 -0
  147. package/icc-x-api/auth/JwtBridgedAuthService.js.map +1 -0
  148. package/icc-x-api/crypto/EntitiesEncryption.d.ts +5 -4
  149. package/icc-x-api/crypto/EntitiesEncryption.js +20 -16
  150. package/icc-x-api/crypto/EntitiesEncryption.js.map +1 -1
  151. package/icc-x-api/filters/ServiceByHcPartyTagCodeDateFilter.d.ts +1 -0
  152. package/icc-x-api/filters/ServiceByHcPartyTagCodeDateFilter.js.map +1 -1
  153. package/icc-x-api/filters/filters.d.ts +4 -0
  154. package/icc-x-api/filters/filters.js +4 -0
  155. package/icc-x-api/filters/filters.js.map +1 -1
  156. package/icc-x-api/icc-accesslog-x-api.d.ts +2 -2
  157. package/icc-x-api/icc-accesslog-x-api.js +17 -24
  158. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  159. package/icc-x-api/icc-calendar-item-x-api.d.ts +1 -1
  160. package/icc-x-api/icc-calendar-item-x-api.js +18 -22
  161. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  162. package/icc-x-api/icc-classification-x-api.js +13 -19
  163. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  164. package/icc-x-api/icc-contact-x-api.d.ts +17 -1
  165. package/icc-x-api/icc-contact-x-api.js +81 -99
  166. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  167. package/icc-x-api/icc-data-owner-x-api.d.ts +1 -1
  168. package/icc-x-api/icc-data-owner-x-api.js.map +1 -1
  169. package/icc-x-api/icc-doctemplate-x-api.js +2 -13
  170. package/icc-x-api/icc-doctemplate-x-api.js.map +1 -1
  171. package/icc-x-api/icc-document-x-api.d.ts +12 -4
  172. package/icc-x-api/icc-document-x-api.js +29 -25
  173. package/icc-x-api/icc-document-x-api.js.map +1 -1
  174. package/icc-x-api/icc-form-x-api.js +13 -17
  175. package/icc-x-api/icc-form-x-api.js.map +1 -1
  176. package/icc-x-api/icc-helement-x-api.d.ts +1 -1
  177. package/icc-x-api/icc-helement-x-api.js +15 -20
  178. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  179. package/icc-x-api/icc-icure-maintenance-x-api.js +4 -4
  180. package/icc-x-api/icc-icure-maintenance-x-api.js.map +1 -1
  181. package/icc-x-api/icc-invoice-x-api.js +13 -19
  182. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  183. package/icc-x-api/icc-maintenance-task-x-api.d.ts +1 -1
  184. package/icc-x-api/icc-maintenance-task-x-api.js +13 -14
  185. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  186. package/icc-x-api/icc-message-x-api.js +13 -18
  187. package/icc-x-api/icc-message-x-api.js.map +1 -1
  188. package/icc-x-api/icc-patient-x-api.d.ts +5 -2
  189. package/icc-x-api/icc-patient-x-api.js +17 -24
  190. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  191. package/icc-x-api/icc-receipt-x-api.js +11 -16
  192. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  193. package/icc-x-api/icc-time-table-x-api.js +11 -16
  194. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  195. package/icc-x-api/index.d.ts +284 -35
  196. package/icc-x-api/index.js +303 -79
  197. package/icc-x-api/index.js.map +1 -1
  198. package/icc-x-api/maintenance/KeyPairUpdateRequest.d.ts +12 -9
  199. package/icc-x-api/maintenance/KeyPairUpdateRequest.js +11 -17
  200. package/icc-x-api/maintenance/KeyPairUpdateRequest.js.map +1 -1
  201. package/icc-x-api/utils/crypto-utils.d.ts +140 -11
  202. package/icc-x-api/utils/crypto-utils.js +285 -36
  203. package/icc-x-api/utils/crypto-utils.js.map +1 -1
  204. package/package.json +1 -1
  205. package/icc-api/api/IccBemikronoApi.d.ts +0 -81
  206. package/icc-api/api/IccBemikronoApi.js +0 -162
  207. package/icc-api/api/IccBemikronoApi.js.map +0 -1
@@ -1,9 +1,10 @@
1
1
  import { AuthService } from './AuthService';
2
2
  import { XHR } from '../../icc-api/api/XHR';
3
- import { JwtAuthService } from './JwtAuthService';
3
+ import { JwtBridgedAuthService } from './JwtBridgedAuthService';
4
4
  import { NoAuthService } from './NoAuthService';
5
5
  import { BasicAuthService } from './BasicAuthService';
6
6
  import Header = XHR.Header;
7
+ import { JwtAuthService } from './JwtAuthService';
7
8
  export declare class EnsembleAuthService implements AuthService {
8
9
  private readonly jwtAuth;
9
10
  private readonly sessionAuth;
@@ -11,7 +12,11 @@ export declare class EnsembleAuthService implements AuthService {
11
12
  private currentState;
12
13
  private error;
13
14
  private stateMap;
14
- constructor(jwtAuth: JwtAuthService | null, sessionAuth: NoAuthService, basicAuth: BasicAuthService);
15
+ constructor(jwtAuth: JwtBridgedAuthService | JwtAuthService | null, sessionAuth: NoAuthService, basicAuth: BasicAuthService);
16
+ getIcureTokens(): Promise<{
17
+ token: string;
18
+ refreshToken: string;
19
+ } | undefined>;
15
20
  getAuthHeaders(): Promise<Array<Header>>;
16
21
  invalidateHeader(error: Error): void;
17
22
  }
@@ -10,6 +10,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.EnsembleAuthService = void 0;
13
+ const XHR_1 = require("../../icc-api/api/XHR");
14
+ var XHRError = XHR_1.XHR.XHRError;
13
15
  class EnsembleAuthService {
14
16
  constructor(jwtAuth, sessionAuth, basicAuth) {
15
17
  this.jwtAuth = jwtAuth;
@@ -24,6 +26,10 @@ class EnsembleAuthService {
24
26
  };
25
27
  this.currentState = 'start';
26
28
  }
29
+ getIcureTokens() {
30
+ var _a, _b;
31
+ return (_b = (_a = this.jwtAuth) === null || _a === void 0 ? void 0 : _a.getIcureTokens()) !== null && _b !== void 0 ? _b : Promise.resolve();
32
+ }
27
33
  getAuthHeaders() {
28
34
  return __awaiter(this, void 0, void 0, function* () {
29
35
  this.currentState = !!this.currentState ? this.stateMap[this.currentState].next : this.currentState;
@@ -32,6 +38,9 @@ class EnsembleAuthService {
32
38
  // And delegate the responsibility of handling the error to the next call
33
39
  return !!this.stateMap[this.currentState].state
34
40
  ? this.stateMap[this.currentState].state.getAuthHeaders().catch((e) => {
41
+ if (e instanceof XHRError && e.statusCode === 417) {
42
+ throw e;
43
+ }
35
44
  // If I get an error, it is also responsibility of the next call, but I give a warning
36
45
  console.warn(e.message);
37
46
  this.error = e;
@@ -1 +1 @@
1
- {"version":3,"file":"EnsembleAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/EnsembleAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAOA,MAAa,mBAAmB;IAK9B,YACmB,OAA8B,EAC9B,WAA0B,EAC1B,SAA2B;QAF3B,YAAO,GAAP,OAAO,CAAuB;QAC9B,gBAAW,GAAX,WAAW,CAAe;QAC1B,cAAS,GAAT,SAAS,CAAkB;QANtC,UAAK,GAAiB,IAAI,CAAA;QAQhC,IAAI,CAAC,QAAQ,GAAG;YACd,KAAK,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE;YACnC,GAAG,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE;YAC7C,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE;YACnD,KAAK,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE;SAC7C,CAAA;QACD,IAAI,CAAC,YAAY,GAAG,OAAO,CAAA;IAC7B,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HR } from '../../icc-api/api/XHR'\nimport { JwtAuthService } from './JwtAuthService'\nimport { NoAuthService } from './NoAuthService'\nimport { BasicAuthService } from './BasicAuthService'\nimport Header = XHR.Header\n\nexport class EnsembleAuthService implements AuthService {\n private currentState: string | null\n private error: Error | null = null\n private stateMap: { [key: string]: { state: AuthService | null; next: string | null } }\n\n constructor(\n private readonly jwtAuth: JwtAuthService | null,\n private readonly sessionAuth: NoAuthService,\n private readonly basicAuth: BasicAuthService\n ) {\n this.stateMap = {\n start: { state: null, next: 'jwt' },\n jwt: { state: this.jwtAuth, next: 'session' },\n session: { state: this.sessionAuth, next: 'basic' },\n basic: { state: this.basicAuth, next: null },\n }\n this.currentState = 'start'\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n this.currentState = !!this.currentState ? this.stateMap[this.currentState].next : this.currentState\n\n if (!!this.currentState) {\n // If I have a state I return the headers, otherwise I return empty headers\n // And delegate the responsibility of handling the error to the next call\n return !!this.stateMap[this.currentState].state\n ? this.stateMap[this.currentState].state!.getAuthHeaders().catch((e) => {\n // If I get an error, it is also responsibility of the next call, but I give a warning\n console.warn(e.message)\n this.error = e\n return []\n })\n : Promise.resolve([])\n } else if (!!this.error) {\n // If I have no more states, I throw the last error or a default one\n throw this.error\n } else {\n throw new Error('Cannot authenticate')\n }\n }\n\n invalidateHeader(error: Error): void {\n this.error = error\n if (!!this.currentState) {\n this.stateMap[this.currentState].state?.invalidateHeader(error)\n }\n }\n}\n"]}
1
+ {"version":3,"file":"EnsembleAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/EnsembleAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAK3C,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAG9B,MAAa,mBAAmB;IAK9B,YACmB,OAAsD,EACtD,WAA0B,EAC1B,SAA2B;QAF3B,YAAO,GAAP,OAAO,CAA+C;QACtD,gBAAW,GAAX,WAAW,CAAe;QAC1B,cAAS,GAA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O,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;wBACvB,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;wBAEd,OAAO,EAAE,CAAA;oBACX,CAAC,CAAC;oBACJ,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;aACxB;iBAAM,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE;gBACvB,oEAAoE;gBACpE,MAAM,IAAI,CAAC,KAAK,CAAA;aACjB;iBAAM;gBACL,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAA;aACvC;QACH,CAAC;KAAA;IAED,gBAAgB,CAAC,KAAY;;QAC3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;QAClB,IAAI,CAAC,CAAC,IAAI,CAAC,YAAY,EAAE;YACvB,MAAA,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,KAAK,0CAAE,gBAAgB,CAAC,KAAK,CAAC,CAAA;SAChE;IACH,CAAC;CACF;AAvDD,kDAuDC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { JwtBridgedAuthService } from './JwtBridgedAuthService'\nimport { NoAuthService } from './NoAuthService'\nimport { BasicAuthService } from './BasicAuthService'\nimport Header = XHR.Header\nimport XHRError = XHR.XHRError\nimport { JwtAuthService } from './JwtAuthService'\n\nexport class EnsembleAuthService implements AuthService {\n private currentState: string | null\n private error: Error | null = null\n private stateMap: { [key: string]: { state: AuthService | null; next: string | null } }\n\n constructor(\n private readonly jwtAuth: JwtBridgedAuthService | JwtAuthService | null,\n private readonly sessionAuth: NoAuthService,\n private readonly basicAuth: BasicAuthService\n ) {\n this.stateMap = {\n start: { state: null, next: 'jwt' },\n jwt: { state: this.jwtAuth, next: 'session' },\n session: { state: this.sessionAuth, next: 'basic' },\n basic: { state: this.basicAuth, next: null },\n }\n this.currentState = 'start'\n }\n\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this.jwtAuth?.getIcureTokens() ?? (Promise.resolve() as Promise<undefined>)\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n this.currentState = !!this.currentState ? this.stateMap[this.currentState].next : this.currentState\n\n if (!!this.currentState) {\n // If I have a state I return the headers, otherwise I return empty headers\n // And delegate the responsibility of handling the error to the next call\n return !!this.stateMap[this.currentState].state\n ? this.stateMap[this.currentState].state!.getAuthHeaders().catch((e) => {\n if (e instanceof XHRError && e.statusCode === 417) {\n throw e\n }\n // If I get an error, it is also responsibility of the next call, but I give a warning\n console.warn(e.message)\n this.error = e\n\n return []\n })\n : Promise.resolve([])\n } else if (!!this.error) {\n // If I have no more states, I throw the last error or a default one\n throw this.error\n } else {\n throw new Error('Cannot authenticate')\n }\n }\n\n invalidateHeader(error: Error): void {\n this.error = error\n if (!!this.currentState) {\n this.stateMap[this.currentState].state?.invalidateHeader(error)\n }\n }\n}\n"]}
@@ -3,15 +3,20 @@ import { XHR } from '../../icc-api/api/XHR';
3
3
  import { IccAuthApi } from '../../icc-api';
4
4
  import Header = XHR.Header;
5
5
  export declare class JwtAuthService implements AuthService {
6
- private authApi;
7
- private username;
8
- private password;
6
+ private readonly authApi;
9
7
  private _error;
10
8
  private _currentPromise;
11
- constructor(authApi: IccAuthApi, username: string, password: string);
9
+ constructor(authApi: IccAuthApi, initialJwt?: {
10
+ authJwt: string;
11
+ refreshJwt: string;
12
+ });
13
+ getIcureTokens(): Promise<{
14
+ token: string;
15
+ refreshToken: string;
16
+ } | undefined>;
17
+ get refreshToken(): Promise<string | undefined>;
12
18
  getAuthHeaders(): Promise<Array<Header>>;
13
19
  private _refreshAuthJwt;
14
- private _loginAndGetTokens;
15
20
  private _isJwtExpired;
16
21
  private _base64Decode;
17
22
  invalidateHeader(error: Error): void;
@@ -11,21 +11,30 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.JwtAuthService = void 0;
13
13
  const XHR_1 = require("../../icc-api/api/XHR");
14
- const LoginCredentials_1 = require("../../icc-api/model/LoginCredentials");
15
14
  const utils_1 = require("../utils");
16
15
  class JwtAuthService {
17
- constructor(authApi, username, password) {
16
+ constructor(authApi, initialJwt) {
18
17
  this.authApi = authApi;
19
- this.username = username;
20
- this.password = password;
21
18
  this._error = null;
22
- this._currentPromise = Promise.resolve({});
19
+ this._currentPromise = Promise.resolve(undefined);
20
+ if (!!initialJwt) {
21
+ this._currentPromise = Promise.resolve(initialJwt);
22
+ }
23
+ }
24
+ getIcureTokens() {
25
+ return this._currentPromise.then((x) => (x ? { token: x.authJwt, refreshToken: x.refreshJwt } : undefined));
26
+ }
27
+ get refreshToken() {
28
+ return this._currentPromise.then((x) => x === null || x === void 0 ? void 0 : x.refreshJwt);
23
29
  }
24
30
  getAuthHeaders() {
25
31
  return __awaiter(this, void 0, void 0, function* () {
26
32
  return this._currentPromise
27
- .then(({ authJwt, refreshJwt }) => {
28
- if (!authJwt || this._isJwtExpired(authJwt)) {
33
+ .then((x) => {
34
+ var _a;
35
+ const authJwt = x === null || x === void 0 ? void 0 : x.authJwt;
36
+ const refreshJwt = x === null || x === void 0 ? void 0 : x.refreshJwt;
37
+ if ((!authJwt || this._isJwtExpired(authJwt)) && refreshJwt) {
29
38
  // If it does not have the JWT, tries to get it
30
39
  // If the JWT is expired, tries to refresh it
31
40
  this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {
@@ -37,13 +46,13 @@ class JwtAuthService {
37
46
  return updatedTokens;
38
47
  });
39
48
  }
40
- else if (!!this._error) {
41
- throw this._error;
49
+ else {
50
+ throw (_a = this._error) !== null && _a !== void 0 ? _a : 'Expired JWT refresh token in pure JwtAuthService incapable of relogging';
42
51
  }
43
52
  return this._currentPromise;
44
53
  })
45
- .then(({ authJwt }) => {
46
- return [new XHR_1.XHR.Header('Authorization', `Bearer ${authJwt}`)];
54
+ .then((x) => {
55
+ return (x === null || x === void 0 ? void 0 : x.authJwt) ? [new XHR_1.XHR.Header('Authorization', `Bearer ${x.authJwt}`)] : Promise.reject('Cannot provide auth: No JWT');
47
56
  });
48
57
  });
49
58
  }
@@ -51,8 +60,8 @@ class JwtAuthService {
51
60
  return __awaiter(this, void 0, void 0, function* () {
52
61
  // If I do not have a refresh JWT or the refresh JWT is expired,
53
62
  // I have to log in again
54
- if (!refreshJwt || this._isJwtExpired(refreshJwt)) {
55
- return this._loginAndGetTokens();
63
+ if (this._isJwtExpired(refreshJwt)) {
64
+ throw Error('Missing or expired refresh token: please log in again');
56
65
  }
57
66
  else {
58
67
  return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({
@@ -62,19 +71,6 @@ class JwtAuthService {
62
71
  }
63
72
  });
64
73
  }
65
- _loginAndGetTokens() {
66
- return __awaiter(this, void 0, void 0, function* () {
67
- return this.authApi
68
- .login(new LoginCredentials_1.LoginCredentials({
69
- username: this.username,
70
- password: this.password,
71
- }))
72
- .then((authResponse) => ({
73
- authJwt: authResponse.token,
74
- refreshJwt: authResponse.refreshToken,
75
- }));
76
- });
77
- }
78
74
  _isJwtExpired(jwt) {
79
75
  const parts = jwt.split('.');
80
76
  if (parts.length !== 3) {
@@ -1 +1 @@
1
- {"version":3,"file":"JwtAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAE3C,2EAAuE;AAEvE,oCAA8B;AAE9B,MAAa,cAAc;IAIzB,YAAoB,OAAmB,EAAU,QAAgB,EAAU,QAAgB;QAAvE,YAAO,GAAP,OAAO,CAAY;QAAU,aAAQ,GAAR,QAAQ,CAAQ;QAAU,aAAQ,GAAR,QAAQ,CAAQ;QAHnF,WAAM,GAAiB,IAAI,CAAA;QAC3B,oBAAe,GAAuD,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;IAEH,CAAC;IAEzF,cAAc;;YAClB,OAAO,IAAI,CAAC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CAAC;KAAA;IAEa,kBAAkB;;YAC9B,OAAO,IAAI,CAAC,OAAO;iBAChB,KAAK,CACJ,IAAI,mCAAgB,CAAC;gBACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ;gBACvB,QAAQ,EAAE,IAAI,CAAC,QAAQ;aACxB,CAAC,CACH;iBACA,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;gBACvB,OAAO,EAAE,YAAY,CAAC,KAAK;gBAC3B,UAAU,EAAE,YAAY,CAAC,YAAY;aACtC,CAAC,CAAC,CAAA;QACP,CAAC;KAAA;IAEO,aAAa,CAAC,GAAW;QAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QAC5B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,OAAO,KAAK,CAAA;SACb;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;QAC5C,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;IAC5E,CAAC;IAEO,aAAa,CAAC,aAAqB;QACzC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAA,WAAG,EAAC,aAAa,CAAC,CAAC,CAAA;IACvC,CAAC;IAED,gBAAgB,CAAC,KAAY;QAC3B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,cAAc;QACZ,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AA/ED,wCA+EC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi } from '../../icc-api'\nimport { LoginCredentials } from '../../icc-api/model/LoginCredentials'\nimport Header = XHR.Header\nimport { a2b } from '../utils'\n\nexport class JwtAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt?: string; refreshJwt?: string }> = Promise.resolve({})\n\n constructor(private authApi: IccAuthApi, private username: string, private password: string) {}\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this._currentPromise\n .then(({ authJwt, refreshJwt }) => {\n if (!authJwt || this._isJwtExpired(authJwt)) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n })\n } else if (!!this._error) {\n throw this._error\n }\n return this._currentPromise\n })\n .then(({ authJwt }) => {\n return [new XHR.Header('Authorization', `Bearer ${authJwt}`)]\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string | undefined): Promise<{ authJwt?: string; refreshJwt?: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (!refreshJwt || this._isJwtExpired(refreshJwt)) {\n return this._loginAndGetTokens()\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n private async _loginAndGetTokens(): Promise<{ authJwt?: string; refreshJwt?: string }> {\n return this.authApi\n .login(\n new LoginCredentials({\n username: this.username,\n password: this.password,\n })\n )\n .then((authResponse) => ({\n authJwt: authResponse.token,\n refreshJwt: authResponse.refreshToken,\n }))\n }\n\n private _isJwtExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return false\n }\n const payload = this._base64Decode(parts[1])\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime()\n }\n\n private _base64Decode(encodedString: string): any {\n return JSON.parse(a2b(encodedString))\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]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;QAC5B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,OAAO,KAAK,CAAA;SACb;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;QAC5C,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;IAC5E,CAAC;IAEO,aAAa,CAAC,aAAqB;QACzC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAA,WAAG,EAAC,aAAa,CAAC,CAAC,CAAA;IACvC,CAAC;IAED,gBAAgB,CAAC,KAAY;QAC3B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,cAAc;QACZ,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AAhFD,wCAgFC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { LoginCredentials } from '../../icc-api/model/LoginCredentials'\nimport Header = XHR.Header\nimport { a2b } from '../utils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\nimport XHRError = XHR.XHRError\n\nexport class JwtAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt: string; refreshJwt: string } | undefined> = Promise.resolve(undefined as any)\n\n constructor(private readonly authApi: IccAuthApi, initialJwt?: { authJwt: string; refreshJwt: string }) {\n if (!!initialJwt) {\n this._currentPromise = Promise.resolve(initialJwt)\n }\n }\n\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this._currentPromise.then((x) => (x ? { token: x.authJwt, refreshToken: x.refreshJwt } : undefined) as any)\n }\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x?.refreshJwt as any)\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this._currentPromise\n .then((x) => {\n const authJwt = x?.authJwt\n const refreshJwt = x?.refreshJwt\n\n if ((!authJwt || this._isJwtExpired(authJwt)) && refreshJwt) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n })\n } else {\n throw this._error ?? 'Expired JWT refresh token in pure JwtAuthService incapable of relogging'\n }\n return this._currentPromise\n })\n .then((x) => {\n return x?.authJwt ? [new XHR.Header('Authorization', `Bearer ${x.authJwt}`)] : Promise.reject('Cannot provide auth: No JWT')\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string): Promise<{ authJwt: string; refreshJwt: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (this._isJwtExpired(refreshJwt)) {\n throw Error('Missing or expired refresh token: please log in again')\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token!,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n private _isJwtExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return false\n }\n const payload = this._base64Decode(parts[1])\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime()\n }\n\n private _base64Decode(encodedString: string): any {\n return JSON.parse(a2b(encodedString))\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]}
@@ -0,0 +1,27 @@
1
+ import { AuthService } from './AuthService';
2
+ import { XHR } from '../../icc-api/api/XHR';
3
+ import { IccAuthApi } from '../../icc-api';
4
+ import Header = XHR.Header;
5
+ export declare class JwtBridgedAuthService implements AuthService {
6
+ private authApi;
7
+ private username;
8
+ private password;
9
+ private thirdPartyTokens;
10
+ private _error;
11
+ private _currentPromise;
12
+ constructor(authApi: IccAuthApi, username: string, password: string, thirdPartyTokens?: {
13
+ [thirdParty: string]: string;
14
+ });
15
+ get refreshToken(): Promise<string | undefined>;
16
+ getIcureTokens(): Promise<{
17
+ token: string;
18
+ refreshToken: string;
19
+ } | undefined>;
20
+ getAuthHeaders(): Promise<Array<Header>>;
21
+ private _refreshAuthJwt;
22
+ private _loginAndGetTokens;
23
+ private _isJwtExpired;
24
+ private _base64Decode;
25
+ invalidateHeader(error: Error): void;
26
+ isInErrorState(): boolean;
27
+ }
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.JwtBridgedAuthService = void 0;
13
+ const XHR_1 = require("../../icc-api/api/XHR");
14
+ const LoginCredentials_1 = require("../../icc-api/model/LoginCredentials");
15
+ const utils_1 = require("../utils");
16
+ var XHRError = XHR_1.XHR.XHRError;
17
+ class JwtBridgedAuthService {
18
+ constructor(authApi, username, password, thirdPartyTokens = {}) {
19
+ this.authApi = authApi;
20
+ this.username = username;
21
+ this.password = password;
22
+ this.thirdPartyTokens = thirdPartyTokens;
23
+ this._error = null;
24
+ this._currentPromise = Promise.resolve({});
25
+ }
26
+ get refreshToken() {
27
+ return this._currentPromise.then((x) => x.refreshJwt);
28
+ }
29
+ getIcureTokens() {
30
+ return this.getAuthHeaders().then(() => this._currentPromise.then(({ authJwt, refreshJwt }) => ({ token: authJwt, refreshToken: refreshJwt })));
31
+ }
32
+ getAuthHeaders() {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ return this._currentPromise
35
+ .then(({ authJwt, refreshJwt }) => {
36
+ if (!authJwt || this._isJwtExpired(authJwt)) {
37
+ // If it does not have the JWT, tries to get it
38
+ // If the JWT is expired, tries to refresh it
39
+ this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {
40
+ // If here the token is null,
41
+ // it goes in a suspension status
42
+ if (!updatedTokens.authJwt) {
43
+ throw new Error('Your iCure back-end version does not support JWT authentication');
44
+ }
45
+ return updatedTokens;
46
+ });
47
+ }
48
+ else if (!!this._error) {
49
+ throw this._error;
50
+ }
51
+ return this._currentPromise;
52
+ })
53
+ .then(({ authJwt }) => {
54
+ return [new XHR_1.XHR.Header('Authorization', `Bearer ${authJwt}`)];
55
+ });
56
+ });
57
+ }
58
+ _refreshAuthJwt(refreshJwt) {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ // If I do not have a refresh JWT or the refresh JWT is expired,
61
+ // I have to log in again
62
+ if (!refreshJwt || this._isJwtExpired(refreshJwt)) {
63
+ return this._loginAndGetTokens();
64
+ }
65
+ else {
66
+ return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({
67
+ authJwt: refreshResponse.token,
68
+ refreshJwt: refreshJwt,
69
+ }));
70
+ }
71
+ });
72
+ }
73
+ _loginAndGetTokens() {
74
+ return __awaiter(this, void 0, void 0, function* () {
75
+ let authResponse;
76
+ let firstError;
77
+ if (this.username && this.password) {
78
+ try {
79
+ authResponse = yield this.authApi.login(new LoginCredentials_1.LoginCredentials({
80
+ username: this.username,
81
+ password: this.password,
82
+ }));
83
+ }
84
+ catch (e) {
85
+ firstError = e;
86
+ }
87
+ }
88
+ if (!authResponse) {
89
+ authResponse = yield Object.entries(this.thirdPartyTokens).reduce((acc, [thirdParty, token]) => __awaiter(this, void 0, void 0, function* () {
90
+ const prev = yield acc;
91
+ return (prev !== null && prev !== void 0 ? prev : (token
92
+ ? this.authApi.loginWithThirdPartyToken(thirdParty, token).catch((e) => {
93
+ if (!firstError) {
94
+ firstError = e;
95
+ }
96
+ return Promise.resolve();
97
+ })
98
+ : undefined));
99
+ }), Promise.resolve());
100
+ }
101
+ if (!authResponse) {
102
+ if (firstError)
103
+ throw firstError;
104
+ throw new XHRError('', 'Unknown error', 401, 'Unauthorized', new Headers());
105
+ }
106
+ return {
107
+ authJwt: authResponse.token,
108
+ refreshJwt: authResponse.refreshToken,
109
+ };
110
+ });
111
+ }
112
+ _isJwtExpired(jwt) {
113
+ const parts = jwt.split('.');
114
+ if (parts.length !== 3) {
115
+ return false;
116
+ }
117
+ const payload = this._base64Decode(parts[1]);
118
+ return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime();
119
+ }
120
+ _base64Decode(encodedString) {
121
+ return JSON.parse((0, utils_1.a2b)(encodedString));
122
+ }
123
+ invalidateHeader(error) {
124
+ this._error = error;
125
+ }
126
+ isInErrorState() {
127
+ return !!this._error;
128
+ }
129
+ }
130
+ exports.JwtBridgedAuthService = JwtBridgedAuthService;
131
+ //# sourceMappingURL=JwtBridgedAuthService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"JwtBridgedAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtBridgedAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAE3C,2EAAuE;AAEvE,oCAA8B;AAE9B,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAE9B,MAAa,qBAAqB;IAIhC,YACU,OAAmB,EACnB,QAAgB,EAChB,QAAgB,EAChB,mBAAqD,EAAE;QAHvD,YAAO,GAAP,OAAO,CAAY;QACnB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,qBAAgB,GAAhB,gBAAgB,CAAuC;QAPzD,WAAM,GAAiB,IAAI,CAAA;QAC3B,oB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AAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,cAAc;QACZ,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AAxHD,sDAwHC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { LoginCredentials } from '../../icc-api/model/LoginCredentials'\nimport Header = XHR.Header\nimport { a2b } from '../utils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\nimport XHRError = XHR.XHRError\n\nexport class JwtBridgedAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt?: string; refreshJwt?: string }> = Promise.resolve({})\n\n constructor(\n private authApi: IccAuthApi,\n private username: string,\n private password: string,\n private thirdPartyTokens: { [thirdParty: string]: string } = {}\n ) {}\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x.refreshJwt as any)\n }\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this.getAuthHeaders().then(() => this._currentPromise.then(({ authJwt, refreshJwt }) => ({ token: authJwt!, refreshToken: refreshJwt! })))\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this._currentPromise\n .then(({ authJwt, refreshJwt }) => {\n if (!authJwt || this._isJwtExpired(authJwt)) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n })\n } else if (!!this._error) {\n throw this._error\n }\n return this._currentPromise\n })\n .then(({ authJwt }) => {\n return [new XHR.Header('Authorization', `Bearer ${authJwt}`)]\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string | undefined): Promise<{ authJwt?: string; refreshJwt?: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (!refreshJwt || this._isJwtExpired(refreshJwt)) {\n return this._loginAndGetTokens()\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n private async _loginAndGetTokens(): Promise<{ authJwt?: string; refreshJwt?: string }> {\n let authResponse: AuthenticationResponse | undefined\n let firstError: XHRError | undefined\n if (this.username && this.password) {\n try {\n authResponse = await this.authApi.login(\n new LoginCredentials({\n username: this.username,\n password: this.password,\n })\n )\n } catch (e) {\n firstError = e as XHRError\n }\n }\n if (!authResponse) {\n authResponse = await (Object.entries(this.thirdPartyTokens) as [OAuthThirdParty, string][]).reduce(async (acc, [thirdParty, token]) => {\n const prev = await acc\n return (\n prev ??\n (token\n ? this.authApi.loginWithThirdPartyToken(thirdParty, token).catch((e) => {\n if (!firstError) {\n firstError = e as XHRError\n }\n return Promise.resolve() as Promise<undefined>\n })\n : undefined)\n )\n }, Promise.resolve() as Promise<AuthenticationResponse | undefined>)\n }\n\n if (!authResponse) {\n if (firstError) throw firstError\n throw new XHRError('', 'Unknown error', 401, 'Unauthorized', new Headers())\n }\n\n return {\n authJwt: authResponse.token,\n refreshJwt: authResponse.refreshToken,\n }\n }\n\n private _isJwtExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return false\n }\n const payload = this._base64Decode(parts[1])\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime()\n }\n\n private _base64Decode(encodedString: string): any {\n return JSON.parse(a2b(encodedString))\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models';
2
2
  import { IccDataOwnerXApi } from '../icc-data-owner-x-api';
3
3
  import { ExchangeKeysManager } from './ExchangeKeysManager';
4
+ import { EncryptedFieldsManifest } from '../utils';
4
5
  import { CryptoPrimitives } from './CryptoPrimitives';
5
6
  import { ShareMetadataBehaviour } from './ShareMetadataBehaviour';
6
7
  /**
@@ -122,7 +123,7 @@ export declare class EntitiesEncryption {
122
123
  shareEncryptionKey?: ShareMetadataBehaviour;
123
124
  shareOwningEntityIds?: ShareMetadataBehaviour;
124
125
  };
125
- }): Promise<T>;
126
+ }): Promise<T | undefined>;
126
127
  /**
127
128
  * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing
128
129
  * delegate.
@@ -142,7 +143,7 @@ export declare class EntitiesEncryption {
142
143
  * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.
143
144
  * @return an updated copy of the entity.
144
145
  */
145
- entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(entity: T, delegateId: string, shareSecretIds: string[], shareEncryptionKeys: string[], shareOwningEntityIds: string[], newTags?: string[]): Promise<T>;
146
+ entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(entity: T, delegateId: string, shareSecretIds: string[], shareEncryptionKeys: string[], shareOwningEntityIds: string[], newTags?: string[]): Promise<T | undefined>;
146
147
  /**
147
148
  * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can
148
149
  * access multiple encryption keys of the entity there is no guarantee on which key will be used.
@@ -201,14 +202,14 @@ export declare class EntitiesEncryption {
201
202
  * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field
202
203
  * which should be encrypted the method throws an error, otherwise the method returns the original entity.
203
204
  */
204
- tryEncryptEntity<T extends EncryptedEntity>(entity: T, dataOwnerId: string | undefined, cryptedKeys: string[], encodeBinaryData: boolean, requireEncryption: boolean, constructor: (json: any) => T): Promise<T>;
205
+ tryEncryptEntity<T extends EncryptedEntity>(entity: T, dataOwnerId: string | undefined, fieldsToEncrypt: EncryptedFieldsManifest, encodeBinaryData: boolean, requireEncryption: boolean, constructor: (json: any) => T): Promise<T>;
205
206
  /**
206
207
  * @internal This method is for internal use only and may be changed without notice.
207
208
  * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of
208
209
  * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities
209
210
  * which were previously not encrypted.
210
211
  */
211
- ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T>;
212
+ ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T | undefined>;
212
213
  /**
213
214
  * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does
214
215
  * not consider exchange keys for parents).
@@ -167,7 +167,7 @@ class EntitiesEncryption {
167
167
  });
168
168
  }
169
169
  entityWithAutoExtendedEncryptedMetadata(entity, autoShareSecretIds, delegatesShareInfo) {
170
- var _a;
170
+ var _a, _b;
171
171
  return __awaiter(this, void 0, void 0, function* () {
172
172
  if (!Object.keys(delegatesShareInfo).length) {
173
173
  throw new Error('Must specify at least a delegate');
@@ -184,7 +184,7 @@ class EntitiesEncryption {
184
184
  }
185
185
  const availableEncryptionKeys = yield this.encryptionKeysOf(entity);
186
186
  const availableOwningEntityIds = yield this.owningEntityIdsOf(entity);
187
- let updatedEntity = entity;
187
+ let updatedEntity = undefined;
188
188
  for (const [delegateId, requests] of Object.entries(delegatesShareInfo)) {
189
189
  let shareSecretIds = autoShareSecretIds ? defaultSecretIds : (_a = requests.shareSecretIds) !== null && _a !== void 0 ? _a : [];
190
190
  let actualShareEncryptionKeys = [];
@@ -201,7 +201,8 @@ class EntitiesEncryption {
201
201
  }
202
202
  actualShareOwningEntityIds = availableOwningEntityIds;
203
203
  }
204
- updatedEntity = yield this.entityWithExtendedEncryptedMetadata(updatedEntity, delegateId, shareSecretIds, actualShareEncryptionKeys, actualShareOwningEntityIds);
204
+ updatedEntity =
205
+ (_b = (yield this.entityWithExtendedEncryptedMetadata(updatedEntity !== null && updatedEntity !== void 0 ? updatedEntity : entity, delegateId, shareSecretIds, actualShareEncryptionKeys, actualShareOwningEntityIds))) !== null && _b !== void 0 ? _b : updatedEntity;
205
206
  }
206
207
  return updatedEntity;
207
208
  });
@@ -256,7 +257,7 @@ class EntitiesEncryption {
256
257
  if (deduplicateInfoSecretIds.missingEntries.length === 0 &&
257
258
  deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&
258
259
  deduplicateInfoOwningEntityIds.missingEntries.length === 0)
259
- return _.cloneDeep(entity);
260
+ return undefined;
260
261
  const { updatedEntity, keysForDelegates } = yield this.loadEncryptionKeysForDelegates(entity, [delegateId]);
261
262
  return this.createOrUpdateEntityDelegations(updatedEntity, delegateId, deduplicateInfoSecretIds.deduplicatedDelegations, deduplicateInfoEncryptionKeys.deduplicatedDelegations, deduplicateInfoOwningEntityIds.deduplicatedDelegations, deduplicateInfoSecretIds.missingEntries, deduplicateInfoEncryptionKeys.missingEntries, deduplicateInfoOwningEntityIds.missingEntries, newTags, keysForDelegates);
262
263
  });
@@ -274,8 +275,9 @@ class EntitiesEncryption {
274
275
  * @throws if the provided data owner can't access any encryption keys for the entity.
275
276
  */
276
277
  encryptDataOf(entity, content, dataOwnerId, tagsFilter = () => Promise.resolve(true)) {
278
+ var _a;
277
279
  return __awaiter(this, void 0, void 0, function* () {
278
- const keys = yield this.encryptionKeysOf(yield this.ensureEncryptionKeysInitialised(entity), dataOwnerId, tagsFilter);
280
+ const keys = yield this.encryptionKeysOf((_a = (yield this.ensureEncryptionKeysInitialised(entity))) !== null && _a !== void 0 ? _a : entity, dataOwnerId, tagsFilter);
279
281
  if (keys.length === 0)
280
282
  throw new Error(`Could not extract any encryption keys of entity ${entity} for data owner ${dataOwnerId !== null && dataOwnerId !== void 0 ? dataOwnerId : (yield this.dataOwnerApi.getCurrentDataOwnerId())}.`);
281
283
  return this.primitives.AES.encryptWithRawKey(keys[0], content);
@@ -319,13 +321,11 @@ class EntitiesEncryption {
319
321
  */
320
322
  decryptEntity(entity, ownerId, constructor) {
321
323
  return __awaiter(this, void 0, void 0, function* () {
322
- if (!entity.encryptedSelf)
323
- return { entity, decrypted: true };
324
324
  const encryptionKeys = yield this.importAllValidKeys(yield this.encryptionKeysOf(entity, ownerId));
325
325
  if (!encryptionKeys.length)
326
326
  return { entity, decrypted: false };
327
327
  return {
328
- entity: constructor(yield (0, utils_1.decrypt)(entity, (encrypted) => __awaiter(this, void 0, void 0, function* () {
328
+ entity: constructor(yield (0, utils_1.decryptObject)(entity, (encrypted) => __awaiter(this, void 0, void 0, function* () {
329
329
  var _a;
330
330
  return (_a = (yield this.tryDecryptJson(encryptionKeys, encrypted, false))) !== null && _a !== void 0 ? _a : {};
331
331
  }))),
@@ -360,12 +360,13 @@ class EntitiesEncryption {
360
360
  * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field
361
361
  * which should be encrypted the method throws an error, otherwise the method returns the original entity.
362
362
  */
363
- tryEncryptEntity(entity, dataOwnerId, cryptedKeys, encodeBinaryData, requireEncryption, constructor) {
363
+ tryEncryptEntity(entity, dataOwnerId, fieldsToEncrypt, encodeBinaryData, requireEncryption, constructor) {
364
364
  return __awaiter(this, void 0, void 0, function* () {
365
365
  const entityWithInitialisedEncryptionKeys = yield this.ensureEncryptionKeysInitialised(entity);
366
366
  const encryptionKey = yield this.tryImportFirstValidKey(yield this.encryptionKeysOf(entity, dataOwnerId), entity.id);
367
367
  if (!!encryptionKey) {
368
- return constructor(yield (0, utils_1.crypt)(entityWithInitialisedEncryptionKeys, (obj) => {
368
+ return constructor(yield (0, utils_1.encryptObject)(entityWithInitialisedEncryptionKeys !== null && entityWithInitialisedEncryptionKeys !== void 0 ? entityWithInitialisedEncryptionKeys : entity, (obj) => {
369
+ // TODO should encoding of binary data should probably be applied to everything?
369
370
  const json = encodeBinaryData
370
371
  ? JSON.stringify(obj, (k, v) => {
371
372
  return v instanceof ArrayBuffer || v instanceof Uint8Array
@@ -374,16 +375,19 @@ class EntitiesEncryption {
374
375
  })
375
376
  : JSON.stringify(obj);
376
377
  return this.primitives.AES.encrypt(encryptionKey.key, (0, utils_1.utf8_2ua)(json), encryptionKey.raw);
377
- }, cryptedKeys));
378
+ }, fieldsToEncrypt, 'entity'));
378
379
  }
379
380
  else if (requireEncryption) {
380
381
  throw new Error(`No key found for encryption of entity ${entity}`);
381
382
  }
382
383
  else {
383
- const cryptedCopyWithRandomKey = yield (0, utils_1.crypt)(_.cloneDeep(entity), (obj) => __awaiter(this, void 0, void 0, function* () { return Promise.resolve(new ArrayBuffer(1)); }), cryptedKeys);
384
- if (!_.isEqual(_.omitBy(Object.assign(Object.assign({}, cryptedCopyWithRandomKey), { encryptedSelf: undefined }), _.isNil), _.omitBy(Object.assign(Object.assign({}, entity), { encryptedSelf: undefined }), _.isNil))) {
385
- throw new Error(`Impossible to modify encrypted value of an entity if no encryption key is known.\n${entity}`);
386
- }
384
+ yield (0, utils_1.encryptObject)(entity, (obj) => __awaiter(this, void 0, void 0, function* () {
385
+ const hasNonEmptyValues = Object.values(obj).some((v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0));
386
+ if (hasNonEmptyValues) {
387
+ throw new Error(`Impossible to modify encrypted content of an entity if no encryption key is known.\nEntity: ${JSON.stringify(entity)}\nTo encrypt: ${JSON.stringify(obj)}`);
388
+ }
389
+ return Promise.resolve(new ArrayBuffer(1));
390
+ }), fieldsToEncrypt, 'entity');
387
391
  return entity;
388
392
  }
389
393
  });
@@ -398,7 +402,7 @@ class EntitiesEncryption {
398
402
  var _a;
399
403
  return __awaiter(this, void 0, void 0, function* () {
400
404
  if (Object.keys((_a = entity.encryptionKeys) !== null && _a !== void 0 ? _a : {}).length > 0)
401
- return entity;
405
+ return undefined;
402
406
  if (!entity.rev) {
403
407
  throw new Error('New encrypted entity is lacking encryption metadata. ' +
404
408
  'Please instantiate new entities using the `newInstance` method from the respective extended api.');