@icure/api 8.0.40 → 8.0.42

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.
@@ -30,7 +30,7 @@ export declare class Partnership {
30
30
  otherToMeRelationshipDescription?: string;
31
31
  }
32
32
  export declare namespace Partnership {
33
- type TypeEnum = 'primary_contact' | 'primary_contact_for' | 'family' | 'friend' | 'counselor' | 'contact' | 'brother' | 'brotherinlaw' | 'child' | 'daughter' | 'employer' | 'father' | 'grandchild' | 'grandparent' | 'husband' | 'lawyer' | 'mother' | 'neighbour' | 'notary' | 'partner' | 'sister' | 'sisterinlaw' | 'son' | 'spouse' | 'stepdaughter' | 'stepfather' | 'stepmother' | 'stepson' | 'tutor' | 'next_of_kin' | 'federal_agency' | 'insurance_company' | 'state_agency' | 'unknown' | 'seealso' | 'refer';
33
+ type TypeEnum = 'primary_contact' | 'primary_contact_for' | 'family' | 'friend' | 'counselor' | 'contact' | 'brother' | 'brotherinlaw' | 'child' | 'daughter' | 'employer' | 'father' | 'grandchild' | 'grandparent' | 'husband' | 'lawyer' | 'mother' | 'neighbour' | 'notary' | 'partner' | 'sister' | 'sisterinlaw' | 'son' | 'spouse' | 'stepdaughter' | 'stepfather' | 'stepmother' | 'stepson' | 'tutor' | 'cohabiting' | 'registered_partner' | 'next_of_kin' | 'federal_agency' | 'insurance_company' | 'state_agency' | 'unknown' | 'seealso' | 'refer';
34
34
  const TypeEnum: {
35
35
  PrimaryContact: TypeEnum;
36
36
  PrimaryContactFor: TypeEnum;
@@ -61,6 +61,8 @@ export declare namespace Partnership {
61
61
  Stepmother: TypeEnum;
62
62
  Stepson: TypeEnum;
63
63
  Tutor: TypeEnum;
64
+ Cohabiting: TypeEnum;
65
+ RegisteredPartner: TypeEnum;
64
66
  NextOfKin: TypeEnum;
65
67
  FederalAgency: TypeEnum;
66
68
  InsuranceCompany: TypeEnum;
@@ -52,6 +52,8 @@ exports.Partnership = Partnership;
52
52
  Stepmother: 'stepmother',
53
53
  Stepson: 'stepson',
54
54
  Tutor: 'tutor',
55
+ Cohabiting: 'cohabiting',
56
+ RegisteredPartner: 'registered_partner',
55
57
  NextOfKin: 'next_of_kin',
56
58
  FederalAgency: 'federal_agency',
57
59
  InsuranceCompany: 'insurance_company',
@@ -1 +1 @@
1
- {"version":3,"file":"Partnership.js","sourceRoot":"","sources":["../../../icc-api/model/Partnership.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAEH;;GAEG;AACH,MAAa,WAAW;IACtB,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAAmB,EAAE,IAAI,CAAC,CAAA;IAC1C,CAAC;CAgBF;AAnBD,kCAmBC;AACD,WAAiB,WAAW;IAsCb,oBAAQ,GAAG;QACtB,cAAc,EAAE,iBAA6B;QAC7C,iBAAiB,EAAE,qBAAiC;QACpD,MAAM,EAAE,QAAoB;QAC5B,MAAM,EAAE,QAAoB;QAC5B,SAAS,EAAE,WAAuB;QAClC,OAAO,EAAE,SAAqB;QAC9B,OAAO,EAAE,SAAqB;QAC9B,YAAY,EAAE,cAA0B;QACxC,KAAK,EAAE,OAAmB;QAC1B,QAAQ,EAAE,UAAsB;QAChC,QAAQ,EAAE,UAAsB;QAChC,MAAM,EAAE,QAAoB;QAC5B,UAAU,EAAE,YAAwB;QACpC,WAAW,EAAE,aAAyB;QACtC,OAAO,EAAE,SAAqB;QAC9B,MAAM,EAAE,QAAoB;QAC5B,MAAM,EAAE,QAAoB;QAC5B,SAAS,EAAE,WAAuB;QAClC,MAAM,EAAE,QAAoB;QAC5B,OAAO,EAAE,SAAqB;QAC9B,MAAM,EAAE,QAAoB;QAC5B,WAAW,EAAE,aAAyB;QACtC,GAAG,EAAE,KAAiB;QACtB,MAAM,EAAE,QAAoB;QAC5B,YAAY,EAAE,cAA0B;QACxC,UAAU,EAAE,YAAwB;QACpC,UAAU,EAAE,YAAwB;QACpC,OAAO,EAAE,SAAqB;QAC9B,KAAK,EAAE,OAAmB;QAC1B,SAAS,EAAE,aAAyB;QACpC,aAAa,EAAE,gBAA4B;QAC3C,gBAAgB,EAAE,mBAA+B;QACjD,WAAW,EAAE,cAA0B;QACvC,OAAO,EAAE,SAAqB;QAC9B,OAAO,EAAE,SAAqB;QAC9B,KAAK,EAAE,OAAmB;KAC3B,CAAA;IAEY,sBAAU,GAAG;QACxB,MAAM,EAAE,QAAsB;QAC9B,WAAW,EAAE,aAA2B;QACxC,IAAI,EAAE,MAAoB;KAC3B,CAAA;AACH,CAAC,EAlFgB,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAkF3B","sourcesContent":["/**\n * iCure Data Stack API Documentation\n * The iCure Data Stack Application API is the native interface to iCure. This version is obsolete, please use v2.\n *\n * OpenAPI spec version: v1\n *\n *\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen.git\n * Do not edit the class manually.\n */\n\n/**\n * A relationship between this patient and another person.\n */\nexport class Partnership {\n constructor(json: JSON | any) {\n Object.assign(this as Partnership, json)\n }\n\n /**\n * Type of relationship.\n */\n type?: Partnership.TypeEnum\n /**\n * Status of the relationship.\n */\n status?: Partnership.StatusEnum\n /**\n * UUID of the contact person or patient in this relationship.\n */\n partnerId?: string\n meToOtherRelationshipDescription?: string\n otherToMeRelationshipDescription?: string\n}\nexport namespace Partnership {\n export type TypeEnum =\n | 'primary_contact'\n | 'primary_contact_for'\n | 'family'\n | 'friend'\n | 'counselor'\n | 'contact'\n | 'brother'\n | 'brotherinlaw'\n | 'child'\n | 'daughter'\n | 'employer'\n | 'father'\n | 'grandchild'\n | 'grandparent'\n | 'husband'\n | 'lawyer'\n | 'mother'\n | 'neighbour'\n | 'notary'\n | 'partner'\n | 'sister'\n | 'sisterinlaw'\n | 'son'\n | 'spouse'\n | 'stepdaughter'\n | 'stepfather'\n | 'stepmother'\n | 'stepson'\n | 'tutor'\n | 'next_of_kin'\n | 'federal_agency'\n | 'insurance_company'\n | 'state_agency'\n | 'unknown'\n | 'seealso'\n | 'refer'\n export const TypeEnum = {\n PrimaryContact: 'primary_contact' as TypeEnum,\n PrimaryContactFor: 'primary_contact_for' as TypeEnum,\n Family: 'family' as TypeEnum,\n Friend: 'friend' as TypeEnum,\n Counselor: 'counselor' as TypeEnum,\n Contact: 'contact' as TypeEnum,\n Brother: 'brother' as TypeEnum,\n Brotherinlaw: 'brotherinlaw' as TypeEnum,\n Child: 'child' as TypeEnum,\n Daughter: 'daughter' as TypeEnum,\n Employer: 'employer' as TypeEnum,\n Father: 'father' as TypeEnum,\n Grandchild: 'grandchild' as TypeEnum,\n Grandparent: 'grandparent' as TypeEnum,\n Husband: 'husband' as TypeEnum,\n Lawyer: 'lawyer' as TypeEnum,\n Mother: 'mother' as TypeEnum,\n Neighbour: 'neighbour' as TypeEnum,\n Notary: 'notary' as TypeEnum,\n Partner: 'partner' as TypeEnum,\n Sister: 'sister' as TypeEnum,\n Sisterinlaw: 'sisterinlaw' as TypeEnum,\n Son: 'son' as TypeEnum,\n Spouse: 'spouse' as TypeEnum,\n Stepdaughter: 'stepdaughter' as TypeEnum,\n Stepfather: 'stepfather' as TypeEnum,\n Stepmother: 'stepmother' as TypeEnum,\n Stepson: 'stepson' as TypeEnum,\n Tutor: 'tutor' as TypeEnum,\n NextOfKin: 'next_of_kin' as TypeEnum,\n FederalAgency: 'federal_agency' as TypeEnum,\n InsuranceCompany: 'insurance_company' as TypeEnum,\n StateAgency: 'state_agency' as TypeEnum,\n Unknown: 'unknown' as TypeEnum,\n Seealso: 'seealso' as TypeEnum,\n Refer: 'refer' as TypeEnum,\n }\n export type StatusEnum = 'active' | 'complicated' | 'past'\n export const StatusEnum = {\n Active: 'active' as StatusEnum,\n Complicated: 'complicated' as StatusEnum,\n Past: 'past' as StatusEnum,\n }\n}\n"]}
1
+ {"version":3,"file":"Partnership.js","sourceRoot":"","sources":["../../../icc-api/model/Partnership.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAEH;;GAEG;AACH,MAAa,WA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AAE,aAA2B;QACxC,IAAI,EAAE,MAAoB;KAC3B,CAAA;AACH,CAAC,EAtFgB,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAsF3B","sourcesContent":["/**\n * iCure Data Stack API Documentation\n * The iCure Data Stack Application API is the native interface to iCure. This version is obsolete, please use v2.\n *\n * OpenAPI spec version: v1\n *\n *\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen.git\n * Do not edit the class manually.\n */\n\n/**\n * A relationship between this patient and another person.\n */\nexport class Partnership {\n constructor(json: JSON | any) {\n Object.assign(this as Partnership, json)\n }\n\n /**\n * Type of relationship.\n */\n type?: Partnership.TypeEnum\n /**\n * Status of the relationship.\n */\n status?: Partnership.StatusEnum\n /**\n * UUID of the contact person or patient in this relationship.\n */\n partnerId?: string\n meToOtherRelationshipDescription?: string\n otherToMeRelationshipDescription?: string\n}\nexport namespace Partnership {\n export type TypeEnum =\n | 'primary_contact'\n | 'primary_contact_for'\n | 'family'\n | 'friend'\n | 'counselor'\n | 'contact'\n | 'brother'\n | 'brotherinlaw'\n | 'child'\n | 'daughter'\n | 'employer'\n | 'father'\n | 'grandchild'\n | 'grandparent'\n | 'husband'\n | 'lawyer'\n | 'mother'\n | 'neighbour'\n | 'notary'\n | 'partner'\n | 'sister'\n | 'sisterinlaw'\n | 'son'\n | 'spouse'\n | 'stepdaughter'\n | 'stepfather'\n | 'stepmother'\n | 'stepson'\n | 'tutor'\n | 'cohabiting'\n | 'registered_partner'\n | 'next_of_kin'\n | 'federal_agency'\n | 'insurance_company'\n | 'state_agency'\n | 'unknown'\n | 'seealso'\n | 'refer'\n export const TypeEnum = {\n PrimaryContact: 'primary_contact' as TypeEnum,\n PrimaryContactFor: 'primary_contact_for' as TypeEnum,\n Family: 'family' as TypeEnum,\n Friend: 'friend' as TypeEnum,\n Counselor: 'counselor' as TypeEnum,\n Contact: 'contact' as TypeEnum,\n Brother: 'brother' as TypeEnum,\n Brotherinlaw: 'brotherinlaw' as TypeEnum,\n Child: 'child' as TypeEnum,\n Daughter: 'daughter' as TypeEnum,\n Employer: 'employer' as TypeEnum,\n Father: 'father' as TypeEnum,\n Grandchild: 'grandchild' as TypeEnum,\n Grandparent: 'grandparent' as TypeEnum,\n Husband: 'husband' as TypeEnum,\n Lawyer: 'lawyer' as TypeEnum,\n Mother: 'mother' as TypeEnum,\n Neighbour: 'neighbour' as TypeEnum,\n Notary: 'notary' as TypeEnum,\n Partner: 'partner' as TypeEnum,\n Sister: 'sister' as TypeEnum,\n Sisterinlaw: 'sisterinlaw' as TypeEnum,\n Son: 'son' as TypeEnum,\n Spouse: 'spouse' as TypeEnum,\n Stepdaughter: 'stepdaughter' as TypeEnum,\n Stepfather: 'stepfather' as TypeEnum,\n Stepmother: 'stepmother' as TypeEnum,\n Stepson: 'stepson' as TypeEnum,\n Tutor: 'tutor' as TypeEnum,\n Cohabiting: 'cohabiting' as TypeEnum,\n RegisteredPartner: 'registered_partner' as TypeEnum,\n NextOfKin: 'next_of_kin' as TypeEnum,\n FederalAgency: 'federal_agency' as TypeEnum,\n InsuranceCompany: 'insurance_company' as TypeEnum,\n StateAgency: 'state_agency' as TypeEnum,\n Unknown: 'unknown' as TypeEnum,\n Seealso: 'seealso' as TypeEnum,\n Refer: 'refer' as TypeEnum,\n }\n export type StatusEnum = 'active' | 'complicated' | 'past'\n export const StatusEnum = {\n Active: 'active' as StatusEnum,\n Complicated: 'complicated' as StatusEnum,\n Past: 'past' as StatusEnum,\n }\n}\n"]}
@@ -113,7 +113,9 @@ export declare class SmartAuthProvider implements AuthenticationProvider {
113
113
  */
114
114
  static initialise(authApi: IccAuthApi, login: string, secretProvider: AuthSecretProvider, props?: {
115
115
  initialSecret?: {
116
- plainSecret: string;
116
+ password: string;
117
+ } | {
118
+ longToken: string;
117
119
  } | {
118
120
  oauthToken: string;
119
121
  oauthType: OAuthThirdParty;
@@ -81,8 +81,11 @@ class SmartAuthProvider {
81
81
  static initialise(authApi, login, secretProvider, props = {}) {
82
82
  let initialSecret = undefined;
83
83
  if (props.initialSecret) {
84
- if ('plainSecret' in props.initialSecret) {
85
- initialSecret = { value: props.initialSecret.plainSecret, type: undefined };
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 };
86
89
  }
87
90
  else {
88
91
  initialSecret = {
@@ -251,7 +254,7 @@ class TokenProvider {
251
254
  return __awaiter(this, void 0, void 0, function* () {
252
255
  let authResultPromise;
253
256
  if ('oauthType' in secret && !!secret.oauthType) {
254
- authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value);
257
+ authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value); // TODO add group id
255
258
  }
256
259
  else {
257
260
  authResultPromise = this.authApi.login({ username: this.login, password: secret.value }, this.groupId);
@@ -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;AAmDnE;;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,GAAd,sBAAc,KAAd,sBAAc,QA8BzB;AAED,kEAAkE;AAElE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAa,iBAAiB;IAC5B;;;;;;OAMG;I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AAE,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;SAC/F;IACH,CAAC;CACF","sourcesContent":["import { AuthenticationProvider } from './AuthenticationProvider'\nimport { UserGroup } from '../../icc-api/model/UserGroup'\nimport { AuthService } from './AuthService'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { XHR } from '../../icc-api/api/XHR'\nimport XHRError = XHR.XHRError\nimport { decodeJwtClaims, isJwtInvalidOrExpired } from './JwtUtils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\n\n/**\n * Needed by a {@link SmartAuthProvider} to get the secrets (password, token, etc.) for authentication to the iCure SDK as needed.\n */\nexport interface AuthSecretProvider {\n /**\n * Provides a secret for authentication to the iCure SDK.\n *\n * ## Accepted secrets\n *\n * The method will be provided with an array of the secrets types that are acceptable (`acceptedSecrets`). Usually this array will contain multiple\n * elements, but this depends on the group configuration, the user (if he has 2fa setup or not), or the operation being performed. For groups using\n * default configurations and for patients without 2fa enabled for example the array will always contain the {@link AuthSecretType.PASSWORD} element.\n * Usually the array contain also the {@link AuthSecretType.LONG_LIVED_TOKEN} element, but if the user is attempting to perform a sensitive operations\n * such as changing his password the default group configuration does not allow for the user to authenticate using a JWT obtained from a long-lived\n * token for this operation, meaning the array will not contain the {@link AuthSecretType.LONG_LIVED_TOKEN} element.\n *\n * Regardless of the number of elements in the array only one secret of the accepted types is sufficient for the operation to succeed.\n *\n * ## TWO_FACTOR_AUTHENTICATION_TOKEN secret type\n *\n * The {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN} secret type is only used when the user has 2fa enabled. In this case the SDK will call\n * this method twice, once containing the {@link AuthSecretType.PASSWORD} element in the `acceptedSecrets` array, and if the provided secret is a\n * valid password the SDK will immediately call this method again, this time containing the {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN}\n * instead of the {@link AuthSecretType.PASSWORD} element.\n *\n * Any future call to this method from the same provider instance will not contain the {@link AuthSecretType.PASSWORD} element anymore, as it is\n * cached, but it may contain the {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN} element instead.\n *\n * Note that the 2fa token is not needed for logging in through a long-lived or short-lived token, it is only used in combination with a password.\n * If the user is using 2fa, and you get in input as `acceptedSecrets` an array `[PASSWORD, LONG_LIVED_TOKEN, SHORT_LIVED_TOKEN]`, and you pass to\n * authenticate a long-lived token, the SDK will not call this method again to ask for the 2fa token.\n *\n * @param acceptedSecrets the types of secrets that are acceptable for the operation being performed.\n * @param previousAttempts the secrets that were previously attempted by the SDK for this operation. This array will be empty the first time this\n * method is called for a given operation, but it may contain multiple elements if the SDK has already called this method multiple times because the\n * previously returned secrets were not valid. The first element is the first secret that was attempted, and the last element is the most recently\n * attempted.\n * @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[]): 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?: { plainSecret: string } | { oauthToken: string; oauthType: OAuthThirdParty }\n initialAuthToken?: string\n initialRefreshToken?: string\n loginGroupId?: string\n } = {}\n ): SmartAuthProvider {\n let initialSecret: CachedSecretType | undefined = undefined\n if (props.initialSecret) {\n if ('plainSecret' in props.initialSecret) {\n initialSecret = { value: props.initialSecret.plainSecret, type: undefined }\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(login, props.loginGroupId, initialSecret, props.initialAuthToken, props.initialRefreshToken, authApi, secretProvider),\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 Promise.resolve(undefined)\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 ) {}\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 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 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.currentLongLivedSecret && (!this.currentLongLivedSecret.type || this.currentLongLivedSecret.type >= minimumAuthenticationClassLevel)) {\n const resultWithCachedSecret = await this.doGetTokenWithSecret(this.currentLongLivedSecret, minimumAuthenticationClassLevel)\n if ('success' in resultWithCachedSecret) {\n return resultWithCachedSecret.success\n } else if (\n resultWithCachedSecret.failure === DoGetTokenResultFailureReason.NEEDS_2FA &&\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION\n ) {\n return this.askTotpAndGetToken(this.currentLongLivedSecret.value, minimumAuthenticationClassLevel)\n } else return this.askSecretAndGetToken(minimumAuthenticationClassLevel, true)\n } else {\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 while (true) {\n const secretDetails = await this.authSecretProvider.getSecret([...acceptedSecrets], attempts)\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)\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)\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 )\n }\n\n private updateCachedSecret(details: AuthSecretDetails) {\n switch (details.secretType) {\n case AuthSecretType.PASSWORD:\n this.currentLongLivedSecret = { value: details.value, type: ServerAuthenticationClass.PASSWORD }\n break\n case AuthSecretType.LONG_LIVED_TOKEN:\n this.currentLongLivedSecret = { value: details.value, type: ServerAuthenticationClass.LONG_LIVED_TOKEN }\n break\n case AuthSecretType.EXTERNAL_AUTHENTICATION:\n if (longLivedOAuthTokens.has(details.oauthType)) {\n this.currentLongLivedSecret = {\n value: details.value,\n type: ServerAuthenticationClass.EXTERNAL_AUTHENTICATION,\n oauthType: details.oauthType,\n }\n }\n break\n }\n }\n}\ntype DoGetTokenResult = { success: { token: string; refreshToken: string } } | { failure: DoGetTokenResultFailureReason }\nenum DoGetTokenResultFailureReason {\n NEEDS_2FA,\n INVALID_2FA,\n INVALID_PW_OR_TOKEN,\n INVALID_AUTH_CLASS_LEVEL,\n}\nenum RetrievedTokenType {\n CACHED,\n REFRESHED,\n NEW,\n}\n\nenum SmartAuthServiceState {\n INITIAL,\n DONE_INITIAL,\n REATTEMPT,\n REATTEMPTED_WITH_NEW_UNBOUND_TOKEN,\n REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN,\n EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS,\n TERMINAL_ERROR,\n}\nclass SmartAuthService implements AuthService {\n private currentState:\n | { id: SmartAuthServiceState.INITIAL }\n | { id: SmartAuthServiceState.DONE_INITIAL; initialToken: string }\n | { id: SmartAuthServiceState.REATTEMPT; initialToken: string; initialError: Error }\n | { id: SmartAuthServiceState.REATTEMPTED_WITH_NEW_UNBOUND_TOKEN }\n | { id: SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN }\n | { id: SmartAuthServiceState.EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS; errorFromNewToken: Error }\n | { id: SmartAuthServiceState.TERMINAL_ERROR; error: Error } = { id: SmartAuthServiceState.INITIAL }\n\n constructor(private readonly tokenProvider: TokenProvider) {}\n\n async jwtGetter(): Promise<{ token: string; refreshToken: string | undefined }> {\n const token = await this.getAuthToken(undefined)\n return { token, refreshToken: undefined }\n }\n\n async getAuthHeaders(minimumAuthenticationClassLevel: number | undefined): Promise<Array<XHR.Header>> {\n return [new XHR.Header('Authorization', `Bearer ${await this.getAuthToken(minimumAuthenticationClassLevel)}`)]\n }\n\n private async getAuthToken(minimumAuthenticationClassLevel: number | undefined): Promise<string> {\n switch (this.currentState.id) {\n case SmartAuthServiceState.INITIAL:\n if (minimumAuthenticationClassLevel != undefined) {\n throw new Error('Illegal state: cannot ask for a specific auth class level at the first request attempt.')\n } else {\n const { token } = await this.tokenProvider.getCachedOrRefreshedOrNewToken()\n this.currentState = { id: SmartAuthServiceState.DONE_INITIAL, initialToken: token }\n return token\n }\n case SmartAuthServiceState.REATTEMPT:\n if (minimumAuthenticationClassLevel != undefined) {\n const token = await this.tokenProvider.getNewTokenWithClass(minimumAuthenticationClassLevel)\n this.currentState = { id: SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN }\n return token\n } else {\n const { token } = await this.tokenProvider.getCachedOrRefreshedOrNewToken()\n if (token == this.currentState.initialToken) throw this.currentState.initialError\n this.currentState = { id: SmartAuthServiceState.REATTEMPTED_WITH_NEW_UNBOUND_TOKEN }\n return token\n }\n case SmartAuthServiceState.EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS:\n if (minimumAuthenticationClassLevel != undefined) {\n const token = await this.tokenProvider.getNewTokenWithClass(minimumAuthenticationClassLevel)\n this.currentState = { id: SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN }\n return token\n } else throw this.currentState.errorFromNewToken\n case SmartAuthServiceState.TERMINAL_ERROR:\n throw this.currentState.error\n default:\n throw new Error(`Illegal state: cannot get token in state ${this.currentState.id}.`)\n }\n }\n\n invalidateHeader(error: Error): void {\n switch (this.currentState.id) {\n case SmartAuthServiceState.DONE_INITIAL:\n this.currentState = { id: SmartAuthServiceState.REATTEMPT, initialToken: this.currentState.initialToken, initialError: error }\n break\n case SmartAuthServiceState.REATTEMPTED_WITH_NEW_UNBOUND_TOKEN:\n this.currentState = { id: SmartAuthServiceState.EXPECT_REQUEST_WITH_SPECIFIC_AUTH_CLASS, errorFromNewToken: error }\n break\n case SmartAuthServiceState.REATTEMPTED_WITH_AUTH_CLASS_SPECIFIC_TOKEN:\n this.currentState = { id: SmartAuthServiceState.TERMINAL_ERROR, error: error }\n break\n default:\n throw new Error(`Illegal state: cannot invalidate header in state ${this.currentState.id}.`)\n }\n }\n}\n"]}
1
+ {"version":3,"file":"SmartAuthProvider.js","sourceRoot":"","sources":["../../../icc-x-api/auth/SmartAuthProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,2CAA2D;AAC3D,+CAA2C;AAC3C,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAC9B,yCAAmE;AAmDnE;;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,GAAd,sBAAc,KAAd,sBAAc,QA8BzB;AAED,kEAAkE;AAElE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAa,iBAAiB;IAC5B;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CACf,OAAmB,EACnB,KAAa,EACb,cAAkC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AAC;KAAA;IAED,gBAAgB,CAAC,KAAY;QAC3B,QAAQ,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE;YAC5B,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;SAC/F;IACH,CAAC;CACF","sourcesContent":["import { AuthenticationProvider } from './AuthenticationProvider'\nimport { UserGroup } from '../../icc-api/model/UserGroup'\nimport { AuthService } from './AuthService'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { XHR } from '../../icc-api/api/XHR'\nimport XHRError = XHR.XHRError\nimport { decodeJwtClaims, isJwtInvalidOrExpired } from './JwtUtils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\n\n/**\n * Needed by a {@link SmartAuthProvider} to get the secrets (password, token, etc.) for authentication to the iCure SDK as needed.\n */\nexport interface AuthSecretProvider {\n /**\n * Provides a secret for authentication to the iCure SDK.\n *\n * ## Accepted secrets\n *\n * The method will be provided with an array of the secrets types that are acceptable (`acceptedSecrets`). Usually this array will contain multiple\n * elements, but this depends on the group configuration, the user (if he has 2fa setup or not), or the operation being performed. For groups using\n * default configurations and for patients without 2fa enabled for example the array will always contain the {@link AuthSecretType.PASSWORD} element.\n * Usually the array contain also the {@link AuthSecretType.LONG_LIVED_TOKEN} element, but if the user is attempting to perform a sensitive operations\n * such as changing his password the default group configuration does not allow for the user to authenticate using a JWT obtained from a long-lived\n * token for this operation, meaning the array will not contain the {@link AuthSecretType.LONG_LIVED_TOKEN} element.\n *\n * Regardless of the number of elements in the array only one secret of the accepted types is sufficient for the operation to succeed.\n *\n * ## TWO_FACTOR_AUTHENTICATION_TOKEN secret type\n *\n * The {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN} secret type is only used when the user has 2fa enabled. In this case the SDK will call\n * this method twice, once containing the {@link AuthSecretType.PASSWORD} element in the `acceptedSecrets` array, and if the provided secret is a\n * valid password the SDK will immediately call this method again, this time containing the {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN}\n * instead of the {@link AuthSecretType.PASSWORD} element.\n *\n * Any future call to this method from the same provider instance will not contain the {@link AuthSecretType.PASSWORD} element anymore, as it is\n * cached, but it may contain the {@link AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN} element instead.\n *\n * Note that the 2fa token is not needed for logging in through a long-lived or short-lived token, it is only used in combination with a password.\n * If the user is using 2fa, and you get in input as `acceptedSecrets` an array `[PASSWORD, LONG_LIVED_TOKEN, SHORT_LIVED_TOKEN]`, and you pass to\n * authenticate a long-lived token, the SDK will not call this method again to ask for the 2fa token.\n *\n * @param acceptedSecrets the types of secrets that are acceptable for the operation being performed.\n * @param previousAttempts the secrets that were previously attempted by the SDK for this operation. This array will be empty the first time this\n * method is called for a given operation, but it may contain multiple elements if the SDK has already called this method multiple times because the\n * previously returned secrets were not valid. The first element is the first secret that was attempted, and the last element is the most recently\n * attempted.\n * @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[]): 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 } = {}\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(login, props.loginGroupId, initialSecret, props.initialAuthToken, props.initialRefreshToken, authApi, secretProvider),\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 Promise.resolve(undefined)\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 ) {}\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 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 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.currentLongLivedSecret && (!this.currentLongLivedSecret.type || this.currentLongLivedSecret.type >= minimumAuthenticationClassLevel)) {\n const resultWithCachedSecret = await this.doGetTokenWithSecret(this.currentLongLivedSecret, minimumAuthenticationClassLevel)\n if ('success' in resultWithCachedSecret) {\n return resultWithCachedSecret.success\n } else if (\n resultWithCachedSecret.failure === DoGetTokenResultFailureReason.NEEDS_2FA &&\n minimumAuthenticationClassLevel <= ServerAuthenticationClass.TWO_FACTOR_AUTHENTICATION\n ) {\n return this.askTotpAndGetToken(this.currentLongLivedSecret.value, minimumAuthenticationClassLevel)\n } else return this.askSecretAndGetToken(minimumAuthenticationClassLevel, true)\n } else {\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 while (true) {\n const secretDetails = await this.authSecretProvider.getSecret([...acceptedSecrets], attempts)\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)\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 )\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"]}
@@ -59,6 +59,7 @@ export * from './crypto/RSA';
59
59
  export * from './crypto/CryptoPrimitives';
60
60
  export * from './crypto/ShareMetadataBehaviour';
61
61
  export * from './auth/AuthenticationProvider';
62
+ export { AuthSecretDetails, AuthSecretType, AuthSecretProvider } from './auth/SmartAuthProvider';
62
63
  export { KeyStorageFacade } from './storage/KeyStorageFacade';
63
64
  export { LocalStorageImpl } from './storage/LocalStorageImpl';
64
65
  export { StorageFacade } from './storage/StorageFacade';
@@ -398,7 +399,9 @@ export type SmartAuthenticationDetails = {
398
399
  username: string;
399
400
  secretProvider: AuthSecretProvider;
400
401
  initialSecret?: {
401
- plainSecret: string;
402
+ password: string;
403
+ } | {
404
+ longToken: string;
402
405
  } | {
403
406
  oauthToken: string;
404
407
  oauthType: OAuthThirdParty;
@@ -23,7 +23,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
23
23
  });
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.IcureBasicApi = exports.IcureApi = exports.EncryptedFieldsConfig = exports.getShaVersionForKey = exports.NativeCryptoPrimitivesBridge = exports.KeyStorageImpl = exports.LocalStorageImpl = void 0;
26
+ exports.IcureBasicApi = exports.IcureApi = exports.EncryptedFieldsConfig = exports.getShaVersionForKey = exports.NativeCryptoPrimitivesBridge = exports.KeyStorageImpl = exports.LocalStorageImpl = exports.AuthSecretType = void 0;
27
27
  const icc_api_1 = require("../icc-api");
28
28
  const icc_user_x_api_1 = require("./icc-user-x-api");
29
29
  const icc_crypto_x_api_1 = require("./icc-crypto-x-api");
@@ -112,6 +112,8 @@ __exportStar(require("./crypto/RSA"), exports);
112
112
  __exportStar(require("./crypto/CryptoPrimitives"), exports);
113
113
  __exportStar(require("./crypto/ShareMetadataBehaviour"), exports);
114
114
  __exportStar(require("./auth/AuthenticationProvider"), exports);
115
+ var SmartAuthProvider_2 = require("./auth/SmartAuthProvider");
116
+ Object.defineProperty(exports, "AuthSecretType", { enumerable: true, get: function () { return SmartAuthProvider_2.AuthSecretType; } });
115
117
  var LocalStorageImpl_2 = require("./storage/LocalStorageImpl");
116
118
  Object.defineProperty(exports, "LocalStorageImpl", { enumerable: true, get: function () { return LocalStorageImpl_2.LocalStorageImpl; } });
117
119
  var KeyStorageImpl_2 = require("./storage/KeyStorageImpl");
@@ -167,25 +169,11 @@ var IcureApi;
167
169
  : typeof self !== 'undefined'
168
170
  ? self.fetch
169
171
  : fetch, options = {}) {
170
- var _a;
171
172
  return __awaiter(this, void 0, void 0, function* () {
172
173
  const params = new IcureApiOptions.WithDefaults(options);
173
- let grouplessAuthenticationProvider = yield getAuthenticationProvider(host, authenticationOptions, params.headers, fetchImpl);
174
- // TODO if this uses a smart auth provider the groupless auth provider does not share the secret cache with the group specific one.
175
- const grouplessUserApi = new icc_api_1.IccUserApi(host, params.headers, grouplessAuthenticationProvider, fetchImpl);
176
- const matches = yield getMatchesOrEmpty(grouplessUserApi);
177
- const tokens = yield grouplessAuthenticationProvider.getIcureTokens();
178
- const currentGroupId = tokens ? (0, JwtUtils_1.getGroupOfJwt)(tokens.token) : undefined;
179
- const chosenGroupId = matches.length > 1 && !!options.groupSelector ? yield options.groupSelector(matches, currentGroupId) : (_a = matches[0]) === null || _a === void 0 ? void 0 : _a.groupId;
180
- /*TODO
181
- * On new very new users switching the authentication provider to a specific group may fail and block the user for too many requests. This is
182
- * probably linked to replication of the user in the fallback database.
183
- */
184
- const groupSpecificAuthenticationProvider = matches.length > 1 && chosenGroupId && chosenGroupId !== currentGroupId
185
- ? yield grouplessAuthenticationProvider.switchGroup(chosenGroupId, matches)
186
- : grouplessAuthenticationProvider;
187
- const cryptoInitInfo = yield initialiseCryptoWithProvider(host, fetchImpl, groupSpecificAuthenticationProvider, params, cryptoStrategies, crypto);
188
- return new IcureApiImpl(cryptoInitInfo, host, groupSpecificAuthenticationProvider, fetch, grouplessUserApi, matches, matches.find((match) => match.groupId === chosenGroupId), params, cryptoStrategies);
174
+ let authenticationProviderInfo = yield initialiseAuthProviderWithGroupSelector(host, authenticationOptions, params.headers, fetchImpl, params.groupSelector);
175
+ const cryptoInitInfo = yield initialiseCryptoWithProvider(host, fetchImpl, authenticationProviderInfo.groupSpecificAuthenticationProvider, params, cryptoStrategies, crypto);
176
+ return new IcureApiImpl(cryptoInitInfo, host, authenticationProviderInfo.groupSpecificAuthenticationProvider, fetch, authenticationProviderInfo.grouplessUserApi, authenticationProviderInfo.matches, authenticationProviderInfo.matches.find((match) => match.groupId === authenticationProviderInfo.chosenGroupId), params, cryptoStrategies);
189
177
  });
190
178
  }
191
179
  IcureApi.initialise = initialise;
@@ -222,6 +210,39 @@ function getAuthenticationProvider(host, authenticationOptions, headers, fetchIm
222
210
  return authenticationProvider;
223
211
  });
224
212
  }
213
+ function initialiseAuthProviderWithGroupSelector(host, authenticationOptions, headers, fetchImpl, groupSelector) {
214
+ var _a;
215
+ return __awaiter(this, void 0, void 0, function* () {
216
+ let grouplessAuthenticationProvider = yield getAuthenticationProvider(host, authenticationOptions, headers, fetchImpl);
217
+ const grouplessUserApi = new icc_api_1.IccUserApi(host, headers, grouplessAuthenticationProvider, fetchImpl);
218
+ const matches = yield getMatchesOrEmpty(grouplessUserApi);
219
+ const tokens = yield grouplessAuthenticationProvider.getIcureTokens();
220
+ const currentGroupId = tokens ? (0, JwtUtils_1.getGroupOfJwt)(tokens.token) : undefined;
221
+ const chosenGroupId = matches.length > 1 && !!groupSelector ? yield groupSelector(matches, currentGroupId) : (_a = matches[0]) === null || _a === void 0 ? void 0 : _a.groupId;
222
+ /*TODO
223
+ * On new very new users switching the authentication provider to a specific group may fail and block the user for too many requests. This is
224
+ * probably linked to replication of the user in the fallback database.
225
+ */
226
+ /*
227
+ * If the auth provider is initialized with credentials and jwt not switching the group will may cause issues:
228
+ * 1. The default group for the user is group A
229
+ * 2. The user logs in to group B -> the provider is switched
230
+ * 3. The user refreshes the page -> a new instance of the api with initial iCure tokens is created
231
+ * 4. The refresh token is expired / the user needs to do a high security operation -> a new login is done .If we did
232
+ * not switch the provider here the login would default to group A, potentially causing a lot of issues...
233
+ */
234
+ const groupSpecificAuthenticationProvider = !!chosenGroupId
235
+ ? yield grouplessAuthenticationProvider.switchGroup(chosenGroupId, matches)
236
+ : grouplessAuthenticationProvider;
237
+ return {
238
+ groupSpecificAuthenticationProvider,
239
+ // No need for a groupless user api on a group-specific smart auth provider
240
+ grouplessUserApi: groupSpecificAuthenticationProvider instanceof SmartAuthProvider_1.SmartAuthProvider ? undefined : grouplessUserApi,
241
+ matches,
242
+ chosenGroupId,
243
+ };
244
+ });
245
+ }
225
246
  const REQUEST_AUTOFIX_ANONYMITY_HEADER = 'Icure-Request-Autofix-Anonymity';
226
247
  function initialiseCryptoWithProvider(host, fetchImpl, groupSpecificAuthenticationProvider, params, cryptoStrategies, crypto) {
227
248
  var _a;
@@ -503,8 +524,9 @@ class IcureApiImpl {
503
524
  return this.cryptoInitInfos.userApi;
504
525
  }
505
526
  getGroupsInfo() {
527
+ var _a;
506
528
  return __awaiter(this, void 0, void 0, function* () {
507
- this.latestGroupsRequest = this.grouplessUserApi.getMatchingUsers();
529
+ this.latestGroupsRequest = ((_a = this.grouplessUserApi) !== null && _a !== void 0 ? _a : this.userApi).getMatchingUsers();
508
530
  return { currentGroup: this.currentGroupInfo, availableGroups: yield this.latestGroupsRequest };
509
531
  });
510
532
  }
@@ -559,10 +581,11 @@ class IcureBasicApiImpl {
559
581
  return ((_a = this._userApi) !== null && _a !== void 0 ? _a : (this._userApi = new icc_user_x_api_1.IccUserXApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.authApi, this.fetch)));
560
582
  }
561
583
  getGroupsInfo() {
584
+ var _a;
562
585
  return __awaiter(this, void 0, void 0, function* () {
563
586
  if (!this.currentGroupInfo)
564
587
  return { currentGroup: undefined, availableGroups: [] };
565
- this.latestGroupsRequest = this.grouplessUserApi ? this.grouplessUserApi.getMatchingUsers() : this.userApi.getMatchingUsers();
588
+ this.latestGroupsRequest = ((_a = this.grouplessUserApi) !== null && _a !== void 0 ? _a : this.userApi).getMatchingUsers();
566
589
  return { currentGroup: this.currentGroupInfo, availableGroups: yield this.latestGroupsRequest };
567
590
  });
568
591
  }
@@ -618,19 +641,11 @@ var IcureBasicApi;
618
641
  : typeof self !== 'undefined'
619
642
  ? self.fetch
620
643
  : fetch, options = {}) {
621
- var _a, _b;
644
+ var _a;
622
645
  return __awaiter(this, void 0, void 0, function* () {
623
646
  const params = new IcureBasicApiOptions.WithDefaults(options);
624
- const grouplessAuthenticationProvider = yield getAuthenticationProvider(host, authenticationOptions, (_a = params.headers) !== null && _a !== void 0 ? _a : {}, fetchImpl);
625
- const grouplessUserApi = new icc_api_1.IccUserApi(host, params.headers, grouplessAuthenticationProvider, fetchImpl);
626
- const matches = yield getMatchesOrEmpty(grouplessUserApi);
627
- const tokens = yield grouplessAuthenticationProvider.getIcureTokens();
628
- const currentGroupId = tokens ? (0, JwtUtils_1.getGroupOfJwt)(tokens.token) : undefined;
629
- const chosenGroupId = matches.length > 1 && !!options.groupSelector ? yield options.groupSelector(matches, currentGroupId) : (_b = matches[0]) === null || _b === void 0 ? void 0 : _b.groupId;
630
- const groupSpecificAuthenticationProvider = matches.length > 1 && chosenGroupId && chosenGroupId !== currentGroupId
631
- ? yield grouplessAuthenticationProvider.switchGroup(chosenGroupId, matches)
632
- : grouplessAuthenticationProvider;
633
- return new IcureBasicApiImpl(host, groupSpecificAuthenticationProvider, fetch, grouplessUserApi, matches, matches.find((match) => match.groupId === chosenGroupId), params);
647
+ const authProviderInfo = yield initialiseAuthProviderWithGroupSelector(host, authenticationOptions, (_a = params.headers) !== null && _a !== void 0 ? _a : {}, fetchImpl, params.groupSelector);
648
+ return new IcureBasicApiImpl(host, authProviderInfo.groupSpecificAuthenticationProvider, fetch, authProviderInfo.grouplessUserApi, authProviderInfo.matches, authProviderInfo.matches.find((match) => match.groupId === authProviderInfo.chosenGroupId), params);
634
649
  });
635
650
  }
636
651
  IcureBasicApi.initialise = initialise;