mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat(auth): enhance token management and synchronization with user data
This commit is contained in:
@@ -13,43 +13,121 @@ export type Role = keyof typeof roles;
|
||||
|
||||
const TOKEN_KEY = 'token';
|
||||
const REFRESH_TOKEN_KEY = 'refreshToken';
|
||||
const TOKEN_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 180;
|
||||
const AUTH_TOKENS_UPDATED_EVENT = 'auth:tokens-updated';
|
||||
const AUTH_TOKENS_CLEARED_EVENT = 'auth:tokens-cleared';
|
||||
|
||||
let refreshPromise: Promise<void> | null = null;
|
||||
let lastRefreshAttempt = 0;
|
||||
let refreshFailureCount = 0;
|
||||
let refreshIntervalId: ReturnType<typeof setInterval> | null = null;
|
||||
let listenersRegistered = false;
|
||||
|
||||
export function getToken() {
|
||||
function getCookieValue(key: string) {
|
||||
if (!browser) return null;
|
||||
const entry = document.cookie
|
||||
.split('; ')
|
||||
.find((cookieEntry) => cookieEntry.startsWith(`${key}=`));
|
||||
if (!entry) return null;
|
||||
const value = entry.slice(key.length + 1);
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function getCookieSecurityAttributes() {
|
||||
if (!browser) return '';
|
||||
return window.location.protocol === 'https:' ? '; secure' : '';
|
||||
}
|
||||
|
||||
function emitAuthEvent(eventName: string) {
|
||||
if (!browser) return;
|
||||
window.dispatchEvent(new CustomEvent(eventName));
|
||||
}
|
||||
|
||||
function decodeBase64Url(value: string) {
|
||||
const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const padding = normalized.length % 4 === 0 ? '' : '='.repeat(4 - (normalized.length % 4));
|
||||
return atob(normalized + padding);
|
||||
}
|
||||
|
||||
function decodeJwtPayload(token: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const [, payload] = token.split('.');
|
||||
if (!payload) return null;
|
||||
return JSON.parse(decodeBase64Url(payload));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseBooleanClaim(value: unknown) {
|
||||
if (typeof value === 'string') return value.toLowerCase() === 'true';
|
||||
return Boolean(value);
|
||||
}
|
||||
|
||||
function parseNumberClaim(value: unknown): number | null {
|
||||
const numeric = typeof value === 'number' ? value : typeof value === 'string' ? parseInt(value, 10) : NaN;
|
||||
return Number.isFinite(numeric) ? numeric : null;
|
||||
}
|
||||
|
||||
function isPermanentRefreshFailure(status: number, message?: string) {
|
||||
if (status === 401 || status === 403) return true;
|
||||
if (!message) return false;
|
||||
const normalized = message.toLowerCase();
|
||||
return (
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith(`${TOKEN_KEY}=`))
|
||||
?.split('=')[1] || null
|
||||
normalized.includes('invalid') ||
|
||||
normalized.includes('expired') ||
|
||||
normalized.includes('revoked') ||
|
||||
normalized.includes('malformed')
|
||||
);
|
||||
}
|
||||
|
||||
async function queueRefresh(token: string, refreshToken: string) {
|
||||
if (refreshPromise) {
|
||||
await refreshPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const timeSinceLastAttempt = now - lastRefreshAttempt;
|
||||
const minDelay = getBackoffDelay(refreshFailureCount);
|
||||
if (timeSinceLastAttempt < minDelay) return;
|
||||
|
||||
refreshPromise = performRefresh(token, refreshToken);
|
||||
try {
|
||||
await refreshPromise;
|
||||
} finally {
|
||||
refreshPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken() {
|
||||
return getCookieValue(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function getRefreshToken() {
|
||||
if (!browser) return null;
|
||||
return (
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith(`${REFRESH_TOKEN_KEY}=`))
|
||||
?.split('=')[1] || null
|
||||
);
|
||||
return getCookieValue(REFRESH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function setTokens(token: string, refreshToken: string) {
|
||||
if (!browser) return;
|
||||
document.cookie = `${TOKEN_KEY}=${token}; path=/; secure; samesite=strict`;
|
||||
document.cookie = `${REFRESH_TOKEN_KEY}=${refreshToken}; path=/; secure; samesite=strict`;
|
||||
const secureAttributes = getCookieSecurityAttributes();
|
||||
document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=${TOKEN_COOKIE_MAX_AGE_SECONDS}; samesite=strict${secureAttributes}`;
|
||||
document.cookie = `${REFRESH_TOKEN_KEY}=${encodeURIComponent(refreshToken)}; path=/; max-age=${TOKEN_COOKIE_MAX_AGE_SECONDS}; samesite=strict${secureAttributes}`;
|
||||
refreshFailureCount = 0;
|
||||
emitAuthEvent(AUTH_TOKENS_UPDATED_EVENT);
|
||||
}
|
||||
|
||||
export function clearTokens() {
|
||||
if (!browser) return;
|
||||
document.cookie = `${TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
||||
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
||||
const secureAttributes = getCookieSecurityAttributes();
|
||||
document.cookie = `${TOKEN_KEY}=; path=/; max-age=0; samesite=strict${secureAttributes}`;
|
||||
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; max-age=0; samesite=strict${secureAttributes}`;
|
||||
user.set(null);
|
||||
emitAuthEvent(AUTH_TOKENS_CLEARED_EVENT);
|
||||
}
|
||||
|
||||
function getBackoffDelay(attempt: number): number {
|
||||
@@ -64,27 +142,18 @@ export async function refreshTokenIfNeeded() {
|
||||
const refreshToken = getRefreshToken();
|
||||
if (!token || !refreshToken) return;
|
||||
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
const exp = payload.exp * 1000;
|
||||
const now = Date.now();
|
||||
|
||||
if (exp - now >= 2 * 60 * 1000) return;
|
||||
|
||||
if (refreshPromise) {
|
||||
await refreshPromise;
|
||||
const payload = decodeJwtPayload(token);
|
||||
const expClaim = payload ? parseNumberClaim(payload.exp) : null;
|
||||
if (expClaim === null) {
|
||||
await queueRefresh(token, refreshToken);
|
||||
return;
|
||||
}
|
||||
|
||||
const timeSinceLastAttempt = now - lastRefreshAttempt;
|
||||
const minDelay = getBackoffDelay(refreshFailureCount);
|
||||
if (timeSinceLastAttempt < minDelay) return;
|
||||
const exp = expClaim * 1000;
|
||||
const now = Date.now();
|
||||
|
||||
refreshPromise = performRefresh(token, refreshToken);
|
||||
try {
|
||||
await refreshPromise;
|
||||
} finally {
|
||||
refreshPromise = null;
|
||||
}
|
||||
if (exp - now >= 2 * 60 * 1000) return;
|
||||
await queueRefresh(token, refreshToken);
|
||||
}
|
||||
|
||||
async function performRefresh(token: string, refreshToken: string) {
|
||||
@@ -96,21 +165,30 @@ async function performRefresh(token: string, refreshToken: string) {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token, refreshToken })
|
||||
});
|
||||
let data: {
|
||||
success?: boolean;
|
||||
message?: string;
|
||||
token?: { token?: string; refreshToken?: string };
|
||||
} | null = null;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch {
|
||||
data = null;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
refreshFailureCount++;
|
||||
if (res.status === 400 || res.status === 401 || res.status === 403) {
|
||||
if (isPermanentRefreshFailure(res.status, data?.message)) {
|
||||
clearTokens();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
if (data.success && data.token?.token && data.token?.refreshToken) {
|
||||
if (data?.success && data.token?.token && data.token?.refreshToken) {
|
||||
setTokens(data.token.token, data.token.refreshToken);
|
||||
} else {
|
||||
refreshFailureCount++;
|
||||
if (!data.success) {
|
||||
if (isPermanentRefreshFailure(res.status, data?.message)) {
|
||||
clearTokens();
|
||||
}
|
||||
}
|
||||
@@ -121,7 +199,27 @@ async function performRefresh(token: string, refreshToken: string) {
|
||||
|
||||
export function startTokenRefreshInterval() {
|
||||
if (!browser) return;
|
||||
setInterval(refreshTokenIfNeeded, 60 * 1000);
|
||||
if (refreshIntervalId !== null) return;
|
||||
refreshIntervalId = setInterval(() => {
|
||||
void refreshTokenIfNeeded();
|
||||
}, 60 * 1000);
|
||||
|
||||
if (!listenersRegistered) {
|
||||
window.addEventListener('focus', () => {
|
||||
void refreshTokenIfNeeded();
|
||||
});
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void refreshTokenIfNeeded();
|
||||
}
|
||||
});
|
||||
window.addEventListener('online', () => {
|
||||
void refreshTokenIfNeeded();
|
||||
});
|
||||
listenersRegistered = true;
|
||||
}
|
||||
|
||||
void refreshTokenIfNeeded();
|
||||
}
|
||||
|
||||
export function getServerToken(cookies: Cookies) {
|
||||
@@ -133,12 +231,19 @@ export function getServerRefreshToken(cookies: Cookies) {
|
||||
}
|
||||
|
||||
export function setServerTokens(cookies: Cookies, token: string, refreshToken: string) {
|
||||
cookies.set('token', token, { path: '/', httpOnly: true, sameSite: 'strict', secure: true });
|
||||
cookies.set('token', token, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'strict',
|
||||
secure: true,
|
||||
maxAge: TOKEN_COOKIE_MAX_AGE_SECONDS
|
||||
});
|
||||
cookies.set('refreshToken', refreshToken, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'strict',
|
||||
secure: true
|
||||
secure: true,
|
||||
maxAge: TOKEN_COOKIE_MAX_AGE_SECONDS
|
||||
});
|
||||
}
|
||||
|
||||
@@ -148,19 +253,24 @@ export function clearServerTokens(cookies: Cookies) {
|
||||
}
|
||||
|
||||
export function getUserFromToken(token: string): JWTUser | null {
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
return {
|
||||
uuid: payload.uuid,
|
||||
username: payload.username,
|
||||
displayname: payload.displayname,
|
||||
totpEnabled: payload.totp_enabled === 'True',
|
||||
roles: typeof payload.roles === 'string' ? parseInt(payload.roles, 10) : payload.roles,
|
||||
isBanned: payload.is_banned === 'True'
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const payload = decodeJwtPayload(token);
|
||||
if (!payload) return null;
|
||||
|
||||
const uuid = typeof payload.uuid === 'string' ? payload.uuid : null;
|
||||
const username = typeof payload.username === 'string' ? payload.username : null;
|
||||
const displayname = typeof payload.displayname === 'string' ? payload.displayname : '';
|
||||
const rolesClaim = parseNumberClaim(payload.roles);
|
||||
|
||||
if (!uuid || !username || rolesClaim === null) return null;
|
||||
|
||||
return {
|
||||
uuid,
|
||||
username,
|
||||
displayname,
|
||||
totpEnabled: parseBooleanClaim(payload.totp_enabled),
|
||||
roles: rolesClaim,
|
||||
isBanned: parseBooleanClaim(payload.is_banned)
|
||||
};
|
||||
}
|
||||
|
||||
export const hasRole = (userRoles: number, role: number) => (userRoles & role) !== 0;
|
||||
|
||||
@@ -13,26 +13,25 @@
|
||||
|
||||
export let data: LayoutData;
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
startTokenRefreshInterval();
|
||||
window.turnstileLoaded = () => {
|
||||
window.dispatchEvent(new CustomEvent('turnstile:loaded'));
|
||||
};
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
await refreshTokenIfNeeded();
|
||||
async function syncUserFromToken() {
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
user.set(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch('/api/user/me', {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
try {
|
||||
const res = await fetch('/api/user/me', {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
user.set(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (res.ok) {
|
||||
const me = await res.json();
|
||||
let userData = me;
|
||||
if (me && 'user' in me && typeof me.user === 'object') {
|
||||
@@ -40,9 +39,55 @@
|
||||
userData = { ...rest, ...nestedUser };
|
||||
}
|
||||
user.set({ ...userData, totpEnabled: parseTotpEnabled(getToken()) });
|
||||
} else {
|
||||
user.set(null);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
startTokenRefreshInterval();
|
||||
window.turnstileLoaded = () => {
|
||||
window.dispatchEvent(new CustomEvent('turnstile:loaded'));
|
||||
};
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
const refreshAndSync = async () => {
|
||||
await refreshTokenIfNeeded();
|
||||
await syncUserFromToken();
|
||||
};
|
||||
|
||||
const handleFocus = () => {
|
||||
void refreshAndSync();
|
||||
};
|
||||
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void refreshAndSync();
|
||||
}
|
||||
};
|
||||
|
||||
const handleTokensUpdated = () => {
|
||||
void syncUserFromToken();
|
||||
};
|
||||
|
||||
const handleTokensCleared = () => {
|
||||
user.set(null);
|
||||
};
|
||||
|
||||
void refreshAndSync();
|
||||
|
||||
window.addEventListener('focus', handleFocus);
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
window.addEventListener('auth:tokens-updated', handleTokensUpdated);
|
||||
window.addEventListener('auth:tokens-cleared', handleTokensCleared);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
window.removeEventListener('auth:tokens-updated', handleTokensUpdated);
|
||||
window.removeEventListener('auth:tokens-cleared', handleTokensCleared);
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user