@icure/api 8.0.41 → 8.0.43
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.
- package/icc-x-api/auth/SmartAuthProvider.d.ts +3 -1
- package/icc-x-api/auth/SmartAuthProvider.js +15 -4
- package/icc-x-api/auth/SmartAuthProvider.js.map +1 -1
- package/icc-x-api/index.d.ts +4 -1
- package/icc-x-api/index.js +46 -31
- package/icc-x-api/index.js.map +1 -1
- package/package.json +1 -1
- package/test/icc-x-api/auth/smart-auth-provider-test.js +1 -1
- package/test/icc-x-api/auth/smart-auth-provider-test.js.map +1 -1
|
@@ -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
|
-
|
|
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 ('
|
|
85
|
-
initialSecret = { value: 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 };
|
|
86
89
|
}
|
|
87
90
|
else {
|
|
88
91
|
initialSecret = {
|
|
@@ -112,7 +115,7 @@ class SmartAuthProvider {
|
|
|
112
115
|
});
|
|
113
116
|
}
|
|
114
117
|
getIcureTokens() {
|
|
115
|
-
return
|
|
118
|
+
return this.tokenProvider.getCachedTokensOrLoad();
|
|
116
119
|
}
|
|
117
120
|
}
|
|
118
121
|
exports.SmartAuthProvider = SmartAuthProvider;
|
|
@@ -151,6 +154,14 @@ class TokenProvider {
|
|
|
151
154
|
}
|
|
152
155
|
});
|
|
153
156
|
}
|
|
157
|
+
getCachedTokensOrLoad() {
|
|
158
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
159
|
+
if (!this.cachedToken || !this.cachedRefreshToken) {
|
|
160
|
+
yield this.getAndCacheNewToken(undefined);
|
|
161
|
+
}
|
|
162
|
+
return { token: this.cachedToken, refreshToken: this.cachedRefreshToken };
|
|
163
|
+
});
|
|
164
|
+
}
|
|
154
165
|
getNewTokenWithClass(minimumAuthenticationClass) {
|
|
155
166
|
return __awaiter(this, void 0, void 0, function* () {
|
|
156
167
|
return yield this.getAndCacheNewToken(minimumAuthenticationClass);
|
|
@@ -251,7 +262,7 @@ class TokenProvider {
|
|
|
251
262
|
return __awaiter(this, void 0, void 0, function* () {
|
|
252
263
|
let authResultPromise;
|
|
253
264
|
if ('oauthType' in secret && !!secret.oauthType) {
|
|
254
|
-
authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value);
|
|
265
|
+
authResultPromise = this.authApi.loginWithThirdPartyToken(secret.oauthType, secret.value); // TODO add group id
|
|
255
266
|
}
|
|
256
267
|
else {
|
|
257
268
|
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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AAqB,CAAC,cAAc;oBACvC,MAAM,IAAI,CAAC,YAAY,CAAC,KAAK,CAAA;gBAC/B;oBACE,MAAM,IAAI,KAAK,CAAC,4CAA4C,IAAI,CAAC,YAAY,CAAC,EAAE,GAAG,CAAC,CAAA;aACvF;QACH,CAAC;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?: { 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;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,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 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 ) {}\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 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"]}
|
package/icc-x-api/index.d.ts
CHANGED
|
@@ -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
|
-
|
|
402
|
+
password: string;
|
|
403
|
+
} | {
|
|
404
|
+
longToken: string;
|
|
402
405
|
} | {
|
|
403
406
|
oauthToken: string;
|
|
404
407
|
oauthType: OAuthThirdParty;
|
package/icc-x-api/index.js
CHANGED
|
@@ -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
|
|
174
|
-
|
|
175
|
-
|
|
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 =
|
|
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
|
|
644
|
+
var _a;
|
|
622
645
|
return __awaiter(this, void 0, void 0, function* () {
|
|
623
646
|
const params = new IcureBasicApiOptions.WithDefaults(options);
|
|
624
|
-
const
|
|
625
|
-
|
|
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;
|
package/icc-x-api/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../icc-x-api/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;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ccArticleApi,\n IccAuthApi,\n IccBeefactApi,\n IccBeresultexportApi,\n IccBeresultimportApi,\n IccBesamv2Api,\n IccCalendarItemTypeApi,\n IccClassificationTemplateApi,\n IccEntityrefApi,\n IccEntitytemplateApi,\n IccFrontendmigrationApi,\n IccGroupApi,\n IccIcureApi,\n IccInsuranceApi,\n IccKeywordApi,\n IccMedexApi,\n IccMedicallocationApi,\n IccPatientApi,\n IccPermissionApi,\n IccPlaceApi,\n IccPubsubApi,\n IccReplicationApi,\n IccTarificationApi,\n IccTmpApi,\n IccUserApi,\n OAuthThirdParty,\n} from '../icc-api'\nimport { IccUserXApi } from './icc-user-x-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccInvoiceXApi } from './icc-invoice-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHcpartyXApi } from './icc-hcparty-x-api'\nimport { IccFormXApi } from './icc-form-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { IccClassificationXApi } from './icc-classification-x-api'\nimport { IccCalendarItemXApi } from './icc-calendar-item-x-api'\nimport { IccPatientXApi } from './icc-patient-x-api'\nimport { IccMessageXApi } from './icc-message-x-api'\nimport { IccReceiptXApi } from './icc-receipt-x-api'\nimport { IccAccesslogXApi } from './icc-accesslog-x-api'\nimport { IccTimeTableXApi } from './icc-time-table-x-api'\nimport { IccCodeXApi } from './icc-code-x-api'\nimport { IccMaintenanceTaskXApi } from './icc-maintenance-task-x-api'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\nimport { LocalStorageImpl } from './storage/LocalStorageImpl'\nimport { KeyStorageImpl } from './storage/KeyStorageImpl'\nimport {\n AuthenticationProvider,\n EnsembleAuthenticationProvider,\n JwtAuthenticationProvider,\n NoAuthenticationProvider,\n} from './auth/AuthenticationProvider'\nimport { CryptoPrimitives, WebCryptoPrimitives } from './crypto/CryptoPrimitives'\nimport { UserEncryptionKeysManager } from './crypto/UserEncryptionKeysManager'\nimport { IcureStorageFacade } from './storage/IcureStorageFacade'\nimport { DefaultStorageEntryKeysFactory } from './storage/DefaultStorageEntryKeysFactory'\nimport { KeyRecovery } from './crypto/KeyRecovery'\nimport { BaseExchangeKeysManager } from './crypto/BaseExchangeKeysManager'\nimport { StorageEntryKeysFactory } from './storage/StorageEntryKeysFactory'\nimport { CryptoStrategies } from './crypto/CryptoStrategies'\nimport { ExchangeKeysManager } from './crypto/ExchangeKeysManager'\nimport { ShamirKeysManager } from './crypto/ShamirKeysManager'\nimport { TransferKeysManager } from './crypto/TransferKeysManager'\nimport { IccIcureMaintenanceXApi } from './icc-icure-maintenance-x-api'\nimport { ConfidentialEntities } from './crypto/ConfidentialEntities'\nimport { ensureDelegationForSelf } from './crypto/utils'\nimport { SecureDelegationsSecurityMetadataDecryptor } from './crypto/SecureDelegationsSecurityMetadataDecryptor'\nimport { initialiseExchangeDataManagerForCurrentDataOwner } from './crypto/ExchangeDataManager'\nimport { BaseExchangeDataManager } from './crypto/BaseExchangeDataManager'\nimport { IccExchangeDataApi } from '../icc-api/api/internal/IccExchangeDataApi'\nimport { UserSignatureKeysManager } from './crypto/UserSignatureKeysManager'\nimport { AccessControlSecretUtils } from './crypto/AccessControlSecretUtils'\nimport { SecureDelegationsEncryption } from './crypto/SecureDelegationsEncryption'\nimport { LegacyDelegationSecurityMetadataDecryptor } from './crypto/LegacyDelegationSecurityMetadataDecryptor'\nimport { ExtendedApisUtilsImpl } from './crypto/ExtendedApisUtilsImpl'\nimport { SecureDelegationsManager } from './crypto/SecureDelegationsManager'\nimport { AccessControlKeysHeadersProvider } from './crypto/AccessControlKeysHeadersProvider'\nimport { IccExchangeDataMapApi } from '../icc-api/api/internal/IccExchangeDataMapApi'\nimport { ExchangeDataMapManager } from './crypto/ExchangeDataMapManager'\nimport { IccDeviceXApi } from './icc-device-x-api'\nimport { IccBekmehrXApi } from './icc-bekmehr-x-api'\nimport { IccDoctemplateXApi } from './icc-doctemplate-x-api'\nimport { UserGroup } from '../icc-api/model/UserGroup'\nimport { IccTopicXApi } from './icc-topic-x-api'\nimport { IccRoleApi } from '../icc-api/api/IccRoleApi'\nimport { DataOwnerTypeEnum } from '../icc-api/model/DataOwnerTypeEnum'\nimport { DelegationsDeAnonymization } from './crypto/DelegationsDeAnonymization'\nimport { JwtBridgedAuthService } from './auth/JwtBridgedAuthService'\nimport { AuthSecretProvider, SmartAuthProvider } from './auth/SmartAuthProvider'\nimport { KeyPairRecoverer } from './crypto/KeyPairRecoverer'\nimport { IccRecoveryDataApi } from '../icc-api/api/internal/IccRecoveryDataApi'\nimport { RecoveryDataEncryption } from './crypto/RecoveryDataEncryption'\nimport { IccRecoveryXApi } from './icc-recovery-x-api'\nimport { getGroupOfJwt } from './auth/JwtUtils'\n\nexport * from './icc-accesslog-x-api'\nexport * from './icc-bekmehr-x-api'\nexport * from './icc-calendar-item-x-api'\nexport * from './icc-classification-x-api'\nexport * from './icc-code-x-api'\nexport * from './icc-contact-x-api'\nexport * from './icc-crypto-x-api'\nexport * from './icc-doctemplate-x-api'\nexport * from './icc-document-x-api'\nexport * from './icc-form-x-api'\nexport * from './icc-hcparty-x-api'\nexport * from './icc-helement-x-api'\nexport * from './icc-invoice-x-api'\nexport * from './icc-message-x-api'\nexport * from './icc-patient-x-api'\nexport * from './icc-user-x-api'\nexport * from './icc-time-table-x-api'\nexport * from './icc-receipt-x-api'\nexport * from './icc-data-owner-x-api'\nexport * from './icc-icure-maintenance-x-api'\nexport * from './icc-maintenance-task-x-api'\nexport * from './icc-recovery-x-api'\nexport * from './utils'\n\nexport * from './crypto/RSA'\nexport * from './crypto/CryptoPrimitives'\nexport * from './crypto/ShareMetadataBehaviour'\nexport * from './auth/AuthenticationProvider'\n\nexport { KeyStorageFacade } from './storage/KeyStorageFacade'\nexport { LocalStorageImpl } from './storage/LocalStorageImpl'\nexport { StorageFacade } from './storage/StorageFacade'\nexport { KeyStorageImpl } from './storage/KeyStorageImpl'\nexport { CryptoStrategies } from './crypto/CryptoStrategies'\nexport { NativeCryptoPrimitivesBridge } from './crypto/NativeCryptoPrimitivesBridge'\nexport { getShaVersionForKey } from './crypto/utils'\n\nexport interface BasicApis {\n readonly authApi: IccAuthApi\n readonly codeApi: IccCodeXApi\n readonly userApi: IccUserXApi\n readonly permissionApi: IccPermissionApi\n readonly insuranceApi: IccInsuranceApi\n readonly entityReferenceApi: IccEntityrefApi\n readonly agendaApi: IccAgendaApi\n readonly groupApi: IccGroupApi\n readonly healthcarePartyApi: IccHcpartyXApi\n readonly deviceApi: IccDeviceXApi\n readonly patientApi: IccPatientApi\n readonly roleApi: IccRoleApi\n}\nexport interface Apis extends BasicApis {\n readonly calendarItemTypeApi: IccCalendarItemTypeApi\n readonly medicalLocationApi: IccMedicallocationApi\n readonly cryptoApi: IccCryptoXApi\n readonly accessLogApi: IccAccesslogXApi\n readonly contactApi: IccContactXApi\n readonly formApi: IccFormXApi\n readonly invoiceApi: IccInvoiceXApi\n readonly documentApi: IccDocumentXApi\n readonly healthcareElementApi: IccHelementXApi\n readonly classificationApi: IccClassificationXApi\n readonly calendarItemApi: IccCalendarItemXApi\n readonly receiptApi: IccReceiptXApi\n readonly timetableApi: IccTimeTableXApi\n readonly patientApi: IccPatientXApi\n readonly messageApi: IccMessageXApi\n readonly maintenanceTaskApi: IccMaintenanceTaskXApi\n readonly dataOwnerApi: IccDataOwnerXApi\n readonly icureMaintenanceTaskApi: IccIcureMaintenanceXApi\n readonly anonymousAccessApi: IccAnonymousAccessApi\n readonly applicationSettingsApi: IccApplicationsettingsApi\n readonly articleApi: IccArticleApi\n readonly bekmehrApi: IccBekmehrXApi\n readonly beefactApi: IccBeefactApi\n readonly beresultexportApi: IccBeresultexportApi\n readonly beresultimportApi: IccBeresultimportApi\n readonly besamv2Api: IccBesamv2Api\n readonly classificationTemplateApi: IccClassificationTemplateApi\n readonly doctemplateApi: IccDoctemplateXApi\n readonly entitytemplateApi: IccEntitytemplateApi\n readonly frontendmigrationApi: IccFrontendmigrationApi\n readonly icureApi: IccIcureApi\n readonly keywordApi: IccKeywordApi\n readonly medexApi: IccMedexApi\n readonly placeApi: IccPlaceApi\n readonly pubsubApi: IccPubsubApi\n readonly replicationApi: IccReplicationApi\n readonly tarificationApi: IccTarificationApi\n readonly tmpApi: IccTmpApi\n readonly topicApi: IccTopicXApi\n readonly recoveryApi: IccRecoveryXApi\n}\n\n/**\n * Allows to customise the behaviour of the iCure API by providing various optional parameters.\n */\nexport interface IcureApiOptions {\n /**\n * Specifies how iCure can store string values (e.g. json). In production this should be persistent storage.\n * @default the browser's localStorage.\n */\n readonly storage?: StorageFacade<string>\n /**\n * Specifies how iCure can store cryptographic keys. Preferably this should be some ad-hoc storage key storage.\n * @default stores the json of the jwk representation of the key in {@link storage}.\n */\n readonly keyStorage?: KeyStorageFacade\n /**\n * Specifies where iCure should store his data within the {@link storage} and {@link keyStorage}.\n * @default {@link DefaultStorageEntryKeysFactory}\n */\n readonly entryKeysFactory?: StorageEntryKeysFactory\n /**\n * Specifies if iCure should automatically create maintenance tasks for requesting access back when a new key is generated at initialisation time.\n * Note that the maintenance task will be created only towards HCP data owners: if you want to create a maintenance task also to other types of data\n * owners you should disable this and call {@link IccIcureMaintenanceXApi.createMaintenanceTasksForNewKeypair} yourself.\n * @default true\n */\n readonly createMaintenanceTasksOnNewKey?: boolean\n /**\n * Additional headers to use on each request made by the iCure api.\n * @default no additional headers\n */\n readonly headers?: { [headerName: string]: string }\n /**\n * Specifies which fields should be encrypted for each kind of encryptable entity. You should make sure that every application in your environment\n * specifies the same values for this configuration.\n * @default see documentation for {@link EncryptedFieldsConfig}\n */\n readonly encryptedFieldsConfig?: EncryptedFieldsConfig\n /**\n * Each user may exist in multiple groups, but an instance of {@link IcureApi} is specialised for a single group. This function allows you to decide\n * the group to use for a given user.\n * This functions will be called only if a user exists in at least 2 groups, and takes in input:\n * - the information on the groups the user can access (in no specific order)\n * - if the authentication method uses JWT also the current group id (undefined otherwise)\n * The function must return the id of one of the available groups.\n * @default takes the first group provided. The group chosen by this method may vary between different instantiations of the {@link IcureApi} even\n * if for the same user and if the groups available for the user do not change.\n */\n readonly groupSelector?: (availableGroupsInfo: UserGroup[], currentGroupId?: string) => Promise<string>\n /**\n * Temporary value to support EHR Lite and MedTech api implementations.\n *\n * Currently, all hcps are able to access encrypted data shared with any of their parents, and on initialisation the api will verify that there is a\n * key pair available for the current user and for every parent of the user. If this option is set to true, the api will not load keys for the\n * parent users.\n *\n * This \"implicit data-sharing scheme\" (each parent HCP is essentially sharing data with all its children HCPs), however, may not be ideal for all\n * use cases, and it will be changed in future to be configurable in order to make it more general.\n * @default false, equivalent to previous behaviour.\n */\n readonly disableParentKeysInitialisation?: boolean\n}\n\nnamespace IcureApiOptions {\n export namespace Defaults {\n export const entryKeysFactory = new DefaultStorageEntryKeysFactory()\n export const createMaintenanceTasksOnNewKey = true\n export const headers = {}\n }\n\n export class WithDefaults implements IcureApiOptions {\n readonly entryKeysFactory: StorageEntryKeysFactory\n readonly createMaintenanceTasksOnNewKey: boolean\n readonly storage: StorageFacade<string>\n readonly keyStorage: KeyStorageFacade\n readonly headers: { [headerName: string]: string }\n readonly encryptedFieldsConfig: EncryptedFieldsConfig\n readonly groupSelector: (availableGroupsInfo: UserGroup[]) => Promise<string>\n readonly disableParentKeysInitialisation: boolean\n\n constructor(custom: IcureApiOptions) {\n this.entryKeysFactory = custom.entryKeysFactory ?? Defaults.entryKeysFactory\n this.createMaintenanceTasksOnNewKey = custom.createMaintenanceTasksOnNewKey ?? Defaults.createMaintenanceTasksOnNewKey\n this.storage = custom.storage ?? new LocalStorageImpl()\n this.keyStorage = custom.keyStorage ?? new KeyStorageImpl(this.storage)\n this.headers = custom.headers ?? Defaults.headers\n this.encryptedFieldsConfig = custom.encryptedFieldsConfig ?? {}\n this.groupSelector = custom.groupSelector ?? ((groups) => Promise.resolve(groups[0].groupId!))\n this.disableParentKeysInitialisation = custom.disableParentKeysInitialisation ?? false\n }\n }\n}\n\n/**\n * Specifies which fields should be encrypted for each kind of encryptable entity.\n *\n * Note that any value you specify here overrides the default values. For example if you specify `['medicalLocationId']` for `healthElement` the\n * fields `['descr', 'note']` which are usually encrypted by default will no longer be encrypted. If you want to add fields to the default values\n * you can use {@link EncryptedFieldsConfig.Defaults}, for example `[...EncryptedFieldsConfig.Defaults.healthElement, 'medicalLocationId'].\n *\n * # Encrypted fields syntax\n *\n * ## Grammar\n *\n * The grammar for each encrypted field is the following:\n * ```\n * fieldName :=\n * regex([a-zA-Z_][a-zA-Z0-9_]+)\n * encryptedField :=\n * fieldName\n * | fieldName + (\".\" | \".*.\" | \"[].\") + encryptedField\n * ```\n *\n * This grammar allows you to specify the fields to encrypt for the object and recursively for nested objects.\n * - A string containing only a single `fieldName` will encrypt the field with the given name.\n * - A string starting with `fieldName.` allows to specify the encrypted fields of a nested object. The encrypted values of the\n * fields in the nested object will be saved in the nested object.\n * - A string starting with `fieldName.*.` treats `fieldName` as a map/dictionary data structure and allows to specify the encrypted fields of the\n * values of the map. Note that the values of the map must be objects as well. The encrypted content of each map value is stored in that value.\n * - A string starting with `fieldName[].` treats `fieldName` as an array and allows to specify the encrypted fields of the values of the array.\n * Note that the values of the array must be objects as well. The encrypted content of each array element is stored in that element.\n *\n * ## Example\n *\n * Consider the following object and encryption keys:\n * ```javascript\n * const obj = {\n * a: { x: 0, y: 1 },\n * b: \"hello\",\n * c: [ { public: \"a\", secret: \"b\" }, { public: \"c\", secret: \"d\" } ],\n * d: \"ok\",\n * e: {\n * info: \"something\",\n * private: \"secret\",\n * dataMap: {\n * \"en\": {\n * a: 1,\n * b: 2\n * },\n * \"fr\": {\n * a: 3,\n * b: 4\n * }\n * }\n * }\n * }\n * const encryptedFields = [\n * \"a\",\n * \"c[].secret\",\n * \"d\",\n * \"e.private\",\n * \"e.datamap.*.a\"\n * ]\n * ```\n * If you use them with the crypt method you will get the following result:\n * ```json\n * {\n * b: \"hello\",\n * c: [\n * { public: \"a\", encryptedSelf: 'encrypted+encoded { secret: \"b\" }' },\n * { public: \"c\", encryptedSelf: 'encrypted+encoded { secret: \"d\" }' }\n * ],\n * e: {\n * info: \"something\",\n * dataMap: {\n * \"en\": { b: 2, encryptedSelf: 'encrypted+encoded { a: 1 }' },\n * \"fr\": { b: 4, encryptedSelf: 'encrypted+encoded { a: 3 }' }\n * },\n * encryptedSelf: 'encrypted+encoded { private: \"secret\" }'\n * },\n * encryptedSelf: 'encrypted+encoded { a: { x: 0, y: 1 }, d: \"ok\" }'\n * }\n * ```\n *\n * ## Shortened representation\n *\n * You can also group encrypted fields having the same prefix by concatenating to the prefix the JSON representation of an array of all the postfixes.\n * For example the following encrypted fields:\n * ```javascript\n * const encryptedFields = [\"a.b.c.d.e.f1\", \"a.b.c.d.e.f2\", \"a.b.c.d.e.f3\", \"a.b.c.d.e.f4\"]\n * ```\n * can be shortened to\n * ```javascript\n * const encryptedFields = ['a.b.c.d.e.[\"f1\",\"f2\",\"f3\",\"f4\"]'] // Note the use of single quotes to avoid escaping the double quotes\n * ```\n * If you use the shortened representation you may need to escape nested json representations. In that case the use of `JSON.stringify` is\n * recommended.\n */\nexport interface EncryptedFieldsConfig {\n /**\n * Fields to encrypt for entities of type {@link AccessLog}\n * @default ['detail', 'objectId']\n */\n readonly accessLog?: string[]\n /**\n * Fields to encrypt for entities of type {@link CalendarItem}\n * @default ['details', 'title', 'patientId']\n */\n readonly calendarItem?: string[]\n /**\n * Fields to encrypt for entities of type {@link Contact}, excluding `services`. You can specify which fields of `services` should be encrypted\n * using {@link service}.\n * @default ['descr'] // encryption of `services` is managed through {@link service}\n */\n readonly contact?: string[]\n /**\n * Fields to encrypt for entities of type {@link Service}. Note that encryption of the `content` field and recursively contained `Services` through\n * `content.compoundValue` is automatically managed by the sdk, and you are not allowed to modify it.\n *\n * Note: any non-empty values for this field will break bi-directional data compatibility between v7 and previous: Contacts created with\n * v7 will not be read properly by previous versions. If you want\n * @default ['notes[].markdown'] // encryption of `content` is managed in a special way\n */\n readonly service?: string[]\n /**\n * Fields to encrypt for entities of type {@link HealthElement}\n * @default ['descr', 'note', 'notes[].markdown']\n */\n readonly healthElement?: string[]\n /**\n * Fields to encrypt for entities of type {@link MaintenanceTask}\n * @default ['properties']\n */\n readonly maintenanceTask?: string[]\n /**\n * Fields to encrypt for entities of type {@link Patient}\n * @default ['note', 'notes[].markdown']\n */\n readonly patient?: string[]\n\n /**\n * Fields to encrypt for entities of type {@link Message}\n * @default []\n */\n readonly message?: string[]\n\n /**\n * Fields to encrypt for entities of type {@link Topic}\n * @default ['description']\n */\n readonly topic?: string[]\n}\n\nexport namespace EncryptedFieldsConfig {\n export const Defaults = {\n accessLog: ['detail', 'objectId'],\n calendarItem: ['details', 'title', 'patientId'],\n contact: ['descr', 'notes[].markdown'],\n service: ['notes[].markdown'],\n healthElement: ['descr', 'note', 'notes[].markdown'],\n maintenanceTask: ['properties'],\n patient: ['note', 'notes[].markdown'],\n message: [],\n topic: ['description', 'linkedServices', 'linkedHealthElements'],\n }\n}\n\n/**\n * Details for the authentication of a user\n */\nexport type AuthenticationDetails =\n | {\n username: string\n password: string\n thirdPartyTokens?: { [thirdParty: string]: string }\n }\n | {\n icureTokens: { token: string; refreshToken: string }\n credentials?: { username: string; password: string }\n }\n | {\n thirdPartyTokens: { [thirdParty: string]: string }\n }\n | SmartAuthenticationDetails\n\n/**\n * Allows to perform authentication through an {@link AuthSecretProvider}.\n *\n * The iCure SDK can authenticate to the backend using different kinds of secrets, such as passwords, long-lived authentication tokens, and\n * short-lived authentication tokens generated through the message gateway. iCure associates to each kind of secret a certain security level, and for\n * some sensitive operations, depending on the configurations of the user and his group, some operations may require a secret of a certain security\n * level. For example, with the default configurations, in order to change his own email the user can't have logged in with a long-lived token, but he\n * needs to provide his current password or a short-lived token.\n *\n * By using this authentication option, the iCure SDK will automatically request and cache the secret from the {@link AuthSecretProvider} only when\n * needed, which should help to minimise the interaction with the user.\n *\n * Another advantage of using this authentication option over others is that in case all the cached tokens and secrets were to expire while performing\n * a request, instead of having the request fail the SDK will ask for a new secret from the {@link SmartAuthProvider} and the request will\n * automatically be retried with the new secret.\n *\n * You must provide the following information:\n * - username: any kind of value that can identify the user (userId, groupId/userId, username, email, ...). More generic identifiers, valid\n * on multiple groups, allow for simpler group switching by using {@link IcureApi.switchGroup}.\n * - secretProvider: the secret provider to use for authentication. Will handle interaction with the gui.\n *\n * You can also provide the following optional information, which may allow to reduce the requests for secrets initially:\n * - initialSecret: an initial secret (password, token, ...) that will be used to get new authentication tokens as needed. If it is expired it will be ignored.\n * - initialAuthToken: an initial authentication token used on each request. If it is expired it will be ignored.\n * - initialRefreshToken: an initial refresh token used to get new authentication tokens as needed. If it is expired it will be ignored.\n */\nexport type SmartAuthenticationDetails = {\n username: string\n secretProvider: AuthSecretProvider\n initialSecret?: { plainSecret: string } | { oauthToken: string; oauthType: OAuthThirdParty }\n initialAuthToken?: string\n initialRefreshToken?: string\n}\n\n/**\n * Main entry point for the iCure API. Provides entity-specific sub-apis and some general methods which are not related to a specific entity.\n */\nexport interface IcureApi extends Apis {\n /**\n * Get the information on groups that the current user can access and the current group that this api instance is working on.\n * Note that the values you will get for `availableGroups` may differ from the values you would get if you call {@link IccUserApi.getMatchingUsers}\n * on {@link Apis.userApi}, since the latter is specialised on the specific instance of the user in `currentGroup`.\n * - `currentGroup`: the group that this api instance is working on, or undefined if the backend environment is not multi-group.\n * - `availableGroups`: the list of groups that the current user can access with the provided secret. Empty if the backend environment is not\n * multi-group.\n */\n getGroupsInfo(): Promise<{ currentGroup: UserGroup | undefined; availableGroups: UserGroup[] }>\n\n /**\n * Switches the api to allow the user to work on a different group.\n * @param newGroupId the id of the group to switch to.\n * @return a new api for the specified group.\n */\n switchGroup(newGroupId: string): Promise<IcureApi>\n}\n\nexport namespace IcureApi {\n /**\n * Initialises a new instance of the iCure API.\n */\n export async function initialise(\n host: string,\n authenticationOptions: AuthenticationDetails | AuthenticationProvider,\n cryptoStrategies: CryptoStrategies,\n crypto: Crypto | CryptoPrimitives = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n options: IcureApiOptions = {}\n ): Promise<IcureApi> {\n const params = new IcureApiOptions.WithDefaults(options)\n let grouplessAuthenticationProvider = await getAuthenticationProvider(host, authenticationOptions, params.headers, fetchImpl)\n // TODO if this uses a smart auth provider the groupless auth provider does not share the secret cache with the group specific one.\n const grouplessUserApi = new IccUserApi(host, params.headers, grouplessAuthenticationProvider, fetchImpl)\n const matches = await getMatchesOrEmpty(grouplessUserApi)\n const tokens = await grouplessAuthenticationProvider.getIcureTokens()\n const currentGroupId = tokens ? getGroupOfJwt(tokens.token) : undefined\n const chosenGroupId = matches.length > 1 && !!options.groupSelector ? await options.groupSelector(matches, currentGroupId) : matches[0]?.groupId\n /*TODO\n * 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\n * probably linked to replication of the user in the fallback database.\n */\n const groupSpecificAuthenticationProvider =\n matches.length > 1 && chosenGroupId && chosenGroupId !== currentGroupId\n ? await grouplessAuthenticationProvider.switchGroup(chosenGroupId, matches)\n : grouplessAuthenticationProvider\n const cryptoInitInfo = await initialiseCryptoWithProvider(host, fetchImpl, groupSpecificAuthenticationProvider, params, cryptoStrategies, crypto)\n return new IcureApiImpl(\n cryptoInitInfo,\n host,\n groupSpecificAuthenticationProvider,\n fetch,\n grouplessUserApi,\n matches,\n matches.find((match) => match.groupId === chosenGroupId),\n params,\n cryptoStrategies\n )\n }\n}\n\nasync function getAuthenticationProvider(\n host: string,\n authenticationOptions: AuthenticationDetails | AuthenticationProvider,\n headers: { [headerName: string]: string },\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response>\n) {\n let authenticationProvider: AuthenticationProvider\n if ('getIcureTokens' in authenticationOptions && 'switchGroup' in authenticationOptions && 'getAuthService' in authenticationOptions) {\n authenticationProvider = authenticationOptions\n } else if ('icureTokens' in authenticationOptions && !!authenticationOptions.icureTokens) {\n authenticationProvider = new JwtAuthenticationProvider(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n authenticationOptions?.credentials?.username,\n authenticationOptions?.credentials?.password,\n undefined,\n authenticationOptions.icureTokens\n )\n } else if (\n 'username' in authenticationOptions &&\n 'password' in authenticationOptions &&\n !!authenticationOptions.username &&\n !!authenticationOptions.password\n ) {\n authenticationProvider = new EnsembleAuthenticationProvider(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n authenticationOptions.username,\n authenticationOptions.password,\n 3600,\n undefined,\n undefined,\n authenticationOptions.thirdPartyTokens\n )\n } else if ('thirdPartyTokens' in authenticationOptions && !!authenticationOptions.thirdPartyTokens) {\n authenticationProvider = new JwtAuthenticationProvider(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n undefined,\n undefined,\n new JwtBridgedAuthService(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n undefined,\n undefined,\n authenticationOptions.thirdPartyTokens,\n undefined\n )\n )\n } else if ('username' in authenticationOptions && 'secretProvider' in authenticationOptions) {\n authenticationProvider = SmartAuthProvider.initialise(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n authenticationOptions.username,\n authenticationOptions.secretProvider,\n {\n initialSecret: authenticationOptions.initialSecret,\n initialAuthToken: authenticationOptions.initialAuthToken,\n initialRefreshToken: authenticationOptions.initialRefreshToken,\n }\n )\n } else {\n throw new Error('Invalid authentication options provided')\n }\n return authenticationProvider\n}\n\n// Apis which are used during crypto api initialisation, to avoid re-instantiating them later\ntype CryptoInitialisationInfo = {\n cryptoApi: IccCryptoXApi\n healthcarePartyApi: IccHcpartyXApi\n deviceApi: IccDeviceXApi\n // no patient api since it is base\n dataOwnerApi: IccDataOwnerXApi\n userApi: IccUserXApi\n icureMaintenanceTaskApi: IccIcureMaintenanceXApi\n maintenanceTaskApi: IccMaintenanceTaskXApi\n headers: { [headerName: string]: string }\n dataOwnerRequiresAnonymousDelegation: boolean\n recoveryApi: IccRecoveryXApi\n}\n\nconst REQUEST_AUTOFIX_ANONYMITY_HEADER = 'Icure-Request-Autofix-Anonymity'\n\nasync function initialiseCryptoWithProvider(\n host: string,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n groupSpecificAuthenticationProvider: AuthenticationProvider,\n params: IcureApiOptions.WithDefaults,\n cryptoStrategies: CryptoStrategies,\n crypto: Crypto | CryptoPrimitives\n): Promise<CryptoInitialisationInfo> {\n const initialDataOwnerStub = await new IccDataOwnerXApi(\n host,\n params.headers,\n groupSpecificAuthenticationProvider,\n fetchImpl\n ).getCurrentDataOwnerStub()\n const dataOwnerRequiresAnonymousDelegation = cryptoStrategies.dataOwnerRequiresAnonymousDelegation(initialDataOwnerStub)\n let updatedHeaders = params.headers\n if (!Object.keys(updatedHeaders).includes(REQUEST_AUTOFIX_ANONYMITY_HEADER)) {\n if (initialDataOwnerStub.type == DataOwnerTypeEnum.Patient || initialDataOwnerStub.type == DataOwnerTypeEnum.Device) {\n if (!dataOwnerRequiresAnonymousDelegation) {\n updatedHeaders = { ...updatedHeaders, [REQUEST_AUTOFIX_ANONYMITY_HEADER]: 'false' }\n }\n } else {\n if (dataOwnerRequiresAnonymousDelegation) {\n updatedHeaders = { ...updatedHeaders, [REQUEST_AUTOFIX_ANONYMITY_HEADER]: 'true' }\n }\n }\n }\n\n const authApi = new IccAuthApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n const userApi = new IccUserXApi(host, updatedHeaders, groupSpecificAuthenticationProvider, authApi, fetchImpl)\n const healthcarePartyApi = new IccHcpartyXApi(host, updatedHeaders, groupSpecificAuthenticationProvider, authApi, fetchImpl)\n const deviceApi = new IccDeviceXApi(host, updatedHeaders, groupSpecificAuthenticationProvider, userApi, authApi, fetchImpl)\n const basePatientApi = new IccPatientApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n const dataOwnerApi = new IccDataOwnerXApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n const exchangeDataApi = new IccExchangeDataApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n const baseRecoveryDataApi = new IccRecoveryDataApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n // Crypto initialisation\n const icureStorage = new IcureStorageFacade(params.keyStorage, params.storage, params.entryKeysFactory)\n const cryptoPrimitives = 'AES' in crypto && 'RSA' in crypto && 'HMAC' in crypto ? crypto : new WebCryptoPrimitives(crypto)\n const baseExchangeKeysManager = new BaseExchangeKeysManager(cryptoPrimitives, dataOwnerApi, healthcarePartyApi, basePatientApi, deviceApi)\n const baseExchangeDataManager = new BaseExchangeDataManager(exchangeDataApi, dataOwnerApi, cryptoPrimitives, dataOwnerRequiresAnonymousDelegation)\n const keyRecovery = new KeyRecovery(cryptoPrimitives, dataOwnerApi, baseExchangeKeysManager, baseExchangeDataManager)\n const recoveryDataEncryption = new RecoveryDataEncryption(cryptoPrimitives, baseRecoveryDataApi)\n const keyPairRecoverer = new KeyPairRecoverer(recoveryDataEncryption)\n const userEncryptionKeysManager = new UserEncryptionKeysManager(\n cryptoPrimitives,\n dataOwnerApi,\n icureStorage,\n keyRecovery,\n cryptoStrategies,\n !params.disableParentKeysInitialisation,\n keyPairRecoverer\n )\n const userSignatureKeysManager = new UserSignatureKeysManager(icureStorage, dataOwnerApi, cryptoPrimitives)\n const newKey = await userEncryptionKeysManager.initialiseKeys()\n await new TransferKeysManager(\n cryptoPrimitives,\n baseExchangeDataManager,\n dataOwnerApi,\n userEncryptionKeysManager,\n userSignatureKeysManager,\n icureStorage\n ).updateTransferKeys(await dataOwnerApi.getCurrentDataOwnerStub())\n // TODO customise cache size?\n const exchangeKeysManager = new ExchangeKeysManager(\n 100,\n 500,\n 600000,\n 60000,\n cryptoStrategies,\n cryptoPrimitives,\n userEncryptionKeysManager,\n baseExchangeKeysManager,\n dataOwnerApi,\n !params.disableParentKeysInitialisation,\n icureStorage\n )\n const accessControlSecretUtils = new AccessControlSecretUtils(cryptoPrimitives)\n const exchangeDataManager = await initialiseExchangeDataManagerForCurrentDataOwner(\n baseExchangeDataManager,\n userEncryptionKeysManager,\n userSignatureKeysManager,\n accessControlSecretUtils,\n cryptoStrategies,\n dataOwnerApi,\n cryptoPrimitives,\n !params.disableParentKeysInitialisation\n )\n const exchangeDataMapManager = new ExchangeDataMapManager(\n new IccExchangeDataMapApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n )\n const secureDelegationsEncryption = new SecureDelegationsEncryption(userEncryptionKeysManager, cryptoPrimitives)\n const secureDelegationsSecurityMetadataEncryption = new SecureDelegationsSecurityMetadataDecryptor(\n exchangeDataManager,\n exchangeDataMapManager,\n secureDelegationsEncryption,\n dataOwnerApi\n )\n const xApiUtils = new ExtendedApisUtilsImpl(\n cryptoPrimitives,\n dataOwnerApi,\n new LegacyDelegationSecurityMetadataDecryptor(exchangeKeysManager, cryptoPrimitives),\n secureDelegationsSecurityMetadataEncryption,\n new SecureDelegationsManager(\n exchangeDataManager,\n exchangeDataMapManager,\n secureDelegationsEncryption,\n accessControlSecretUtils,\n userEncryptionKeysManager,\n cryptoPrimitives,\n dataOwnerApi,\n cryptoStrategies,\n dataOwnerRequiresAnonymousDelegation\n ),\n userApi,\n !params.disableParentKeysInitialisation\n )\n const shamirManager = new ShamirKeysManager(cryptoPrimitives, dataOwnerApi, userEncryptionKeysManager, exchangeDataManager)\n const confidentialEntitites = new ConfidentialEntities(xApiUtils, cryptoPrimitives, dataOwnerApi)\n await ensureDelegationForSelf(dataOwnerApi, xApiUtils, basePatientApi, cryptoPrimitives)\n const accessControlKeysHeadersProvider = new AccessControlKeysHeadersProvider(exchangeDataManager)\n const delegationsDeAnonymisation = new DelegationsDeAnonymization(\n dataOwnerApi,\n secureDelegationsSecurityMetadataEncryption,\n xApiUtils,\n cryptoPrimitives,\n accessControlSecretUtils,\n host,\n updatedHeaders,\n groupSpecificAuthenticationProvider,\n fetchImpl,\n accessControlKeysHeadersProvider\n )\n const cryptoApi = new IccCryptoXApi(\n exchangeKeysManager,\n cryptoPrimitives,\n userEncryptionKeysManager,\n dataOwnerApi,\n xApiUtils,\n shamirManager,\n params.storage,\n params.keyStorage,\n confidentialEntitites,\n exchangeDataManager,\n accessControlKeysHeadersProvider,\n delegationsDeAnonymisation\n )\n const maintenanceTaskApi = new IccMaintenanceTaskXApi(\n host,\n updatedHeaders,\n cryptoApi,\n healthcarePartyApi,\n dataOwnerApi,\n userApi,\n authApi,\n !dataOwnerRequiresAnonymousDelegation,\n params.encryptedFieldsConfig.maintenanceTask ?? EncryptedFieldsConfig.Defaults.maintenanceTask,\n groupSpecificAuthenticationProvider,\n fetchImpl\n )\n const icureMaintenanceTaskApi = new IccIcureMaintenanceXApi(cryptoApi, maintenanceTaskApi, dataOwnerApi, exchangeDataApi)\n\n if (newKey && params.createMaintenanceTasksOnNewKey) {\n await icureMaintenanceTaskApi.createMaintenanceTasksForNewKeypair(await userApi.getCurrentUser(), newKey.newKeyPair)\n }\n return {\n cryptoApi,\n userApi,\n healthcarePartyApi,\n deviceApi,\n maintenanceTaskApi,\n dataOwnerApi,\n icureMaintenanceTaskApi,\n headers: updatedHeaders,\n dataOwnerRequiresAnonymousDelegation,\n recoveryApi: new IccRecoveryXApi(\n baseRecoveryDataApi,\n recoveryDataEncryption,\n userEncryptionKeysManager,\n dataOwnerApi,\n cryptoPrimitives,\n exchangeDataManager\n ),\n }\n}\n\nclass IcureApiImpl implements IcureApi {\n private latestGroupsRequest: Promise<UserGroup[]>\n\n constructor(\n private readonly cryptoInitInfos: CryptoInitialisationInfo,\n private readonly host: string,\n private readonly groupSpecificAuthenticationProvider: AuthenticationProvider,\n private readonly fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n private readonly grouplessUserApi: IccUserApi,\n latestMatches: UserGroup[],\n private readonly currentGroupInfo: UserGroup | undefined,\n private readonly params: IcureApiOptions.WithDefaults,\n private readonly cryptoStrategies: CryptoStrategies\n ) {\n this.latestGroupsRequest = Promise.resolve(latestMatches)\n }\n\n private _authApi: IccAuthApi | undefined\n\n get recoveryApi(): IccRecoveryXApi {\n return this.cryptoInitInfos.recoveryApi\n }\n\n get authApi(): IccAuthApi {\n return (\n this._authApi ?? (this._authApi = new IccAuthApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _codeApi: IccCodeXApi | undefined\n\n get codeApi(): IccCodeXApi {\n return (\n this._codeApi ??\n (this._codeApi = new IccCodeXApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _calendarItemTypeApi: IccCalendarItemTypeApi | undefined\n\n get calendarItemTypeApi(): IccCalendarItemTypeApi {\n return (\n this._calendarItemTypeApi ??\n (this._calendarItemTypeApi = new IccCalendarItemTypeApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _medicalLocationApi: IccMedicallocationApi | undefined\n\n get medicalLocationApi(): IccMedicallocationApi {\n return (\n this._medicalLocationApi ??\n (this._medicalLocationApi = new IccMedicallocationApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _roleApi: IccRoleApi | undefined\n\n get roleApi(): IccRoleApi {\n return this._roleApi ?? (this._roleApi = new IccRoleApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n\n private _entityReferenceApi: IccEntityrefApi | undefined\n\n get entityReferenceApi(): IccEntityrefApi {\n return (\n this._entityReferenceApi ??\n (this._entityReferenceApi = new IccEntityrefApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _permissionApi: IccPermissionApi | undefined\n\n get permissionApi(): IccPermissionApi {\n return (\n this._permissionApi ??\n (this._permissionApi = new IccPermissionApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _accessLogApi: IccAccesslogXApi | undefined\n\n get accessLogApi(): IccAccesslogXApi {\n return (\n this._accessLogApi ??\n (this._accessLogApi = new IccAccesslogXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.params.encryptedFieldsConfig.accessLog ?? EncryptedFieldsConfig.Defaults.accessLog,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _agendaApi: IccAgendaApi | undefined\n\n get agendaApi(): IccAgendaApi {\n return (\n this._agendaApi ??\n (this._agendaApi = new IccAgendaApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _contactApi: IccContactXApi | undefined\n\n get contactApi(): IccContactXApi {\n return (\n this._contactApi ??\n (this._contactApi = new IccContactXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.userApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch,\n this.params.encryptedFieldsConfig.contact ?? EncryptedFieldsConfig.Defaults.contact,\n this.params.encryptedFieldsConfig.service ?? EncryptedFieldsConfig.Defaults.service\n ))\n )\n }\n\n private _formApi: IccFormXApi | undefined\n\n get formApi(): IccFormXApi {\n return (\n this._formApi ??\n (this._formApi = new IccFormXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _groupApi: IccGroupApi | undefined\n\n get groupApi(): IccGroupApi {\n return (\n this._groupApi ??\n (this._groupApi = new IccGroupApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _invoiceApi: IccInvoiceXApi | undefined\n\n get invoiceApi(): IccInvoiceXApi {\n return (\n this._invoiceApi ??\n (this._invoiceApi = new IccInvoiceXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.entityReferenceApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _insuranceApi: IccInsuranceApi | undefined\n\n get insuranceApi(): IccInsuranceApi {\n return (\n this._insuranceApi ??\n (this._insuranceApi = new IccInsuranceApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _documentApi: IccDocumentXApi | undefined\n\n get documentApi(): IccDocumentXApi {\n return (\n this._documentApi ??\n (this._documentApi = new IccDocumentXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.authApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _healthcareElementApi: IccHelementXApi | undefined\n\n get healthcareElementApi(): IccHelementXApi {\n return (\n this._healthcareElementApi ??\n (this._healthcareElementApi = new IccHelementXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.userApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.params.encryptedFieldsConfig.healthElement ?? EncryptedFieldsConfig.Defaults.healthElement,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _classificationApi: IccClassificationXApi | undefined\n\n get classificationApi(): IccClassificationXApi {\n return (\n this._classificationApi ??\n (this._classificationApi = new IccClassificationXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _calendarItemApi: IccCalendarItemXApi | undefined\n\n get calendarItemApi(): IccCalendarItemXApi {\n return (\n this._calendarItemApi ??\n (this._calendarItemApi = new IccCalendarItemXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.params.encryptedFieldsConfig.calendarItem ?? EncryptedFieldsConfig.Defaults.calendarItem,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _receiptApi: IccReceiptXApi | undefined\n\n get receiptApi(): IccReceiptXApi {\n return (\n this._receiptApi ??\n (this._receiptApi = new IccReceiptXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _timetableApi: IccTimeTableXApi | undefined\n\n get timetableApi(): IccTimeTableXApi {\n return (\n this._timetableApi ??\n (this._timetableApi = new IccTimeTableXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _patientApi: IccPatientXApi | undefined\n\n get patientApi(): IccPatientXApi {\n return (\n this._patientApi ??\n (this._patientApi = new IccPatientXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.contactApi,\n this.formApi,\n this.healthcareElementApi,\n this.invoiceApi,\n this.documentApi,\n this.healthcarePartyApi,\n this.classificationApi,\n this.dataOwnerApi,\n this.calendarItemApi,\n this.userApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.params.encryptedFieldsConfig.patient ?? EncryptedFieldsConfig.Defaults.patient,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _messageApi: IccMessageXApi | undefined\n\n get messageApi(): IccMessageXApi {\n return (\n this._messageApi ??\n (this._messageApi = new IccMessageXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.params.encryptedFieldsConfig.message ?? EncryptedFieldsConfig.Defaults.message,\n this.fetch\n ))\n )\n }\n\n private _topicApi: IccTopicXApi | undefined\n\n get topicApi(): IccTopicXApi {\n return (\n this._topicApi ??\n (this._topicApi = new IccTopicXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.params.encryptedFieldsConfig.topic ?? EncryptedFieldsConfig.Defaults.topic,\n this.fetch\n ))\n )\n }\n\n private _anonymousAccessApi: IccAnonymousAccessApi | undefined\n\n get anonymousAccessApi(): IccAnonymousAccessApi {\n return (\n this._anonymousAccessApi ??\n (this._anonymousAccessApi = new IccAnonymousAccessApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _applicationSettingsApi: IccApplicationsettingsApi | undefined\n\n get applicationSettingsApi(): IccApplicationsettingsApi {\n return (\n this._applicationSettingsApi ??\n (this._applicationSettingsApi = new IccApplicationsettingsApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _articleApi: IccArticleApi | undefined\n\n get articleApi(): IccArticleApi {\n return (\n this._articleApi ??\n (this._articleApi = new IccArticleApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _bekmehrApi: IccBekmehrXApi | undefined\n\n get bekmehrApi(): IccBekmehrXApi {\n return (\n this._bekmehrApi ??\n (this._bekmehrApi = new IccBekmehrXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.contactApi,\n this.healthcareElementApi,\n this.documentApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _beefactApi: IccBeefactApi | undefined\n\n get beefactApi(): IccBeefactApi {\n return (\n this._beefactApi ??\n (this._beefactApi = new IccBeefactApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _beresultexportApi: IccBeresultexportApi | undefined\n\n get beresultexportApi(): IccBeresultexportApi {\n return (\n this._beresultexportApi ??\n (this._beresultexportApi = new IccBeresultexportApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _beresultimportApi: IccBeresultimportApi | undefined\n\n get beresultimportApi(): IccBeresultimportApi {\n return (\n this._beresultimportApi ??\n (this._beresultimportApi = new IccBeresultimportApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _besamv2Api: IccBesamv2Api | undefined\n\n get besamv2Api(): IccBesamv2Api {\n return (\n this._besamv2Api ??\n (this._besamv2Api = new IccBesamv2Api(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _classificationTemplateApi: IccClassificationTemplateApi | undefined\n\n get classificationTemplateApi(): IccClassificationTemplateApi {\n return (\n this._classificationTemplateApi ??\n (this._classificationTemplateApi = new IccClassificationTemplateApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _doctemplateApi: IccDoctemplateXApi | undefined\n\n get doctemplateApi(): IccDoctemplateXApi {\n return (\n this._doctemplateApi ??\n (this._doctemplateApi = new IccDoctemplateXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _entitytemplateApi: IccEntitytemplateApi | undefined\n\n get entitytemplateApi(): IccEntitytemplateApi {\n return (\n this._entitytemplateApi ??\n (this._entitytemplateApi = new IccEntitytemplateApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _frontendmigrationApi: IccFrontendmigrationApi | undefined\n\n get frontendmigrationApi(): IccFrontendmigrationApi {\n return (\n this._frontendmigrationApi ??\n (this._frontendmigrationApi = new IccFrontendmigrationApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _icureApi: IccIcureApi | undefined\n\n get icureApi(): IccIcureApi {\n return (\n this._icureApi ??\n (this._icureApi = new IccIcureApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _keywordApi: IccKeywordApi | undefined\n\n get keywordApi(): IccKeywordApi {\n return (\n this._keywordApi ??\n (this._keywordApi = new IccKeywordApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _medexApi: IccMedexApi | undefined\n\n get medexApi(): IccMedexApi {\n return (\n this._medexApi ??\n (this._medexApi = new IccMedexApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _placeApi: IccPlaceApi | undefined\n\n get placeApi(): IccPlaceApi {\n return (\n this._placeApi ??\n (this._placeApi = new IccPlaceApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _pubsubApi: IccPubsubApi | undefined\n\n get pubsubApi(): IccPubsubApi {\n return (\n this._pubsubApi ??\n (this._pubsubApi = new IccPubsubApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _replicationApi: IccReplicationApi | undefined\n\n get replicationApi(): IccReplicationApi {\n return (\n this._replicationApi ??\n (this._replicationApi = new IccReplicationApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _tarificationApi: IccTarificationApi | undefined\n\n get tarificationApi(): IccTarificationApi {\n return (\n this._tarificationApi ??\n (this._tarificationApi = new IccTarificationApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _tmpApi: IccTmpApi | undefined\n\n get tmpApi(): IccTmpApi {\n return (\n this._tmpApi ?? (this._tmpApi = new IccTmpApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n get cryptoApi(): IccCryptoXApi {\n return this.cryptoInitInfos.cryptoApi\n }\n\n get dataOwnerApi(): IccDataOwnerXApi {\n return this.cryptoInitInfos.dataOwnerApi\n }\n\n get deviceApi(): IccDeviceXApi {\n return this.cryptoInitInfos.deviceApi\n }\n\n get healthcarePartyApi(): IccHcpartyXApi {\n return this.cryptoInitInfos.healthcarePartyApi\n }\n\n get icureMaintenanceTaskApi(): IccIcureMaintenanceXApi {\n return this.cryptoInitInfos.icureMaintenanceTaskApi\n }\n\n get maintenanceTaskApi(): IccMaintenanceTaskXApi {\n return this.cryptoInitInfos.maintenanceTaskApi\n }\n\n get userApi(): IccUserXApi {\n return this.cryptoInitInfos.userApi\n }\n\n async getGroupsInfo(): Promise<{ currentGroup: UserGroup | undefined; availableGroups: UserGroup[] }> {\n this.latestGroupsRequest = this.grouplessUserApi.getMatchingUsers()\n return { currentGroup: this.currentGroupInfo, availableGroups: await this.latestGroupsRequest }\n }\n\n async switchGroup(newGroupId: string): Promise<IcureApi> {\n const availableGroups = await this.latestGroupsRequest\n const switchedProvider = await this.groupSpecificAuthenticationProvider.switchGroup(newGroupId, availableGroups)\n const cryptoInitInfos = await initialiseCryptoWithProvider(\n this.host,\n this.fetch,\n switchedProvider,\n this.params,\n this.cryptoStrategies,\n this.cryptoApi.primitives\n )\n return new IcureApiImpl(\n cryptoInitInfos,\n this.host,\n switchedProvider,\n this.fetch,\n this.grouplessUserApi,\n availableGroups,\n availableGroups.find((x) => x.groupId === newGroupId)!,\n this.params,\n this.cryptoStrategies\n )\n }\n}\n\nexport interface IcureBasicApi extends BasicApis {\n /**\n * Get the information on groups that the current user can access and the current group that this api instance is working on.\n * Note that the values you will get for `availableGroups` may differ from the values you would get if you call {@link IccUserApi.getMatchingUsers}\n * on {@link Apis.userApi}, since the latter is specialised on the specific instance of the user in `currentGroup`.\n * - `currentGroup`: the group that this api instance is working on, or undefined if the backend environment is not multi-group.\n * - `availableGroups`: the list of groups that the current user can access with the provided secret. Empty if the backend environment is not\n * multi-group.\n */\n getGroupsInfo(): Promise<{ currentGroup: UserGroup | undefined; availableGroups: UserGroup[] }>\n\n /**\n * Switches the api to allow the user to work on a different group.\n * @param newGroupId the id of the group to switch to.\n * @return a new api for the specified group.\n */\n switchGroup(newGroupId: string): Promise<IcureBasicApi>\n}\n\nclass IcureBasicApiImpl implements IcureBasicApi {\n private latestGroupsRequest: Promise<UserGroup[]>\n private _agendaApi: IccAgendaApi | undefined\n private _authApi: IccAuthApi | undefined\n private _codeApi: IccCodeXApi | undefined\n private _deviceApi: IccDeviceXApi | undefined\n private _entityReferenceApi: IccEntityrefApi | undefined\n private _groupApi: IccGroupApi | undefined\n private _healthcarePartyApi: IccHcpartyXApi | undefined\n private _insuranceApi: IccInsuranceApi | undefined\n private _permissionApi: IccPermissionApi | undefined\n private _userApi: IccUserXApi | undefined\n private _patientApi: IccPatientApi | undefined\n private _roleApi: IccRoleApi | undefined\n\n get agendaApi(): IccAgendaApi {\n return (\n this._agendaApi ?? (this._agendaApi = new IccAgendaApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get authApi(): IccAuthApi {\n return this._authApi ?? (this._authApi = new IccAuthApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get codeApi(): IccCodeXApi {\n return this._codeApi ?? (this._codeApi = new IccCodeXApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get deviceApi(): IccDeviceXApi {\n return (\n this._deviceApi ??\n (this._deviceApi = new IccDeviceXApi(\n this.host,\n this.params.headers,\n this.groupSpecificAuthenticationProvider,\n this.userApi,\n this.authApi,\n this.fetch\n ))\n )\n }\n get entityReferenceApi(): IccEntityrefApi {\n return (\n this._entityReferenceApi ??\n (this._entityReferenceApi = new IccEntityrefApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get groupApi(): IccGroupApi {\n return this._groupApi ?? (this._groupApi = new IccGroupApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get healthcarePartyApi(): IccHcpartyXApi {\n return (\n this._healthcarePartyApi ??\n (this._healthcarePartyApi = new IccHcpartyXApi(\n this.host,\n this.params.headers,\n this.groupSpecificAuthenticationProvider,\n this.authApi,\n this.fetch\n ))\n )\n }\n get insuranceApi(): IccInsuranceApi {\n return (\n this._insuranceApi ??\n (this._insuranceApi = new IccInsuranceApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get permissionApi(): IccPermissionApi {\n return (\n this._permissionApi ??\n (this._permissionApi = new IccPermissionApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get userApi(): IccUserXApi {\n return (\n this._userApi ??\n (this._userApi = new IccUserXApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.authApi, this.fetch))\n )\n }\n\n async getGroupsInfo(): Promise<{ currentGroup: UserGroup | undefined; availableGroups: UserGroup[] }> {\n if (!this.currentGroupInfo) return { currentGroup: undefined, availableGroups: [] }\n this.latestGroupsRequest = this.grouplessUserApi ? this.grouplessUserApi.getMatchingUsers() : this.userApi.getMatchingUsers()\n return { currentGroup: this.currentGroupInfo, availableGroups: await this.latestGroupsRequest }\n }\n\n get patientApi(): IccPatientApi {\n return (\n this._patientApi ?? (this._patientApi = new IccPatientApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n get roleApi(): IccRoleApi {\n return this._roleApi ?? (this._roleApi = new IccRoleApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n\n async switchGroup(newGroupId: string): Promise<IcureBasicApi> {\n if (!this.currentGroupInfo) throw new Error('Cannot switch group: the backend environment does not support multiple groups.')\n const availableGroups = await this.latestGroupsRequest\n const switchedProvider = await this.groupSpecificAuthenticationProvider.switchGroup(newGroupId, availableGroups)\n return new IcureBasicApiImpl(\n this.host,\n switchedProvider,\n this.fetch,\n this.grouplessUserApi,\n availableGroups,\n availableGroups.find((x) => x.groupId === newGroupId)!,\n this.params\n )\n }\n\n constructor(\n private readonly host: string,\n private readonly groupSpecificAuthenticationProvider: AuthenticationProvider,\n private readonly fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n private readonly grouplessUserApi: IccUserApi,\n latestMatches: UserGroup[],\n private readonly currentGroupInfo: UserGroup | undefined,\n private readonly params: IcureBasicApiOptions.WithDefaults\n ) {\n this.latestGroupsRequest = Promise.resolve(latestMatches)\n }\n}\n\nexport interface IcureBasicApiOptions {\n /**\n * Additional headers to use on each request made by the iCure api.\n * @default no additional headers\n */\n readonly headers?: { [headerName: string]: string }\n /**\n * Each user may exist in multiple groups, but an instance of {@link IcureApi} is specialised for a single group. This function allows you to decide\n * the group to use for a given user.\n * This functions will be called only if a user exists in at least 2 groups, and takes in input:\n * - the information on the groups the user can access (in no specific order)\n * - if the authentication method uses JWT also the current group id (undefined otherwise)\n * The function must return the id of one of the available groups.\n * @default takes the first group provided. The group chosen by this method may vary between different instantiations of the {@link IcureApi} even\n * if for the same user and if the groups available for the user do not change.\n */\n readonly groupSelector?: (availableGroupsInfo: UserGroup[], currentGroupId?: string) => Promise<string>\n}\n\nnamespace IcureBasicApiOptions {\n export namespace Defaults {\n export const headers = {}\n }\n export class WithDefaults implements IcureBasicApiOptions {\n constructor(custom: IcureBasicApiOptions) {\n this.headers = custom.headers ?? Defaults.headers\n this.groupSelector = custom.groupSelector ?? ((groups) => Promise.resolve(groups[0].groupId!))\n }\n\n readonly headers: { [headerName: string]: string }\n readonly groupSelector: (availableGroupsInfo: UserGroup[]) => Promise<string>\n }\n}\n\nexport namespace IcureBasicApi {\n /**\n * Initialises a new instance of the iCure API.\n */\n export async function initialise(\n host: string,\n authenticationOptions: AuthenticationDetails | AuthenticationProvider,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n options: IcureBasicApiOptions = {}\n ): Promise<IcureBasicApi> {\n const params = new IcureBasicApiOptions.WithDefaults(options)\n\n const grouplessAuthenticationProvider = await getAuthenticationProvider(host, authenticationOptions, params.headers ?? {}, fetchImpl)\n const grouplessUserApi = new IccUserApi(host, params.headers, grouplessAuthenticationProvider, fetchImpl)\n const matches: UserGroup[] = await getMatchesOrEmpty(grouplessUserApi)\n const tokens = await grouplessAuthenticationProvider.getIcureTokens()\n const currentGroupId = tokens ? getGroupOfJwt(tokens.token) : undefined\n const chosenGroupId = matches.length > 1 && !!options.groupSelector ? await options.groupSelector(matches, currentGroupId) : matches[0]?.groupId\n const groupSpecificAuthenticationProvider =\n matches.length > 1 && chosenGroupId && chosenGroupId !== currentGroupId\n ? await grouplessAuthenticationProvider.switchGroup(chosenGroupId, matches)\n : grouplessAuthenticationProvider\n return new IcureBasicApiImpl(\n host,\n groupSpecificAuthenticationProvider,\n fetch,\n grouplessUserApi,\n matches,\n matches.find((match) => match.groupId === chosenGroupId),\n params\n )\n }\n}\n\nasync function getMatchesOrEmpty(userApi: IccUserApi): Promise<UserGroup[]> {\n try {\n return await userApi.getMatchingUsers()\n } catch (err) {\n if (err instanceof Error && 'statusCode' in err && (err as any).statusCode === 404) return Promise.resolve([])\n else return Promise.reject(err)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../icc-x-api/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wCA8BmB;AACnB,qDAA8C;AAC9C,yDAAkD;AAClD,2DAAoD;AACpD,2DAAoD;AACpD,6DAAsD;AACtD,2DAAoD;AACpD,qDAA8C;AAC9C,6DAAsD;AACtD,yEAAkE;AAClE,uEAA+D;AAC/D,2DAAoD;AACpD,2DAAoD;AACpD,2DAAoD;AACpD,+DAAwD;AACxD,iEAAyD;AACzD,qDAA8C;AAC9C,6EAAqE;AACrE,iEAAyD;AAGzD,iEAA6D;AAC7D,6DAAyD;AACzD,0EAKsC;AACtC,gEAAiF;AACjF,kFAA8E;AAC9E,qEAAiE;AACjE,6FAAyF;AACzF,sDAAkD;AAClD,8EAA0E;AAG1E,sEAAkE;AAClE,kEAA8D;AAC9D,sEAAkE;AAClE,+EAAuE;AACvE,wEAAoE;AACpE,0CAAwD;AACxD,oHAAgH;AAChH,sEAA+F;AAC/F,8EAA0E;AAC1E,mFAA+E;AAC/E,gFAA4E;AAC5E,gFAA4E;AAC5E,sFAAkF;AAClF,kHAA8G;AAC9G,0EAAsE;AACtE,gFAA4E;AAC5E,gGAA4F;AAC5F,yFAAqF;AACrF,4EAAwE;AACxE,yDAAkD;AAClD,2DAAoD;AACpD,mEAA4D;AAE5D,uDAAgD;AAChD,0DAAsD;AACtD,0EAAsE;AACtE,oFAAgF;AAChF,wEAAoE;AACpE,gEAAgF;AAChF,gEAA4D;AAC5D,mFAA+E;AAC/E,4EAAwE;AACxE,6DAAsD;AACtD,8CAA+C;AAE/C,wDAAqC;AACrC,sDAAmC;AACnC,4DAAyC;AACzC,6DAA0C;AAC1C,mDAAgC;AAChC,sDAAmC;AACnC,qDAAkC;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K;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK,EACT,UAAgC,EAAE;;;YAElC,MAAM,MAAM,GAAG,IAAI,oBAAoB,CAAC,YAAY,CAAC,OAAO,CAAC,CAAA;YAC7D,MAAM,gBAAgB,GAAG,MAAM,uCAAuC,CACpE,IAAI,EACJ,qBAAqB,EACrB,MAAA,MAAM,CAAC,OAAO,mCAAI,EAAE,EACpB,SAAS,EACT,MAAM,CAAC,aAAa,CACrB,CAAA;YACD,OAAO,IAAI,iBAAiB,CAC1B,IAAI,EACJ,gBAAgB,CAAC,mCAAmC,EACpD,KAAK,EACL,gBAAgB,CAAC,gBAAgB,EACjC,gBAAgB,CAAC,OAAO,EACxB,gBAAgB,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,gBAAgB,CAAC,aAAa,CAAC,EAC1F,MAAM,CACP,CAAA;;KACF;IA3BqB,wBAAU,aA2B/B,CAAA;AACH,CAAC,EAhCgB,aAAa,GAAb,qBAAa,KAAb,qBAAa,QAgC7B;AAED,SAAe,iBAAiB,CAAC,OAAmB;;QAClD,IAAI;YACF,OAAO,MAAM,OAAO,CAAC,gBAAgB,EAAE,CAAA;SACxC;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,YAAY,KAAK,IAAI,YAAY,IAAI,GAAG,IAAK,GAAW,CAAC,UAAU,KAAK,GAAG;gBAAE,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;;gBACzG,OAAO,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;SAChC;IACH,CAAC;CAAA","sourcesContent":["import {\n IccAgendaApi,\n IccAnonymousAccessApi,\n IccApplicationsettingsApi,\n IccArticleApi,\n IccAuthApi,\n IccBeefactApi,\n IccBeresultexportApi,\n IccBeresultimportApi,\n IccBesamv2Api,\n IccCalendarItemTypeApi,\n IccClassificationTemplateApi,\n IccEntityrefApi,\n IccEntitytemplateApi,\n IccFrontendmigrationApi,\n IccGroupApi,\n IccIcureApi,\n IccInsuranceApi,\n IccKeywordApi,\n IccMedexApi,\n IccMedicallocationApi,\n IccPatientApi,\n IccPermissionApi,\n IccPlaceApi,\n IccPubsubApi,\n IccReplicationApi,\n IccTarificationApi,\n IccTmpApi,\n IccUserApi,\n OAuthThirdParty,\n} from '../icc-api'\nimport { IccUserXApi } from './icc-user-x-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccInvoiceXApi } from './icc-invoice-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHcpartyXApi } from './icc-hcparty-x-api'\nimport { IccFormXApi } from './icc-form-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { IccClassificationXApi } from './icc-classification-x-api'\nimport { IccCalendarItemXApi } from './icc-calendar-item-x-api'\nimport { IccPatientXApi } from './icc-patient-x-api'\nimport { IccMessageXApi } from './icc-message-x-api'\nimport { IccReceiptXApi } from './icc-receipt-x-api'\nimport { IccAccesslogXApi } from './icc-accesslog-x-api'\nimport { IccTimeTableXApi } from './icc-time-table-x-api'\nimport { IccCodeXApi } from './icc-code-x-api'\nimport { IccMaintenanceTaskXApi } from './icc-maintenance-task-x-api'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { StorageFacade } from './storage/StorageFacade'\nimport { KeyStorageFacade } from './storage/KeyStorageFacade'\nimport { LocalStorageImpl } from './storage/LocalStorageImpl'\nimport { KeyStorageImpl } from './storage/KeyStorageImpl'\nimport {\n AuthenticationProvider,\n EnsembleAuthenticationProvider,\n JwtAuthenticationProvider,\n NoAuthenticationProvider,\n} from './auth/AuthenticationProvider'\nimport { CryptoPrimitives, WebCryptoPrimitives } from './crypto/CryptoPrimitives'\nimport { UserEncryptionKeysManager } from './crypto/UserEncryptionKeysManager'\nimport { IcureStorageFacade } from './storage/IcureStorageFacade'\nimport { DefaultStorageEntryKeysFactory } from './storage/DefaultStorageEntryKeysFactory'\nimport { KeyRecovery } from './crypto/KeyRecovery'\nimport { BaseExchangeKeysManager } from './crypto/BaseExchangeKeysManager'\nimport { StorageEntryKeysFactory } from './storage/StorageEntryKeysFactory'\nimport { CryptoStrategies } from './crypto/CryptoStrategies'\nimport { ExchangeKeysManager } from './crypto/ExchangeKeysManager'\nimport { ShamirKeysManager } from './crypto/ShamirKeysManager'\nimport { TransferKeysManager } from './crypto/TransferKeysManager'\nimport { IccIcureMaintenanceXApi } from './icc-icure-maintenance-x-api'\nimport { ConfidentialEntities } from './crypto/ConfidentialEntities'\nimport { ensureDelegationForSelf } from './crypto/utils'\nimport { SecureDelegationsSecurityMetadataDecryptor } from './crypto/SecureDelegationsSecurityMetadataDecryptor'\nimport { initialiseExchangeDataManagerForCurrentDataOwner } from './crypto/ExchangeDataManager'\nimport { BaseExchangeDataManager } from './crypto/BaseExchangeDataManager'\nimport { IccExchangeDataApi } from '../icc-api/api/internal/IccExchangeDataApi'\nimport { UserSignatureKeysManager } from './crypto/UserSignatureKeysManager'\nimport { AccessControlSecretUtils } from './crypto/AccessControlSecretUtils'\nimport { SecureDelegationsEncryption } from './crypto/SecureDelegationsEncryption'\nimport { LegacyDelegationSecurityMetadataDecryptor } from './crypto/LegacyDelegationSecurityMetadataDecryptor'\nimport { ExtendedApisUtilsImpl } from './crypto/ExtendedApisUtilsImpl'\nimport { SecureDelegationsManager } from './crypto/SecureDelegationsManager'\nimport { AccessControlKeysHeadersProvider } from './crypto/AccessControlKeysHeadersProvider'\nimport { IccExchangeDataMapApi } from '../icc-api/api/internal/IccExchangeDataMapApi'\nimport { ExchangeDataMapManager } from './crypto/ExchangeDataMapManager'\nimport { IccDeviceXApi } from './icc-device-x-api'\nimport { IccBekmehrXApi } from './icc-bekmehr-x-api'\nimport { IccDoctemplateXApi } from './icc-doctemplate-x-api'\nimport { UserGroup } from '../icc-api/model/UserGroup'\nimport { IccTopicXApi } from './icc-topic-x-api'\nimport { IccRoleApi } from '../icc-api/api/IccRoleApi'\nimport { DataOwnerTypeEnum } from '../icc-api/model/DataOwnerTypeEnum'\nimport { DelegationsDeAnonymization } from './crypto/DelegationsDeAnonymization'\nimport { JwtBridgedAuthService } from './auth/JwtBridgedAuthService'\nimport { AuthSecretProvider, SmartAuthProvider } from './auth/SmartAuthProvider'\nimport { KeyPairRecoverer } from './crypto/KeyPairRecoverer'\nimport { IccRecoveryDataApi } from '../icc-api/api/internal/IccRecoveryDataApi'\nimport { RecoveryDataEncryption } from './crypto/RecoveryDataEncryption'\nimport { IccRecoveryXApi } from './icc-recovery-x-api'\nimport { getGroupOfJwt } from './auth/JwtUtils'\n\nexport * from './icc-accesslog-x-api'\nexport * from './icc-bekmehr-x-api'\nexport * from './icc-calendar-item-x-api'\nexport * from './icc-classification-x-api'\nexport * from './icc-code-x-api'\nexport * from './icc-contact-x-api'\nexport * from './icc-crypto-x-api'\nexport * from './icc-doctemplate-x-api'\nexport * from './icc-document-x-api'\nexport * from './icc-form-x-api'\nexport * from './icc-hcparty-x-api'\nexport * from './icc-helement-x-api'\nexport * from './icc-invoice-x-api'\nexport * from './icc-message-x-api'\nexport * from './icc-patient-x-api'\nexport * from './icc-user-x-api'\nexport * from './icc-time-table-x-api'\nexport * from './icc-receipt-x-api'\nexport * from './icc-data-owner-x-api'\nexport * from './icc-icure-maintenance-x-api'\nexport * from './icc-maintenance-task-x-api'\nexport * from './icc-recovery-x-api'\nexport * from './utils'\n\nexport * from './crypto/RSA'\nexport * from './crypto/CryptoPrimitives'\nexport * from './crypto/ShareMetadataBehaviour'\nexport * from './auth/AuthenticationProvider'\n\nexport { AuthSecretDetails, AuthSecretType, AuthSecretProvider } from './auth/SmartAuthProvider'\nexport { KeyStorageFacade } from './storage/KeyStorageFacade'\nexport { LocalStorageImpl } from './storage/LocalStorageImpl'\nexport { StorageFacade } from './storage/StorageFacade'\nexport { KeyStorageImpl } from './storage/KeyStorageImpl'\nexport { CryptoStrategies } from './crypto/CryptoStrategies'\nexport { NativeCryptoPrimitivesBridge } from './crypto/NativeCryptoPrimitivesBridge'\nexport { getShaVersionForKey } from './crypto/utils'\n\nexport interface BasicApis {\n readonly authApi: IccAuthApi\n readonly codeApi: IccCodeXApi\n readonly userApi: IccUserXApi\n readonly permissionApi: IccPermissionApi\n readonly insuranceApi: IccInsuranceApi\n readonly entityReferenceApi: IccEntityrefApi\n readonly agendaApi: IccAgendaApi\n readonly groupApi: IccGroupApi\n readonly healthcarePartyApi: IccHcpartyXApi\n readonly deviceApi: IccDeviceXApi\n readonly patientApi: IccPatientApi\n readonly roleApi: IccRoleApi\n}\nexport interface Apis extends BasicApis {\n readonly calendarItemTypeApi: IccCalendarItemTypeApi\n readonly medicalLocationApi: IccMedicallocationApi\n readonly cryptoApi: IccCryptoXApi\n readonly accessLogApi: IccAccesslogXApi\n readonly contactApi: IccContactXApi\n readonly formApi: IccFormXApi\n readonly invoiceApi: IccInvoiceXApi\n readonly documentApi: IccDocumentXApi\n readonly healthcareElementApi: IccHelementXApi\n readonly classificationApi: IccClassificationXApi\n readonly calendarItemApi: IccCalendarItemXApi\n readonly receiptApi: IccReceiptXApi\n readonly timetableApi: IccTimeTableXApi\n readonly patientApi: IccPatientXApi\n readonly messageApi: IccMessageXApi\n readonly maintenanceTaskApi: IccMaintenanceTaskXApi\n readonly dataOwnerApi: IccDataOwnerXApi\n readonly icureMaintenanceTaskApi: IccIcureMaintenanceXApi\n readonly anonymousAccessApi: IccAnonymousAccessApi\n readonly applicationSettingsApi: IccApplicationsettingsApi\n readonly articleApi: IccArticleApi\n readonly bekmehrApi: IccBekmehrXApi\n readonly beefactApi: IccBeefactApi\n readonly beresultexportApi: IccBeresultexportApi\n readonly beresultimportApi: IccBeresultimportApi\n readonly besamv2Api: IccBesamv2Api\n readonly classificationTemplateApi: IccClassificationTemplateApi\n readonly doctemplateApi: IccDoctemplateXApi\n readonly entitytemplateApi: IccEntitytemplateApi\n readonly frontendmigrationApi: IccFrontendmigrationApi\n readonly icureApi: IccIcureApi\n readonly keywordApi: IccKeywordApi\n readonly medexApi: IccMedexApi\n readonly placeApi: IccPlaceApi\n readonly pubsubApi: IccPubsubApi\n readonly replicationApi: IccReplicationApi\n readonly tarificationApi: IccTarificationApi\n readonly tmpApi: IccTmpApi\n readonly topicApi: IccTopicXApi\n readonly recoveryApi: IccRecoveryXApi\n}\n\n/**\n * Allows to customise the behaviour of the iCure API by providing various optional parameters.\n */\nexport interface IcureApiOptions {\n /**\n * Specifies how iCure can store string values (e.g. json). In production this should be persistent storage.\n * @default the browser's localStorage.\n */\n readonly storage?: StorageFacade<string>\n /**\n * Specifies how iCure can store cryptographic keys. Preferably this should be some ad-hoc storage key storage.\n * @default stores the json of the jwk representation of the key in {@link storage}.\n */\n readonly keyStorage?: KeyStorageFacade\n /**\n * Specifies where iCure should store his data within the {@link storage} and {@link keyStorage}.\n * @default {@link DefaultStorageEntryKeysFactory}\n */\n readonly entryKeysFactory?: StorageEntryKeysFactory\n /**\n * Specifies if iCure should automatically create maintenance tasks for requesting access back when a new key is generated at initialisation time.\n * Note that the maintenance task will be created only towards HCP data owners: if you want to create a maintenance task also to other types of data\n * owners you should disable this and call {@link IccIcureMaintenanceXApi.createMaintenanceTasksForNewKeypair} yourself.\n * @default true\n */\n readonly createMaintenanceTasksOnNewKey?: boolean\n /**\n * Additional headers to use on each request made by the iCure api.\n * @default no additional headers\n */\n readonly headers?: { [headerName: string]: string }\n /**\n * Specifies which fields should be encrypted for each kind of encryptable entity. You should make sure that every application in your environment\n * specifies the same values for this configuration.\n * @default see documentation for {@link EncryptedFieldsConfig}\n */\n readonly encryptedFieldsConfig?: EncryptedFieldsConfig\n /**\n * Each user may exist in multiple groups, but an instance of {@link IcureApi} is specialised for a single group. This function allows you to decide\n * the group to use for a given user.\n * This functions will be called only if a user exists in at least 2 groups, and takes in input:\n * - the information on the groups the user can access (in no specific order)\n * - if the authentication method uses JWT also the current group id (undefined otherwise)\n * The function must return the id of one of the available groups.\n * @default takes the first group provided. The group chosen by this method may vary between different instantiations of the {@link IcureApi} even\n * if for the same user and if the groups available for the user do not change.\n */\n readonly groupSelector?: (availableGroupsInfo: UserGroup[], currentGroupId?: string) => Promise<string>\n /**\n * Temporary value to support EHR Lite and MedTech api implementations.\n *\n * Currently, all hcps are able to access encrypted data shared with any of their parents, and on initialisation the api will verify that there is a\n * key pair available for the current user and for every parent of the user. If this option is set to true, the api will not load keys for the\n * parent users.\n *\n * This \"implicit data-sharing scheme\" (each parent HCP is essentially sharing data with all its children HCPs), however, may not be ideal for all\n * use cases, and it will be changed in future to be configurable in order to make it more general.\n * @default false, equivalent to previous behaviour.\n */\n readonly disableParentKeysInitialisation?: boolean\n}\n\nnamespace IcureApiOptions {\n export namespace Defaults {\n export const entryKeysFactory = new DefaultStorageEntryKeysFactory()\n export const createMaintenanceTasksOnNewKey = true\n export const headers = {}\n }\n\n export class WithDefaults implements IcureApiOptions {\n readonly entryKeysFactory: StorageEntryKeysFactory\n readonly createMaintenanceTasksOnNewKey: boolean\n readonly storage: StorageFacade<string>\n readonly keyStorage: KeyStorageFacade\n readonly headers: { [headerName: string]: string }\n readonly encryptedFieldsConfig: EncryptedFieldsConfig\n readonly groupSelector: (availableGroupsInfo: UserGroup[]) => Promise<string>\n readonly disableParentKeysInitialisation: boolean\n\n constructor(custom: IcureApiOptions) {\n this.entryKeysFactory = custom.entryKeysFactory ?? Defaults.entryKeysFactory\n this.createMaintenanceTasksOnNewKey = custom.createMaintenanceTasksOnNewKey ?? Defaults.createMaintenanceTasksOnNewKey\n this.storage = custom.storage ?? new LocalStorageImpl()\n this.keyStorage = custom.keyStorage ?? new KeyStorageImpl(this.storage)\n this.headers = custom.headers ?? Defaults.headers\n this.encryptedFieldsConfig = custom.encryptedFieldsConfig ?? {}\n this.groupSelector = custom.groupSelector ?? ((groups) => Promise.resolve(groups[0].groupId!))\n this.disableParentKeysInitialisation = custom.disableParentKeysInitialisation ?? false\n }\n }\n}\n\n/**\n * Specifies which fields should be encrypted for each kind of encryptable entity.\n *\n * Note that any value you specify here overrides the default values. For example if you specify `['medicalLocationId']` for `healthElement` the\n * fields `['descr', 'note']` which are usually encrypted by default will no longer be encrypted. If you want to add fields to the default values\n * you can use {@link EncryptedFieldsConfig.Defaults}, for example `[...EncryptedFieldsConfig.Defaults.healthElement, 'medicalLocationId'].\n *\n * # Encrypted fields syntax\n *\n * ## Grammar\n *\n * The grammar for each encrypted field is the following:\n * ```\n * fieldName :=\n * regex([a-zA-Z_][a-zA-Z0-9_]+)\n * encryptedField :=\n * fieldName\n * | fieldName + (\".\" | \".*.\" | \"[].\") + encryptedField\n * ```\n *\n * This grammar allows you to specify the fields to encrypt for the object and recursively for nested objects.\n * - A string containing only a single `fieldName` will encrypt the field with the given name.\n * - A string starting with `fieldName.` allows to specify the encrypted fields of a nested object. The encrypted values of the\n * fields in the nested object will be saved in the nested object.\n * - A string starting with `fieldName.*.` treats `fieldName` as a map/dictionary data structure and allows to specify the encrypted fields of the\n * values of the map. Note that the values of the map must be objects as well. The encrypted content of each map value is stored in that value.\n * - A string starting with `fieldName[].` treats `fieldName` as an array and allows to specify the encrypted fields of the values of the array.\n * Note that the values of the array must be objects as well. The encrypted content of each array element is stored in that element.\n *\n * ## Example\n *\n * Consider the following object and encryption keys:\n * ```javascript\n * const obj = {\n * a: { x: 0, y: 1 },\n * b: \"hello\",\n * c: [ { public: \"a\", secret: \"b\" }, { public: \"c\", secret: \"d\" } ],\n * d: \"ok\",\n * e: {\n * info: \"something\",\n * private: \"secret\",\n * dataMap: {\n * \"en\": {\n * a: 1,\n * b: 2\n * },\n * \"fr\": {\n * a: 3,\n * b: 4\n * }\n * }\n * }\n * }\n * const encryptedFields = [\n * \"a\",\n * \"c[].secret\",\n * \"d\",\n * \"e.private\",\n * \"e.datamap.*.a\"\n * ]\n * ```\n * If you use them with the crypt method you will get the following result:\n * ```json\n * {\n * b: \"hello\",\n * c: [\n * { public: \"a\", encryptedSelf: 'encrypted+encoded { secret: \"b\" }' },\n * { public: \"c\", encryptedSelf: 'encrypted+encoded { secret: \"d\" }' }\n * ],\n * e: {\n * info: \"something\",\n * dataMap: {\n * \"en\": { b: 2, encryptedSelf: 'encrypted+encoded { a: 1 }' },\n * \"fr\": { b: 4, encryptedSelf: 'encrypted+encoded { a: 3 }' }\n * },\n * encryptedSelf: 'encrypted+encoded { private: \"secret\" }'\n * },\n * encryptedSelf: 'encrypted+encoded { a: { x: 0, y: 1 }, d: \"ok\" }'\n * }\n * ```\n *\n * ## Shortened representation\n *\n * You can also group encrypted fields having the same prefix by concatenating to the prefix the JSON representation of an array of all the postfixes.\n * For example the following encrypted fields:\n * ```javascript\n * const encryptedFields = [\"a.b.c.d.e.f1\", \"a.b.c.d.e.f2\", \"a.b.c.d.e.f3\", \"a.b.c.d.e.f4\"]\n * ```\n * can be shortened to\n * ```javascript\n * const encryptedFields = ['a.b.c.d.e.[\"f1\",\"f2\",\"f3\",\"f4\"]'] // Note the use of single quotes to avoid escaping the double quotes\n * ```\n * If you use the shortened representation you may need to escape nested json representations. In that case the use of `JSON.stringify` is\n * recommended.\n */\nexport interface EncryptedFieldsConfig {\n /**\n * Fields to encrypt for entities of type {@link AccessLog}\n * @default ['detail', 'objectId']\n */\n readonly accessLog?: string[]\n /**\n * Fields to encrypt for entities of type {@link CalendarItem}\n * @default ['details', 'title', 'patientId']\n */\n readonly calendarItem?: string[]\n /**\n * Fields to encrypt for entities of type {@link Contact}, excluding `services`. You can specify which fields of `services` should be encrypted\n * using {@link service}.\n * @default ['descr'] // encryption of `services` is managed through {@link service}\n */\n readonly contact?: string[]\n /**\n * Fields to encrypt for entities of type {@link Service}. Note that encryption of the `content` field and recursively contained `Services` through\n * `content.compoundValue` is automatically managed by the sdk, and you are not allowed to modify it.\n *\n * Note: any non-empty values for this field will break bi-directional data compatibility between v7 and previous: Contacts created with\n * v7 will not be read properly by previous versions. If you want\n * @default ['notes[].markdown'] // encryption of `content` is managed in a special way\n */\n readonly service?: string[]\n /**\n * Fields to encrypt for entities of type {@link HealthElement}\n * @default ['descr', 'note', 'notes[].markdown']\n */\n readonly healthElement?: string[]\n /**\n * Fields to encrypt for entities of type {@link MaintenanceTask}\n * @default ['properties']\n */\n readonly maintenanceTask?: string[]\n /**\n * Fields to encrypt for entities of type {@link Patient}\n * @default ['note', 'notes[].markdown']\n */\n readonly patient?: string[]\n\n /**\n * Fields to encrypt for entities of type {@link Message}\n * @default []\n */\n readonly message?: string[]\n\n /**\n * Fields to encrypt for entities of type {@link Topic}\n * @default ['description']\n */\n readonly topic?: string[]\n}\n\nexport namespace EncryptedFieldsConfig {\n export const Defaults = {\n accessLog: ['detail', 'objectId'],\n calendarItem: ['details', 'title', 'patientId'],\n contact: ['descr', 'notes[].markdown'],\n service: ['notes[].markdown'],\n healthElement: ['descr', 'note', 'notes[].markdown'],\n maintenanceTask: ['properties'],\n patient: ['note', 'notes[].markdown'],\n message: [],\n topic: ['description', 'linkedServices', 'linkedHealthElements'],\n }\n}\n\n/**\n * Details for the authentication of a user\n */\nexport type AuthenticationDetails =\n | {\n username: string\n password: string\n thirdPartyTokens?: { [thirdParty: string]: string }\n }\n | {\n icureTokens: { token: string; refreshToken: string }\n credentials?: { username: string; password: string }\n }\n | {\n thirdPartyTokens: { [thirdParty: string]: string }\n }\n | SmartAuthenticationDetails\n\n/**\n * Allows to perform authentication through an {@link AuthSecretProvider}.\n *\n * The iCure SDK can authenticate to the backend using different kinds of secrets, such as passwords, long-lived authentication tokens, and\n * short-lived authentication tokens generated through the message gateway. iCure associates to each kind of secret a certain security level, and for\n * some sensitive operations, depending on the configurations of the user and his group, some operations may require a secret of a certain security\n * level. For example, with the default configurations, in order to change his own email the user can't have logged in with a long-lived token, but he\n * needs to provide his current password or a short-lived token.\n *\n * By using this authentication option, the iCure SDK will automatically request and cache the secret from the {@link AuthSecretProvider} only when\n * needed, which should help to minimise the interaction with the user.\n *\n * Another advantage of using this authentication option over others is that in case all the cached tokens and secrets were to expire while performing\n * a request, instead of having the request fail the SDK will ask for a new secret from the {@link SmartAuthProvider} and the request will\n * automatically be retried with the new secret.\n *\n * You must provide the following information:\n * - username: any kind of value that can identify the user (userId, groupId/userId, username, email, ...). More generic identifiers, valid\n * on multiple groups, allow for simpler group switching by using {@link IcureApi.switchGroup}.\n * - secretProvider: the secret provider to use for authentication. Will handle interaction with the gui.\n *\n * You can also provide the following optional information, which may allow to reduce the requests for secrets initially:\n * - initialSecret: an initial secret (password, token, ...) that will be used to get new authentication tokens as needed. If it is expired it will be ignored.\n * - initialAuthToken: an initial authentication token used on each request. If it is expired it will be ignored.\n * - initialRefreshToken: an initial refresh token used to get new authentication tokens as needed. If it is expired it will be ignored.\n */\nexport type SmartAuthenticationDetails = {\n username: string\n secretProvider: AuthSecretProvider\n initialSecret?:\n | {\n password: string\n }\n | {\n longToken: string\n }\n | {\n oauthToken: string\n oauthType: OAuthThirdParty\n }\n initialAuthToken?: string\n initialRefreshToken?: string\n}\n\n/**\n * Main entry point for the iCure API. Provides entity-specific sub-apis and some general methods which are not related to a specific entity.\n */\nexport interface IcureApi extends Apis {\n /**\n * Get the information on groups that the current user can access and the current group that this api instance is working on.\n * Note that the values you will get for `availableGroups` may differ from the values you would get if you call {@link IccUserApi.getMatchingUsers}\n * on {@link Apis.userApi}, since the latter is specialised on the specific instance of the user in `currentGroup`.\n * - `currentGroup`: the group that this api instance is working on, or undefined if the backend environment is not multi-group.\n * - `availableGroups`: the list of groups that the current user can access with the provided secret. Empty if the backend environment is not\n * multi-group.\n */\n getGroupsInfo(): Promise<{ currentGroup: UserGroup | undefined; availableGroups: UserGroup[] }>\n\n /**\n * Switches the api to allow the user to work on a different group.\n * @param newGroupId the id of the group to switch to.\n * @return a new api for the specified group.\n */\n switchGroup(newGroupId: string): Promise<IcureApi>\n}\n\nexport namespace IcureApi {\n /**\n * Initialises a new instance of the iCure API.\n */\n export async function initialise(\n host: string,\n authenticationOptions: AuthenticationDetails | AuthenticationProvider,\n cryptoStrategies: CryptoStrategies,\n crypto: Crypto | CryptoPrimitives = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n options: IcureApiOptions = {}\n ): Promise<IcureApi> {\n const params = new IcureApiOptions.WithDefaults(options)\n let authenticationProviderInfo = await initialiseAuthProviderWithGroupSelector(\n host,\n authenticationOptions,\n params.headers,\n fetchImpl,\n params.groupSelector\n )\n const cryptoInitInfo = await initialiseCryptoWithProvider(\n host,\n fetchImpl,\n authenticationProviderInfo.groupSpecificAuthenticationProvider,\n params,\n cryptoStrategies,\n crypto\n )\n return new IcureApiImpl(\n cryptoInitInfo,\n host,\n authenticationProviderInfo.groupSpecificAuthenticationProvider,\n fetch,\n authenticationProviderInfo.grouplessUserApi,\n authenticationProviderInfo.matches,\n authenticationProviderInfo.matches.find((match) => match.groupId === authenticationProviderInfo.chosenGroupId),\n params,\n cryptoStrategies\n )\n }\n}\n\nasync function getAuthenticationProvider(\n host: string,\n authenticationOptions: AuthenticationDetails | AuthenticationProvider,\n headers: { [headerName: string]: string },\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response>\n) {\n let authenticationProvider: AuthenticationProvider\n if ('getIcureTokens' in authenticationOptions && 'switchGroup' in authenticationOptions && 'getAuthService' in authenticationOptions) {\n authenticationProvider = authenticationOptions\n } else if ('icureTokens' in authenticationOptions && !!authenticationOptions.icureTokens) {\n authenticationProvider = new JwtAuthenticationProvider(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n authenticationOptions?.credentials?.username,\n authenticationOptions?.credentials?.password,\n undefined,\n authenticationOptions.icureTokens\n )\n } else if (\n 'username' in authenticationOptions &&\n 'password' in authenticationOptions &&\n !!authenticationOptions.username &&\n !!authenticationOptions.password\n ) {\n authenticationProvider = new EnsembleAuthenticationProvider(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n authenticationOptions.username,\n authenticationOptions.password,\n 3600,\n undefined,\n undefined,\n authenticationOptions.thirdPartyTokens\n )\n } else if ('thirdPartyTokens' in authenticationOptions && !!authenticationOptions.thirdPartyTokens) {\n authenticationProvider = new JwtAuthenticationProvider(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n undefined,\n undefined,\n new JwtBridgedAuthService(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n undefined,\n undefined,\n authenticationOptions.thirdPartyTokens,\n undefined\n )\n )\n } else if ('username' in authenticationOptions && 'secretProvider' in authenticationOptions) {\n authenticationProvider = SmartAuthProvider.initialise(\n new IccAuthApi(host, headers, new NoAuthenticationProvider(), fetchImpl),\n authenticationOptions.username,\n authenticationOptions.secretProvider,\n {\n initialSecret: authenticationOptions.initialSecret,\n initialAuthToken: authenticationOptions.initialAuthToken,\n initialRefreshToken: authenticationOptions.initialRefreshToken,\n }\n )\n } else {\n throw new Error('Invalid authentication options provided')\n }\n return authenticationProvider\n}\n\nasync function initialiseAuthProviderWithGroupSelector(\n host: string,\n authenticationOptions: AuthenticationDetails | AuthenticationProvider,\n headers: { [headerName: string]: string },\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n groupSelector: ((availableGroupsInfo: UserGroup[], currentGroupId?: string) => Promise<string>) | undefined\n) {\n let grouplessAuthenticationProvider = await getAuthenticationProvider(host, authenticationOptions, headers, fetchImpl)\n const grouplessUserApi = new IccUserApi(host, headers, grouplessAuthenticationProvider, fetchImpl)\n const matches = await getMatchesOrEmpty(grouplessUserApi)\n const tokens = await grouplessAuthenticationProvider.getIcureTokens()\n const currentGroupId = tokens ? getGroupOfJwt(tokens.token) : undefined\n const chosenGroupId = matches.length > 1 && !!groupSelector ? await groupSelector(matches, currentGroupId) : matches[0]?.groupId\n /*TODO\n * 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\n * probably linked to replication of the user in the fallback database.\n */\n /*\n * If the auth provider is initialized with credentials and jwt not switching the group will may cause issues:\n * 1. The default group for the user is group A\n * 2. The user logs in to group B -> the provider is switched\n * 3. The user refreshes the page -> a new instance of the api with initial iCure tokens is created\n * 4. The refresh token is expired / the user needs to do a high security operation -> a new login is done .If we did\n * not switch the provider here the login would default to group A, potentially causing a lot of issues...\n */\n const groupSpecificAuthenticationProvider = !!chosenGroupId\n ? await grouplessAuthenticationProvider.switchGroup(chosenGroupId, matches)\n : grouplessAuthenticationProvider\n return {\n groupSpecificAuthenticationProvider,\n // No need for a groupless user api on a group-specific smart auth provider\n grouplessUserApi: groupSpecificAuthenticationProvider instanceof SmartAuthProvider ? undefined : grouplessUserApi,\n matches,\n chosenGroupId,\n }\n}\n\n// Apis which are used during crypto api initialisation, to avoid re-instantiating them later\ntype CryptoInitialisationInfo = {\n cryptoApi: IccCryptoXApi\n healthcarePartyApi: IccHcpartyXApi\n deviceApi: IccDeviceXApi\n // no patient api since it is base\n dataOwnerApi: IccDataOwnerXApi\n userApi: IccUserXApi\n icureMaintenanceTaskApi: IccIcureMaintenanceXApi\n maintenanceTaskApi: IccMaintenanceTaskXApi\n headers: { [headerName: string]: string }\n dataOwnerRequiresAnonymousDelegation: boolean\n recoveryApi: IccRecoveryXApi\n}\n\nconst REQUEST_AUTOFIX_ANONYMITY_HEADER = 'Icure-Request-Autofix-Anonymity'\n\nasync function initialiseCryptoWithProvider(\n host: string,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n groupSpecificAuthenticationProvider: AuthenticationProvider,\n params: IcureApiOptions.WithDefaults,\n cryptoStrategies: CryptoStrategies,\n crypto: Crypto | CryptoPrimitives\n): Promise<CryptoInitialisationInfo> {\n const initialDataOwnerStub = await new IccDataOwnerXApi(\n host,\n params.headers,\n groupSpecificAuthenticationProvider,\n fetchImpl\n ).getCurrentDataOwnerStub()\n const dataOwnerRequiresAnonymousDelegation = cryptoStrategies.dataOwnerRequiresAnonymousDelegation(initialDataOwnerStub)\n let updatedHeaders = params.headers\n if (!Object.keys(updatedHeaders).includes(REQUEST_AUTOFIX_ANONYMITY_HEADER)) {\n if (initialDataOwnerStub.type == DataOwnerTypeEnum.Patient || initialDataOwnerStub.type == DataOwnerTypeEnum.Device) {\n if (!dataOwnerRequiresAnonymousDelegation) {\n updatedHeaders = { ...updatedHeaders, [REQUEST_AUTOFIX_ANONYMITY_HEADER]: 'false' }\n }\n } else {\n if (dataOwnerRequiresAnonymousDelegation) {\n updatedHeaders = { ...updatedHeaders, [REQUEST_AUTOFIX_ANONYMITY_HEADER]: 'true' }\n }\n }\n }\n\n const authApi = new IccAuthApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n const userApi = new IccUserXApi(host, updatedHeaders, groupSpecificAuthenticationProvider, authApi, fetchImpl)\n const healthcarePartyApi = new IccHcpartyXApi(host, updatedHeaders, groupSpecificAuthenticationProvider, authApi, fetchImpl)\n const deviceApi = new IccDeviceXApi(host, updatedHeaders, groupSpecificAuthenticationProvider, userApi, authApi, fetchImpl)\n const basePatientApi = new IccPatientApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n const dataOwnerApi = new IccDataOwnerXApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n const exchangeDataApi = new IccExchangeDataApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n const baseRecoveryDataApi = new IccRecoveryDataApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n // Crypto initialisation\n const icureStorage = new IcureStorageFacade(params.keyStorage, params.storage, params.entryKeysFactory)\n const cryptoPrimitives = 'AES' in crypto && 'RSA' in crypto && 'HMAC' in crypto ? crypto : new WebCryptoPrimitives(crypto)\n const baseExchangeKeysManager = new BaseExchangeKeysManager(cryptoPrimitives, dataOwnerApi, healthcarePartyApi, basePatientApi, deviceApi)\n const baseExchangeDataManager = new BaseExchangeDataManager(exchangeDataApi, dataOwnerApi, cryptoPrimitives, dataOwnerRequiresAnonymousDelegation)\n const keyRecovery = new KeyRecovery(cryptoPrimitives, dataOwnerApi, baseExchangeKeysManager, baseExchangeDataManager)\n const recoveryDataEncryption = new RecoveryDataEncryption(cryptoPrimitives, baseRecoveryDataApi)\n const keyPairRecoverer = new KeyPairRecoverer(recoveryDataEncryption)\n const userEncryptionKeysManager = new UserEncryptionKeysManager(\n cryptoPrimitives,\n dataOwnerApi,\n icureStorage,\n keyRecovery,\n cryptoStrategies,\n !params.disableParentKeysInitialisation,\n keyPairRecoverer\n )\n const userSignatureKeysManager = new UserSignatureKeysManager(icureStorage, dataOwnerApi, cryptoPrimitives)\n const newKey = await userEncryptionKeysManager.initialiseKeys()\n await new TransferKeysManager(\n cryptoPrimitives,\n baseExchangeDataManager,\n dataOwnerApi,\n userEncryptionKeysManager,\n userSignatureKeysManager,\n icureStorage\n ).updateTransferKeys(await dataOwnerApi.getCurrentDataOwnerStub())\n // TODO customise cache size?\n const exchangeKeysManager = new ExchangeKeysManager(\n 100,\n 500,\n 600000,\n 60000,\n cryptoStrategies,\n cryptoPrimitives,\n userEncryptionKeysManager,\n baseExchangeKeysManager,\n dataOwnerApi,\n !params.disableParentKeysInitialisation,\n icureStorage\n )\n const accessControlSecretUtils = new AccessControlSecretUtils(cryptoPrimitives)\n const exchangeDataManager = await initialiseExchangeDataManagerForCurrentDataOwner(\n baseExchangeDataManager,\n userEncryptionKeysManager,\n userSignatureKeysManager,\n accessControlSecretUtils,\n cryptoStrategies,\n dataOwnerApi,\n cryptoPrimitives,\n !params.disableParentKeysInitialisation\n )\n const exchangeDataMapManager = new ExchangeDataMapManager(\n new IccExchangeDataMapApi(host, updatedHeaders, groupSpecificAuthenticationProvider, fetchImpl)\n )\n const secureDelegationsEncryption = new SecureDelegationsEncryption(userEncryptionKeysManager, cryptoPrimitives)\n const secureDelegationsSecurityMetadataEncryption = new SecureDelegationsSecurityMetadataDecryptor(\n exchangeDataManager,\n exchangeDataMapManager,\n secureDelegationsEncryption,\n dataOwnerApi\n )\n const xApiUtils = new ExtendedApisUtilsImpl(\n cryptoPrimitives,\n dataOwnerApi,\n new LegacyDelegationSecurityMetadataDecryptor(exchangeKeysManager, cryptoPrimitives),\n secureDelegationsSecurityMetadataEncryption,\n new SecureDelegationsManager(\n exchangeDataManager,\n exchangeDataMapManager,\n secureDelegationsEncryption,\n accessControlSecretUtils,\n userEncryptionKeysManager,\n cryptoPrimitives,\n dataOwnerApi,\n cryptoStrategies,\n dataOwnerRequiresAnonymousDelegation\n ),\n userApi,\n !params.disableParentKeysInitialisation\n )\n const shamirManager = new ShamirKeysManager(cryptoPrimitives, dataOwnerApi, userEncryptionKeysManager, exchangeDataManager)\n const confidentialEntitites = new ConfidentialEntities(xApiUtils, cryptoPrimitives, dataOwnerApi)\n await ensureDelegationForSelf(dataOwnerApi, xApiUtils, basePatientApi, cryptoPrimitives)\n const accessControlKeysHeadersProvider = new AccessControlKeysHeadersProvider(exchangeDataManager)\n const delegationsDeAnonymisation = new DelegationsDeAnonymization(\n dataOwnerApi,\n secureDelegationsSecurityMetadataEncryption,\n xApiUtils,\n cryptoPrimitives,\n accessControlSecretUtils,\n host,\n updatedHeaders,\n groupSpecificAuthenticationProvider,\n fetchImpl,\n accessControlKeysHeadersProvider\n )\n const cryptoApi = new IccCryptoXApi(\n exchangeKeysManager,\n cryptoPrimitives,\n userEncryptionKeysManager,\n dataOwnerApi,\n xApiUtils,\n shamirManager,\n params.storage,\n params.keyStorage,\n confidentialEntitites,\n exchangeDataManager,\n accessControlKeysHeadersProvider,\n delegationsDeAnonymisation\n )\n const maintenanceTaskApi = new IccMaintenanceTaskXApi(\n host,\n updatedHeaders,\n cryptoApi,\n healthcarePartyApi,\n dataOwnerApi,\n userApi,\n authApi,\n !dataOwnerRequiresAnonymousDelegation,\n params.encryptedFieldsConfig.maintenanceTask ?? EncryptedFieldsConfig.Defaults.maintenanceTask,\n groupSpecificAuthenticationProvider,\n fetchImpl\n )\n const icureMaintenanceTaskApi = new IccIcureMaintenanceXApi(cryptoApi, maintenanceTaskApi, dataOwnerApi, exchangeDataApi)\n\n if (newKey && params.createMaintenanceTasksOnNewKey) {\n await icureMaintenanceTaskApi.createMaintenanceTasksForNewKeypair(await userApi.getCurrentUser(), newKey.newKeyPair)\n }\n return {\n cryptoApi,\n userApi,\n healthcarePartyApi,\n deviceApi,\n maintenanceTaskApi,\n dataOwnerApi,\n icureMaintenanceTaskApi,\n headers: updatedHeaders,\n dataOwnerRequiresAnonymousDelegation,\n recoveryApi: new IccRecoveryXApi(\n baseRecoveryDataApi,\n recoveryDataEncryption,\n userEncryptionKeysManager,\n dataOwnerApi,\n cryptoPrimitives,\n exchangeDataManager\n ),\n }\n}\n\nclass IcureApiImpl implements IcureApi {\n private latestGroupsRequest: Promise<UserGroup[]>\n\n constructor(\n private readonly cryptoInitInfos: CryptoInitialisationInfo,\n private readonly host: string,\n private readonly groupSpecificAuthenticationProvider: AuthenticationProvider,\n private readonly fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n private readonly grouplessUserApi: IccUserApi | undefined,\n latestMatches: UserGroup[],\n private readonly currentGroupInfo: UserGroup | undefined,\n private readonly params: IcureApiOptions.WithDefaults,\n private readonly cryptoStrategies: CryptoStrategies\n ) {\n this.latestGroupsRequest = Promise.resolve(latestMatches)\n }\n\n private _authApi: IccAuthApi | undefined\n\n get recoveryApi(): IccRecoveryXApi {\n return this.cryptoInitInfos.recoveryApi\n }\n\n get authApi(): IccAuthApi {\n return (\n this._authApi ?? (this._authApi = new IccAuthApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _codeApi: IccCodeXApi | undefined\n\n get codeApi(): IccCodeXApi {\n return (\n this._codeApi ??\n (this._codeApi = new IccCodeXApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _calendarItemTypeApi: IccCalendarItemTypeApi | undefined\n\n get calendarItemTypeApi(): IccCalendarItemTypeApi {\n return (\n this._calendarItemTypeApi ??\n (this._calendarItemTypeApi = new IccCalendarItemTypeApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _medicalLocationApi: IccMedicallocationApi | undefined\n\n get medicalLocationApi(): IccMedicallocationApi {\n return (\n this._medicalLocationApi ??\n (this._medicalLocationApi = new IccMedicallocationApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _roleApi: IccRoleApi | undefined\n\n get roleApi(): IccRoleApi {\n return this._roleApi ?? (this._roleApi = new IccRoleApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n\n private _entityReferenceApi: IccEntityrefApi | undefined\n\n get entityReferenceApi(): IccEntityrefApi {\n return (\n this._entityReferenceApi ??\n (this._entityReferenceApi = new IccEntityrefApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _permissionApi: IccPermissionApi | undefined\n\n get permissionApi(): IccPermissionApi {\n return (\n this._permissionApi ??\n (this._permissionApi = new IccPermissionApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _accessLogApi: IccAccesslogXApi | undefined\n\n get accessLogApi(): IccAccesslogXApi {\n return (\n this._accessLogApi ??\n (this._accessLogApi = new IccAccesslogXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.params.encryptedFieldsConfig.accessLog ?? EncryptedFieldsConfig.Defaults.accessLog,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _agendaApi: IccAgendaApi | undefined\n\n get agendaApi(): IccAgendaApi {\n return (\n this._agendaApi ??\n (this._agendaApi = new IccAgendaApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _contactApi: IccContactXApi | undefined\n\n get contactApi(): IccContactXApi {\n return (\n this._contactApi ??\n (this._contactApi = new IccContactXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.userApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch,\n this.params.encryptedFieldsConfig.contact ?? EncryptedFieldsConfig.Defaults.contact,\n this.params.encryptedFieldsConfig.service ?? EncryptedFieldsConfig.Defaults.service\n ))\n )\n }\n\n private _formApi: IccFormXApi | undefined\n\n get formApi(): IccFormXApi {\n return (\n this._formApi ??\n (this._formApi = new IccFormXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _groupApi: IccGroupApi | undefined\n\n get groupApi(): IccGroupApi {\n return (\n this._groupApi ??\n (this._groupApi = new IccGroupApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _invoiceApi: IccInvoiceXApi | undefined\n\n get invoiceApi(): IccInvoiceXApi {\n return (\n this._invoiceApi ??\n (this._invoiceApi = new IccInvoiceXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.entityReferenceApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _insuranceApi: IccInsuranceApi | undefined\n\n get insuranceApi(): IccInsuranceApi {\n return (\n this._insuranceApi ??\n (this._insuranceApi = new IccInsuranceApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _documentApi: IccDocumentXApi | undefined\n\n get documentApi(): IccDocumentXApi {\n return (\n this._documentApi ??\n (this._documentApi = new IccDocumentXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.authApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _healthcareElementApi: IccHelementXApi | undefined\n\n get healthcareElementApi(): IccHelementXApi {\n return (\n this._healthcareElementApi ??\n (this._healthcareElementApi = new IccHelementXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.userApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.params.encryptedFieldsConfig.healthElement ?? EncryptedFieldsConfig.Defaults.healthElement,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _classificationApi: IccClassificationXApi | undefined\n\n get classificationApi(): IccClassificationXApi {\n return (\n this._classificationApi ??\n (this._classificationApi = new IccClassificationXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _calendarItemApi: IccCalendarItemXApi | undefined\n\n get calendarItemApi(): IccCalendarItemXApi {\n return (\n this._calendarItemApi ??\n (this._calendarItemApi = new IccCalendarItemXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.params.encryptedFieldsConfig.calendarItem ?? EncryptedFieldsConfig.Defaults.calendarItem,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _receiptApi: IccReceiptXApi | undefined\n\n get receiptApi(): IccReceiptXApi {\n return (\n this._receiptApi ??\n (this._receiptApi = new IccReceiptXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _timetableApi: IccTimeTableXApi | undefined\n\n get timetableApi(): IccTimeTableXApi {\n return (\n this._timetableApi ??\n (this._timetableApi = new IccTimeTableXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _patientApi: IccPatientXApi | undefined\n\n get patientApi(): IccPatientXApi {\n return (\n this._patientApi ??\n (this._patientApi = new IccPatientXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.contactApi,\n this.formApi,\n this.healthcareElementApi,\n this.invoiceApi,\n this.documentApi,\n this.healthcarePartyApi,\n this.classificationApi,\n this.dataOwnerApi,\n this.calendarItemApi,\n this.userApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.params.encryptedFieldsConfig.patient ?? EncryptedFieldsConfig.Defaults.patient,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _messageApi: IccMessageXApi | undefined\n\n get messageApi(): IccMessageXApi {\n return (\n this._messageApi ??\n (this._messageApi = new IccMessageXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.params.encryptedFieldsConfig.message ?? EncryptedFieldsConfig.Defaults.message,\n this.fetch\n ))\n )\n }\n\n private _topicApi: IccTopicXApi | undefined\n\n get topicApi(): IccTopicXApi {\n return (\n this._topicApi ??\n (this._topicApi = new IccTopicXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.dataOwnerApi,\n this.authApi,\n !this.cryptoInitInfos.dataOwnerRequiresAnonymousDelegation,\n this.groupSpecificAuthenticationProvider,\n this.params.encryptedFieldsConfig.topic ?? EncryptedFieldsConfig.Defaults.topic,\n this.fetch\n ))\n )\n }\n\n private _anonymousAccessApi: IccAnonymousAccessApi | undefined\n\n get anonymousAccessApi(): IccAnonymousAccessApi {\n return (\n this._anonymousAccessApi ??\n (this._anonymousAccessApi = new IccAnonymousAccessApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _applicationSettingsApi: IccApplicationsettingsApi | undefined\n\n get applicationSettingsApi(): IccApplicationsettingsApi {\n return (\n this._applicationSettingsApi ??\n (this._applicationSettingsApi = new IccApplicationsettingsApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _articleApi: IccArticleApi | undefined\n\n get articleApi(): IccArticleApi {\n return (\n this._articleApi ??\n (this._articleApi = new IccArticleApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _bekmehrApi: IccBekmehrXApi | undefined\n\n get bekmehrApi(): IccBekmehrXApi {\n return (\n this._bekmehrApi ??\n (this._bekmehrApi = new IccBekmehrXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.contactApi,\n this.healthcareElementApi,\n this.documentApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _beefactApi: IccBeefactApi | undefined\n\n get beefactApi(): IccBeefactApi {\n return (\n this._beefactApi ??\n (this._beefactApi = new IccBeefactApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _beresultexportApi: IccBeresultexportApi | undefined\n\n get beresultexportApi(): IccBeresultexportApi {\n return (\n this._beresultexportApi ??\n (this._beresultexportApi = new IccBeresultexportApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _beresultimportApi: IccBeresultimportApi | undefined\n\n get beresultimportApi(): IccBeresultimportApi {\n return (\n this._beresultimportApi ??\n (this._beresultimportApi = new IccBeresultimportApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _besamv2Api: IccBesamv2Api | undefined\n\n get besamv2Api(): IccBesamv2Api {\n return (\n this._besamv2Api ??\n (this._besamv2Api = new IccBesamv2Api(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _classificationTemplateApi: IccClassificationTemplateApi | undefined\n\n get classificationTemplateApi(): IccClassificationTemplateApi {\n return (\n this._classificationTemplateApi ??\n (this._classificationTemplateApi = new IccClassificationTemplateApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _doctemplateApi: IccDoctemplateXApi | undefined\n\n get doctemplateApi(): IccDoctemplateXApi {\n return (\n this._doctemplateApi ??\n (this._doctemplateApi = new IccDoctemplateXApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.cryptoApi,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _entitytemplateApi: IccEntitytemplateApi | undefined\n\n get entitytemplateApi(): IccEntitytemplateApi {\n return (\n this._entitytemplateApi ??\n (this._entitytemplateApi = new IccEntitytemplateApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _frontendmigrationApi: IccFrontendmigrationApi | undefined\n\n get frontendmigrationApi(): IccFrontendmigrationApi {\n return (\n this._frontendmigrationApi ??\n (this._frontendmigrationApi = new IccFrontendmigrationApi(\n this.host,\n this.cryptoInitInfos.headers,\n this.groupSpecificAuthenticationProvider,\n this.fetch\n ))\n )\n }\n\n private _icureApi: IccIcureApi | undefined\n\n get icureApi(): IccIcureApi {\n return (\n this._icureApi ??\n (this._icureApi = new IccIcureApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _keywordApi: IccKeywordApi | undefined\n\n get keywordApi(): IccKeywordApi {\n return (\n this._keywordApi ??\n (this._keywordApi = new IccKeywordApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _medexApi: IccMedexApi | undefined\n\n get medexApi(): IccMedexApi {\n return (\n this._medexApi ??\n (this._medexApi = new IccMedexApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _placeApi: IccPlaceApi | undefined\n\n get placeApi(): IccPlaceApi {\n return (\n this._placeApi ??\n (this._placeApi = new IccPlaceApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _pubsubApi: IccPubsubApi | undefined\n\n get pubsubApi(): IccPubsubApi {\n return (\n this._pubsubApi ??\n (this._pubsubApi = new IccPubsubApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _replicationApi: IccReplicationApi | undefined\n\n get replicationApi(): IccReplicationApi {\n return (\n this._replicationApi ??\n (this._replicationApi = new IccReplicationApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _tarificationApi: IccTarificationApi | undefined\n\n get tarificationApi(): IccTarificationApi {\n return (\n this._tarificationApi ??\n (this._tarificationApi = new IccTarificationApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n private _tmpApi: IccTmpApi | undefined\n\n get tmpApi(): IccTmpApi {\n return (\n this._tmpApi ?? (this._tmpApi = new IccTmpApi(this.host, this.cryptoInitInfos.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n get cryptoApi(): IccCryptoXApi {\n return this.cryptoInitInfos.cryptoApi\n }\n\n get dataOwnerApi(): IccDataOwnerXApi {\n return this.cryptoInitInfos.dataOwnerApi\n }\n\n get deviceApi(): IccDeviceXApi {\n return this.cryptoInitInfos.deviceApi\n }\n\n get healthcarePartyApi(): IccHcpartyXApi {\n return this.cryptoInitInfos.healthcarePartyApi\n }\n\n get icureMaintenanceTaskApi(): IccIcureMaintenanceXApi {\n return this.cryptoInitInfos.icureMaintenanceTaskApi\n }\n\n get maintenanceTaskApi(): IccMaintenanceTaskXApi {\n return this.cryptoInitInfos.maintenanceTaskApi\n }\n\n get userApi(): IccUserXApi {\n return this.cryptoInitInfos.userApi\n }\n\n async getGroupsInfo(): Promise<{ currentGroup: UserGroup | undefined; availableGroups: UserGroup[] }> {\n this.latestGroupsRequest = (this.grouplessUserApi ?? this.userApi).getMatchingUsers()\n return { currentGroup: this.currentGroupInfo, availableGroups: await this.latestGroupsRequest }\n }\n\n async switchGroup(newGroupId: string): Promise<IcureApi> {\n const availableGroups = await this.latestGroupsRequest\n const switchedProvider = await this.groupSpecificAuthenticationProvider.switchGroup(newGroupId, availableGroups)\n const cryptoInitInfos = await initialiseCryptoWithProvider(\n this.host,\n this.fetch,\n switchedProvider,\n this.params,\n this.cryptoStrategies,\n this.cryptoApi.primitives\n )\n return new IcureApiImpl(\n cryptoInitInfos,\n this.host,\n switchedProvider,\n this.fetch,\n this.grouplessUserApi,\n availableGroups,\n availableGroups.find((x) => x.groupId === newGroupId)!,\n this.params,\n this.cryptoStrategies\n )\n }\n}\n\nexport interface IcureBasicApi extends BasicApis {\n /**\n * Get the information on groups that the current user can access and the current group that this api instance is working on.\n * Note that the values you will get for `availableGroups` may differ from the values you would get if you call {@link IccUserApi.getMatchingUsers}\n * on {@link Apis.userApi}, since the latter is specialised on the specific instance of the user in `currentGroup`.\n * - `currentGroup`: the group that this api instance is working on, or undefined if the backend environment is not multi-group.\n * - `availableGroups`: the list of groups that the current user can access with the provided secret. Empty if the backend environment is not\n * multi-group.\n */\n getGroupsInfo(): Promise<{ currentGroup: UserGroup | undefined; availableGroups: UserGroup[] }>\n\n /**\n * Switches the api to allow the user to work on a different group.\n * @param newGroupId the id of the group to switch to.\n * @return a new api for the specified group.\n */\n switchGroup(newGroupId: string): Promise<IcureBasicApi>\n}\n\nclass IcureBasicApiImpl implements IcureBasicApi {\n private latestGroupsRequest: Promise<UserGroup[]>\n private _agendaApi: IccAgendaApi | undefined\n private _authApi: IccAuthApi | undefined\n private _codeApi: IccCodeXApi | undefined\n private _deviceApi: IccDeviceXApi | undefined\n private _entityReferenceApi: IccEntityrefApi | undefined\n private _groupApi: IccGroupApi | undefined\n private _healthcarePartyApi: IccHcpartyXApi | undefined\n private _insuranceApi: IccInsuranceApi | undefined\n private _permissionApi: IccPermissionApi | undefined\n private _userApi: IccUserXApi | undefined\n private _patientApi: IccPatientApi | undefined\n private _roleApi: IccRoleApi | undefined\n\n get agendaApi(): IccAgendaApi {\n return (\n this._agendaApi ?? (this._agendaApi = new IccAgendaApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get authApi(): IccAuthApi {\n return this._authApi ?? (this._authApi = new IccAuthApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get codeApi(): IccCodeXApi {\n return this._codeApi ?? (this._codeApi = new IccCodeXApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get deviceApi(): IccDeviceXApi {\n return (\n this._deviceApi ??\n (this._deviceApi = new IccDeviceXApi(\n this.host,\n this.params.headers,\n this.groupSpecificAuthenticationProvider,\n this.userApi,\n this.authApi,\n this.fetch\n ))\n )\n }\n get entityReferenceApi(): IccEntityrefApi {\n return (\n this._entityReferenceApi ??\n (this._entityReferenceApi = new IccEntityrefApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get groupApi(): IccGroupApi {\n return this._groupApi ?? (this._groupApi = new IccGroupApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n get healthcarePartyApi(): IccHcpartyXApi {\n return (\n this._healthcarePartyApi ??\n (this._healthcarePartyApi = new IccHcpartyXApi(\n this.host,\n this.params.headers,\n this.groupSpecificAuthenticationProvider,\n this.authApi,\n this.fetch\n ))\n )\n }\n get insuranceApi(): IccInsuranceApi {\n return (\n this._insuranceApi ??\n (this._insuranceApi = new IccInsuranceApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get permissionApi(): IccPermissionApi {\n return (\n this._permissionApi ??\n (this._permissionApi = new IccPermissionApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n get userApi(): IccUserXApi {\n return (\n this._userApi ??\n (this._userApi = new IccUserXApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.authApi, this.fetch))\n )\n }\n\n async getGroupsInfo(): Promise<{ currentGroup: UserGroup | undefined; availableGroups: UserGroup[] }> {\n if (!this.currentGroupInfo) return { currentGroup: undefined, availableGroups: [] }\n this.latestGroupsRequest = (this.grouplessUserApi ?? this.userApi).getMatchingUsers()\n return { currentGroup: this.currentGroupInfo, availableGroups: await this.latestGroupsRequest }\n }\n\n get patientApi(): IccPatientApi {\n return (\n this._patientApi ?? (this._patientApi = new IccPatientApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n )\n }\n\n get roleApi(): IccRoleApi {\n return this._roleApi ?? (this._roleApi = new IccRoleApi(this.host, this.params.headers, this.groupSpecificAuthenticationProvider, this.fetch))\n }\n\n async switchGroup(newGroupId: string): Promise<IcureBasicApi> {\n if (!this.currentGroupInfo) throw new Error('Cannot switch group: the backend environment does not support multiple groups.')\n const availableGroups = await this.latestGroupsRequest\n const switchedProvider = await this.groupSpecificAuthenticationProvider.switchGroup(newGroupId, availableGroups)\n return new IcureBasicApiImpl(\n this.host,\n switchedProvider,\n this.fetch,\n this.grouplessUserApi,\n availableGroups,\n availableGroups.find((x) => x.groupId === newGroupId)!,\n this.params\n )\n }\n\n constructor(\n private readonly host: string,\n private readonly groupSpecificAuthenticationProvider: AuthenticationProvider,\n private readonly fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>,\n private readonly grouplessUserApi: IccUserApi | undefined,\n latestMatches: UserGroup[],\n private readonly currentGroupInfo: UserGroup | undefined,\n private readonly params: IcureBasicApiOptions.WithDefaults\n ) {\n this.latestGroupsRequest = Promise.resolve(latestMatches)\n }\n}\n\nexport interface IcureBasicApiOptions {\n /**\n * Additional headers to use on each request made by the iCure api.\n * @default no additional headers\n */\n readonly headers?: { [headerName: string]: string }\n /**\n * Each user may exist in multiple groups, but an instance of {@link IcureApi} is specialised for a single group. This function allows you to decide\n * the group to use for a given user.\n * This functions will be called only if a user exists in at least 2 groups, and takes in input:\n * - the information on the groups the user can access (in no specific order)\n * - if the authentication method uses JWT also the current group id (undefined otherwise)\n * The function must return the id of one of the available groups.\n * @default takes the first group provided. The group chosen by this method may vary between different instantiations of the {@link IcureApi} even\n * if for the same user and if the groups available for the user do not change.\n */\n readonly groupSelector?: (availableGroupsInfo: UserGroup[], currentGroupId?: string) => Promise<string>\n}\n\nnamespace IcureBasicApiOptions {\n export namespace Defaults {\n export const headers = {}\n }\n export class WithDefaults implements IcureBasicApiOptions {\n constructor(custom: IcureBasicApiOptions) {\n this.headers = custom.headers ?? Defaults.headers\n this.groupSelector = custom.groupSelector ?? ((groups) => Promise.resolve(groups[0].groupId!))\n }\n\n readonly headers: { [headerName: string]: string }\n readonly groupSelector: (availableGroupsInfo: UserGroup[]) => Promise<string>\n }\n}\n\nexport namespace IcureBasicApi {\n /**\n * Initialises a new instance of the iCure API.\n */\n export async function initialise(\n host: string,\n authenticationOptions: AuthenticationDetails | AuthenticationProvider,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n options: IcureBasicApiOptions = {}\n ): Promise<IcureBasicApi> {\n const params = new IcureBasicApiOptions.WithDefaults(options)\n const authProviderInfo = await initialiseAuthProviderWithGroupSelector(\n host,\n authenticationOptions,\n params.headers ?? {},\n fetchImpl,\n params.groupSelector\n )\n return new IcureBasicApiImpl(\n host,\n authProviderInfo.groupSpecificAuthenticationProvider,\n fetch,\n authProviderInfo.grouplessUserApi,\n authProviderInfo.matches,\n authProviderInfo.matches.find((match) => match.groupId === authProviderInfo.chosenGroupId),\n params\n )\n }\n}\n\nasync function getMatchesOrEmpty(userApi: IccUserApi): Promise<UserGroup[]> {\n try {\n return await userApi.getMatchingUsers()\n } catch (err) {\n if (err instanceof Error && 'statusCode' in err && (err as any).statusCode === 404) return Promise.resolve([])\n else return Promise.reject(err)\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -184,7 +184,7 @@ describe('Smart authentication provider', () => {
|
|
|
184
184
|
return { value: totp.generate(), secretType: SmartAuthProvider_1.AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN };
|
|
185
185
|
}),
|
|
186
186
|
}, {
|
|
187
|
-
initialSecret: {
|
|
187
|
+
initialSecret: { password: userPw },
|
|
188
188
|
});
|
|
189
189
|
const userApi = userApiWithProvider(authProvider);
|
|
190
190
|
(0, chai_1.expect)((yield userApi.getCurrentUser()).rev).to.equal(userWithPwAnd2fa.rev);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"smart-auth-provider-test.js","sourceRoot":"","sources":["../../../../test/icc-x-api/auth/smart-auth-provider-test.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,mDAAmE;AACnE,iCAA8B;AAC9B,uDAAqJ;AACrJ,kDAAkH;AAClH,8CAAyD;AACzD,4BAAyB;AACzB,iFAAgH;AAChH,+BAA6B;AAC7B,mCAAmC;AACnC,IAAO,aAAa,GAAG,sBAAS,CAAC,aAAa,CAAA;AAC9C,mCAA6B;AAC7B,qCAA8B;AAC9B,IAAA,4BAAe,EAAC,KAAK,CAAC,CAAA;AAE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AAA;QACzD,IAAA,aAAM,EAAC,MAAM,CAAC,IAAI,CAAC,MAAA,cAAc,CAAC,oBAAoB,mCAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAA;IAChF,CAAC,CAAA,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA","sourcesContent":["import { getEnvVariables, TestVars } from '@icure/test-setup/types'\nimport { before } from 'mocha'\nimport { createNewHcpApi, createUserInMultipleGroups, getEnvironmentInitializer, itNoLite, setLocalStorage, TestUtils } from '../../utils/test_utils'\nimport { AuthenticationProvider, BasicAuthenticationProvider, NoAuthenticationProvider } from '../../../icc-x-api'\nimport { IccAuthApi, IccUserApi } from '../../../icc-api'\nimport 'isomorphic-fetch'\nimport { AuthSecretDetails, AuthSecretType, SmartAuthProvider } from '../../../icc-x-api/auth/SmartAuthProvider'\nimport { expect } from 'chai'\nimport { randomUUID } from 'crypto'\nimport initMasterApi = TestUtils.initMasterApi\nimport { fail } from 'assert'\nimport { TOTP } from 'otpauth'\nsetLocalStorage(fetch)\n\nlet env: TestVars\nlet authApi: IccAuthApi\n\ndescribe('Smart authentication provider', () => {\n before(async function () {\n this.timeout(600000)\n const initializer = await getEnvironmentInitializer()\n env = await initializer.execute(getEnvVariables())\n authApi = new IccAuthApi(env.iCureUrl, {}, new NoAuthenticationProvider(), fetch)\n })\n\n function userApiWithProvider(authProvider: AuthenticationProvider): IccUserApi {\n return new IccUserApi(env.iCureUrl, {}, authProvider, fetch)\n }\n\n it('Should automatically ask for secret to get a new token, and reasks the secret if it is not valid', async () => {\n const { credentials } = await createNewHcpApi(env)\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(authApi, credentials.user, {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n expect(acceptedSecrets).to.include(AuthSecretType.PASSWORD)\n expect(acceptedSecrets).to.include(AuthSecretType.LONG_LIVED_TOKEN)\n expect(acceptedSecrets).to.include(AuthSecretType.SHORT_LIVED_TOKEN)\n expect(acceptedSecrets).to.not.include(AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n if (calls == 0) {\n expect(previousAttempts).to.be.empty\n } else if (calls == 1) {\n expect(previousAttempts).to.have.length(1)\n expect(previousAttempts[0].value).to.equal('wrong')\n expect(previousAttempts[0].secretType).to.equal(AuthSecretType.LONG_LIVED_TOKEN)\n } else fail(`Unexpected number of calls: ${calls}`)\n return calls++ == 0\n ? { value: 'wrong', secretType: AuthSecretType.LONG_LIVED_TOKEN } // pragma: allowlist secret\n : { value: credentials.password, secretType: AuthSecretType.LONG_LIVED_TOKEN }\n },\n })\n const userApi = userApiWithProvider(authProvider)\n const user = await userApi.getCurrentUser()\n expect(user.healthcarePartyId).to.equal(credentials.dataOwnerId)\n expect(calls).to.equal(2)\n })\n\n itNoLite(\n 'Should automatically ask for a more powerful secret to perform elevated-security operations if the available secret/token is not good enough',\n async () => {\n const { credentials, api } = await createNewHcpApi(env)\n const initialUser = await api.userApi.getCurrentUser()\n const masterApi = await initMasterApi(env)\n const userToken = randomUUID()\n const userPw = randomUUID()\n const userWithLongTokenAndPw = await masterApi.userApi.modifyUser({\n ...initialUser,\n passwordHash: userPw,\n authenticationTokens: {\n 'test-long-lived-token': {\n token: userToken,\n creationTime: Date.now(),\n validity: 60 * 60 * 24 * 7,\n },\n },\n })\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(authApi, credentials.user, {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n if (calls == 0) {\n expect(acceptedSecrets).to.include(AuthSecretType.PASSWORD)\n expect(acceptedSecrets).to.include(AuthSecretType.LONG_LIVED_TOKEN)\n expect(acceptedSecrets).to.include(AuthSecretType.SHORT_LIVED_TOKEN)\n expect(acceptedSecrets).to.not.include(AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n expect(previousAttempts).to.be.empty\n calls++\n return { value: userToken, secretType: AuthSecretType.LONG_LIVED_TOKEN }\n } else if (calls == 1) {\n expect(acceptedSecrets).to.include(AuthSecretType.PASSWORD)\n expect(acceptedSecrets).to.not.include(AuthSecretType.LONG_LIVED_TOKEN)\n expect(acceptedSecrets).to.include(AuthSecretType.SHORT_LIVED_TOKEN)\n expect(acceptedSecrets).to.not.include(AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n expect(previousAttempts).to.be.empty\n calls++\n return { value: userPw, secretType: AuthSecretType.PASSWORD }\n } else throw new Error(`Unexpected number of calls: ${calls}`)\n },\n })\n const userApi = userApiWithProvider(authProvider)\n expect((await userApi.getCurrentUser()).rev).to.equal(userWithLongTokenAndPw.rev)\n expect(calls).to.equal(1)\n const newPw = randomUUID()\n const userWithNewPw = await userApi.modifyUser({ ...userWithLongTokenAndPw, passwordHash: newPw })\n expect(userWithNewPw.rev).to.not.equal(userWithLongTokenAndPw.rev)\n expect(calls).to.equal(2)\n const retrievedWithNewPw = await userApiWithProvider(new BasicAuthenticationProvider(credentials.user, newPw)).getCurrentUser()\n expect(retrievedWithNewPw.rev).to.equal(userWithNewPw.rev)\n const couldRetrieveWithOldPw = await userApiWithProvider(new BasicAuthenticationProvider(credentials.user, userPw))\n .getCurrentUser()\n .then(\n () => true,\n () => false\n )\n expect(couldRetrieveWithOldPw).to.be.false\n }\n )\n\n itNoLite('Should automatically ask for TOTP after password if user has 2fa enabled', async () => {\n const { credentials, api } = await createNewHcpApi(env)\n const initialUser = await api.userApi.getCurrentUser()\n const masterApi = await initMasterApi(env)\n const totpSecret = 'AAPX7PW2RJIGZ3D4' // pragma: allowlist secret (fake secret generated only for test)\n const totp = new TOTP({\n algorithm: 'SHA1',\n digits: 6,\n period: 30,\n secret: totpSecret,\n })\n const userPw = randomUUID()\n await masterApi.userApi.enable2fa(initialUser.id!, totpSecret)\n const userWithPwAnd2fa = await masterApi.userApi.modifyUser({\n ...initialUser,\n passwordHash: userPw,\n })\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(authApi, credentials.user, {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n if (calls == 0) {\n expect(acceptedSecrets).to.include(AuthSecretType.PASSWORD)\n expect(acceptedSecrets).to.include(AuthSecretType.LONG_LIVED_TOKEN)\n expect(acceptedSecrets).to.include(AuthSecretType.SHORT_LIVED_TOKEN)\n expect(acceptedSecrets).to.not.include(AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n expect(previousAttempts).to.be.empty\n calls++\n return { value: userPw, secretType: AuthSecretType.PASSWORD }\n } else if (calls == 1 || calls == 2) {\n expect(acceptedSecrets).to.have.members([AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN])\n if (calls == 1) expect(previousAttempts).to.be.empty\n if (calls == 2) expect(previousAttempts).to.have.length(1)\n return calls++ == 1\n ? { value: totp.generate() + '13', secretType: AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN }\n : { value: totp.generate(), secretType: AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN }\n } else throw new Error(`Unexpected number of calls: ${calls}`)\n },\n })\n const userApi = userApiWithProvider(authProvider)\n expect((await userApi.getCurrentUser()).rev).to.equal(userWithPwAnd2fa.rev)\n expect(calls).to.equal(3)\n })\n\n itNoLite('Should ask for TOTP directly if password is cached', async () => {\n const { credentials, api } = await createNewHcpApi(env)\n const initialUser = await api.userApi.getCurrentUser()\n const masterApi = await initMasterApi(env)\n const totpSecret = 'AAPX7PW2RJIGZ3D4' // pragma: allowlist secret (fake secret generated only for test)\n const totp = new TOTP({\n algorithm: 'SHA1',\n digits: 6,\n period: 30,\n secret: totpSecret,\n })\n const userPw = randomUUID()\n await masterApi.userApi.enable2fa(initialUser.id!, totpSecret)\n const userWithPwAnd2fa = await masterApi.userApi.modifyUser({\n ...initialUser,\n passwordHash: userPw,\n })\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(\n authApi,\n credentials.user,\n {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n expect(acceptedSecrets).to.have.members([AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN])\n expect(previousAttempts).to.be.empty\n expect(calls++).to.equal(0)\n return { value: totp.generate(), secretType: AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN }\n },\n },\n {\n initialSecret: { plainSecret: userPw },\n }\n )\n const userApi = userApiWithProvider(authProvider)\n expect((await userApi.getCurrentUser()).rev).to.equal(userWithPwAnd2fa.rev)\n expect(calls).to.equal(1)\n })\n\n itNoLite('Switched provider should keep cached secrets and should be able to have elevated security context', async () => {\n const details = await createUserInMultipleGroups(env)\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(authApi, details.userLogin, {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n expect(acceptedSecrets).to.have.include(AuthSecretType.PASSWORD)\n expect(previousAttempts).to.be.empty\n expect(calls++).to.equal(0)\n return { value: details.userPw12, secretType: AuthSecretType.PASSWORD }\n },\n })\n const defaultGroupUserApi = userApiWithProvider(authProvider)\n const defaultGroupUser = await defaultGroupUserApi.getCurrentUser()\n const otherGroupId = details.group1.id == defaultGroupUser.groupId ? details.group2.id : details.group1.id\n const matches = await defaultGroupUserApi.getMatchingUsers()\n const switchedUserApi = userApiWithProvider(await authProvider.switchGroup(otherGroupId!, matches))\n const switchedUser = await switchedUserApi.getCurrentUser()\n expect(switchedUser.id).to.not.equal(defaultGroupUser.id)\n expect(switchedUser.groupId).to.equal(otherGroupId)\n const updatedDefault = await switchedUserApi.modifyUser({\n ...switchedUser,\n authenticationTokens: {\n 'new-token': {\n token: randomUUID(),\n creationTime: Date.now(),\n validity: 60 * 60 * 24 * 7,\n },\n },\n })\n expect(updatedDefault.rev).to.not.equal(switchedUser.rev)\n expect(Object.keys(updatedDefault.authenticationTokens ?? {})).to.not.be.empty\n })\n})\n"]}
|
|
1
|
+
{"version":3,"file":"smart-auth-provider-test.js","sourceRoot":"","sources":["../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YAAY,KACf,oBAAoB,EAAE;gBACpB,WAAW,EAAE;oBACX,KAAK,EAAE,IAAA,mBAAU,GAAE;oBACnB,YAAY,EAAE,IAAI,CAAC,GAAG,EAAE;oBACxB,QAAQ,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;iBAC3B;aACF,IACD,CAAA;QACF,IAAA,aAAM,EAAC,cAAc,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;QACzD,IAAA,aAAM,EAAC,MAAM,CAAC,IAAI,CAAC,MAAA,cAAc,CAAC,oBAAoB,mCAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAA;IAChF,CAAC,CAAA,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA","sourcesContent":["import { getEnvVariables, TestVars } from '@icure/test-setup/types'\nimport { before } from 'mocha'\nimport { createNewHcpApi, createUserInMultipleGroups, getEnvironmentInitializer, itNoLite, setLocalStorage, TestUtils } from '../../utils/test_utils'\nimport { AuthenticationProvider, BasicAuthenticationProvider, NoAuthenticationProvider } from '../../../icc-x-api'\nimport { IccAuthApi, IccUserApi } from '../../../icc-api'\nimport 'isomorphic-fetch'\nimport { AuthSecretDetails, AuthSecretType, SmartAuthProvider } from '../../../icc-x-api/auth/SmartAuthProvider'\nimport { expect } from 'chai'\nimport { randomUUID } from 'crypto'\nimport initMasterApi = TestUtils.initMasterApi\nimport { fail } from 'assert'\nimport { TOTP } from 'otpauth'\nsetLocalStorage(fetch)\n\nlet env: TestVars\nlet authApi: IccAuthApi\n\ndescribe('Smart authentication provider', () => {\n before(async function () {\n this.timeout(600000)\n const initializer = await getEnvironmentInitializer()\n env = await initializer.execute(getEnvVariables())\n authApi = new IccAuthApi(env.iCureUrl, {}, new NoAuthenticationProvider(), fetch)\n })\n\n function userApiWithProvider(authProvider: AuthenticationProvider): IccUserApi {\n return new IccUserApi(env.iCureUrl, {}, authProvider, fetch)\n }\n\n it('Should automatically ask for secret to get a new token, and reasks the secret if it is not valid', async () => {\n const { credentials } = await createNewHcpApi(env)\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(authApi, credentials.user, {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n expect(acceptedSecrets).to.include(AuthSecretType.PASSWORD)\n expect(acceptedSecrets).to.include(AuthSecretType.LONG_LIVED_TOKEN)\n expect(acceptedSecrets).to.include(AuthSecretType.SHORT_LIVED_TOKEN)\n expect(acceptedSecrets).to.not.include(AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n if (calls == 0) {\n expect(previousAttempts).to.be.empty\n } else if (calls == 1) {\n expect(previousAttempts).to.have.length(1)\n expect(previousAttempts[0].value).to.equal('wrong')\n expect(previousAttempts[0].secretType).to.equal(AuthSecretType.LONG_LIVED_TOKEN)\n } else fail(`Unexpected number of calls: ${calls}`)\n return calls++ == 0\n ? { value: 'wrong', secretType: AuthSecretType.LONG_LIVED_TOKEN } // pragma: allowlist secret\n : { value: credentials.password, secretType: AuthSecretType.LONG_LIVED_TOKEN }\n },\n })\n const userApi = userApiWithProvider(authProvider)\n const user = await userApi.getCurrentUser()\n expect(user.healthcarePartyId).to.equal(credentials.dataOwnerId)\n expect(calls).to.equal(2)\n })\n\n itNoLite(\n 'Should automatically ask for a more powerful secret to perform elevated-security operations if the available secret/token is not good enough',\n async () => {\n const { credentials, api } = await createNewHcpApi(env)\n const initialUser = await api.userApi.getCurrentUser()\n const masterApi = await initMasterApi(env)\n const userToken = randomUUID()\n const userPw = randomUUID()\n const userWithLongTokenAndPw = await masterApi.userApi.modifyUser({\n ...initialUser,\n passwordHash: userPw,\n authenticationTokens: {\n 'test-long-lived-token': {\n token: userToken,\n creationTime: Date.now(),\n validity: 60 * 60 * 24 * 7,\n },\n },\n })\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(authApi, credentials.user, {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n if (calls == 0) {\n expect(acceptedSecrets).to.include(AuthSecretType.PASSWORD)\n expect(acceptedSecrets).to.include(AuthSecretType.LONG_LIVED_TOKEN)\n expect(acceptedSecrets).to.include(AuthSecretType.SHORT_LIVED_TOKEN)\n expect(acceptedSecrets).to.not.include(AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n expect(previousAttempts).to.be.empty\n calls++\n return { value: userToken, secretType: AuthSecretType.LONG_LIVED_TOKEN }\n } else if (calls == 1) {\n expect(acceptedSecrets).to.include(AuthSecretType.PASSWORD)\n expect(acceptedSecrets).to.not.include(AuthSecretType.LONG_LIVED_TOKEN)\n expect(acceptedSecrets).to.include(AuthSecretType.SHORT_LIVED_TOKEN)\n expect(acceptedSecrets).to.not.include(AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n expect(previousAttempts).to.be.empty\n calls++\n return { value: userPw, secretType: AuthSecretType.PASSWORD }\n } else throw new Error(`Unexpected number of calls: ${calls}`)\n },\n })\n const userApi = userApiWithProvider(authProvider)\n expect((await userApi.getCurrentUser()).rev).to.equal(userWithLongTokenAndPw.rev)\n expect(calls).to.equal(1)\n const newPw = randomUUID()\n const userWithNewPw = await userApi.modifyUser({ ...userWithLongTokenAndPw, passwordHash: newPw })\n expect(userWithNewPw.rev).to.not.equal(userWithLongTokenAndPw.rev)\n expect(calls).to.equal(2)\n const retrievedWithNewPw = await userApiWithProvider(new BasicAuthenticationProvider(credentials.user, newPw)).getCurrentUser()\n expect(retrievedWithNewPw.rev).to.equal(userWithNewPw.rev)\n const couldRetrieveWithOldPw = await userApiWithProvider(new BasicAuthenticationProvider(credentials.user, userPw))\n .getCurrentUser()\n .then(\n () => true,\n () => false\n )\n expect(couldRetrieveWithOldPw).to.be.false\n }\n )\n\n itNoLite('Should automatically ask for TOTP after password if user has 2fa enabled', async () => {\n const { credentials, api } = await createNewHcpApi(env)\n const initialUser = await api.userApi.getCurrentUser()\n const masterApi = await initMasterApi(env)\n const totpSecret = 'AAPX7PW2RJIGZ3D4' // pragma: allowlist secret (fake secret generated only for test)\n const totp = new TOTP({\n algorithm: 'SHA1',\n digits: 6,\n period: 30,\n secret: totpSecret,\n })\n const userPw = randomUUID()\n await masterApi.userApi.enable2fa(initialUser.id!, totpSecret)\n const userWithPwAnd2fa = await masterApi.userApi.modifyUser({\n ...initialUser,\n passwordHash: userPw,\n })\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(authApi, credentials.user, {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n if (calls == 0) {\n expect(acceptedSecrets).to.include(AuthSecretType.PASSWORD)\n expect(acceptedSecrets).to.include(AuthSecretType.LONG_LIVED_TOKEN)\n expect(acceptedSecrets).to.include(AuthSecretType.SHORT_LIVED_TOKEN)\n expect(acceptedSecrets).to.not.include(AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN)\n expect(previousAttempts).to.be.empty\n calls++\n return { value: userPw, secretType: AuthSecretType.PASSWORD }\n } else if (calls == 1 || calls == 2) {\n expect(acceptedSecrets).to.have.members([AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN])\n if (calls == 1) expect(previousAttempts).to.be.empty\n if (calls == 2) expect(previousAttempts).to.have.length(1)\n return calls++ == 1\n ? { value: totp.generate() + '13', secretType: AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN }\n : { value: totp.generate(), secretType: AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN }\n } else throw new Error(`Unexpected number of calls: ${calls}`)\n },\n })\n const userApi = userApiWithProvider(authProvider)\n expect((await userApi.getCurrentUser()).rev).to.equal(userWithPwAnd2fa.rev)\n expect(calls).to.equal(3)\n })\n\n itNoLite('Should ask for TOTP directly if password is cached', async () => {\n const { credentials, api } = await createNewHcpApi(env)\n const initialUser = await api.userApi.getCurrentUser()\n const masterApi = await initMasterApi(env)\n const totpSecret = 'AAPX7PW2RJIGZ3D4' // pragma: allowlist secret (fake secret generated only for test)\n const totp = new TOTP({\n algorithm: 'SHA1',\n digits: 6,\n period: 30,\n secret: totpSecret,\n })\n const userPw = randomUUID()\n await masterApi.userApi.enable2fa(initialUser.id!, totpSecret)\n const userWithPwAnd2fa = await masterApi.userApi.modifyUser({\n ...initialUser,\n passwordHash: userPw,\n })\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(\n authApi,\n credentials.user,\n {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n expect(acceptedSecrets).to.have.members([AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN])\n expect(previousAttempts).to.be.empty\n expect(calls++).to.equal(0)\n return { value: totp.generate(), secretType: AuthSecretType.TWO_FACTOR_AUTHENTICATION_TOKEN }\n },\n },\n {\n initialSecret: { password: userPw },\n }\n )\n const userApi = userApiWithProvider(authProvider)\n expect((await userApi.getCurrentUser()).rev).to.equal(userWithPwAnd2fa.rev)\n expect(calls).to.equal(1)\n })\n\n itNoLite('Switched provider should keep cached secrets and should be able to have elevated security context', async () => {\n const details = await createUserInMultipleGroups(env)\n let calls = 0\n const authProvider = SmartAuthProvider.initialise(authApi, details.userLogin, {\n getSecret: async (acceptedSecrets: AuthSecretType[], previousAttempts: AuthSecretDetails[]) => {\n expect(acceptedSecrets).to.have.include(AuthSecretType.PASSWORD)\n expect(previousAttempts).to.be.empty\n expect(calls++).to.equal(0)\n return { value: details.userPw12, secretType: AuthSecretType.PASSWORD }\n },\n })\n const defaultGroupUserApi = userApiWithProvider(authProvider)\n const defaultGroupUser = await defaultGroupUserApi.getCurrentUser()\n const otherGroupId = details.group1.id == defaultGroupUser.groupId ? details.group2.id : details.group1.id\n const matches = await defaultGroupUserApi.getMatchingUsers()\n const switchedUserApi = userApiWithProvider(await authProvider.switchGroup(otherGroupId!, matches))\n const switchedUser = await switchedUserApi.getCurrentUser()\n expect(switchedUser.id).to.not.equal(defaultGroupUser.id)\n expect(switchedUser.groupId).to.equal(otherGroupId)\n const updatedDefault = await switchedUserApi.modifyUser({\n ...switchedUser,\n authenticationTokens: {\n 'new-token': {\n token: randomUUID(),\n creationTime: Date.now(),\n validity: 60 * 60 * 24 * 7,\n },\n },\n })\n expect(updatedDefault.rev).to.not.equal(switchedUser.rev)\n expect(Object.keys(updatedDefault.authenticationTokens ?? {})).to.not.be.empty\n })\n})\n"]}
|