Move JWT from localStorage to HttpOnly cookie; fix CSRF

- JWT stored in HttpOnly, Secure, SameSite=Strict cookie — JS cannot
  read the token at all; SameSite=Strict prevents CSRF without tokens
- Non-sensitive user payload returned in response body and stored in
  localStorage for UI purposes only (not usable for auth)
- Add POST /api/auth/logout endpoint that clears the cookie server-side
- Add SECURE_COOKIES env var (default true) for local HTTP testing
- Extract login.html inline script to login.js (CSP compliance)
- Remove Authorization: Bearer header from API calls; add credentials:
  include so cookies are sent automatically
- CSP script-src includes unsafe-inline to support existing onclick
  handlers throughout the app

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-19 23:57:22 -07:00
parent 6d09e40f58
commit 59f9685e2b
10 changed files with 229 additions and 165 deletions

View File

@@ -1,28 +1,25 @@
// auth.js — authentication utilities used by every authenticated page
const Auth = {
getToken() {
return localStorage.getItem('token');
},
setToken(token) {
localStorage.setItem('token', token);
// Store/retrieve the non-sensitive user payload (not the token itself)
setToken(userData) {
localStorage.setItem('user', JSON.stringify(userData));
},
removeToken() {
localStorage.removeItem('token');
localStorage.removeItem('user');
},
getUser() {
const token = this.getToken();
if (!token) return null;
const raw = localStorage.getItem('user');
if (!raw) return null;
try {
const payload = JSON.parse(atob(token.split('.')[1]));
if (payload.exp < Date.now() / 1000) {
const user = JSON.parse(raw);
if (user.exp < Date.now() / 1000) {
this.removeToken();
return null;
}
return payload;
return user;
} catch (_) {
return null;
}
@@ -37,7 +34,10 @@ const Auth = {
return user;
},
logout() {
async logout() {
try {
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
} catch (_) { /* best-effort */ }
this.removeToken();
window.location.href = '/login';
},
@@ -46,7 +46,7 @@ const Auth = {
async function returnToAdmin() {
try {
const data = await API.post('/api/admin/unimpersonate', {});
Auth.setToken(data.access_token);
Auth.setToken(data.user);
window.location.href = '/admin';
} catch (err) {
Auth.logout();
@@ -198,7 +198,7 @@ async function submitTimezone() {
const msgEl = document.getElementById('settings-msg');
try {
const data = await API.put('/api/auth/timezone', { timezone: tz });
Auth.setToken(data.access_token);
Auth.setToken(data.user);
msgEl.textContent = `Timezone saved: ${tz.replace(/_/g, ' ')}`;
msgEl.className = 'message success visible';
setTimeout(() => { msgEl.className = 'message'; }, 3000);