@icure/api 8.3.5 → 8.4.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 (44) hide show
  1. package/icc-api/api/IccAuthApi.d.ts +10 -1
  2. package/icc-api/api/IccAuthApi.js +20 -3
  3. package/icc-api/api/IccAuthApi.js.map +1 -1
  4. package/icc-api/api/IccClassificationApi.d.ts +1 -0
  5. package/icc-api/api/IccClassificationApi.js +12 -0
  6. package/icc-api/api/IccClassificationApi.js.map +1 -1
  7. package/icc-api/api/IccMessageApi.d.ts +0 -6
  8. package/icc-api/api/IccMessageApi.js +0 -15
  9. package/icc-api/api/IccMessageApi.js.map +1 -1
  10. package/icc-x-api/auth/SmartAuthProvider.d.ts +37 -13
  11. package/icc-x-api/auth/SmartAuthProvider.js +105 -29
  12. package/icc-x-api/auth/SmartAuthProvider.js.map +1 -1
  13. package/icc-x-api/icc-bekmehr-x-api.js +2 -1
  14. package/icc-x-api/icc-bekmehr-x-api.js.map +1 -1
  15. package/icc-x-api/icc-document-x-api.d.ts +51 -6
  16. package/icc-x-api/icc-document-x-api.js +231 -69
  17. package/icc-x-api/icc-document-x-api.js.map +1 -1
  18. package/icc-x-api/icc-message-x-api.d.ts +45 -6
  19. package/icc-x-api/icc-message-x-api.js +202 -30
  20. package/icc-x-api/icc-message-x-api.js.map +1 -1
  21. package/icc-x-api/icc-patient-x-api.d.ts +9 -1
  22. package/icc-x-api/icc-patient-x-api.js +92 -100
  23. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  24. package/icc-x-api/index.d.ts +14 -14
  25. package/icc-x-api/index.js +5 -4
  26. package/icc-x-api/index.js.map +1 -1
  27. package/package.json +1 -1
  28. package/test/icc-api/api/IccDocumentApi.js +27 -35
  29. package/test/icc-api/api/IccDocumentApi.js.map +1 -1
  30. package/test/icc-x-api/auth/group-switch-test.js +5 -5
  31. package/test/icc-x-api/auth/group-switch-test.js.map +1 -1
  32. package/test/icc-x-api/auth/jwt-provider-test.js +1 -1
  33. package/test/icc-x-api/auth/jwt-provider-test.js.map +1 -1
  34. package/test/icc-x-api/auth/smart-auth-provider-test.js +5 -5
  35. package/test/icc-x-api/auth/smart-auth-provider-test.js.map +1 -1
  36. package/test/icc-x-api/icc-document-x-api.js +28 -4
  37. package/test/icc-x-api/icc-document-x-api.js.map +1 -1
  38. package/test/icc-x-api/icc-message-x-api.js +19 -293
  39. package/test/icc-x-api/icc-message-x-api.js.map +1 -1
  40. package/test/icc-x-api/icc-user-x-api-test.js +1 -1
  41. package/test/icc-x-api/icc-user-x-api-test.js.map +1 -1
  42. package/test/utils/test_utils.d.ts +4 -2
  43. package/test/utils/test_utils.js +4 -3
  44. package/test/utils/test_utils.js.map +1 -1
@@ -1,7 +1,7 @@
1
1
  import { AuthenticationProvider } from './AuthenticationProvider';
2
2
  import { UserGroup } from '../../icc-api/model/UserGroup';
3
3
  import { AuthService } from './AuthService';
4
- import { IccAuthApi, OAuthThirdParty } from '../../icc-api';
4
+ import { DigitalIdProvider, IccAuthApi, OAuthThirdParty } from '../../icc-api';
5
5
  /**
6
6
  * Needed by a {@link SmartAuthProvider} to get the secrets (password, token, etc.) for authentication to the iCure SDK as needed.
7
7
  */
@@ -47,11 +47,19 @@ export interface AuthSecretProvider {
47
47
  }
48
48
  export type AuthSecretDetails = {
49
49
  value: string;
50
- secretType: Exclude<AuthSecretType, AuthSecretType.EXTERNAL_AUTHENTICATION>;
50
+ secretType: Exclude<AuthSecretType, AuthSecretType.EXTERNAL_AUTHENTICATION | AuthSecretType.DIGITAL_ID | AuthSecretType.ICURE_CLOUD>;
51
51
  } | {
52
52
  value: string;
53
53
  secretType: AuthSecretType.EXTERNAL_AUTHENTICATION;
54
54
  oauthType: OAuthThirdParty;
55
+ } | {
56
+ value: string;
57
+ secretType: AuthSecretType.DIGITAL_ID;
58
+ provider: DigitalIdProvider;
59
+ } | {
60
+ value: string;
61
+ secretType: AuthSecretType.ICURE_CLOUD;
62
+ issuer: string;
55
63
  };
56
64
  /**
57
65
  * Represents a type of secret that can be used for authentication with iCure.
@@ -80,8 +88,31 @@ export declare enum AuthSecretType {
80
88
  * A token provided by an external authentication provider (e.g. Oauth/Google).
81
89
  * Not yet in use.
82
90
  */
