feat(auth): use the cookie session and refresh on 401

The token is no longer stored; a tbp_session flag remembers the
login. apiFetch renews the session once on a 401 and sends the
request again. Parallel requests and other tabs share one refresh,
because Auth revokes the session when a refresh token is used twice.
Only a 401 from the refresh ends the session; a 502 or no network
shows the normal error.
This commit is contained in:
lobo committed 2026-09-25 13:45:08 +02:00
1 parent 5ff8d48c53
commit d9a39dda22
34 files changed
+297 -147

No files matched your search

+54 -6
View File
@@ -1,10 +1,58 @@
import {getToken} from './auth.js';
// Auth and Core refuse a request that changes data without this header (CSRF guard, see ClientHeaderFilter).
export const CLIENT_HEADER = 'X-TBP-Client';
/**
* fetch with the login token. The caller handles the response status, 401 included.
* fetch with the login cookies and the client header, without a refresh. For login, registration, refresh and
* logout, where a 401 is an answer and not an expired session.
*/
export function apiFetch(url, init = {}) {
const token = getToken();
const headers = token ? {...init.headers, 'Authorization': `Bearer ${token}`} : init.headers;
return fetch(url, {...init, headers});
export function clientFetch(url, init = {}) {
return fetch(url, {...init, credentials: 'include', headers: {...init.headers, [CLIENT_HEADER]: 'web'}});
}
/**
* Revokes the session in Auth and clears both cookies. A failure is ignored: the page logs out anyway.
*/
export const logout = () =>
clientFetch(`${import.meta.env.VITE_API_URL}/api/auth/logout`, {method: 'POST'}).catch(() => undefined);
const REFRESH_TIMEOUT_MS = 10_000;
let runningRefresh = null;
/**
* Renews the access cookie. False when Auth says the session is over (401). Any other failure, e.g. a 502 during a
* deploy or no network, rejects: the session may still be fine, so the caller shows its network error instead.
* Parallel callers share one request. The lock also holds other tabs back: Auth revokes the whole session when one
* refresh token is used twice.
*/
export function refreshSession() {
if (!runningRefresh) {
const refresh = async () => {
// A hung request would hold the lock, and with it the refresh in every tab.
const response = await clientFetch(`${import.meta.env.VITE_API_URL}/api/auth/refresh`,
{method: 'POST', signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS)});
if (response.ok || response.status === 401) {
return response.ok;
}
throw new Error(`Session refresh failed with ${response.status}`);
};
const locked = globalThis.navigator?.locks ? navigator.locks.request('tbp-refresh', refresh) : refresh();
runningRefresh = locked.finally(() => {
runningRefresh = null;
});
}
return runningRefresh;
}
/**
* fetch for the logged-in user. A 401 renews the access cookie once and sends the request again. When that fails,
* the 401 goes back to the caller. Ending the session is the caller's job (useSessionExpired), so the user sees
* why and comes back to the same page.
*/
export async function apiFetch(url, init = {}) {
const response = await clientFetch(url, init);
if (response.status !== 401 || !(await refreshSession())) {
return response;
}
return clientFetch(url, init);
}
+118 -20
View File
@@ -1,40 +1,138 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {apiFetch} from './api.js';
import {apiFetch, clientFetch, logout} from './api.js';
describe('apiFetch', () => {
beforeEach(() => {
globalThis.fetch = vi.fn(async () => new Response(null, {status: 204}));
});
const response = (status) => ({ok: status >= 200 && status < 300, status, json: async () => ({})});
const isRefresh = (url) => url.endsWith('/api/auth/refresh');
const dataCalls = () => fetch.mock.calls.filter(([url]) => !isRefresh(url));
const refreshCalls = () => fetch.mock.calls.filter(([url]) => isRefresh(url));
afterEach(() => {
localStorage.clear();
});
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
});
it('sends the stored token and keeps the other headers and options', async () => {
localStorage.setItem('tbp_jwt', 'the-token');
afterEach(() => {
localStorage.clear();
});
await apiFetch('/api/x', {method: 'PUT', headers: {'Content-Type': 'application/json'}, body: '{}'});
describe('clientFetch', () => {
it('sends the cookies and the client header and keeps the other options', async () => {
globalThis.fetch = vi.fn(async () => response(204));
await clientFetch('/api/x', {method: 'PUT', headers: {'Content-Type': 'application/json'}, body: '{}'});
expect(fetch).toHaveBeenCalledWith('/api/x', {
method: 'PUT',
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer the-token'},
headers: {'Content-Type': 'application/json', 'X-TBP-Client': 'web'},
body: '{}',
credentials: 'include',
});
});
});
it('sends no Authorization header without a token', async () => {
await apiFetch('/api/x');
describe('apiFetch', () => {
it('renews the session once on a 401 and sends the request again', async () => {
let dataAnswers = [401, 200];
globalThis.fetch = vi.fn(async (url) => response(isRefresh(url) ? 204 : dataAnswers.shift()));
expect(fetch).toHaveBeenCalledWith('/api/x', {headers: undefined});
const result = await apiFetch('/api/x', {method: 'PUT', body: '{"a":1}'});
expect(result.status).toBe(200);
expect(refreshCalls()).toHaveLength(1);
expect(dataCalls()).toHaveLength(2);
expect(dataCalls()[1][1]).toMatchObject({method: 'PUT', body: '{"a":1}'});
expect(localStorage.getItem('tbp_session')).toBe('1');
});
it('reads the token on every call', async () => {
localStorage.setItem('tbp_jwt', 'old');
await apiFetch('/api/x');
localStorage.setItem('tbp_jwt', 'new');
it('asks only once when parallel calls get a 401', async () => {
const seen = new Set();
globalThis.fetch = vi.fn(async (url) => {
if (isRefresh(url)) return response(204);
if (seen.has(url)) return response(200);
seen.add(url);
return response(401);
});
const results = await Promise.all(['/a', '/b', '/c'].map((url) => apiFetch(url)));
expect(results.map((r) => r.status)).toEqual([200, 200, 200]);
expect(refreshCalls()).toHaveLength(1);
});
it('returns the 401 when the refresh fails, without a loop, and leaves ending the session to the caller', async () => {
globalThis.fetch = vi.fn(async () => response(401));
const result = await apiFetch('/api/x');
expect(result.status).toBe(401);
expect(refreshCalls()).toHaveLength(1);
expect(dataCalls()).toHaveLength(1);
expect(localStorage.getItem('tbp_session')).toBe('1');
});
it('keeps the session and rejects when the refresh has no network', async () => {
globalThis.fetch = vi.fn(async (url) => {
if (isRefresh(url)) throw new TypeError('offline');
return response(401);
});
await expect(apiFetch('/api/x')).rejects.toThrow('offline');
expect(localStorage.getItem('tbp_session')).toBe('1');
});
it('keeps the session and rejects when Auth is down during a deploy', async () => {
globalThis.fetch = vi.fn(async (url) => response(isRefresh(url) ? 502 : 401));
await expect(apiFetch('/api/x')).rejects.toThrow('502');
expect(localStorage.getItem('tbp_session')).toBe('1');
});
it('tries the refresh again on the next 401 after a failed one', async () => {
const refreshAnswers = [502, 204];
const dataAnswers = [401, 401, 200];
globalThis.fetch = vi.fn(async (url) => response(isRefresh(url) ? refreshAnswers.shift() : dataAnswers.shift()));
await expect(apiFetch('/api/x')).rejects.toThrow();
expect((await apiFetch('/api/x')).status).toBe(200);
});
it('passes other errors through without a refresh', async () => {
globalThis.fetch = vi.fn(async () => response(403));
expect((await apiFetch('/api/x')).status).toBe(403);
expect(refreshCalls()).toHaveLength(0);
});
it('gives up on a refresh that hangs, so the lock does not block every tab', async () => {
globalThis.fetch = vi.fn(async (url, init) => {
if (!isRefresh(url)) return response(401);
expect(init.signal).toBeInstanceOf(AbortSignal);
throw new DOMException('timed out', 'TimeoutError');
});
await expect(apiFetch('/api/x')).rejects.toThrow('timed out');
});
it('runs the refresh under a lock that other tabs share', async () => {
const request = vi.fn((name, callback) => callback());
vi.stubGlobal('navigator', {...navigator, locks: {request}});
let dataAnswers = [401, 200];
globalThis.fetch = vi.fn(async (url) => response(isRefresh(url) ? 204 : dataAnswers.shift()));
await apiFetch('/api/x');
expect(fetch).toHaveBeenLastCalledWith('/api/x', {headers: {'Authorization': 'Bearer new'}});
expect(request).toHaveBeenCalledWith('tbp-refresh', expect.any(Function));
vi.unstubAllGlobals();
});
});
describe('logout', () => {
it('posts to Auth and ignores a network error', async () => {
globalThis.fetch = vi.fn(async () => {
throw new TypeError('offline');
});
await expect(logout()).resolves.toBeUndefined();
expect(fetch).toHaveBeenCalledWith(expect.stringContaining('/api/auth/logout'), expect.objectContaining({method: 'POST'}));
});
});
+17 -27
View File
@@ -1,35 +1,25 @@
const TOKEN_KEY = 'tbp_jwt';
// The tokens live in HttpOnly cookies that no script can read. This flag only remembers that a login happened; a
// stale flag costs one 401 and a failed refresh, then the login page opens.
const SESSION_KEY = 'tbp_session';
// Where the token lived before the cookies. Removed on the next login or logout.
const LEGACY_TOKEN_KEY = 'tbp_jwt';
export const getToken = () => localStorage.getItem(TOKEN_KEY);
export const setToken = (token) => localStorage.setItem(TOKEN_KEY, token);
export const clearToken = () => localStorage.removeItem(TOKEN_KEY);
export const hasSession = () => localStorage.getItem(SESSION_KEY) !== null;
/**
* Only checks `exp`. The signature is checked by the backends.
* Changes on every login and on every settings save, so a hook that shows the user's Steam data can load again.
*/
export function isTokenValid(token, nowMs = Date.now()) {
try {
const payload = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
const {exp} = JSON.parse(atob(payload));
return typeof exp === 'number' && exp * 1000 > nowMs;
} catch {
return false;
}
}
export const sessionStamp = () => localStorage.getItem(SESSION_KEY);
/**
* Returns the stored token, or null. Removes an expired token.
*/
export function getValidToken() {
const token = getToken();
if (token && !isTokenValid(token)) {
clearToken();
return null;
}
return token;
}
export const markSession = () => {
localStorage.setItem(SESSION_KEY, String(Date.now()));
localStorage.removeItem(LEGACY_TOKEN_KEY);
};
export const clearSession = () => {
localStorage.removeItem(SESSION_KEY);
localStorage.removeItem(LEGACY_TOKEN_KEY);
};
/**
* Returns the path when it is a path inside this app, else null. The login page uses it to go back after a
+26 -17
View File
@@ -1,28 +1,37 @@
import {describe, expect, it} from 'vitest';
import {isTokenValid, safeReturnPath} from './auth.js';
// @vitest-environment jsdom
import {afterEach, describe, expect, it} from 'vitest';
import {clearSession, hasSession, markSession, safeReturnPath, sessionStamp} from './auth.js';
const tokenWithPayload = (payload) => {
const encode = (obj) => btoa(JSON.stringify(obj)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
return `${encode({alg: 'EdDSA'})}.${encode(payload)}.signature`;
};
afterEach(() => localStorage.clear());
describe('isTokenValid', () => {
const now = Date.UTC(2026, 8, 24, 12, 0, 0);
describe('session flag', () => {
it('is set by a login and removed by clearSession', () => {
expect(hasSession()).toBe(false);
it('accepts a token that expires in the future', () => {
expect(isTokenValid(tokenWithPayload({exp: now / 1000 + 60}), now)).toBe(true);
markSession();
expect(hasSession()).toBe(true);
clearSession();
expect(hasSession()).toBe(false);
});
it('rejects an expired token', () => {
expect(isTokenValid(tokenWithPayload({exp: now / 1000 - 60}), now)).toBe(false);
it('removes the token of the old localStorage login', () => {
localStorage.setItem('tbp_jwt', 'old');
markSession();
expect(localStorage.getItem('tbp_jwt')).toBeNull();
localStorage.setItem('tbp_jwt', 'old');
clearSession();
expect(localStorage.getItem('tbp_jwt')).toBeNull();
});
it('rejects a token without exp', () => {
expect(isTokenValid(tokenWithPayload({sub: 'a@b.de'}), now)).toBe(false);
});
it('gives a new stamp on every mark', async () => {
markSession();
const first = sessionStamp();
await new Promise((resolve) => setTimeout(resolve, 2));
markSession();
it.each([null, '', 'not-a-jwt', 'a.%%%.c'])('rejects %j', (token) => {
expect(isTokenValid(token, now)).toBe(false);
expect(sessionStamp()).not.toBe(first);
});
});