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 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; + } + } } }