83
- EXTERNAL_AUTHENTICATION = "EXTERNAL_AUTHENTICATION"
91
+ EXTERNAL_AUTHENTICATION = "EXTERNAL_AUTHENTICATION",
92
+ /**
93
+ * A special case of external authentication where the provider is a digital identity provider.
94
+ */
95
+ DIGITAL_ID = "DIGITAL_ID",
96
+ /**
97
+ * The secret is an authentication token for a cloud instance of icure (kraken-cloud).
98
+ * Supported only on lite instances.
99
+ */
100
+ ICURE_CLOUD = "ICURE_CLOUD"
84
101
  }
102
+ export type SmartAuthProviderInitialSecret = {
103
+ password: string;
104
+ } | {
105
+ longToken: string;
106
+ } | {
107
+ oauthToken: string;
108
+ oauthType: OAuthThirdParty;
109
+ } | {
110
+ digitalIdToken: string;
111
+ provider: DigitalIdProvider;
112
+ } | {
113
+ cloudToken: string;
114
+ issuer: string;
115
+ };
85
116
  /**
86
117
  * @internal this class is meant for internal use only and may be changed without notice. The SmartAuthProvider will be initialised automatically
87
118
  * by the iCure api depending on the authentication options you provide.
@@ -112,20 +143,13 @@ export declare class SmartAuthProvider implements AuthenticationProvider {
112
143
  * @param secretProvider
113
144
  * @param props optional initialisation properties.
114
145
  */
115
- static initialise(authApi: IccAuthApi, login: string, secretProvider: AuthSecretProvider, props?: {
116
- initialSecret?: {
117
- password: string;
118
- } | {
119
- longToken: string;
120
- } | {
121
- oauthToken: string;
122
- oauthType: OAuthThirdParty;
123
- };
146
+ static initialise(authApi: IccAuthApi, login: string | undefined, secretProvider: AuthSecretProvider, props?: {
147
+ initialSecret?: SmartAuthProviderInitialSecret;
124
148
  initialAuthToken?: string;
125
149
  initialRefreshToken?: string;
126
150
  loginGroupId?: string;
127
151
  debugLog?: boolean;
128
- }): SmartAuthProvider;
152
+ }): Promise<SmartAuthProvider>;
129
153
  private constructor();
130
154
  getAuthService(): AuthService;
131
155
  switchGroup(newGroupId: string, matches: Array<UserGroup>): Promise<AuthenticationProvider>;
@@ -45,9 +45,13 @@ var AuthSecretType;
45
45
  AuthSecretType["EXTERNAL_AUTHENTICATION"] = "EXTERNAL_AUTHENTICATION";
46
46
  /**
47
47
  * A special case of external authentication where the provider is a digital identity provider.
48
- * Not yet in use.
49
48
  */
50
- // DIGITAL_ID = 'DIGITAL_ID',
49
+ AuthSecretType["DIGITAL_ID"] = "DIGITAL_ID";
50
+ /**
51
+ * The secret is an authentication token for a cloud instance of icure (kraken-cloud).
52
+ * Supported only on lite instances.
53
+ */
54
+ AuthSecretType["ICURE_CLOUD"] = "ICURE_CLOUD";
51
55
  })(AuthSecretType || (exports.AuthSecretType = AuthSecretType = {}));
52
56
  // Here starts internal entities that should not be used directly.
53
57
  /**
@@ -78,24 +82,70 @@ class SmartAuthProvider {
78
82
  * @param secretProvider
79
83
  * @param props optional initialisation properties.
80
84
  */
