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

@@ -118,7 +118,7 @@ async function toggleUser(id, disable) {
async function impersonateUser(id) {
try {
const data = await API.post(`/api/admin/users/${id}/impersonate`, {});
Auth.setToken(data.access_token);
Auth.setToken(data.user);
window.location.href = '/';
} catch (err) {
showMessage(document.getElementById('msg'), err.message, 'error');

View File

@@ -2,14 +2,11 @@
const API = {
async _fetch(url, options = {}) {
const token = localStorage.getItem('token');
const headers = { 'Content-Type': 'application/json' };
if (token) headers['Authorization'] = `Bearer ${token}`;
const res = await fetch(url, { headers, ...options });
const res = await fetch(url, { credentials: 'include', headers, ...options });
if (res.status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = '/login';
return;
}

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);

110
nginx/html/js/login.js Normal file
View File

@@ -0,0 +1,110 @@
// login.js — login / register page logic
// Redirect if already logged in
(function () {
const raw = localStorage.getItem('user');
if (raw) {
try {
const user = JSON.parse(raw);
if (user.exp > Date.now() / 1000) {
window.location.href = '/';
return;
}
} catch (_) {}
localStorage.removeItem('user');
}
})();
function showLogin() {
document.getElementById('register-panel').style.display = 'none';
document.getElementById('login-panel').style.display = 'block';
document.getElementById('username').focus();
}
function showRegister() {
document.getElementById('login-panel').style.display = 'none';
document.getElementById('register-panel').style.display = 'block';
document.getElementById('reg-username').focus();
}
function showError(elId, text) {
const el = document.getElementById(elId);
el.textContent = text;
el.className = 'message error visible';
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('show-register-link').addEventListener('click', (e) => {
e.preventDefault();
showRegister();
});
document.getElementById('show-login-link').addEventListener('click', (e) => {
e.preventDefault();
showLogin();
});
// ── Login ──
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = document.getElementById('login-btn');
btn.disabled = true;
btn.textContent = 'Signing in…';
document.getElementById('login-msg').className = 'message';
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value;
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (res.status === 429) { showError('login-msg', 'Too many attempts — please wait a minute and try again.'); return; }
if (!res.ok) { showError('login-msg', data.detail || 'Login failed'); return; }
localStorage.setItem('user', JSON.stringify(data.user));
window.location.href = '/';
} catch (err) {
showError('login-msg', 'Could not reach the server. Please try again.');
} finally {
btn.disabled = false;
btn.textContent = 'Sign In';
}
});
// ── Register ──
document.getElementById('reg-form').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = document.getElementById('reg-btn');
const username = document.getElementById('reg-username').value.trim();
const password = document.getElementById('reg-password').value;
const confirm = document.getElementById('reg-confirm').value;
if (password !== confirm) { showError('reg-msg', 'Passwords do not match'); return; }
btn.disabled = true;
btn.textContent = 'Creating account…';
document.getElementById('reg-msg').className = 'message';
try {
const res = await fetch('/api/auth/register', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (!res.ok) { showError('reg-msg', data.detail || 'Registration failed'); return; }
localStorage.setItem('user', JSON.stringify(data.user));
window.location.href = '/';
} catch (err) {
showError('reg-msg', 'Could not reach the server. Please try again.');
} finally {
btn.disabled = false;
btn.textContent = 'Create Account';
}
});
});

View File

@@ -27,7 +27,7 @@
<button type="submit" class="btn btn-primary" style="width:100%" id="login-btn">Sign In</button>
</form>
<p style="text-align:center;margin-top:1rem;font-size:0.9rem;color:var(--muted)">
No account? <a href="#" onclick="showRegister()">Create one</a>
No account? <a href="#" id="show-register-link">Create one</a>
</p>
</div>
@@ -51,112 +51,11 @@
<button type="submit" class="btn btn-primary" style="width:100%" id="reg-btn">Create Account</button>
</form>
<p style="text-align:center;margin-top:1rem;font-size:0.9rem;color:var(--muted)">
Already have an account? <a href="#" onclick="showLogin()">Sign in</a>
Already have an account? <a href="#" id="show-login-link">Sign in</a>
</p>
</div>
</div>
<script>
// Redirect if already logged in
(function () {
const token = localStorage.getItem('token');
if (token) {
try {
const payload = JSON.parse(atob(token.split('.')[1]));
if (payload.exp > Date.now() / 1000) {
window.location.href = '/';
return;
}
} catch (_) {}
localStorage.removeItem('token');
}
})();
function showLogin() {
document.getElementById('register-panel').style.display = 'none';
document.getElementById('login-panel').style.display = 'block';
document.getElementById('username').focus();
}
function showRegister() {
document.getElementById('login-panel').style.display = 'none';
document.getElementById('register-panel').style.display = 'block';
document.getElementById('reg-username').focus();
}
function showError(elId, text) {
const el = document.getElementById(elId);
el.textContent = text;
el.className = 'message error visible';
}
function showSuccess(elId, text) {
const el = document.getElementById(elId);
el.textContent = text;
el.className = 'message success visible';
}
// ── Login ──
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = document.getElementById('login-btn');
btn.disabled = true;
btn.textContent = 'Signing in…';
document.getElementById('login-msg').className = 'message';
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value;
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (res.status === 429) { showError('login-msg', 'Too many attempts — please wait a minute and try again.'); return; }
if (!res.ok) { showError('login-msg', data.detail || 'Login failed'); return; }
localStorage.setItem('token', data.access_token);
window.location.href = '/';
} catch (err) {
showError('login-msg', 'Could not reach the server. Please try again.');
} finally {
btn.disabled = false;
btn.textContent = 'Sign In';
}
});
// ── Register ──
document.getElementById('reg-form').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = document.getElementById('reg-btn');
const username = document.getElementById('reg-username').value.trim();
const password = document.getElementById('reg-password').value;
const confirm = document.getElementById('reg-confirm').value;
if (password !== confirm) { showError('reg-msg', 'Passwords do not match'); return; }
btn.disabled = true;
btn.textContent = 'Creating account…';
document.getElementById('reg-msg').className = 'message';
try {
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (!res.ok) { showError('reg-msg', data.detail || 'Registration failed'); return; }
localStorage.setItem('token', data.access_token);
window.location.href = '/';
} catch (err) {
showError('reg-msg', 'Could not reach the server. Please try again.');
} finally {
btn.disabled = false;
btn.textContent = 'Create Account';
}
});
</script>
<script src="/js/login.js"></script>
</body>
</html>

View File

@@ -31,7 +31,7 @@ http {
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; font-src 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; font-src 'self'; frame-ancestors 'none'" always;
# ── Static files ──────────────────────────────────────────────────────
location / {