@icure/api 8.0.23 → 8.0.24

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.
@@ -12,6 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.JwtAuthService = void 0;
13
13
  const XHR_1 = require("../../icc-api/api/XHR");
14
14
  const JwtUtils_1 = require("./JwtUtils");
15
+ const JwtError_1 = require("./JwtError");
15
16
  /**
16
17
  * Differs from JwtBridgedAuthService in that it cannot create new refresh tokens
17
18
  */
@@ -33,6 +34,14 @@ class JwtAuthService {
33
34
  getAuthHeaders() {
34
35
  return __awaiter(this, void 0, void 0, function* () {
35
36
  return this._currentPromise
37
+ .then((x) => ({ authJwt: x === null || x === void 0 ? void 0 : x.authJwt, refreshJwt: x === null || x === void 0 ? void 0 : x.refreshJwt }), (e) => {
38
+ if (e instanceof JwtError_1.JwtError && !!e.jwt && !!e.refreshJwt) {
39
+ return { authJwt: e.jwt, refreshJwt: e.refreshJwt };
40
+ }
41
+ else {
42
+ throw new Error('There was an error while refreshing the token, please re-instantiate the API.');
43
+ }
44
+ })
36
45
  .then((x) => {
37
46
  const authJwt = x === null || x === void 0 ? void 0 : x.authJwt;
38
47
  const refreshJwt = x === null || x === void 0 ? void 0 : x.refreshJwt;
@@ -46,6 +55,8 @@ class JwtAuthService {
46
55
  throw new Error('Your iCure back-end version does not support JWT authentication');
47
56
  }
48
57
  return updatedTokens;
58
+ }, (e) => {
59
+ throw new JwtError_1.JwtError(authJwt, refreshJwt, 'There was an error while refreshing the token, please re-instantiate the API or try again.', e);
49
60
  });
50
61
  }
51
62
  else if (!!this._error) {
@@ -1 +1 @@
1
- {"version":3,"file":"JwtAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAM3C,yCAAkD;AAElD;;GAEG;AACH,MAAa,cAAc;IAIzB,YAA6B,OAAmB,EAAE,UAAoD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,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAA;yBACnF;wBAED,OAAO,aAAa,CAAA;oBACtB,CAAC,CAAC,CAAA;iBACH;qBAAM,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE;oBACxB,MAAM,IAAI,CAAC,MAAM,CAAA;iBAClB;gBACD,OAAO,IAAI,CAAC,eAAe,CAAA;YAC7B,CAAC,CAAC;iBACD,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;gBACV,OAAO,CAAA,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,OAAO,EAAC,CAAC,CAAC,CAAC,IAAI,SAAG,CAAC,MAAM,CAAC,eAAe,EAAE,UAAU,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,6BAA6B,CAAC,CAAA;YAC9H,CAAC,CAAC,CAAA;QACN,CAAC;KAAA;IAEa,eAAe,CAAC,UAAkB;;YAC9C,gEAAgE;YAChE,yBAAyB;YACzB,IAAI,IAAA,gCAAqB,EAAC,UAAU,CAAC,EAAE;gBACrC,MAAM,KAAK,CAAC,uDAAuD,CAAC,CAAA;aACrE;iBAAM;gBACL,OAAO,IAAI,CAAC,OAAO,CAAC,wBAAwB,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC;oBAClF,OAAO,EAAE,eAAe,CAAC,KAAM;oBAC/B,UAAU,EAAE,UAAU;iBACvB,CAAC,CAAC,CAAA;aACJ;QACH,CAAC;KAAA;IAED,gBAAgB,CAAC,KAAY;QAC3B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,cAAc;QACZ,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AAnED,wCAmEC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi } from '../../icc-api'\nimport Header = XHR.Header\nimport { a2b } from '../utils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\nimport XHRError = XHR.XHRError\nimport { isJwtInvalidOrExpired } from './JwtUtils'\n\n/**\n * Differs from JwtBridgedAuthService in that it cannot create new refresh tokens\n */\nexport class JwtAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt: string; refreshJwt: string } | undefined> = Promise.resolve(undefined as any)\n\n constructor(private readonly authApi: IccAuthApi, initialJwt?: { authJwt: string; refreshJwt: string }) {\n if (!!initialJwt) {\n this._currentPromise = Promise.resolve(initialJwt)\n }\n }\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x?.refreshJwt as any)\n }\n\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this._currentPromise.then((x) => (x ? { token: x.authJwt, refreshToken: x.refreshJwt } : undefined))\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this._currentPromise\n .then((x) => {\n const authJwt = x?.authJwt\n const refreshJwt = x?.refreshJwt\n\n if ((!authJwt || isJwtInvalidOrExpired(authJwt)) && refreshJwt) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n })\n } else if (!!this._error) {\n throw this._error\n }\n return this._currentPromise\n })\n .then((x) => {\n return x?.authJwt ? [new XHR.Header('Authorization', `Bearer ${x.authJwt}`)] : Promise.reject('Cannot provide auth: No JWT')\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string): Promise<{ authJwt: string; refreshJwt: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (isJwtInvalidOrExpired(refreshJwt)) {\n throw Error('Missing or expired refresh token: please log in again')\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token!,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]}
1
+ {"version":3,"file":"JwtAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAG3C,yCAAkD;AAClD,yCAAqC;AAErC;;GAEG;AACH,MAAa,cAAc;IAIzB,YAA6B,OAAmB,EAAE,UAAoD;QAAzE,YAAO,GAAP,OAAO,CAAY;QAHxC,WAAM,GAAiB,IAAI,CAAA;QAC3B,oBAAe,GAAiE,OAAO,CAAC,OAAO,CAAC,SAAgB,CAAC,CAAA;QAGvH,IAAI,CAAC,CAAC,UAAU,EAAE;YAChB,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;SACnD;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,UAAiB,CAAC,CAAA;IAC/D,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,OAAO,EAAE,YAAY,EAAE,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAA;IAC7G,CAAC;IAEK,cAAc;;YAClB,OAAO,IAAI,CAAC,eAAe;iBACxB,IAAI,CACH,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,OAAO,EAAE,UAAU,EAAE,CAAC,aAAD,CAAC,uB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AAC,eAAe,CAAA;YAC7B,CAAC,CAAC;iBACD,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;gBACV,OAAO,CAAA,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,OAAO,EAAC,CAAC,CAAC,CAAC,IAAI,SAAG,CAAC,MAAM,CAAC,eAAe,EAAE,UAAU,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,6BAA6B,CAAC,CAAA;YAC9H,CAAC,CAAC,CAAA;QACN,CAAC;KAAA;IAEa,eAAe,CAAC,UAAkB;;YAC9C,gEAAgE;YAChE,yBAAyB;YACzB,IAAI,IAAA,gCAAqB,EAAC,UAAU,CAAC,EAAE;gBACrC,MAAM,KAAK,CAAC,uDAAuD,CAAC,CAAA;aACrE;iBAAM;gBACL,OAAO,IAAI,CAAC,OAAO,CAAC,wBAAwB,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC;oBAClF,OAAO,EAAE,eAAe,CAAC,KAAM;oBAC/B,UAAU,EAAE,UAAU;iBACvB,CAAC,CAAC,CAAA;aACJ;QACH,CAAC;KAAA;IAED,gBAAgB,CAAC,KAAY;QAC3B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,cAAc;QACZ,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AAlFD,wCAkFC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi } from '../../icc-api'\nimport Header = XHR.Header\nimport { isJwtInvalidOrExpired } from './JwtUtils'\nimport { JwtError } from './JwtError'\n\n/**\n * Differs from JwtBridgedAuthService in that it cannot create new refresh tokens\n */\nexport class JwtAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt: string; refreshJwt: string } | undefined> = Promise.resolve(undefined as any)\n\n constructor(private readonly authApi: IccAuthApi, initialJwt?: { authJwt: string; refreshJwt: string }) {\n if (!!initialJwt) {\n this._currentPromise = Promise.resolve(initialJwt)\n }\n }\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x?.refreshJwt as any)\n }\n\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this._currentPromise.then((x) => (x ? { token: x.authJwt, refreshToken: x.refreshJwt } : undefined))\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this._currentPromise\n .then(\n (x) => ({ authJwt: x?.authJwt, refreshJwt: x?.refreshJwt }),\n (e: Error) => {\n if (e instanceof JwtError && !!e.jwt && !!e.refreshJwt) {\n return { authJwt: e.jwt, refreshJwt: e.refreshJwt }\n } else {\n throw new Error('There was an error while refreshing the token, please re-instantiate the API.')\n }\n }\n )\n .then((x) => {\n const authJwt = x?.authJwt\n const refreshJwt = x?.refreshJwt\n\n if ((!authJwt || isJwtInvalidOrExpired(authJwt)) && refreshJwt) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then(\n (updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n },\n (e: Error) => {\n throw new JwtError(authJwt, refreshJwt, 'There was an error while refreshing the token, please re-instantiate the API or try again.', e)\n }\n )\n } else if (!!this._error) {\n throw this._error\n }\n return this._currentPromise\n })\n .then((x) => {\n return x?.authJwt ? [new XHR.Header('Authorization', `Bearer ${x.authJwt}`)] : Promise.reject('Cannot provide auth: No JWT')\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string): Promise<{ authJwt: string; refreshJwt: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (isJwtInvalidOrExpired(refreshJwt)) {\n throw Error('Missing or expired refresh token: please log in again')\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token!,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]}
@@ -14,6 +14,7 @@ const XHR_1 = require("../../icc-api/api/XHR");
14
14
  const LoginCredentials_1 = require("../../icc-api/model/LoginCredentials");
15
15
  const utils_1 = require("../utils");
16
16
  var XHRError = XHR_1.XHR.XHRError;
17
+ const JwtError_1 = require("./JwtError");
17
18
  /**
18
19
  * Differs from JwtAuthService in that it can create new refresh tokens if the old one is expired
19
20
  */
@@ -36,6 +37,20 @@ class JwtBridgedAuthService {
36
37
  getJWT() {
37
38
  return __awaiter(this, void 0, void 0, function* () {
38
39
  return this._currentPromise
40
+ .then(({ authJwt, refreshJwt }) => ({ authJwt, refreshJwt }), (e) => {
41
+ if (e instanceof JwtError_1.JwtError) {
42
+ const wrappedError = e.reason;
43
+ if (!!wrappedError.statusCode && wrappedError.statusCode >= 400 && wrappedError.statusCode < 500) {
44
+ return { authJwt: undefined, refreshJwt: undefined };
45
+ }
46
+ else {
47
+ return { authJwt: e.jwt, refreshJwt: e.refreshJwt };
48
+ }
49
+ }
50
+ else {
51
+ return { authJwt: undefined, refreshJwt: undefined };
52
+ }
53
+ })
39
54
  .then(({ authJwt, refreshJwt }) => {
40
55
  if (!authJwt || this._isJwtInvalidOrExpired(authJwt)) {
41
56
  // If it does not have the JWT, tries to get it
@@ -47,6 +62,8 @@ class JwtBridgedAuthService {
47
62
  throw new Error('Your iCure back-end version does not support JWT authentication');
48
63
  }
49
64
  return updatedTokens;
65
+ }, (e) => {
66
+ throw new JwtError_1.JwtError(authJwt, refreshJwt, 'There was an error while refreshing the token, please re-instantiate the API or try again.', e);
50
67
  });
51
68
  }
52
69
  else if (!!this._error) {
@@ -1 +1 @@
1
- {"version":3,"file":"JwtBridgedAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtBridgedA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AAC,CAAA;aAC5E;YAED,OAAO;gBACL,OAAO,EAAE,YAAY,CAAC,KAAK;gBAC3B,UAAU,EAAE,YAAY,CAAC,YAAY;aACtC,CAAA;QACH,CAAC;KAAA;IAEO,sBAAsB,CAAC,GAAW;QACxC,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QAC5B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,OAAO,IAAI,CAAA;SACZ;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;QAC5C,mGAAmG;QACnG,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,CAAA;IACpF,CAAC;IAEO,aAAa,CAAC,aAAqB;QACzC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAA,WAAG,EAAC,aAAa,CAAC,CAAC,CAAA;IACvC,CAAC;IAED,gBAAgB,CAAC,KAAY;QAC3B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,cAAc;QACZ,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AAlID,sDAkIC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { LoginCredentials } from '../../icc-api/model/LoginCredentials'\nimport Header = XHR.Header\nimport { a2b } from '../utils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\nimport XHRError = XHR.XHRError\n\n/**\n * Differs from JwtAuthService in that it can create new refresh tokens if the old one is expired\n */\nexport class JwtBridgedAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt?: string; refreshJwt?: string }> = Promise.resolve({})\n\n constructor(\n private authApi: IccAuthApi,\n private username: string | undefined,\n private password: string | undefined,\n private thirdPartyTokens: { [thirdParty: string]: string } = {},\n initialJwt: { authJwt: string; refreshJwt: string } | undefined\n ) {\n this._currentPromise = Promise.resolve(initialJwt ?? {})\n }\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x.refreshJwt as any)\n }\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this.getAuthHeaders().then(() => this._currentPromise.then(({ authJwt, refreshJwt }) => ({ token: authJwt!, refreshToken: refreshJwt! })))\n }\n\n async getJWT(): Promise<string | undefined> {\n return this._currentPromise\n .then(({ authJwt, refreshJwt }) => {\n if (!authJwt || this._isJwtInvalidOrExpired(authJwt)) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n })\n } else if (!!this._error) {\n throw this._error\n }\n return this._currentPromise\n })\n .then(({ authJwt }) => {\n return authJwt\n })\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this.getJWT().then((authJwt) => {\n return [new XHR.Header('Authorization', `Bearer ${authJwt}`)]\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string | undefined): Promise<{ authJwt?: string; refreshJwt?: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (!refreshJwt || this._isJwtInvalidOrExpired(refreshJwt)) {\n return this._loginAndGetTokens()\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n private async _loginAndGetTokens(): Promise<{ authJwt?: string; refreshJwt?: string }> {\n let authResponse: AuthenticationResponse | undefined\n let firstError: XHRError | undefined\n if (this.username && this.password) {\n try {\n authResponse = await this.authApi.login(\n new LoginCredentials({\n username: this.username,\n password: this.password,\n })\n )\n } catch (e) {\n firstError = e as XHRError\n }\n }\n if (!authResponse) {\n authResponse = await (Object.entries(this.thirdPartyTokens) as [OAuthThirdParty, string][]).reduce(async (acc, [thirdParty, token]) => {\n const prev = await acc\n return (\n prev ??\n (token\n ? this.authApi.loginWithThirdPartyToken(thirdParty, token).catch((e) => {\n if (!firstError) {\n firstError = e as XHRError\n }\n return Promise.resolve() as Promise<undefined>\n })\n : undefined)\n )\n }, Promise.resolve() as Promise<AuthenticationResponse | undefined>)\n }\n\n if (!authResponse) {\n if (firstError) throw firstError\n throw new XHRError('', 'Unknown error', 401, 'Unauthorized', new Headers())\n }\n\n return {\n authJwt: authResponse.token,\n refreshJwt: authResponse.refreshToken,\n }\n }\n\n private _isJwtInvalidOrExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return true\n }\n const payload = this._base64Decode(parts[1])\n // Using the 'exp' string is safe to use as it is part of the JWT RFC and cannot be modified by us.\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime() - 10000\n }\n\n private _base64Decode(encodedString: string): any {\n return JSON.parse(a2b(encodedString))\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]}
1
+ {"version":3,"file":"JwtBridgedAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtBridgedAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAE3C,2EAAuE;AAEvE,oCAA8B;AAE9B,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAC9B,yCAAqC;AAErC;;GAEG;AACH,MAAa,qBAAqB;IAIhC,YACU,OAAmB,EACnB,QAA4B,EAC5B,QAA4B,EAC5B,mBAAqD,EAAE,EAC/D,UAA+D;QAJvD,YAAO,GAAP,OAAO,CAAY;QACnB,aAAQ,GAAR,QAAQ,CAAoB;Q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IAED,cAAc;QACZ,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AAtJD,sDAsJC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { LoginCredentials } from '../../icc-api/model/LoginCredentials'\nimport Header = XHR.Header\nimport { a2b } from '../utils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\nimport XHRError = XHR.XHRError\nimport { JwtError } from './JwtError'\n\n/**\n * Differs from JwtAuthService in that it can create new refresh tokens if the old one is expired\n */\nexport class JwtBridgedAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt?: string; refreshJwt?: string }> = Promise.resolve({})\n\n constructor(\n private authApi: IccAuthApi,\n private username: string | undefined,\n private password: string | undefined,\n private thirdPartyTokens: { [thirdParty: string]: string } = {},\n initialJwt: { authJwt: string; refreshJwt: string } | undefined\n ) {\n this._currentPromise = Promise.resolve(initialJwt ?? {})\n }\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x.refreshJwt as any)\n }\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this.getAuthHeaders().then(() => this._currentPromise.then(({ authJwt, refreshJwt }) => ({ token: authJwt!, refreshToken: refreshJwt! })))\n }\n\n async getJWT(): Promise<string | undefined> {\n return this._currentPromise\n .then(\n ({ authJwt, refreshJwt }) => ({ authJwt, refreshJwt }),\n (e: Error) => {\n if (e instanceof JwtError) {\n const wrappedError = e.reason as any\n if (!!wrappedError.statusCode && wrappedError.statusCode >= 400 && wrappedError.statusCode < 500) {\n return { authJwt: undefined, refreshJwt: undefined }\n } else {\n return { authJwt: e.jwt, refreshJwt: e.refreshJwt }\n }\n } else {\n return { authJwt: undefined, refreshJwt: undefined }\n }\n }\n )\n .then(({ authJwt, refreshJwt }) => {\n if (!authJwt || this._isJwtInvalidOrExpired(authJwt)) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then(\n (updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n },\n (e: Error) => {\n throw new JwtError(authJwt, refreshJwt, 'There was an error while refreshing the token, please re-instantiate the API or try again.', e)\n }\n )\n } else if (!!this._error) {\n throw this._error\n }\n return this._currentPromise\n })\n .then(({ authJwt }) => {\n return authJwt\n })\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this.getJWT().then((authJwt) => {\n return [new XHR.Header('Authorization', `Bearer ${authJwt}`)]\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string | undefined): Promise<{ authJwt?: string; refreshJwt?: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (!refreshJwt || this._isJwtInvalidOrExpired(refreshJwt)) {\n return this._loginAndGetTokens()\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n private async _loginAndGetTokens(): Promise<{ authJwt?: string; refreshJwt?: string }> {\n let authResponse: AuthenticationResponse | undefined\n let firstError: XHRError | undefined\n if (this.username && this.password) {\n try {\n authResponse = await this.authApi.login(\n new LoginCredentials({\n username: this.username,\n password: this.password,\n })\n )\n } catch (e) {\n firstError = e as XHRError\n }\n }\n if (!authResponse) {\n authResponse = await (Object.entries(this.thirdPartyTokens) as [OAuthThirdParty, string][]).reduce(async (acc, [thirdParty, token]) => {\n const prev = await acc\n return (\n prev ??\n (token\n ? this.authApi.loginWithThirdPartyToken(thirdParty, token).catch((e) => {\n if (!firstError) {\n firstError = e as XHRError\n }\n return Promise.resolve() as Promise<undefined>\n })\n : undefined)\n )\n }, Promise.resolve() as Promise<AuthenticationResponse | undefined>)\n }\n\n if (!authResponse) {\n if (firstError) throw firstError\n throw new XHRError('', 'Unknown error', 401, 'Unauthorized', new Headers())\n }\n\n return {\n authJwt: authResponse.token,\n refreshJwt: authResponse.refreshToken,\n }\n }\n\n private _isJwtInvalidOrExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return true\n }\n const payload = this._base64Decode(parts[1])\n // Using the 'exp' string is safe to use as it is part of the JWT RFC and cannot be modified by us.\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime() - 10000\n }\n\n private _base64Decode(encodedString: string): any {\n return JSON.parse(a2b(encodedString))\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ export declare class JwtError extends Error {
2
+ readonly jwt: string | undefined;
3
+ readonly refreshJwt: string | undefined;
4
+ readonly message: string;
5
+ readonly reason: Error;
6
+ constructor(jwt: string | undefined, refreshJwt: string | undefined, message: string, reason: Error);
7
+ }
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JwtError = void 0;
4
+ class JwtError extends Error {
5
+ constructor(jwt, refreshJwt, message, reason) {
6
+ super(message);
7
+ this.jwt = jwt;
8
+ this.refreshJwt = refreshJwt;
9
+ this.message = message;
10
+ this.reason = reason;
11
+ }
12
+ }
13
+ exports.JwtError = JwtError;
14
+ //# sourceMappingURL=JwtError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"JwtError.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtError.ts"],"names":[],"mappings":";;;AAAA,MAAa,QAAS,SAAQ,KAAK;IACjC,YAAqB,GAAuB,EAAW,UAA8B,EAAW,OAAe,EAAW,MAAa;QACrI,KAAK,CAAC,OAAO,CAAC,CAAA;QADK,QAAG,GAAH,GAAG,CAAoB;QAAW,eAAU,GAAV,UAAU,CAAoB;QAAW,YAAO,GAAP,OAAO,CAAQ;QAAW,WAAM,GAAN,MAAM,CAAO;IAEvI,CAAC;CACF;AAJD,4BAIC","sourcesContent":["export class JwtError extends Error {\n constructor(readonly jwt: string | undefined, readonly refreshJwt: string | undefined, readonly message: string, readonly reason: Error) {\n super(message)\n }\n}\n"]}
@@ -79,7 +79,12 @@ class TransferKeysManager {
79
79
  // Result only includes the acyclic label, not the full group
80
80
  transferKeysCandidatesFp(keyToFp, graph) {
81
81
  return Object.entries((0, graph_utils_1.reachSetsAcyclic)(graph.acyclicGraph))
82
- .filter(([from, reachable]) => from != keyToFp && !reachable.has(keyToFp))
82
+ .filter(([from, reachable]) => {
83
+ var _a;
84
+ const currGroup = (_a = graph.acyclicLabelToGroup[from]) !== null && _a !== void 0 ? _a : [from];
85
+ const reachableOriginal = new Set(Array.from(reachable).flatMap((x) => { var _a; return (_a = graph.acyclicLabelToGroup[x]) !== null && _a !== void 0 ? _a : [x]; }));
86
+ return !currGroup.includes(keyToFp) && !reachableOriginal.has(keyToFp);
87
+ })
83
88
  .map((x) => x[0]);
84
89
  }
85
90
  transferTargetKeys(keyManager, graph) {
@@ -1 +1 @@
1
- {"version":3,"file":"TransferKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/TransferKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,+BAA2C;AAE3C,oCAAiC;AAEjC,sDAA+E;AAC/E,mCAAgJ;AAOhJ;;;GAGG;AACH,MAAa,mBAAmB;IAC9B,YACmB,UAA4B,EAC5B,uBAAgD,EAChD,YAA8B,EAC9B,qBAAgD,EAChD,wBAAkD,EAClD,YAAgC;QALhC,eAAU,GAAV,UAAU,CAAkB;QAC5B,4BAAuB,GAAvB,uBAAuB,CAAyB;QAChD,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,0BAAqB,GAArB,qBAAqB,CAA2B;QAChD,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,iBAAY,GAAZ,YAAY,CAAoB;IAChD,CAAC;IAEJ;;;;;;OAMG;IACG,kBA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,KAAK,CAAC,YAAY,CAAC,CAAA;gBACtD,MAAM,mBAAmB,GAAG,uBAAuB,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CACvE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,qBAAqB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CACrG,CAAA;gBACD,IAAI,mBAAmB,CAAC,MAAM,IAAI,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAA;gBACxH,kJAAkJ;gBAClJ,OAAO;gBACP,MAAM,2BAA2B,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE;oBACxE,MAAM,GAAG,GAAG,KAAK,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAA;oBAC9G,IAAI,CAAC,GAAG;wBAAE,MAAM,IAAI,KAAK,CAAC,kFAAkF,CAAC,CAAA;oBAC7G,OAAO,GAAG,CAAA;gBACZ,CAAC,CAAC,CAAA;gBACF,GAAG,CAAC,IAAI,CAAC;oBACP,OAAO,EAAE,2BAA2B;oBACpC,MAAM,EAAE,SAAS;oBACjB,QAAQ,EAAE,WAAW;iBACtB,CAAC,CAAA;aACH;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;CACF;AA5ID,kDA4IC","sourcesContent":["import { KeyPair, ShaVersion } from './RSA'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ua2hex } from '../utils'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { reachSetsAcyclic, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { fingerprintToPublicKeysMapOf, fingerprintV1, loadPublicKeys, transferKeysFpGraphOf, fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeDataManager } from './BaseExchangeDataManager'\nimport { UserSignatureKeysManager } from './UserSignatureKeysManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is intended only for internal use and may be changed without notice.\n * Allows to create new transfer keys.\n */\nexport class TransferKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly baseExchangeDataManager: BaseExchangeDataManager,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly userSignatureKeysManager: UserSignatureKeysManager,\n private readonly icureStorage: IcureStorageFacade\n ) {}\n\n /**\n * Analyses the transfer keys graph and creates new transfer keys which allow to improve data accessibility from other devices.\n * For security reasons transfer keys will only be created between keys verified by the user, but this will be done ignoring any existing edges from\n * unverified keys to verified keys.\n * @param self the current data owner.\n * @return the updated data owner.\n */\n async updateTransferKeys(self: CryptoActorStubWithType): Promise<void> {\n const newEdgesByTarget = await this.getNewVerifiedTransferKeysEdges(self)\n if (!newEdgesByTarget.length) return\n const selfId = self.stub.id!\n const fpToPublicKey = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha1)\n const fpToPublicKeyWithSha256 = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha256)\n const signatureKeyPair = await this.userSignatureKeysManager.getOrCreateSignatureKeyPair()\n const verifiedFps = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n const allVerifiedSourcesAndTarget = Array.from(\n new Set(\n newEdgesByTarget.flatMap((x) =>\n // Sources are guaranteed to be verified, but target may not be\n verifiedFps.has(x.targetFp) ? [x.targetFp, ...x.sources] : x.sources\n )\n )\n )\n const newExchangeKeyPublicKeys = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKey[fp]).filter((key) => !!key)\n const newExchangeKeyPublicKeysWithSha256 = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKeyWithSha256[fp]).filter((key) => !!key)\n const createdExchangeData = await this.baseExchangeDataManager.createExchangeData(\n selfId,\n { [signatureKeyPair.fingerprint]: signatureKeyPair.keyPair.privateKey },\n {\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeys, ShaVersion.Sha1)),\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeysWithSha256, ShaVersion.Sha256)),\n }\n )\n let updatedTransferKeys = self.stub.transferKeys ?? {}\n for (const newEdges of newEdgesByTarget) {\n const encryptedTransferKey = await this.encryptTransferKey(newEdges.target, createdExchangeData.exchangeKey)\n updatedTransferKeys = newEdges.sources.reduce((acc, candidateFp) => {\n const existingKeys = { ...(acc[candidateFp] ?? {}) }\n existingKeys[newEdges.targetFp] = encryptedTransferKey\n acc[candidateFp] = existingKeys\n return acc\n }, updatedTransferKeys)\n }\n await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...self.stub,\n transferKeys: updatedTransferKeys,\n },\n type: self.type,\n })\n }\n\n // encrypts a transfer key in pkcs8 format using an exchange key, returns the hex representation\n private async encryptTransferKey(transferKey: KeyPair<CryptoKey>, exchangeKey: CryptoKey): Promise<string> {\n const exportedKey = await this.primitives.RSA.exportKey(transferKey.privateKey, 'pkcs8')\n return ua2hex(await this.primitives.AES.encrypt(exchangeKey, exportedKey))\n }\n\n // all public keys would go to the stored keys -> no need for specifying the key.\n // Result only includes the acyclic label, not the full group\n private transferKeysCandidatesFp(keyToFp: string, graph: StronglyConnectedGraph): string[] {\n return Object.entries(reachSetsAcyclic(graph.acyclicGraph))\n .filter(([from, reachable]) => from != keyToFp && !reachable.has(keyToFp))\n .map((x) => x[0])\n }\n\n private async transferTargetKeys(\n keyManager: UserEncryptionKeysManager,\n graph: StronglyConnectedGraph\n ): Promise<{ fingerprint: string; pair: KeyPair<CryptoKey> }[]> {\n const availableGroups = new Set(Object.keys(keyManager.getDecryptionKeys()).map((x) => graph.originalLabelToAcyclicLabel[x] ?? x))\n const groupsReachableFromAvailable = new Set(\n Object.entries(graph.acyclicGraph).flatMap(([source, reachables]) => (availableGroups.has(source) ? Array.from(reachables) : []))\n )\n const targetCandidates = Array.from(availableGroups).filter((x) => !groupsReachableFromAvailable.has(x))\n const verifiedFps = new Set(keyManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n return targetCandidates.map((candidateFp) => {\n const candidateGroup = graph.acyclicLabelToGroup[candidateFp] ?? [candidateFp] // May not be part of transfer keys graph yet\n const bestCandidateOfGroup = candidateGroup.find((x) => verifiedFps.has(x)) ?? candidateFp\n return { fingerprint: bestCandidateOfGroup, pair: keyManager.getKeyPairForFingerprint(bestCandidateOfGroup)!.pair }\n })\n }\n\n // Decides the best edges considering the verified public keys.\n private async getNewVerifiedTransferKeysEdges(self: CryptoActorStubWithType): Promise<\n {\n sources: string[]\n target: KeyPair<CryptoKey>\n targetFp: string\n }[]\n > {\n const verifiedKeysFpSet = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(self.stub.id!)).forEach(([key, verified]) => {\n if (verified) verifiedKeysFpSet.add(fingerprintV1(key))\n })\n if (verifiedKeysFpSet.size == 0) return []\n const graph = transferKeysFpGraphOf(self.stub)\n // 1. Choose keys available in this device which should be reachable from all other verified keys\n const targetKeys = await this.transferTargetKeys(this.encryptionKeysManager, graph)\n const res = []\n for (const { fingerprint: targetKeyFp, pair: targetKey } of targetKeys) {\n // 2. Find groups which can't reach the existing target keys\n const candidatesFp = this.transferKeysCandidatesFp(targetKeyFp, graph)\n // 3. Keep only groups which contain at least a verified candidate\n const verifiedGroupCandidates = candidatesFp.filter((candidate) =>\n graph.acyclicLabelToGroup[candidate].some((candidateGroupMember) => verifiedKeysFpSet.has(candidateGroupMember))\n )\n const verifiedCandidatesSet = new Set(verifiedGroupCandidates)\n if (verifiedCandidatesSet.size == 0) continue\n // 4. Drop all candidates which can already reach another candidate group: it is sufficient to create a transfer key from that group.\n const reachSets = reachSetsAcyclic(graph.acyclicGraph)\n const optimizedCandidates = verifiedGroupCandidates.filter((candidate) =>\n Array.from(reachSets[candidate]).every((reachableNode) => !verifiedCandidatesSet.has(reachableNode))\n )\n if (optimizedCandidates.length == 0) throw new Error('Check failed: at least one candidate should survive optimization')\n // 5. Transfer keys could also be faked: to make sure we are not giving access to unauthorised people we remap the candidates to a verified public\n // keys\n const verifiedOptimizedCandidates = optimizedCandidates.map((candidate) => {\n const res = graph.acyclicLabelToGroup[candidate].find((groupMemberFp) => verifiedKeysFpSet.has(groupMemberFp))\n if (!res) throw new Error('Check failed: optimized candidates groups should have at least a verified member')\n return res\n })\n res.push({\n sources: verifiedOptimizedCandidates,\n target: targetKey,\n targetFp: targetKeyFp,\n })\n }\n return res\n }\n}\n"]}
1
+ {"version":3,"file":"TransferKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/TransferKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,+BAA2C;AAE3C,oCAAiC;AAEjC,sDAA+E;AAC/E,mCAAgJ;AAOhJ;;;GAGG;AACH,MAAa,mBAAmB;IAC9B,YACmB,UAA4B,EAC5B,uBAAgD,EAChD,YAA8B,EAC9B,qBAAgD,EAChD,wBAAkD,EAClD,YAAgC;QALhC,eAAU,GAAV,UAAU,CAAkB;QAC5B,4BAAuB,GAAvB,uBAAuB,CAAyB;QAChD,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,0BAAqB,GAArB,qBAAqB,CAA2B;QAChD,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,iBAAY,GAAZ,YAAY,CAAoB;IAChD,CAAC;IAEJ;;;;;;OAMG;IACG,kBAAkB,CAAC,IAA6B;;;YACpD,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,+BAA+B,CAAC,IAAI,CAAC,CAAA;YACzE,IAAI,CAAC,gBAAgB,CAAC,MAAM;gBAAE,OA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air, ShaVersion } from './RSA'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ua2hex } from '../utils'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { reachSetsAcyclic, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { fingerprintToPublicKeysMapOf, fingerprintV1, loadPublicKeys, transferKeysFpGraphOf, fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeDataManager } from './BaseExchangeDataManager'\nimport { UserSignatureKeysManager } from './UserSignatureKeysManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is intended only for internal use and may be changed without notice.\n * Allows to create new transfer keys.\n */\nexport class TransferKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly baseExchangeDataManager: BaseExchangeDataManager,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly userSignatureKeysManager: UserSignatureKeysManager,\n private readonly icureStorage: IcureStorageFacade\n ) {}\n\n /**\n * Analyses the transfer keys graph and creates new transfer keys which allow to improve data accessibility from other devices.\n * For security reasons transfer keys will only be created between keys verified by the user, but this will be done ignoring any existing edges from\n * unverified keys to verified keys.\n * @param self the current data owner.\n * @return the updated data owner.\n */\n async updateTransferKeys(self: CryptoActorStubWithType): Promise<void> {\n const newEdgesByTarget = await this.getNewVerifiedTransferKeysEdges(self)\n if (!newEdgesByTarget.length) return\n const selfId = self.stub.id!\n const fpToPublicKey = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha1)\n const fpToPublicKeyWithSha256 = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha256)\n const signatureKeyPair = await this.userSignatureKeysManager.getOrCreateSignatureKeyPair()\n const verifiedFps = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n const allVerifiedSourcesAndTarget = Array.from(\n new Set(\n newEdgesByTarget.flatMap((x) =>\n // Sources are guaranteed to be verified, but target may not be\n verifiedFps.has(x.targetFp) ? [x.targetFp, ...x.sources] : x.sources\n )\n )\n )\n const newExchangeKeyPublicKeys = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKey[fp]).filter((key) => !!key)\n const newExchangeKeyPublicKeysWithSha256 = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKeyWithSha256[fp]).filter((key) => !!key)\n const createdExchangeData = await this.baseExchangeDataManager.createExchangeData(\n selfId,\n { [signatureKeyPair.fingerprint]: signatureKeyPair.keyPair.privateKey },\n {\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeys, ShaVersion.Sha1)),\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeysWithSha256, ShaVersion.Sha256)),\n }\n )\n let updatedTransferKeys = self.stub.transferKeys ?? {}\n for (const newEdges of newEdgesByTarget) {\n const encryptedTransferKey = await this.encryptTransferKey(newEdges.target, createdExchangeData.exchangeKey)\n updatedTransferKeys = newEdges.sources.reduce((acc, candidateFp) => {\n const existingKeys = { ...(acc[candidateFp] ?? {}) }\n existingKeys[newEdges.targetFp] = encryptedTransferKey\n acc[candidateFp] = existingKeys\n return acc\n }, updatedTransferKeys)\n }\n await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...self.stub,\n transferKeys: updatedTransferKeys,\n },\n type: self.type,\n })\n }\n\n // encrypts a transfer key in pkcs8 format using an exchange key, returns the hex representation\n private async encryptTransferKey(transferKey: KeyPair<CryptoKey>, exchangeKey: CryptoKey): Promise<string> {\n const exportedKey = await this.primitives.RSA.exportKey(transferKey.privateKey, 'pkcs8')\n return ua2hex(await this.primitives.AES.encrypt(exchangeKey, exportedKey))\n }\n\n // all public keys would go to the stored keys -> no need for specifying the key.\n // Result only includes the acyclic label, not the full group\n private transferKeysCandidatesFp(keyToFp: string, graph: StronglyConnectedGraph): string[] {\n return Object.entries(reachSetsAcyclic(graph.acyclicGraph))\n .filter(([from, reachable]) => {\n const currGroup = graph.acyclicLabelToGroup[from] ?? [from]\n const reachableOriginal = new Set(Array.from(reachable).flatMap((x) => graph.acyclicLabelToGroup[x] ?? [x]))\n return !currGroup.includes(keyToFp) && !reachableOriginal.has(keyToFp)\n })\n .map((x) => x[0])\n }\n\n private async transferTargetKeys(\n keyManager: UserEncryptionKeysManager,\n graph: StronglyConnectedGraph\n ): Promise<{ fingerprint: string; pair: KeyPair<CryptoKey> }[]> {\n const availableGroups = new Set(Object.keys(keyManager.getDecryptionKeys()).map((x) => graph.originalLabelToAcyclicLabel[x] ?? x))\n const groupsReachableFromAvailable = new Set(\n Object.entries(graph.acyclicGraph).flatMap(([source, reachables]) => (availableGroups.has(source) ? Array.from(reachables) : []))\n )\n const targetCandidates = Array.from(availableGroups).filter((x) => !groupsReachableFromAvailable.has(x))\n const verifiedFps = new Set(keyManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n return targetCandidates.map((candidateFp) => {\n const candidateGroup = graph.acyclicLabelToGroup[candidateFp] ?? [candidateFp] // May not be part of transfer keys graph yet\n const bestCandidateOfGroup = candidateGroup.find((x) => verifiedFps.has(x)) ?? candidateFp\n return { fingerprint: bestCandidateOfGroup, pair: keyManager.getKeyPairForFingerprint(bestCandidateOfGroup)!.pair }\n })\n }\n\n // Decides the best edges considering the verified public keys.\n private async getNewVerifiedTransferKeysEdges(self: CryptoActorStubWithType): Promise<\n {\n sources: string[]\n target: KeyPair<CryptoKey>\n targetFp: string\n }[]\n > {\n const verifiedKeysFpSet = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(self.stub.id!)).forEach(([key, verified]) => {\n if (verified) verifiedKeysFpSet.add(fingerprintV1(key))\n })\n if (verifiedKeysFpSet.size == 0) return []\n const graph = transferKeysFpGraphOf(self.stub)\n // 1. Choose keys available in this device which should be reachable from all other verified keys\n const targetKeys = await this.transferTargetKeys(this.encryptionKeysManager, graph)\n const res = []\n for (const { fingerprint: targetKeyFp, pair: targetKey } of targetKeys) {\n // 2. Find groups which can't reach the existing target keys\n const candidatesFp = this.transferKeysCandidatesFp(targetKeyFp, graph)\n // 3. Keep only groups which contain at least a verified candidate\n const verifiedGroupCandidates = candidatesFp.filter((candidate) =>\n graph.acyclicLabelToGroup[candidate].some((candidateGroupMember) => verifiedKeysFpSet.has(candidateGroupMember))\n )\n const verifiedCandidatesSet = new Set(verifiedGroupCandidates)\n if (verifiedCandidatesSet.size == 0) continue\n // 4. Drop all candidates which can already reach another candidate group: it is sufficient to create a transfer key from that group.\n const reachSets = reachSetsAcyclic(graph.acyclicGraph)\n const optimizedCandidates = verifiedGroupCandidates.filter((candidate) =>\n Array.from(reachSets[candidate]).every((reachableNode) => !verifiedCandidatesSet.has(reachableNode))\n )\n if (optimizedCandidates.length == 0) throw new Error('Check failed: at least one candidate should survive optimization')\n // 5. Transfer keys could also be faked: to make sure we are not giving access to unauthorised people we remap the candidates to a verified public\n // keys\n const verifiedOptimizedCandidates = optimizedCandidates.map((candidate) => {\n const res = graph.acyclicLabelToGroup[candidate].find((groupMemberFp) => verifiedKeysFpSet.has(groupMemberFp))\n if (!res) throw new Error('Check failed: optimized candidates groups should have at least a verified member')\n return res\n })\n res.push({\n sources: verifiedOptimizedCandidates,\n target: targetKey,\n targetFp: targetKeyFp,\n })\n }\n return res\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icure/api",
3
- "version": "8.0.23",
3
+ "version": "8.0.24",
4
4
  "description": "Typescript version of iCure standalone API client",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const icc_api_1 = require("../../../icc-api");
13
+ const AuthenticationResponse_1 = require("../../../icc-api/model/AuthenticationResponse");
14
+ const ModelHelper_1 = require("../../../icc-api/model/ModelHelper");
15
+ const chai_1 = require("chai");
16
+ const JwtBridgedAuthService_1 = require("../../../icc-x-api/auth/JwtBridgedAuthService");
17
+ const JwtAuthService_1 = require("../../../icc-x-api/auth/JwtAuthService");
18
+ const XHR_1 = require("../../../icc-api/api/XHR");
19
+ var XHRError = XHR_1.XHR.XHRError;
20
+ const JwtError_1 = require("../../../icc-x-api/auth/JwtError");
21
+ describe('JWT provider resiliency test', () => {
22
+ function generateJwt() {
23
+ return `jwt.${(0, ModelHelper_1.b2a)(JSON.stringify({ exp: 1000 }))}.${Math.floor(100000 + Math.random() * 900000)}`;
24
+ }
25
+ function generateRefreshJwt() {
26
+ return `refreshJwt.${(0, ModelHelper_1.b2a)(JSON.stringify({ exp: new Date().getTime() * 10 }))}.${Math.floor(100000 + Math.random() * 900000)}`;
27
+ }
28
+ class FakeAuthApi extends icc_api_1.IccAuthApi {
29
+ constructor() {
30
+ super('', {});
31
+ this.jwt = `jwt.${(0, ModelHelper_1.b2a)(JSON.stringify({ exp: 1000 }))}.signature`;
32
+ this.refreshJwt = `refreshJwt.${(0, ModelHelper_1.b2a)(JSON.stringify({ exp: new Date().getTime() * 10 }))}.signature`;
33
+ }
34
+ login(body) {
35
+ if (!!this.loginException) {
36
+ throw this.loginException;
37
+ }
38
+ this.jwt = generateJwt();
39
+ this.refreshJwt = generateRefreshJwt();
40
+ return Promise.resolve(new AuthenticationResponse_1.AuthenticationResponse({
41
+ token: this.jwt,
42
+ refreshToken: this.refreshJwt,
43
+ }));
44
+ }
45
+ refreshAuthenticationJWT(refreshJWT) {
46
+ var _a;
47
+ if (!!this.refreshException) {
48
+ throw this.refreshException;
49
+ }
50
+ this.jwt = generateJwt();
51
+ return Promise.resolve(new AuthenticationResponse_1.AuthenticationResponse({
52
+ token: this.jwt,
53
+ refreshToken: (_a = this.refreshJwt) !== null && _a !== void 0 ? _a : generateRefreshJwt(),
54
+ }));
55
+ }
56
+ }
57
+ function expectThrowOnGetHeaders(service) {
58
+ return __awaiter(this, void 0, void 0, function* () {
59
+ let caught = null;
60
+ try {
61
+ yield service.getAuthHeaders();
62
+ }
63
+ catch (e) {
64
+ caught = e;
65
+ }
66
+ (0, chai_1.expect)(caught).not.to.be.null;
67
+ (0, chai_1.expect)(caught).to.be.instanceof(JwtError_1.JwtError);
68
+ });
69
+ }
70
+ it('JwtBridgedAuthService - If the login fails for any type of error it is possible to retry', () => __awaiter(void 0, void 0, void 0, function* () {
71
+ const errors = [
72
+ new Error('A generic error'),
73
+ new XHRError('', '', 403, 'FORBIDDEN', new Headers()),
74
+ new XHRError('', '', 503, 'TIMEOUT', new Headers()),
75
+ ];
76
+ for (const e of errors) {
77
+ const fakeAuthApi = new FakeAuthApi();
78
+ const authService = new JwtBridgedAuthService_1.JwtBridgedAuthService(fakeAuthApi, 'username', 'password', {}, undefined);
79
+ fakeAuthApi.loginException = e;
80
+ yield expectThrowOnGetHeaders(authService);
81
+ fakeAuthApi.loginException = null;
82
+ const firstHeader = yield authService.getAuthHeaders();
83
+ (0, chai_1.expect)(firstHeader[0].data).to.be.equal(`Bearer ${fakeAuthApi.jwt}`);
84
+ }
85
+ }));
86
+ function jwtBridgedTest(error, loginAfterError) {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ const fakeAuthApi = new FakeAuthApi();
89
+ const authService = new JwtBridgedAuthService_1.JwtBridgedAuthService(fakeAuthApi, 'username', 'password', {}, undefined);
90
+ fakeAuthApi.refreshException = null;
91
+ const firstHeader = yield authService.getAuthHeaders();
92
+ const initialJwt = fakeAuthApi.jwt;
93
+ const initialRefresh = fakeAuthApi.refreshJwt;
94
+ (0, chai_1.expect)(firstHeader[0].data).to.be.equal(`Bearer ${initialJwt}`);
95
+ fakeAuthApi.refreshException = error;
96
+ yield expectThrowOnGetHeaders(authService);
97
+ fakeAuthApi.refreshException = null;
98
+ const secondHeader = yield authService.getAuthHeaders();
99
+ const secondJwt = fakeAuthApi.jwt;
100
+ const secondRefresh = fakeAuthApi.refreshJwt;
101
+ (0, chai_1.expect)(secondHeader[0].data).to.be.equal(`Bearer ${secondJwt}`);
102
+ (0, chai_1.expect)(secondJwt).not.to.be.equal(initialJwt);
103
+ if (loginAfterError) {
104
+ (0, chai_1.expect)(secondRefresh).not.to.be.equal(initialRefresh);
105
+ }
106
+ else {
107
+ (0, chai_1.expect)(secondRefresh).to.be.equal(initialRefresh);
108
+ }
109
+ });
110
+ }
111
+ it('JwtBridgedAuthService - If the refresh fails for a generic error, it is possible to retry', () => __awaiter(void 0, void 0, void 0, function* () {
112
+ const error = new Error('A generic error');
113
+ yield jwtBridgedTest(error, false);
114
+ }));
115
+ it('JwtBridgedAuthService - If the refresh fails for a 500 error, the login is performed again', () => __awaiter(void 0, void 0, void 0, function* () {
116
+ const error = new XHRError('', '', 500, 'INTERNAL SERVER ERROR', new Headers());
117
+ yield jwtBridgedTest(error, false);
118
+ }));
119
+ it('JwtBridgedAuthService - If the refresh fails for a 400 error, the login is performed again', () => __awaiter(void 0, void 0, void 0, function* () {
120
+ const error = new XHRError('', '', 403, 'FORBIDDEN', new Headers());
121
+ yield jwtBridgedTest(error, true);
122
+ }));
123
+ it('JwtAuthService - If the refresh fails for an error, it is possible to retry', () => __awaiter(void 0, void 0, void 0, function* () {
124
+ const fakeAuthApi = new FakeAuthApi();
125
+ const error = new Error('A generic error');
126
+ const initialJwt = generateJwt();
127
+ const initialRefresh = generateRefreshJwt();
128
+ const authService = new JwtAuthService_1.JwtAuthService(fakeAuthApi, { authJwt: initialJwt, refreshJwt: initialRefresh });
129
+ fakeAuthApi.refreshException = error;
130
+ yield expectThrowOnGetHeaders(authService);
131
+ fakeAuthApi.refreshException = null;
132
+ const secondHeader = yield authService.getAuthHeaders();
133
+ const secondJwt = fakeAuthApi.jwt;
134
+ (0, chai_1.expect)(secondHeader[0].data).to.be.equal(`Bearer ${secondJwt}`);
135
+ (0, chai_1.expect)(secondJwt).not.to.be.equal(initialJwt);
136
+ }));
137
+ });
138
+ //# sourceMappingURL=jwt-provider-test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt-provider-test.js","sourceRoot":"","sources":["../../../../test/icc-x-api/auth/jwt-provider-test.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,8CAA6C;AAE7C,0FAAsF;AACtF,oEAAwD;AACxD,+BAA6B;AAC7B,yFAAqF;AAErF,2EAAuE;AACvE,kDAA8C;AAC9C,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAC9B,+DAA2D;AAE3D,QAAQ,CAAC,8BAA8B,EAAE,GAAG,EAAE;IAC5C,SAAS,WAAW;QAClB,OAAO,OAAO,IAAA,iBAAG,EAAC,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,MAAM,CAAC,EAAE,CAAA;IACnG,CAAC;IAED,SAAS,kBAAkB;QACzB,OAAO,cAAc,IAAA,iBAAG,EAAC,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,MAAM,CAAC,EAAE,CAAA;IAC/H,CAAC;IAED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AA;QAE1C,WAAW,CAAC,gBAAgB,GAAG,IAAI,CAAA;QACnC,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,cAAc,EAAE,CAAA;QACvD,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAA;QACjC,IAAA,aAAM,EAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,UAAU,SAAS,EAAE,CAAC,CAAA;QAC/D,IAAA,aAAM,EAAC,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;IAC/C,CAAC,CAAA,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA","sourcesContent":["import { IccAuthApi } from '../../../icc-api'\nimport { LoginCredentials } from '../../../icc-api/model/LoginCredentials'\nimport { AuthenticationResponse } from '../../../icc-api/model/AuthenticationResponse'\nimport { b2a } from '../../../icc-api/model/ModelHelper'\nimport { expect } from 'chai'\nimport { JwtBridgedAuthService } from '../../../icc-x-api/auth/JwtBridgedAuthService'\nimport { AuthService } from '../../../icc-x-api/auth/AuthService'\nimport { JwtAuthService } from '../../../icc-x-api/auth/JwtAuthService'\nimport { XHR } from '../../../icc-api/api/XHR'\nimport XHRError = XHR.XHRError\nimport { JwtError } from '../../../icc-x-api/auth/JwtError'\n\ndescribe('JWT provider resiliency test', () => {\n function generateJwt() {\n return `jwt.${b2a(JSON.stringify({ exp: 1000 }))}.${Math.floor(100000 + Math.random() * 900000)}`\n }\n\n function generateRefreshJwt() {\n return `refreshJwt.${b2a(JSON.stringify({ exp: new Date().getTime() * 10 }))}.${Math.floor(100000 + Math.random() * 900000)}`\n }\n\n class FakeAuthApi extends IccAuthApi {\n refreshException: Error | undefined | null\n loginException: Error | undefined | null\n jwt = `jwt.${b2a(JSON.stringify({ exp: 1000 }))}.signature`\n refreshJwt = `refreshJwt.${b2a(JSON.stringify({ exp: new Date().getTime() * 10 }))}.signature`\n\n constructor() {\n super('', {})\n }\n\n login(body?: LoginCredentials): Promise<AuthenticationResponse> {\n if (!!this.loginException) {\n throw this.loginException\n }\n\n this.jwt = generateJwt()\n this.refreshJwt = generateRefreshJwt()\n return Promise.resolve(\n new AuthenticationResponse({\n token: this.jwt,\n refreshToken: this.refreshJwt,\n })\n )\n }\n\n refreshAuthenticationJWT(refreshJWT: string): Promise<AuthenticationResponse> {\n if (!!this.refreshException) {\n throw this.refreshException\n }\n\n this.jwt = generateJwt()\n return Promise.resolve(\n new AuthenticationResponse({\n token: this.jwt,\n refreshToken: this.refreshJwt ?? generateRefreshJwt(),\n })\n )\n }\n }\n\n async function expectThrowOnGetHeaders(service: AuthService): Promise<void> {\n let caught: Error | null = null\n try {\n await service.getAuthHeaders()\n } catch (e) {\n caught = e as Error\n }\n expect(caught).not.to.be.null\n expect(caught).to.be.instanceof(JwtError)\n }\n\n it('JwtBridgedAuthService - If the login fails for any type of error it is possible to retry', async () => {\n const errors: Error[] = [\n new Error('A generic error'),\n new XHRError('', '', 403, 'FORBIDDEN', new Headers()),\n new XHRError('', '', 503, 'TIMEOUT', new Headers()),\n ]\n for (const e of errors) {\n const fakeAuthApi = new FakeAuthApi()\n const authService = new JwtBridgedAuthService(fakeAuthApi, 'username', 'password', {}, undefined)\n\n fakeAuthApi.loginException = e\n await expectThrowOnGetHeaders(authService)\n\n fakeAuthApi.loginException = null\n const firstHeader = await authService.getAuthHeaders()\n expect(firstHeader[0].data).to.be.equal(`Bearer ${fakeAuthApi.jwt}`)\n }\n })\n\n async function jwtBridgedTest(error: Error, loginAfterError: boolean) {\n const fakeAuthApi = new FakeAuthApi()\n const authService = new JwtBridgedAuthService(fakeAuthApi, 'username', 'password', {}, undefined)\n\n fakeAuthApi.refreshException = null\n const firstHeader = await authService.getAuthHeaders()\n const initialJwt = fakeAuthApi.jwt\n const initialRefresh = fakeAuthApi.refreshJwt\n expect(firstHeader[0].data).to.be.equal(`Bearer ${initialJwt}`)\n\n fakeAuthApi.refreshException = error\n await expectThrowOnGetHeaders(authService)\n\n fakeAuthApi.refreshException = null\n const secondHeader = await authService.getAuthHeaders()\n const secondJwt = fakeAuthApi.jwt\n const secondRefresh = fakeAuthApi.refreshJwt\n expect(secondHeader[0].data).to.be.equal(`Bearer ${secondJwt}`)\n expect(secondJwt).not.to.be.equal(initialJwt)\n if (loginAfterError) {\n expect(secondRefresh).not.to.be.equal(initialRefresh)\n } else {\n expect(secondRefresh).to.be.equal(initialRefresh)\n }\n }\n\n it('JwtBridgedAuthService - If the refresh fails for a generic error, it is possible to retry', async () => {\n const error = new Error('A generic error')\n await jwtBridgedTest(error, false)\n })\n\n it('JwtBridgedAuthService - If the refresh fails for a 500 error, the login is performed again', async () => {\n const error = new XHRError('', '', 500, 'INTERNAL SERVER ERROR', new Headers())\n await jwtBridgedTest(error, false)\n })\n\n it('JwtBridgedAuthService - If the refresh fails for a 400 error, the login is performed again', async () => {\n const error = new XHRError('', '', 403, 'FORBIDDEN', new Headers())\n await jwtBridgedTest(error, true)\n })\n\n it('JwtAuthService - If the refresh fails for an error, it is possible to retry', async () => {\n const fakeAuthApi = new FakeAuthApi()\n const error = new Error('A generic error')\n const initialJwt = generateJwt()\n const initialRefresh = generateRefreshJwt()\n const authService = new JwtAuthService(fakeAuthApi, { authJwt: initialJwt, refreshJwt: initialRefresh })\n\n fakeAuthApi.refreshException = error\n await expectThrowOnGetHeaders(authService)\n\n fakeAuthApi.refreshException = null\n const secondHeader = await authService.getAuthHeaders()\n const secondJwt = fakeAuthApi.jwt\n expect(secondHeader[0].data).to.be.equal(`Bearer ${secondJwt}`)\n expect(secondJwt).not.to.be.equal(initialJwt)\n })\n})\n"]}