fix(auth): prevent integer overflow in logout timer using safeTimeout

This commit is contained in:
ArielLeyva 2025-10-05 10:11:59 -04:00
parent d0039afbb7
commit 3bdd2546e4
2 changed files with 24 additions and 2 deletions

View File

@ -91,3 +91,23 @@ export function createURL(endpoint: string, searchParams = {}): string {
return url.toString();
}
export function setSafeTimeout(callback: () => void, delay: number): number {
const MAX_DELAY = 86_400_000;
let remaining = delay;
let timerId: number;
function scheduleNext() {
if (remaining <= MAX_DELAY) {
timerId = window.setTimeout(callback, remaining);
} else {
timerId = window.setTimeout(() => {
remaining -= MAX_DELAY;
scheduleNext();
}, MAX_DELAY);
}
}
scheduleNext();
return timerId;
}

View File

@ -4,6 +4,7 @@ import type { JwtPayload } from "jwt-decode";
import { jwtDecode } from "jwt-decode";
import { baseURL, noAuth } from "./constants";
import { StatusError } from "@/api/utils";
import { setSafeTimeout } from "@/api/utils";
export function parseToken(token: string) {
// falsy or malformed jwt will throw InvalidTokenError
@ -22,10 +23,11 @@ export function parseToken(token: string) {
}
const expiresAt = new Date(data.exp! * 1000);
const timeout = expiresAt.getTime() - Date.now();
authStore.setLogoutTimer(
window.setTimeout(() => {
setSafeTimeout(() => {
logout("inactivity");
}, expiresAt.getTime() - Date.now())
}, timeout)
);
}