81
- static initialise(authApi, login, secretProvider, props = {}) {
82
- let initialSecret = undefined;
83
- if (props.initialSecret) {
84
- if ('password' in props.initialSecret) {
85
- initialSecret = { value: props.initialSecret.password, type: ServerAuthenticationClass.PASSWORD };
86
- }
87
- else if ('longToken' in props.initialSecret) {
88
- initialSecret = { value: props.initialSecret.longToken, type: ServerAuthenticationClass.LONG_LIVED_TOKEN };
89
- }
90
- else {
91
- initialSecret = {
92
- value: props.initialSecret.oauthToken,
93
- type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION,
94
- oauthType: props.initialSecret.oauthType,
95
- };
85
+ static initialise(authApi_1, login_1, secretProvider_1) {
86
+ return __awaiter(this, arguments, void 0, function* (authApi, login, secretProvider, props = {}) {
87
+ let initialSecret = undefined;
88
+ let initialAuthToken = props.initialAuthToken;
89
+ let initialRefreshToken = props.initialRefreshToken;
90
+ if (props.initialSecret) {
91
+ if ('password' in props.initialSecret) {
92
+ if (login == undefined)
93
+ throw new Error('To use a password initial secret you must provide a login identifier');
94
+ initialSecret = { value: props.initialSecret.password, type: ServerAuthenticationClass.PASSWORD };
95
+ }
96
+ else if ('longToken' in props.initialSecret) {
97
+ if (login == undefined)
98
+ throw new Error('To use a password initial secret you must provide a login identifier');
99
+ initialSecret = { value: props.initialSecret.longToken, type: ServerAuthenticationClass.LONG_LIVED_TOKEN };
100
+ }
101
+ else if ('oauthToken' in props.initialSecret) {
102
+ if (longLivedOAuthTokens.has(props.initialSecret.oauthType)) {
103
+ initialSecret = {
104
+ value: props.initialSecret.oauthToken,
105
+ type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION,
106
+ oauthType: props.initialSecret.oauthType,
107
+ };
108
+ }
109
+ else {
110
+ try {
111
+ const authResponse = yield authApi.loginWithThirdPartyToken(props.initialSecret.oauthType, props.initialSecret.oauthToken, props.loginGroupId);
112
+ if (authResponse.token != undefined && authResponse.refreshToken != undefined) {
113
+ initialAuthToken = authResponse.token;
114
+ initialRefreshToken = authResponse.refreshToken;
115
+ }
116
+ }
117
+ catch (_) {
118
+ /* ignored */
119
+ }
120
+ }
121
+ }
122
+ else if ('digitalIdToken' in props.initialSecret) {
123
+ try {
124
+ const authResponse = yield authApi.loginWithThirdPartyToken(props.initialSecret.provider, props.initialSecret.digitalIdToken, props.loginGroupId);
125
+ if (authResponse.token != undefined && authResponse.refreshToken != undefined) {
126
+ initialAuthToken = authResponse.token;
127
+ initialRefreshToken = authResponse.refreshToken;
128
+ }
129
+ }
130
+ catch (_) {
131
+ /* ignored */
132
+ }
133
+ }
134
+ else {
135
+ try {
136
+ const authResponse = yield authApi.loginWithCloudToken(props.initialSecret.issuer, props.initialSecret.cloudToken);
137
+ if (authResponse.token != undefined && authResponse.refreshToken != undefined) {
138
+ initialAuthToken = authResponse.token;
139
+ initialRefreshToken = authResponse.refreshToken;
140
+ }
141
+ }
142
+ catch (_) {
143
+ /* ignored */
144
+ }
145
+ }
96
146
  }
97
- }
98
- return new SmartAuthProvider(new TokenProvider(login, props.loginGroupId, initialSecret, props.initialAuthToken, props.initialRefreshToken, authApi, secretProvider, props.debugLog != undefined ? props.debugLog : true), props.loginGroupId);
147
+ return new SmartAuthProvider(new TokenProvider(login, props.loginGroupId, initialSecret, initialAuthToken, initialRefreshToken, authApi, secretProvider, props.debugLog != undefined ? props.debugLog : true), props.loginGroupId);
148
+ });
99
149
  }
100
150
  constructor(tokenProvider, groupId) {
101
151
  this.tokenProvider = tokenProvider;
@@ -121,7 +171,7 @@ class SmartAuthProvider {
121
171
  exports.SmartAuthProvider = SmartAuthProvider;
122
172
  var ServerAuthenticationClass;
123
173
  (function (ServerAuthenticationClass) {
124
- // DIGITAL_ID = 60,
174
+ ServerAuthenticationClass[ServerAuthenticationClass["DIGITAL_ID"] = 60] = "DIGITAL_ID";
125
175
  ServerAuthenticationClass[ServerAuthenticationClass["TWO_FACTOR_AUTHENTICATION"] = 50] = "TWO_FACTOR_AUTHENTICATION";
126
176
  ServerAuthenticationClass[ServerAuthenticationClass["SHORT_LIVED_TOKEN"] = 40] = "SHORT_LIVED_TOKEN";
127
177
  ServerAuthenticationClass[ServerAuthenticationClass["EXTERNAL_AUTHENTICATION"] = 30] = "EXTERNAL_AUTHENTICATION";
@@ -199,7 +249,7 @@ class TokenProvider {
199
249
  if (!!this.currentLongLivedSecret && (!this.currentLongLivedSecret.type || this.currentLongLivedSecret.type >= minimumAuthenticationClassLevel)) {
200
250
  if (this.debugLog)
201
251
  console.log('Using cached secret');
202
- const resultWithCachedSecret = yield this.doGetTokenWithSecret(this.currentLongLivedSecret, minimumAuthenticationClassLevel);
252
+ const resultWithCachedSecret = yield this.doGetTokenWithSecret({ cached: this.currentLongLivedSecret }, minimumAuthenticationClassLevel);
203
253
  if ('success' in resultWithCachedSecret) {
204
254
  if (this.debugLog)
205
255
  console.log('New token using cached secret success');
@@ -227,12 +277,20 @@ class TokenProvider {
227
277
  askSecretAndGetToken(minimumAuthenticationClassLevel, passwordIsValidAs2fa) {
228
278
  return __awaiter(this, void 0, void 0, function* () {
229
279
  const acceptedSecrets = [
230
- minimumAuthenticationClassLevel <= ServerAuthenticationClass.LONG_LIVED_TOKEN ? [AuthSecretType.LONG_LIVED_TOKEN] : [],
231
- minimumAuthenticationClassLevel <= ServerAuthenticationClass.SHORT_LIVED_TOKEN ? [AuthSecretType.SHORT_LIVED_TOKEN] : [],
280
+ minimumAuthenticationClassLevel <= ServerAuthenticationClass.LONG_LIVED_TOKEN && this.login != undefined
281
+ ? [AuthSecretType.LONG_LIVED_TOKEN]
282
+ : [],
283
+ minimumAuthenticationClassLevel <= ServerAuthenticationClass.SHORT_LIVED_TOKEN && this.login != undefined
284
+ ? [AuthSecretType.SHORT_LIVED_TOKEN]
285
+ : [],
232
286
  minimumAuthenticationClassLevel <= ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION &&
287
+ this.login != undefined &&
233
288
  (passwordIsValidAs2fa || minimumAuthenticationClassLevel <= ServerAuthenticationClass.PASSWORD)
234
289
  ? [AuthSecretType.PASSWORD]
235
290
  : [],
291
+ minimumAuthenticationClassLevel <= 0 ? [AuthSecretType.ICURE_CLOUD] : [],
292
+ minimumAuthenticationClassLevel <= ServerAuthenticationClass.DIGITAL_ID ? [AuthSecretType.DIGITAL_ID] : [],
293
+ minimumAuthenticationClassLevel <= ServerAuthenticationClass.EXTERNAL_AUTHENTICATION ? [AuthSecretType.EXTERNAL_AUTHENTICATION] : [],
236
294
  ].flat();
237
295
  if (!acceptedSecrets.length)
238
296
  throw new Error('Internal error: no secret type is accepted for this request. Group may be misconfigured, or client may be outdated.');
@@ -244,7 +302,7 @@ class TokenProvider {
244
302
  if (!acceptedSecrets.includes(secretDetails.secretType))
245
303
  throw new Error(`Accepted secret types are ${JSON.stringify(acceptedSecrets)}, but got a secret of type ${secretDetails.secretType}.`);
246
304
  attempts.push(secretDetails);
247
- const result = yield this.doGetTokenWithSecret(secretDetails, minimumAuthenticationClassLevel);
305
+ const result = yield this.doGetTokenWithSecret({ new: secretDetails }, minimumAuthenticationClassLevel);
248
306
  if ('success' in result) {
249
307
  this.updateCachedSecret(secretDetails);
250
308
  return result.success;
@@ -269,7 +327,7 @@ class TokenProvider {
269
327
  if (details.secretType != AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)
270
328
  throw new Error(`Was expecting a 2fa token but got a secret of type ${details.secretType}.`);
271
329
  attempts.push(details);
272
- const result = yield this.doGetTokenWithSecret({ value: `${password}|${details.value}` }, minimumAuthenticationClassLevel);
330
+ const result = yield this.doGetTokenWithSecret({ new: { value: `${password}|${details.value}`, secretType: AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN } }, minimumAuthenticationClassLevel);
273
331
  if ('success' in result) {
274
332
  this.updateCachedSecret({ value: password, secretType: AuthSecretType.PASSWORD });
275
333
  return result.success;
@@ -280,14 +338,32 @@ class TokenProvider {
280
338
  }
281
339
  });
282
340
  }
283
- doGetTokenWithSecret(secret, minimumAuthenticationClassLevel) {
341
+ doGetTokenWithSecret(secretDetails, minimumAuthenticationClassLevel) {
284
342
  return __awaiter(this, void 0, void 0, function* () {
285
343
  let authResultPromise;
286
- if ('oauthType' in secret && !!secret.oauthType) {
287
- authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value); // TODO add group id
344
+ if ('cached' in secretDetails) {
345
+ const secret = secretDetails.cached;
346
+ if ('oauthType' in secret && !!secret.oauthType) {
347
+ authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value, this.groupId);
348
+ }
349
+ else {
350
+ authResultPromise = this.authApi.login({ username: this.login, password: secret.value }, this.groupId);
351
+ }
288
352
  }
289
353
  else {
290
- authResultPromise = this.authApi.login({ username: this.login, password: secret.value }, this.groupId);
354
+ const secret = secretDetails.new;
355
+ if (secret.secretType == AuthSecretType.DIGITAL_ID) {
356
+ authResultPromise = this.authApi.loginWithThirdPartyToken(secret.provider, secret.value, this.groupId);
357
+ }
358
+ else if (secret.secretType == AuthSecretType.EXTERNAL_AUTHENTICATION) {
359
+ authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value, this.groupId);
360
+ }
361
+ else if (secret.secretType == AuthSecretType.ICURE_CLOUD) {
362
+ authResultPromise = this.authApi.loginWithCloudToken(secret.issuer, secret.value);
363
+ }
364
+ else {
365
+ authResultPromise = this.authApi.login({ username: this.login, password: secret.value }, this.groupId);
366
+ }
291
367
  }
292
368
  return authResultPromise.then((authResult) => {
293
369
  const { token, refreshToken } = authResult;
@@ -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,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,IA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M,IAAI,KAAK,CAAC,oDAAoD,IAAI,CAAC,YAAY,CAAC,EAAE,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
+ {"version":3,"file":"SmartAuthProvider.js","sourceRoot":"","sources":["../../../ic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,CAAC,EAAE,GAAG,CAAC,CAAA;YACxF,CAAC;QACH,CAAC;KAAA;IAED,gBAAgB,CAAC,KAAY;QAC3B,QAAQ,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE,CAAC;YAC7B,KAAK,qBAAqB,CAAC,YAAY;gBACrC,IAAI,CAAC,YAAY,GAAG,EAAE,EAAE,EAAE,qBAAqB,CAAC,SAAS,EAAE,YAAY,EAAE,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE,YAAY,EAAE,KAAK,EAAE,CAAA;gBAC9H,MAAK;YACP,KAAK,qBAAqB,CAAC,kCAAkC;gBAC3D,IAAI,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;QAChG,CAAC;IACH,CAAC;CACF","sourcesContent":["import { AuthenticationProvider } from './AuthenticationProvider'\nimport { UserGroup } from '../../icc-api/model/UserGroup'\nimport { AuthService } from './AuthService'\nimport { DigitalIdProvider, 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 | {\n value: string\n secretType: Exclude<AuthSecretType, AuthSecretType.EXTERNAL_AUTHENTICATION | AuthSecretType.DIGITAL_ID | AuthSecretType.ICURE_CLOUD>\n }\n | { value: string; secretType: AuthSecretType.EXTERNAL_AUTHENTICATION; oauthType: OAuthThirdParty }\n | { value: string; secretType: AuthSecretType.DIGITAL_ID; provider: DigitalIdProvider }\n | { value: string; secretType: AuthSecretType.ICURE_CLOUD; issuer: string }\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 */\n DIGITAL_ID = 'DIGITAL_ID',\n /**\n * The secret is an authentication token for a cloud instance of icure (kraken-cloud).\n * Supported only on lite instances.\n */\n ICURE_CLOUD = 'ICURE_CLOUD',\n}\n\nexport type SmartAuthProviderInitialSecret =\n | { password: string }\n | { longToken: string }\n | { oauthToken: string; oauthType: OAuthThirdParty }\n | { digitalIdToken: string; provider: DigitalIdProvider }\n | { cloudToken: string; issuer: string }\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 async initialise(\n authApi: IccAuthApi,\n login: string | undefined,\n secretProvider: AuthSecretProvider,\n props: {\n initialSecret?: SmartAuthProviderInitialSecret\n initialAuthToken?: string\n initialRefreshToken?: string\n loginGroupId?: string\n debugLog?: boolean\n } = {}\n ): Promise<SmartAuthProvider> {\n let initialSecret: CachedSecretType | undefined = undefined\n let initialAuthToken: string | undefined = props.initialAuthToken\n let initialRefreshToken: string | undefined = props.initialRefreshToken\n if (props.initialSecret) {\n if ('password' in props.initialSecret) {\n if (login == undefined) throw new Error('To use a password initial secret you must provide a login identifier')\n initialSecret = { value: props.initialSecret.password, type: ServerAuthenticationClass.PASSWORD }\n } else if ('longToken' in props.initialSecret) {\n if (login == undefined) throw new Error('To use a password initial secret you must provide a login identifier')\n initialSecret = { value: props.initialSecret.longToken, type: ServerAuthenticationClass.LONG_LIVED_TOKEN }\n } else if ('oauthToken' in props.initialSecret) {\n if (longLivedOAuthTokens.has(props.initialSecret.oauthType)) {\n initialSecret = {\n value: props.initialSecret.oauthToken,\n type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION,\n oauthType: props.initialSecret.oauthType,\n }\n } else {\n try {\n const authResponse = await authApi.loginWithThirdPartyToken(\n props.initialSecret.oauthType,\n props.initialSecret.oauthToken,\n props.loginGroupId\n )\n if (authResponse.token != undefined && authResponse.refreshToken != undefined) {\n initialAuthToken = authResponse.token\n initialRefreshToken = authResponse.refreshToken\n }\n } catch (_) {\n /* ignored */\n }\n }\n } else if ('digitalIdToken' in props.initialSecret) {\n try {\n const authResponse = await authApi.loginWithThirdPartyToken(\n props.initialSecret.provider,\n props.initialSecret.digitalIdToken,\n props.loginGroupId\n )\n if (authResponse.token != undefined && authResponse.refreshToken != undefined) {\n initialAuthToken = authResponse.token\n initialRefreshToken = authResponse.refreshToken\n }\n } catch (_) {\n /* ignored */\n }\n } else {\n try {\n const authResponse = await authApi.loginWithCloudToken(props.initialSecret.issuer, props.initialSecret.cloudToken)\n if (authResponse.token != undefined && authResponse.refreshToken != undefined) {\n initialAuthToken = authResponse.token\n initialRefreshToken = authResponse.refreshToken\n }\n } catch (_) {\n /* ignored */\n }\n }\n }\n return new SmartAuthProvider(\n new TokenProvider(\n login,\n props.loginGroupId,\n initialSecret,\n initialAuthToken,\n 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 | undefined,\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({ cached: 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 && this.login != undefined\n ? [AuthSecretType.LONG_LIVED_TOKEN]\n : [],\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.SHORT_LIVED_TOKEN && this.login != undefined\n ? [AuthSecretType.SHORT_LIVED_TOKEN]\n : [],\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION &&\n this.login != undefined &&\n (passwordIsValidAs2fa || minimumAuthenticationClassLevel <= ServerAuthenticationClass.PASSWORD)\n ? [AuthSecretType.PASSWORD]\n : [],\n minimumAuthenticationClassLevel <= 0 ? [AuthSecretType.ICURE_CLOUD] : [],\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.DIGITAL_ID ? [AuthSecretType.DIGITAL_ID] : [],\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.EXTERNAL_AUTHENTICATION ? [AuthSecretType.EXTERNAL_AUTHENTICATION] : [],\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({ new: 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(\n { new: { value: `${password}|${details.value}`, secretType: AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN } },\n minimumAuthenticationClassLevel\n )\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 secretDetails: { new: AuthSecretDetails } | { cached: CachedSecretType },\n minimumAuthenticationClassLevel: number\n ): Promise<DoGetTokenResult> {\n let authResultPromise: Promise<AuthenticationResponse>\n if ('cached' in secretDetails) {\n const secret = secretDetails.cached\n if ('oauthType' in secret && !!secret.oauthType) {\n authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value, this.groupId)\n } else {\n authResultPromise = this.authApi.login({ username: this.login, password: secret.value }, this.groupId)\n }\n } else {\n const secret = secretDetails.new\n if (secret.secretType == AuthSecretType.DIGITAL_ID) {\n authResultPromise = this.authApi.loginWithThirdPartyToken(secret.provider, secret.value, this.groupId)\n } else if (secret.secretType == AuthSecretType.EXTERNAL_AUTHENTICATION) {\n authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value, this.groupId)\n } else if (secret.secretType == AuthSecretType.ICURE_CLOUD) {\n authResultPromise = this.authApi.loginWithCloudToken(secret.issuer, secret.value)\n } else {\n authResultPromise = this.authApi.login({ username: this.login, password: secret.value }, this.groupId)\n }\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"]}
@@ -80,7 +80,8 @@ class IccBekmehrXApi extends icc_api_1.IccBekmehrApi {
80
80
  }
81
81
  else if (msg.type === 'DocumentDto') {
82
82
  that.documentApi
83
- .decrypt(healthcarePartyId, msg.body.map((d) => new models_1.Document(d)))
83
+ .decrypt(msg.body.map((d) => new models_1.Document(d)))
84
+ .then((res) => res.map((x) => x.entity))
84
85
  .then((res) => patchers
85
86
  .filter((p) => p.type === 'DocumentDto')
86
87
  .reduce((p, patcher) => __awaiter(this, void 0, void 0, function* () { return patcher.patch(yield p); }), Promise.resolve(res)))
@@ -1 +1 @@
1
- {"version":3,"file":"icc-bekmehr-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-bekmehr-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AACA,wCAA0C;AAI1C,uDAA0D;AAC1D,oDAAmF;AACnF,0EAAgG;AAoBhG,MAAa,cAAe,SAAQ,uBAAa;IAM/C,YACE,IAAY,EACZ,OAAkC,EAClC,MAAsB,EACtB,WAA4B,EAC5B,WAA4B,EAC5B,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QACvD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAC9B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAE9B,IAAI,CAAC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,MAAM,KAAK,W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c-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { ua2string, utf8_2ua } from './utils/binary-utils'\nimport { Contact, Document, HealthElement, Service } from '../icc-api/model/models'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport type Patcher = ContactPatcher | HealthElementPatcher | DocumentPatcher | ServicePatcher\nexport interface ContactPatcher {\n type: 'ContactDto'\n patch: (contacts: Contact[]) => Promise<Contact[]>\n}\nexport interface HealthElementPatcher {\n type: 'HealthElementDto'\n patch: (patients: HealthElement[]) => Promise<HealthElement[]>\n}\nexport interface DocumentPatcher {\n type: 'DocumentDto'\n patch: (documents: Document[]) => Promise<Document[]>\n}\nexport interface ServicePatcher {\n type: 'ServiceDto'\n patch: (documents: Service[]) => Promise<Service[]>\n}\n\nexport class IccBekmehrXApi extends IccBekmehrApi {\n private readonly ctcApi: IccContactXApi\n private readonly helementApi: IccHelementXApi\n private readonly documentApi: IccDocumentXApi\n private readonly wssHost: string\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n ctcApi: IccContactXApi,\n helementApi: IccHelementXApi,\n documentApi: IccDocumentXApi,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.ctcApi = ctcApi\n this.helementApi = helementApi\n this.documentApi = documentApi\n\n this.wssHost = new URL(this.host, typeof window !== 'undefined' ? window.location.href : undefined).href\n .replace(/^http/, 'ws')\n .replace(/\\/rest\\/v.+/, '/ws')\n }\n\n private async getJwt(): Promise<string> {\n const authService = this.authenticationProvider.getAuthService()\n if (!!authService.jwtGetter) {\n const tokens = await authService.jwtGetter()\n if (!tokens) {\n throw new Error('Missing JWT')\n }\n return tokens.token\n } else {\n throw new Error('The existing provider is not a JWT provider')\n }\n }\n\n socketEventListener(\n socket: WebSocket,\n healthcarePartyId: string,\n resolve: (value: Blob) => void,\n reject: (reason?: any) => void,\n patchers: Patcher[],\n progressCallback?: (progress: number) => void\n ) {\n const that = this\n\n const send = (command: string, uuid: string, body: any) => {\n const data = JSON.stringify({ command, uuid, body })\n socket.send(data.length > 65000 ? utf8_2ua(data).buffer : data)\n }\n\n const messageHandler = (msg: any, event: any) => {\n if (msg.command === 'decrypt') {\n if (msg.type === 'ContactDto') {\n that.ctcApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ContactDto')\n .reduce(async (p, patcher) => (patcher as ContactPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'HealthElementDto') {\n that.helementApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'HealthElementDto')\n .reduce(async (p, patcher) => (patcher as HealthElementPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'DocumentDto') {\n that.documentApi\n .decrypt(\n healthcarePartyId,\n msg.body.map((d: JSON) => new Document(d))\n )\n .then((res) =>\n patchers\n .filter((p) => p.type === 'DocumentDto')\n .reduce(async (p, patcher) => (patcher as DocumentPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) =>\n send(\n 'decryptResponse',\n msg.uuid,\n res?.map((d) => {\n const de = d.decryptedAttachment\n const { encryptedAttachment, ...stripped } = d\n return de ? { ...stripped, decryptedAttachment: btoa(ua2string(de)) } : stripped\n })\n )\n )\n } else if (msg.type === 'ServiceDto') {\n that.ctcApi\n .decryptServices(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ServiceDto')\n .reduce(async (p, patcher) => (patcher as ServicePatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n }\n } else if (msg.command === 'progress') {\n if (progressCallback && msg.body && msg.body[0]) {\n progressCallback(msg.body[0].progress)\n }\n } else {\n console.error('error received from backend:' + event.data)\n reject('websocket error: ' + event.data)\n socket.close(4000, 'backend error')\n }\n }\n\n return (event: MessageEvent) => {\n if (typeof event.data === 'string') {\n const msg = JSON.parse(event.data)\n messageHandler(msg, event)\n } else {\n const blob: Blob = event.data\n const subBlob = blob.slice(0, 1)\n const br = new FileReader()\n br.onload = function (e) {\n const firstChar = e.target && new Uint8Array((e.target as any).result as ArrayBuffer)[0]\n\n if (firstChar === 0x7b) {\n const tr = new FileReader()\n tr.onload = function (e) {\n const msg = e.target && JSON.parse((e.target as any).result as string)\n messageHandler(msg, event)\n }\n tr.readAsBinaryString(blob)\n } else {\n resolve(blob)\n socket.close(1000, 'Ok')\n }\n }\n br.readAsArrayBuffer(subBlob)\n }\n }\n }\n\n generateSmfExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SoftwareMedicalFileExport,\n progressCallback?: (progress: number) => void,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSmf?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers, progressCallback))\n })\n )\n }\n\n generateSumehrExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehr?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateSumehrV2ExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehrV2?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateDiaryNoteExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateDiaryNote?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateMedicationSchemeWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n recipientSafe: string,\n version: number,\n body: models.MedicationSchemeExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateMedicationScheme?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: {\n patientId: patientId,\n language: language,\n recipientSafe: recipientSafe,\n version: version,\n info: body,\n },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n}\n"]}
1
+ {"version":3,"file":"icc-bekmehr-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-bekmehr-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AACA,wCAA0C;AAI1C,uDAA0D;AAC1D,oDAAmF;AACnF,0EAAgG;AAoBhG,MAAa,cAAe,SAAQ,uBAAa;IAM/C,YACE,IAAY,EACZ,OAAkC,EAClC,MAAsB,EACtB,WAA4B,EAC5B,WAA4B,EAC5B,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QACvD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAC9B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAE9B,IAAI,CAAC,OAAO,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,IAAI;aACrG,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC;aACtB,OAAO,CAAC,aAAa,EAAE,KAAK,CAAC,CAAA;IAClC,CAAC;IAEa,MAAM;;YAClB,MAAM,WAAW,GAAG,IAAI,CAAC,sBAAsB,CAAC,cAAc,EAAE,CAAA;YAChE,IAAI,CA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I,CAAC,mBAAmB,CAAC,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAA;QACpH,CAAC,CAAC,CACL,CAAA;IACH,CAAC;IAED,6CAA6C,CAC3C,SAAiB,EACjB,iBAAyB,EACzB,QAAgB,EAChB,aAAqB,EACrB,OAAe,EACf,IAAuC,EACvC,WAAsB,EAAE;QAExB,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,CACvB,CAAC,GAAG,EAAE,EAAE,CACN,IAAI,OAAO,CAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAChD,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,GAAG,IAAI,CAAC,OAAO,0CAA0C,GAAG,EAAE,CAAC,CAAA;YAC5F,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE;gBAC9B,MAAM,CAAC,IAAI,CACT,IAAI,CAAC,SAAS,CAAC;oBACb,UAAU,EAAE;wBACV,SAAS,EAAE,SAAS;wBACpB,QAAQ,EAAE,QAAQ;wBAClB,aAAa,EAAE,aAAa;wBAC5B,OAAO,EAAE,OAAO;wBAChB,IAAI,EAAE,IAAI;qBACX;iBACF,CAAC,CACH,CAAA;YACH,CAAC,CAAC,CAAA;YACF,sBAAsB;YACtB,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAA;QACpH,CAAC,CAAC,CACL,CAAA;IACH,CAAC;CACF;AAlRD,wCAkRC","sourcesContent":["import * as models from '../icc-api/model/models'\nimport { IccBekmehrApi } from '../icc-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { ua2string, utf8_2ua } from './utils/binary-utils'\nimport { Contact, Document, HealthElement, Service } from '../icc-api/model/models'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport type Patcher = ContactPatcher | HealthElementPatcher | DocumentPatcher | ServicePatcher\nexport interface ContactPatcher {\n type: 'ContactDto'\n patch: (contacts: Contact[]) => Promise<Contact[]>\n}\nexport interface HealthElementPatcher {\n type: 'HealthElementDto'\n patch: (patients: HealthElement[]) => Promise<HealthElement[]>\n}\nexport interface DocumentPatcher {\n type: 'DocumentDto'\n patch: (documents: Document[]) => Promise<Document[]>\n}\nexport interface ServicePatcher {\n type: 'ServiceDto'\n patch: (documents: Service[]) => Promise<Service[]>\n}\n\nexport class IccBekmehrXApi extends IccBekmehrApi {\n private readonly ctcApi: IccContactXApi\n private readonly helementApi: IccHelementXApi\n private readonly documentApi: IccDocumentXApi\n private readonly wssHost: string\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n ctcApi: IccContactXApi,\n helementApi: IccHelementXApi,\n documentApi: IccDocumentXApi,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.ctcApi = ctcApi\n this.helementApi = helementApi\n this.documentApi = documentApi\n\n this.wssHost = new URL(this.host, typeof window !== 'undefined' ? window.location.href : undefined).href\n .replace(/^http/, 'ws')\n .replace(/\\/rest\\/v.+/, '/ws')\n }\n\n private async getJwt(): Promise<string> {\n const authService = this.authenticationProvider.getAuthService()\n if (!!authService.jwtGetter) {\n const tokens = await authService.jwtGetter()\n if (!tokens) {\n throw new Error('Missing JWT')\n }\n return tokens.token\n } else {\n throw new Error('The existing provider is not a JWT provider')\n }\n }\n\n socketEventListener(\n socket: WebSocket,\n healthcarePartyId: string,\n resolve: (value: Blob) => void,\n reject: (reason?: any) => void,\n patchers: Patcher[],\n progressCallback?: (progress: number) => void\n ) {\n const that = this\n\n const send = (command: string, uuid: string, body: any) => {\n const data = JSON.stringify({ command, uuid, body })\n socket.send(data.length > 65000 ? utf8_2ua(data).buffer : data)\n }\n\n const messageHandler = (msg: any, event: any) => {\n if (msg.command === 'decrypt') {\n if (msg.type === 'ContactDto') {\n that.ctcApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ContactDto')\n .reduce(async (p, patcher) => (patcher as ContactPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'HealthElementDto') {\n that.helementApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'HealthElementDto')\n .reduce(async (p, patcher) => (patcher as HealthElementPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'DocumentDto') {\n that.documentApi\n .decrypt(msg.body.map((d: JSON) => new Document(d)))\n .then((res) => res.map((x) => x.entity))\n .then((res) =>\n patchers\n .filter((p) => p.type === 'DocumentDto')\n .reduce(async (p, patcher) => (patcher as DocumentPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) =>\n send(\n 'decryptResponse',\n msg.uuid,\n res?.map((d) => {\n const de = d.decryptedAttachment\n const { encryptedAttachment, ...stripped } = d\n return de ? { ...stripped, decryptedAttachment: btoa(ua2string(de)) } : stripped\n })\n )\n )\n } else if (msg.type === 'ServiceDto') {\n that.ctcApi\n .decryptServices(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ServiceDto')\n .reduce(async (p, patcher) => (patcher as ServicePatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n }\n } else if (msg.command === 'progress') {\n if (progressCallback && msg.body && msg.body[0]) {\n progressCallback(msg.body[0].progress)\n }\n } else {\n console.error('error received from backend:' + event.data)\n reject('websocket error: ' + event.data)\n socket.close(4000, 'backend error')\n }\n }\n\n return (event: MessageEvent) => {\n if (typeof event.data === 'string') {\n const msg = JSON.parse(event.data)\n messageHandler(msg, event)\n } else {\n const blob: Blob = event.data\n const subBlob = blob.slice(0, 1)\n const br = new FileReader()\n br.onload = function (e) {\n const firstChar = e.target && new Uint8Array((e.target as any).result as ArrayBuffer)[0]\n\n if (firstChar === 0x7b) {\n const tr = new FileReader()\n tr.onload = function (e) {\n const msg = e.target && JSON.parse((e.target as any).result as string)\n messageHandler(msg, event)\n }\n tr.readAsBinaryString(blob)\n } else {\n resolve(blob)\n socket.close(1000, 'Ok')\n }\n }\n br.readAsArrayBuffer(subBlob)\n }\n }\n }\n\n generateSmfExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SoftwareMedicalFileExport,\n progressCallback?: (progress: number) => void,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSmf?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers, progressCallback))\n })\n )\n }\n\n generateSumehrExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehr?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateSumehrV2ExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehrV2?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateDiaryNoteExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateDiaryNote?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateMedicationSchemeWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n recipientSafe: string,\n version: number,\n body: models.MedicationSchemeExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateMedicationScheme?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: {\n patientId: patientId,\n language: language,\n recipientSafe: recipientSafe,\n version: version,\n info: body,\n },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n}\n"]}