Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(signer): expire sessions on focus and on timer after init #1112

Merged
merged 1 commit into from
Oct 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 28 additions & 8 deletions account-kit/signer/src/session/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export class SessionManager {
private eventEmitter: EventEmitter<SessionManagerEvents>;
readonly expirationTimeMs: number;
private store: Store;
private clearSessionHandle: NodeJS.Timeout | null = null;

constructor(params: SessionManagerParams) {
const {
Expand Down Expand Up @@ -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 }) => {
Expand Down Expand Up @@ -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<Extract<Session, { type: "email" | "oauth" }>, "expirationDateMs">
| Omit<Extract<Session, { type: "passkey" }>, "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() {
Expand Down Expand Up @@ -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
) {
Expand All @@ -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,
Expand Down
Loading