From 373bddd8df7943a66d63663fd9a6933f93db3ec8 Mon Sep 17 00:00:00 2001 From: f1ames Date: Thu, 23 Nov 2023 14:57:46 +0100 Subject: [PATCH 1/2] fix(synchronizer): allow to clear user data on origin conflict --- .../synchronizer/src/utils/authenticator.ts | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/packages/synchronizer/src/utils/authenticator.ts b/packages/synchronizer/src/utils/authenticator.ts index e0314b3b9..ec57615ca 100644 --- a/packages/synchronizer/src/utils/authenticator.ts +++ b/packages/synchronizer/src/utils/authenticator.ts @@ -19,6 +19,11 @@ export type AuthenticatorLoginEvent = { user: User; }; +export type RefreshTokenOptions = { + logoutOnInvalidGrant?: boolean; + logoutOnFail?: boolean; +}; + export class Authenticator extends EventEmitter { private _user: User; @@ -72,7 +77,7 @@ export class Authenticator extends EventEmitter { } } - async refreshToken(force = false) { + async refreshToken(force = false, options: RefreshTokenOptions = { logoutOnInvalidGrant: true }) { const authData = this._user.data?.auth; const tokenData = authData?.token; @@ -93,8 +98,20 @@ export class Authenticator extends EventEmitter { const expiresAtDateMs = new Date(tokenSetData.expires_at * 1000); const diffMinutes = (expiresAtDateMs.getTime() - new Date().getTime()) / 1000 / 60; if (diffMinutes < 5 || force) { - const newTokenData = await this._deviceFlowHandler.refreshAuthFlow(tokenSetData.refresh_token); - return this.setUserData(newTokenData); + try { + const newTokenData = await this._deviceFlowHandler.refreshAuthFlow(tokenSetData.refresh_token); + return this.setUserData(newTokenData); + } catch (err: any) { + // This is a workaround for origin conflict where user is logged in already with different origin + // and authenticator is querying different one. + if (options?.logoutOnFail || options?.logoutOnInvalidGrant && err.message.toLowerCase().includes('invalid_grant')) { + await this._storageHandler.emptyStoreData(); + this._user = new User(null); + // Do not emit logout event since we treat this as user not being logged in with desired origin. + } else { + throw err; + } + } } } From 1a5a238e4ada80c5b99dc0542be8ed6aa11e2701 Mon Sep 17 00:00:00 2001 From: f1ames Date: Thu, 23 Nov 2023 15:02:50 +0100 Subject: [PATCH 2/2] chore(synchronizer): add changeset --- .changeset/three-crews-applaud.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/three-crews-applaud.md diff --git a/.changeset/three-crews-applaud.md b/.changeset/three-crews-applaud.md new file mode 100644 index 000000000..a4232b64e --- /dev/null +++ b/.changeset/three-crews-applaud.md @@ -0,0 +1,5 @@ +--- +"@monokle/synchronizer": patch +--- + +Clear auth user data on origin conflict by default