Files
yolkbook/nginx/html/js/api.js
derekc 37f19a83ed Implement security hardening across frontend, backend, and infrastructure
- nginx: add X-Content-Type-Options, X-Frame-Options, X-XSS-Protection,
  and Referrer-Policy headers on all responses; rate limit /api/auth/login
  to 5 req/min per IP (burst 3) to prevent brute force
- frontend: add escHtml() utility to api.js; use it on all notes fields
  across dashboard, log, history, flock, and budget pages to prevent XSS
- log.js: fix broken loadRecent() call referencing removed #recent-body
  element; replaced with loadHistory() from history.js
- schemas.py: raise minimum password length from 6 to 10 characters
- admin.py: add audit logging for password reset, disable, delete, and
  impersonate actions; fix impersonate to use named admin param for logging
- main.py: add startup env validation — exits with clear error if any
  required env var is missing; configure structured logging to stdout
- docker-compose.yml: add log rotation (10 MB / 3 files) to all services

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-17 23:55:08 -07:00

90 lines
3.0 KiB
JavaScript

// api.js — shared fetch helpers and utilities used by every page
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,
});
if (res.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
return;
}
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: res.statusText }));
throw new Error(err.detail || `Request failed (${res.status})`);
}
if (res.status === 204) return null; // DELETE returns No Content
return res.json();
},
get: (url) => API._fetch(url),
post: (url, data) => API._fetch(url, { method: 'POST', body: JSON.stringify(data) }),
put: (url, data) => API._fetch(url, { method: 'PUT', body: JSON.stringify(data) }),
del: (url) => API._fetch(url, { method: 'DELETE' }),
};
// Show a timed success or error message inside a .message element
function showMessage(el, text, type = 'success') {
el.textContent = text;
el.className = `message ${type} visible`;
setTimeout(() => { el.className = 'message'; }, 4000);
}
// Set an input[type=date] to today's date in the user's configured timezone
function setToday(inputEl) {
const tz = (typeof Auth !== 'undefined' && Auth.getUser()?.timezone)
|| Intl.DateTimeFormat().resolvedOptions().timeZone
|| 'UTC';
// en-CA locale produces YYYY-MM-DD which is what date inputs expect
inputEl.value = new Date().toLocaleDateString('en-CA', { timeZone: tz });
}
// Format YYYY-MM-DD → MM/DD/YYYY for display
function fmtDate(str) {
if (!str) return '—';
const [y, m, d] = str.split('-');
return `${m}/${d}/${y}`;
}
// Format a number as a dollar amount
function fmtMoney(val) {
if (val == null || val === '' || isNaN(Number(val))) return '—';
return '$' + Number(val).toFixed(2);
}
// Format a small decimal (cost per egg) with 4 decimal places
function fmtMoneyFull(val) {
if (val == null || val === '' || isNaN(Number(val))) return '—';
return '$' + Number(val).toFixed(4);
}
// Escape HTML special characters to prevent XSS when rendering user content
function escHtml(str) {
if (!str) return '';
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
// Highlight the nav link that matches the current page
function highlightNav() {
const path = window.location.pathname.replace(/\.html$/, '').replace(/\/$/, '') || '/';
document.querySelectorAll('.nav-links a').forEach(a => {
const href = a.getAttribute('href').replace(/\/$/, '') || '/';
if (href === path) a.classList.add('active');
});
}
document.addEventListener('DOMContentLoaded', highlightNav);