diff --git a/account-kit/signer/src/session/manager.ts b/account-kit/signer/src/session/manager.ts index 4fedf3fdba..97766a9825 100644 --- a/account-kit/signer/src/session/manager.ts +++ b/account-kit/signer/src/session/manager.ts @@ -45,6 +45,7 @@ export class SessionManager { private eventEmitter: EventEmitter; readonly expirationTimeMs: number; private store: Store; + private clearSessionHandle: NodeJS.Timeout | null = null; constructor(params: SessionManagerParams) { const { @@ -125,6 +126,10 @@ export class SessionManager { public clearSession = () => { this.store.setState({ session: null }); + + if (this.clearSessionHandle) { + clearTimeout(this.clearSessionHandle); + } }; public setTemporarySession = (session: { orgId: string }) => { @@ -170,24 +175,28 @@ export class SessionManager { * We should revisit this later */ if (session.expirationDateMs < Date.now()) { - this.store.setState({ session: null }); + this.clearSession(); return null; } + this.registerSessionExpirationHandler(session); + return session; }; private setSession = ( - session: + session_: | Omit, "expirationDateMs"> | Omit, "expirationDateMs"> ) => { - this.store.setState({ - session: { - ...session, - expirationDateMs: Date.now() + this.expirationTimeMs, - }, - }); + const session = { + ...session_, + expirationDateMs: Date.now() + this.expirationTimeMs, + }; + + this.registerSessionExpirationHandler(session); + + this.store.setState({ session }); }; public initialize() { @@ -249,6 +258,7 @@ export class SessionManager { this.store.persist.rehydrate(); const newSession = this.store.getState().session; if ( + (oldSession?.expirationDateMs ?? 0) < Date.now() || oldSession?.user.orgId !== newSession?.user.orgId || oldSession?.user.userId !== newSession?.user.userId ) { @@ -258,6 +268,16 @@ export class SessionManager { }); }; + private registerSessionExpirationHandler = (session: Session) => { + if (this.clearSessionHandle) { + clearTimeout(this.clearSessionHandle); + } + + this.clearSessionHandle = setTimeout(() => { + this.clearSession(); + }, Math.min(session.expirationDateMs - Date.now(), Math.pow(2, 31) - 1)); + }; + private setSessionWithUserAndBundle = ({ type, user,