Codebase audits, privacy, dark mode, palette (v1.9.0 to v1.9.4-audit) #14

Merged
ngu-git-admin merged 30 commits from audit into main 2026-09-29 18:07:25 +01:00
23 changed files with 420 additions and 139 deletions
Showing only changes of commit f72a9604d2 - Show all commits

View file

@ -34,6 +34,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`.
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`.
- Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`.
- Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`.
- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`. - Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`.
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.md`. - Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.md`.

71
docs/performance.md Normal file
View file

@ -0,0 +1,71 @@
# Performance
What keeps the site fast, and what nginx has to do for it.
## nginx
In the site's `server` block (both are in `nginx-dev`):
```nginx
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/css application/javascript text/javascript application/json
image/svg+xml application/xml application/rss+xml text/plain;
listen 443 ssl http2;
listen [::]:443 ssl http2;
```
Ubuntu's `nginx.conf` turns gzip on for `text/html` only, so without
`gzip_types` the JS, CSS, JSON and SVG go out full size (the main JS is
about 314 kB, about 98 kB gzipped). Check with
`curl -sI -H 'Accept-Encoding: gzip' https://<site>/assets/<file>.js | grep -i content-encoding`.
`http2` on the `listen` line works on every nginx; 1.25.1 and later
also take a separate `http2 on;`.
## Caching
- `/assets/` (hashed build files): a year, `immutable` (nginx).
- `/uploads/`: 30 days, `immutable` (nginx). Filenames are random and
never reused.
- Page HTML: `no-cache` (the API, `routes/pages.js`). The page names the
build's hashed assets, so a cached old page after a deploy would ask
for files that are gone.
- Public API reads: 60 s, plus 5 minutes stale while revalidating
(`CACHE` in `server/src/shape.js`).
- RSS feeds: read at most every 30 minutes; a visitor never waits for
one after the first read (`server/src/feeds.js`).
## The bundle
Only the home page is in the main bundle. Every other page, and the
whole admin, loads when first visited (`src/App.tsx`). A tab still
running an old build that asks for a page removed by a deploy reloads
once to pick up the new one.
The home page asks for events and the timeline alongside its own data
(`src/pages/Home.tsx`), and the server tells the browser to fetch
`/api/front-page` and the first hero photo while the JS downloads
(`preload` in `server/src/pageMeta.js`).
## Images
Every raster upload gets a copy at most 640 px on its longer side,
`<name>-640.webp`, beside it in the uploads folder
(`server/src/media.js`). Logos, avatars and card pictures load that copy
(`useSmallImage` in `src/lib/useSmallImage.ts`) and fall back to the
full file if it's missing. The server makes any missing copies in the
background when it starts, so older uploads and files copied in by hand
get one too; deleting an upload deletes its copy.
## Server
- Password checks run off the event loop (`verifyPassword`, async
scrypt), so a login doesn't stall other requests.
- Only `/api/admin/*` is logged per request; nginx's access log has the
rest.
- ffmpeg encodes run at `nice 19` on Linux, so a clip doesn't slow the
site down.

View file

@ -18,9 +18,11 @@
import { import {
createHash, createHash,
randomBytes, randomBytes,
scrypt,
scryptSync, scryptSync,
timingSafeEqual, timingSafeEqual,
} from "node:crypto"; } from "node:crypto";
import { promisify } from "node:util";
import { getCookie, setCookie, deleteCookie } from "hono/cookie"; import { getCookie, setCookie, deleteCookie } from "hono/cookie";
const SESSION_DAYS = 30; const SESSION_DAYS = 30;
@ -68,7 +70,11 @@ export function hashPassword(password) {
].join("$"); ].join("$");
} }
export function verifyPassword(password, stored) { /* Async: a login's hash runs on libuv's thread pool, so the ~100 ms it
takes doesn't stall every other request while it runs. */
const scryptAsync = promisify(scrypt);
export async function verifyPassword(password, stored) {
if (typeof stored !== "string") return false; if (typeof stored !== "string") return false;
const [scheme, N, r, p, saltHex, keyHex] = stored.split("$"); const [scheme, N, r, p, saltHex, keyHex] = stored.split("$");
@ -76,7 +82,7 @@ export function verifyPassword(password, stored) {
let candidate; let candidate;
try { try {
candidate = scryptSync( candidate = await scryptAsync(
password.normalize("NFKC"), password.normalize("NFKC"),
Buffer.from(saltHex, "hex"), Buffer.from(saltHex, "hex"),
Buffer.from(keyHex, "hex").length, Buffer.from(keyHex, "hex").length,

View file

@ -150,11 +150,16 @@ export function checkClip(input, source) {
/* Runs a tool, calling onLine for each line of its output, and /* Runs a tool, calling onLine for each line of its output, and
resolves with the tail of stderr, or rejects with it. */ resolves with the tail of stderr, or rejects with it. */
function run(command, args, { onLine } = {}) { function run(command, args, { onLine, background = false } = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let child; let child;
// An encode takes every core it can get; at the lowest priority it
// still does, but the API and its pages come first. Linux only
// (the VPS); elsewhere it runs as it is.
const [cmd, argv] =
background && process.platform === "linux" ? ["nice", ["-n", "19", command, ...args]] : [command, args];
try { try {
child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); child = spawn(cmd, argv, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
} catch (err) { } catch (err) {
reject(err); reject(err);
return; return;
@ -425,6 +430,7 @@ async function cut(db, job) {
args.push("-progress", "pipe:1", "-nostats", filePath(name)); args.push("-progress", "pipe:1", "-nostats", filePath(name));
await run(FFMPEG, args, { await run(FFMPEG, args, {
background: true,
onLine: (line) => { onLine: (line) => {
const us = line.match(/^out_time_us=(\d+)/); const us = line.match(/^out_time_us=(\d+)/);
if (us) update(db, job.id, { progress: Math.min(0.99, Number(us[1]) / 1e6 / length) }); if (us) update(db, job.id, { progress: Math.min(0.99, Number(us[1]) / 1e6 / length) });

View file

@ -35,7 +35,7 @@ import adminEntities from "./routes/admin-entities.js";
import media from "./routes/media.js"; import media from "./routes/media.js";
import clips from "./routes/clips.js"; import clips from "./routes/clips.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js"; import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR } from "./media.js"; import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js"; import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { ENTITIES } from "./admin-schema.js"; import { ENTITIES } from "./admin-schema.js";
@ -53,12 +53,20 @@ syncDescriptorsWithSchema(db, ENTITIES);
console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`); console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`);
await mkdir(UPLOADS_DIR, { recursive: true }); await mkdir(UPLOADS_DIR, { recursive: true });
console.log(`uploads ${UPLOADS_DIR}`); console.log(`uploads ${UPLOADS_DIR}`);
// In the background: pages fall back to the full file until it's done.
writeMissingThumbs()
.then((made) => made && console.log(`uploads: made ${made} small copies`))
.catch((err) => console.warn(`uploads: small copies failed: ${err.message}`));
/* ── App ─────────────────────────────────────────────────────── */ /* ── App ─────────────────────────────────────────────────────── */
const app = new Hono(); const app = new Hono();
app.use("*", logger()); // One log line per admin request, for the record of who did what.
// Public traffic is left to nginx's access log: logging every request
// here too would double the lines and, under a spike, cost the event
// loop a synchronous write each.
app.use("/api/admin/*", logger());
/* Headers for every response. Referrer kept to the origin (YouTube /* Headers for every response. Referrer kept to the origin (YouTube
embeds refuse to play without one). No HSTS here: nginx sends it on embeds refuse to play without one). No HSTS here: nginx sends it on

View file

@ -172,6 +172,7 @@ export async function store(buf, { keepOriginal = false } = {}) {
const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`); const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`);
await writeFile(tmp, out); await writeFile(tmp, out);
await rename(tmp, path.join(UPLOADS_DIR, filename)); await rename(tmp, path.join(UPLOADS_DIR, filename));
if (kind !== "svg") await writeThumb(filename, out);
return { return {
filename, filename,
@ -183,18 +184,74 @@ export async function store(buf, { keepOriginal = false } = {}) {
}; };
} }
/* Deletes one stored file. A file that's already gone is not an /* ── Small copies ──────────────────────────────────────────────
error: the row is what's being removed. */ Beside every raster upload, <name>-640.webp: the same image at most
640px on its longer side. Photos and logos shown small (avatars,
cards, marks) load it instead of the full file; the page falls back
to the full file if it's missing (src/lib/media.ts, mediaThumb).
Made when a file is uploaded, and at boot for any upload that
doesn't have one yet (files from before this, or copied in by hand).
───────────────────────────────────────────────────────────── */
export const THUMB_EDGE = 640;
const THUMB = /-640\.webp$/;
export const thumbName = (filename) => `${filename.replace(/\.[^.]+$/, "")}-640.webp`;
async function writeThumb(filename, buf) {
const name = thumbName(filename);
const tmp = path.join(UPLOADS_DIR, `.${name}.tmp`);
try {
await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
.rotate()
.resize({ width: THUMB_EDGE, height: THUMB_EDGE, fit: "inside", withoutEnlargement: true })
.webp({ quality: WEBP_QUALITY })
.toFile(tmp);
await rename(tmp, path.join(UPLOADS_DIR, name));
} catch (err) {
// The full file is what matters; without a copy the page uses it.
await unlink(tmp).catch(() => {});
console.warn(`media: no small copy of ${filename}: ${err.message}`);
}
}
/* Makes the small copy for every raster upload that lacks one.
Returns how many it made. */
export async function writeMissingThumbs() {
let names;
try {
names = await readdir(UPLOADS_DIR);
} catch (err) {
if (err.code === "ENOENT") return 0;
throw err;
}
const present = new Set(names);
let made = 0;
for (const name of names) {
if (name.startsWith(".") || THUMB.test(name) || /\.svg$/i.test(name)) continue;
if (present.has(thumbName(name))) continue;
const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null);
if (!buf || !sniff(buf) || sniff(buf) === "svg") continue;
await writeThumb(name, buf);
made += 1;
}
return made;
}
/* Deletes one stored file and its small copy. A file that's already
gone is not an error: the row is what's being removed. */
export async function remove(filename) { export async function remove(filename) {
// filename comes from our own table, but it's joined onto a // filename comes from our own table, but it's joined onto a
// directory, so refuse anything that isn't a bare name. // directory, so refuse anything that isn't a bare name.
if (path.basename(filename) !== filename) return; if (path.basename(filename) !== filename) return;
for (const name of [filename, thumbName(filename)]) {
try { try {
await unlink(path.join(UPLOADS_DIR, filename)); await unlink(path.join(UPLOADS_DIR, name));
} catch (err) { } catch (err) {
if (err.code !== "ENOENT") throw err; if (err.code !== "ENOENT") throw err;
} }
} }
}
/* ── Files copied in by hand ─────────────────────────────────── */ /* ── Files copied in by hand ─────────────────────────────────── */
@ -252,7 +309,7 @@ export async function registerLooseFiles(db) {
let added = 0; let added = 0;
for (const name of names) { for (const name of names) {
if (known.has(name) || name.startsWith(".") || path.basename(name) !== name) continue; if (known.has(name) || name.startsWith(".") || THUMB.test(name) || path.basename(name) !== name) continue;
let row; let row;
try { try {
row = await describe(name); row = await describe(name);

View file

@ -0,0 +1,10 @@
-- ═══════════════════════════════════════════════════════════════
-- 042 AWARD RECIPIENTS BY AWARD
--
-- person_awards is read by award (an award's page lists its
-- recipients, an organization counts them), but its only index
-- starts with person_id, so those reads scan the table. Tiny today;
-- this keeps it from mattering later.
-- ═══════════════════════════════════════════════════════════════
CREATE INDEX person_awards_award_idx ON person_awards (award_id);

View file

@ -347,8 +347,23 @@ export function metaFor(db, rawPath) {
const meta = defaults(site, db, pathname); const meta = defaults(site, db, pathname);
if (pathname === "/") { if (pathname === "/") {
// The home page's data, and its first hero photo when the hero is
// a slideshow, requested alongside the app's JavaScript instead of
// after it has run.
const hero = db.prepare(`SELECT hero_backdrop FROM front_page WHERE id = 'home'`).get();
const slide =
hero?.hero_backdrop === "photos"
? db
.prepare(`SELECT media FROM front_page_slides WHERE page_id = 'home' ORDER BY sort_order LIMIT 1`)
.get()
: null;
const slideSrc = slide?.media ? (/^(https?:|\/)/.test(slide.media) ? slide.media : `${UPLOADS}/${slide.media}`) : null;
return { return {
...meta, ...meta,
preload: [
{ href: "/api/front-page", as: "fetch" },
...(slideSrc ? [{ href: slideSrc, as: "image" }] : []),
],
jsonLd: { jsonLd: {
"@context": "https://schema.org", "@context": "https://schema.org",
"@type": "Organization", "@type": "Organization",
@ -446,6 +461,11 @@ export function renderPage(html, meta) {
site.icons?.icon && `<link rel="icon" href="${escapeHtml(site.icons.icon)}">`, site.icons?.icon && `<link rel="icon" href="${escapeHtml(site.icons.icon)}">`,
site.icons?.apple && `<link rel="apple-touch-icon" href="${escapeHtml(site.icons.apple)}">`, site.icons?.apple && `<link rel="apple-touch-icon" href="${escapeHtml(site.icons.apple)}">`,
meta.jsonLd && `<script type="application/ld+json">${scriptJson(meta.jsonLd)}</script>`, meta.jsonLd && `<script type="application/ld+json">${scriptJson(meta.jsonLd)}</script>`,
...(meta.preload ?? []).map((p) =>
p.as === "fetch"
? `<link rel="preload" href="${escapeHtml(p.href)}" as="fetch" crossorigin>`
: `<link rel="preload" href="${escapeHtml(p.href)}" as="image" fetchpriority="high">`,
),
// Read by src/lib/site.ts before the app's module runs (a plain // Read by src/lib/site.ts before the app's module runs (a plain
// script in the head runs during parsing; modules wait). // script in the head runs during parsing; modules wait).
`<script>window.__NGU_SITE__ = ${scriptJson(forBrowser(site))}</script>`, `<script>window.__NGU_SITE__ = ${scriptJson(forBrowser(site))}</script>`,

View file

@ -94,8 +94,8 @@ auth.post("/login", async (c) => {
const ok = const ok =
user && user.is_active === 1 user && user.is_active === 1
? verifyPassword(password, user.password_hash) ? await verifyPassword(password, user.password_hash)
: (verifyPassword(password, DUMMY_HASH), false); : (await verifyPassword(password, DUMMY_HASH), false);
if (!ok) { if (!ok) {
loginFailures.fail(email); loginFailures.fail(email);

View file

@ -120,8 +120,12 @@ pages.get("*", (c, next) => {
return c.html(html, 200, { "Cache-Control": "no-store" }); return c.html(html, 200, { "Cache-Control": "no-store" });
} }
// no-cache: a browser may keep the page but asks again each time.
// HTML names the build's hashed /assets files, and after a deploy
// those are gone, so a cached old page would load nothing. Pages
// are rebuilt in well under a millisecond.
return c.html(page, meta.status, { return c.html(page, meta.status, {
"Cache-Control": meta.status === 200 ? CACHE : "no-store", "Cache-Control": meta.status === 200 ? "no-cache" : "no-store",
}); });
}); });

View file

@ -1,50 +1,86 @@
import { BrowserRouter, Routes, Route, Outlet, Navigate } from "react-router-dom"; import {
import { lazy, Suspense } from "react"; BrowserRouter,
Routes,
Route,
Outlet,
Navigate,
} from "react-router-dom"
import { lazy, Suspense } from "react"
/*Components*/ /*Components*/
import Layout from "./components/Layout.tsx"; import Layout from "./components/Layout.tsx"
/*Libraries*/ /*Libraries*/
import { AuthProvider, RequireAuth } from "./lib/auth.tsx"; import { AuthProvider, RequireAuth } from "./lib/auth.tsx"
import RequireRole from "./pages/admin/RequireRole.tsx"; import RequireRole from "./pages/admin/RequireRole.tsx"
/*Primary Pages*/ /*Pages*/
import Home from "./pages/Home.tsx"; // Home is the landing page, so it ships in the main bundle. Every
import Retreats from "./pages/Retreats.tsx"; // other page, and all of the admin, is fetched when first visited:
import Community from "./pages/Community.tsx"; // a visitor to the front page never downloads the admin, the QR
import Leadership from "./pages/Leadership.tsx"; // encoder, the calendar or the chapter map. Layout and AdminLayout
import Resources from "./pages/Resources.tsx"; // wrap their <Outlet /> in <Suspense>, so the header stays put while
import History from "./pages/History.tsx"; // a page loads.
import Home from "./pages/Home.tsx"
/*Secondary Pages*/ /* A page's chunk can be missing when a deploy replaced the build while
import Feedback from "./pages/Feedback.tsx"; this tab still ran the old one. Reload once to pick up the new
import Giving from "./pages/Giving.tsx"; build; if that doesn't help, let the error surface. */
const CHUNK_RELOAD = "ngu-chunk-reload"
const lazyPage = (load) =>
lazy(() =>
load()
.then((page) => {
try {
sessionStorage.removeItem(CHUNK_RELOAD)
} catch {}
return page
})
.catch((err) => {
const key = CHUNK_RELOAD
let reloaded = false
try {
reloaded = sessionStorage.getItem(key) === "1"
sessionStorage.setItem(key, "1")
} catch {}
if (!reloaded) {
window.location.reload()
return new Promise(() => {})
}
throw err
}),
)
const Retreats = lazyPage(() => import("./pages/Retreats.tsx"))
const Community = lazyPage(() => import("./pages/Community.tsx"))
const Leadership = lazyPage(() => import("./pages/Leadership.tsx"))
const Resources = lazyPage(() => import("./pages/Resources.tsx"))
const History = lazyPage(() => import("./pages/History.tsx"))
const Feedback = lazyPage(() => import("./pages/Feedback.tsx"))
const Giving = lazyPage(() => import("./pages/Giving.tsx"))
const QrCodes = lazyPage(() => import("./pages/QrCodes.tsx"))
const Privacy = lazyPage(() => import("./pages/Privacy.tsx"))
const Terms = lazyPage(() => import("./pages/Terms.tsx"))
const NotFound = lazyPage(() => import("./pages/NotFound.tsx"))
/*Entity Pages*/ /*Entity Pages*/
import EventDetail from './pages/EventDetail.tsx' const EventDetail = lazyPage(() => import("./pages/EventDetail.tsx"))
import OrganizationDetail from './pages/OrganizationDetail.tsx' const OrganizationDetail = lazyPage(
import TeamDetail from './pages/TeamDetail.tsx' () => import("./pages/OrganizationDetail.tsx"),
import AwardDetail from './pages/AwardDetail.tsx' )
import PersonDetail from './pages/PersonDetail.tsx' const TeamDetail = lazyPage(() => import("./pages/TeamDetail.tsx"))
import BlogPost from './pages/BlogPost.tsx' const AwardDetail = lazyPage(() => import("./pages/AwardDetail.tsx"))
const PersonDetail = lazyPage(() => import("./pages/PersonDetail.tsx"))
const BlogPost = lazyPage(() => import("./pages/BlogPost.tsx"))
/*Admin Pages*/ /*Admin Pages*/
import AdminLayout from "./pages/admin/AdminLayout.tsx"; const AdminLayout = lazyPage(() => import("./pages/admin/AdminLayout.tsx"))
import AdminLogin from "./pages/admin/AdminLogin.tsx"; const AdminLogin = lazyPage(() => import("./pages/admin/AdminLogin.tsx"))
import AdminPanel from "./pages/admin/AdminPanel.tsx"; const AdminPanel = lazyPage(() => import("./pages/admin/AdminPanel.tsx"))
import AdminHome from "./pages/admin/AdminHome.tsx"; const AdminHome = lazyPage(() => import("./pages/admin/AdminHome.tsx"))
import AdminFeedback from "./pages/admin/AdminFeedback.tsx"; const AdminFeedback = lazyPage(() => import("./pages/admin/AdminFeedback.tsx"))
import AdminMedia from "./pages/admin/AdminMedia.tsx"; const AdminMedia = lazyPage(() => import("./pages/admin/AdminMedia.tsx"))
import AdminClips from "./pages/admin/AdminClips.tsx"; const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx"))
import EntityList from "./pages/admin/EntityList.tsx"; const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
import EntityEdit from "./pages/admin/EntityEdit.tsx"; const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
/*Ternary Pages*/
import Privacy from "./pages/Privacy.tsx";
import Terms from "./pages/Terms.tsx";
import NotFound from "./pages/NotFound.tsx";
// Loaded on demand: it brings the QR encoder, which no other page needs.
const QrCodes = lazy(() => import("./pages/QrCodes.tsx"));
export default function App() { export default function App() {
return ( return (
@ -68,13 +104,21 @@ export default function App() {
<Route path="resources" element={<Resources />} /> <Route path="resources" element={<Resources />} />
<Route path="history" element={<History />} /> <Route path="history" element={<History />} />
<Route path="feedback" element={<Feedback />} /> <Route path="feedback" element={<Feedback />} />
<Route path="qr" element={<Suspense fallback={null}><QrCodes /></Suspense>} /> <Route path="qr" element={<QrCodes />} />
<Route path="give" element={<Giving />} /> <Route path="give" element={<Giving />} />
<Route path="privacy" element={<Privacy />} /> <Route path="privacy" element={<Privacy />} />
<Route path="terms" element={<Terms />} /> <Route path="terms" element={<Terms />} />
<Route path="*" element={<NotFound />} /> <Route path="*" element={<NotFound />} />
</Route> </Route>
<Route element={<AuthProvider><Outlet /></AuthProvider>}> <Route
element={
<AuthProvider>
<Suspense fallback={null}>
<Outlet />
</Suspense>
</AuthProvider>
}
>
<Route path="/admin/login" element={<AdminLogin />} /> <Route path="/admin/login" element={<AdminLogin />} />
<Route element={<RequireAuth />}> <Route element={<RequireAuth />}>
<Route path="/admin" element={<AdminLayout />}> <Route path="/admin" element={<AdminLayout />}>
@ -95,5 +139,5 @@ export default function App() {
</Route> </Route>
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>
); )
} }

View file

@ -18,13 +18,13 @@
panel instead, since cropping a logo to 16:9 cuts it off. panel instead, since cropping a logo to 16:9 cuts it off.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { useState } from 'react'
import HomeLink from '../pages/sections/home/HomeLink.tsx' import HomeLink from '../pages/sections/home/HomeLink.tsx'
import VideoPlayer from './VideoPlayer.tsx' import VideoPlayer from './VideoPlayer.tsx'
import { refHref } from '../lib/hrefs.ts' import { refHref } from '../lib/hrefs.ts'
import { mediaUrl } from '../lib/media.ts' import { mediaUrl } from '../lib/media.ts'
import type { FeaturedCard } from '../lib/useFrontPage.ts' import type { FeaturedCard } from '../lib/useFrontPage.ts'
import { useSmallImage } from '../lib/useSmallImage.ts'
/* Image kinds that are photographs, drawn edge to edge. Anything /* Image kinds that are photographs, drawn edge to edge. Anything
else is a logo, drawn whole. */ else is a logo, drawn whole. */
@ -38,29 +38,28 @@ function hrefFor(card: FeaturedCard): string | null {
} }
function Picture({ card }: { card: FeaturedCard }) { function Picture({ card }: { card: FeaturedCard }) {
const [failed, setFailed] = useState(false) const img = useSmallImage(card.image ? mediaUrl(card.image.file) : null)
const src = card.image ? mediaUrl(card.image.file) : null
const photo = card.image ? PHOTO_KINDS.has(card.image.kind) : false const photo = card.image ? PHOTO_KINDS.has(card.image.kind) : false
if (!src || failed) { if (img.failed) {
return <div className="aspect-video w-full bg-tint" /> return <div className="aspect-video w-full bg-tint" />
} }
return photo ? ( return photo ? (
<img <img
src={src} src={img.src}
alt="" alt=""
loading="lazy" loading="lazy"
onError={() => setFailed(true)} onError={img.onError}
className="aspect-video w-full object-cover" className="aspect-video w-full object-cover"
/> />
) : ( ) : (
<div className="flex aspect-video w-full items-center justify-center bg-tint p-8"> <div className="flex aspect-video w-full items-center justify-center bg-tint p-8">
<img <img
src={src} src={img.src}
alt="" alt=""
loading="lazy" loading="lazy"
onError={() => setFailed(true)} onError={img.onError}
className="max-h-full max-w-full object-contain" className="max-h-full max-w-full object-contain"
/> />
</div> </div>

View file

@ -1,4 +1,4 @@
import { useState, useEffect, useRef } from "react"; import { Suspense, useState, useEffect, useRef } from "react";
import { NavLink, Link, Outlet, useLocation } from "react-router-dom"; import { NavLink, Link, Outlet, useLocation } from "react-router-dom";
import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts"; import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts";
import Banner from "./Banner.tsx"; import Banner from "./Banner.tsx";
@ -268,7 +268,9 @@ export default function Layout() {
{/* Page content */} {/* Page content */}
<main id="main" tabIndex={-1} className="outline-none" inert={mobileMenuOpen}> <main id="main" tabIndex={-1} className="outline-none" inert={mobileMenuOpen}>
<Suspense fallback={null}>
<Outlet /> <Outlet />
</Suspense>
</main> </main>
{/*Site Footer applied to every page*/} {/*Site Footer applied to every page*/}

View file

@ -3,12 +3,14 @@
An <img> for a logo or mark that may not exist: no src, or a file An <img> for a logo or mark that may not exist: no src, or a file
that 404s, and it draws `fallback` instead (initials, a colour dot, that 404s, and it draws `fallback` instead (initials, a colour dot,
or nothing). `src` is already resolved (mediaUrl in media.ts). or nothing). `src` is already resolved (mediaUrl in media.ts). An
Decorative by default (alt ""), since a logo sits next to the upload loads its 640px copy first (useSmallImage). Decorative by
name it stands for. default (alt ""), since a logo sits next to the name it stands for.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { useState, type ReactNode } from 'react' import type { ReactNode } from 'react'
import { useSmallImage } from '../lib/useSmallImage.ts'
export default function Logo({ export default function Logo({
src, src,
@ -21,7 +23,7 @@ export default function Logo({
className?: string className?: string
fallback?: ReactNode fallback?: ReactNode
}) { }) {
const [failed, setFailed] = useState(false) const img = useSmallImage(src)
if (!src || failed) return <>{fallback}</> if (img.failed) return <>{fallback}</>
return <img src={src} alt={alt} loading="lazy" className={className} onError={() => setFailed(true)} /> return <img src={img.src} alt={alt} loading="lazy" className={className} onError={img.onError} />
} }

View file

@ -13,6 +13,7 @@ import { Link } from "react-router-dom";
import { get } from "../lib/api.ts"; import { get } from "../lib/api.ts";
import { isBadId, personHref } from "../lib/hrefs.ts"; import { isBadId, personHref } from "../lib/hrefs.ts";
import { mediaUrl, initials } from "../lib/media.ts"; import { mediaUrl, initials } from "../lib/media.ts";
import { useSmallImage } from "../lib/useSmallImage.ts";
import "./PeopleTiles.css"; import "./PeopleTiles.css";
/** /**
@ -588,13 +589,9 @@ function Tile({
} }
function Photo({ src, name }: { src?: string | null; name: string }) { function Photo({ src, name }: { src?: string | null; name: string }) {
const [failed, setFailed] = useState(false); const img = useSmallImage(src);
useEffect(() => { if (img.failed) {
setFailed(false);
}, [src]);
if (!src || failed) {
return ( return (
<span className="pl__initials" aria-hidden="true"> <span className="pl__initials" aria-hidden="true">
{initials(name)} {initials(name)}
@ -605,11 +602,11 @@ function Photo({ src, name }: { src?: string | null; name: string }) {
return ( return (
<img <img
className="pl__img" className="pl__img"
src={src} src={img.src}
alt="" alt=""
loading="lazy" loading="lazy"
decoding="async" decoding="async"
onError={() => setFailed(true)} onError={img.onError}
/> />
); );
} }

View file

@ -28,6 +28,7 @@ import { mediaUrl, initials } from '../lib/media.ts'
import type { ContentBlockItem } from '../lib/useContent.ts' import type { ContentBlockItem } from '../lib/useContent.ts'
import { Anchor, Paragraphs } from './InlineText.tsx' import { Anchor, Paragraphs } from './InlineText.tsx'
import { withAlpha, accentText, readableOn } from '../lib/color.ts' import { withAlpha, accentText, readableOn } from '../lib/color.ts'
import { useSmallImage } from '../lib/useSmallImage.ts'
const BODY = 'var(--color-muted)' const BODY = 'var(--color-muted)'
const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
@ -65,10 +66,9 @@ const mapLink = (place: string) =>
`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(place)}` `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(place)}`
function Avatar({ person, size }: { person: NonNullable<ContentBlockItem['person']>; size: string }) { function Avatar({ person, size }: { person: NonNullable<ContentBlockItem['person']>; size: string }) {
const [failed, setFailed] = useState(false) const img = useSmallImage(mediaUrl(person.photo))
const src = mediaUrl(person.photo) return !img.failed ? (
return src && !failed ? ( <img src={img.src} alt="" onError={img.onError} className={`${size} shrink-0 rounded-full object-cover`} />
<img src={src} alt="" onError={() => setFailed(true)} className={`${size} shrink-0 rounded-full object-cover`} />
) : ( ) : (
<span <span
aria-hidden="true" aria-hidden="true"

36
src/lib/useSmallImage.ts Normal file
View file

@ -0,0 +1,36 @@
/* ═══════════════════════════════════════════════════════════════
useSmallImage
For an upload shown small (an avatar, a logo, a card picture):
try its 640px copy first (<name>-640.webp, which the server makes
beside every raster upload, server/src/media.js), then the full
file if the copy isn't there, then give up so the caller can draw
its fallback. Anything that isn't an upload, and SVGs, go straight
to the full file.
const img = useSmallImage(mediaUrl(person.photo))
img.failed ? <Initials /> : <img src={img.src} onError={img.onError} />
═══════════════════════════════════════════════════════════════ */
import { useEffect, useState } from 'react'
/* '/uploads/abc.webp' → '/uploads/abc-640.webp'; null for anything else. */
export function smallCopy(src?: string | null): string | null {
if (!src || !src.startsWith('/uploads/') || /\.svg(\?|#|$)/i.test(src)) return null
return src.replace(/\.[^./?#]+(?=$|[?#])/, '') + '-640.webp'
}
export function useSmallImage(src?: string | null) {
// 0: the small copy (when there is one), 1: the full file, 2: failed
const [stage, setStage] = useState(0)
useEffect(() => setStage(0), [src])
const small = smallCopy(src)
const current = !src ? null : stage === 0 && small ? small : stage <= 1 ? src : null
return {
src: current ?? undefined,
failed: current === null,
onError: () => setStage((s) => (s === 0 && small ? 1 : 2)),
}
}

View file

@ -33,6 +33,7 @@ import StatsBand from './sections/home/StatsBand.tsx'
import FeaturedBand from './sections/home/FeaturedBand.tsx' import FeaturedBand from './sections/home/FeaturedBand.tsx'
import FeaturedTimelineRail from './sections/home/FeaturedTimelineRail.tsx' import FeaturedTimelineRail from './sections/home/FeaturedTimelineRail.tsx'
import Pathfinder from './sections/home/Pathfinder.tsx' import Pathfinder from './sections/home/Pathfinder.tsx'
import { get } from '../lib/api.ts'
import { documentTitle } from '../lib/site.ts' import { documentTitle } from '../lib/site.ts'
import { import {
useFrontPage, useFrontPage,
@ -105,6 +106,15 @@ const SECTIONS: Record<
export default function Home() { export default function Home() {
const { data: page, error, reload } = useFrontPage() const { data: page, error, reload } = useFrontPage()
// The bands below ask for events and the timeline once the front
// page has said which of them to show. Start both now, alongside it:
// api.ts hands the same request to the bands when they mount, so
// the page waits for one round trip instead of two.
useEffect(() => {
get('/events').catch(() => {})
get('/history').catch(() => {})
}, [])
// Back to the site name when a visitor returns here from a page. // Back to the site name when a visitor returns here from a page.
useEffect(() => { useEffect(() => {
document.title = documentTitle() document.title = documentTitle()

View file

@ -20,7 +20,7 @@
The route guard and the API are what actually say no. The route guard and the API are what actually say no.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { useCallback, useEffect, useMemo, useState } from "react"; import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { Link, NavLink, Outlet, useLocation, useNavigate } from "react-router-dom"; import { Link, NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "../../lib/auth.tsx"; import { useAuth } from "../../lib/auth.tsx";
import { AdminTitleContext } from "../../lib/adminTitle.tsx"; import { AdminTitleContext } from "../../lib/adminTitle.tsx";
@ -210,7 +210,9 @@ export default function AdminLayout() {
<main className={`mx-auto w-full flex-1 px-6 py-10 ${wide ? "max-w-[82rem]" : "max-w-5xl"}`}> <main className={`mx-auto w-full flex-1 px-6 py-10 ${wide ? "max-w-[82rem]" : "max-w-5xl"}`}>
<AdminTitleContext.Provider value={titleContext}> <AdminTitleContext.Provider value={titleContext}>
<AdminWidthContext.Provider value={setWide}> <AdminWidthContext.Provider value={setWide}>
<Suspense fallback={null}>
<Outlet /> <Outlet />
</Suspense>
</AdminWidthContext.Provider> </AdminWidthContext.Provider>
</AdminTitleContext.Provider> </AdminTitleContext.Provider>
</main> </main>

View file

@ -25,6 +25,7 @@ import { preview } from '../../lib/text.ts'
import { postDate, useCommunityBlog, type BlogPostSummary } from '../../lib/useBlog.ts' import { postDate, useCommunityBlog, type BlogPostSummary } from '../../lib/useBlog.ts'
import HomeLink from './home/HomeLink.tsx' import HomeLink from './home/HomeLink.tsx'
import { accentText } from '../../lib/color.ts' import { accentText } from '../../lib/color.ts'
import { useSmallImage } from '../../lib/useSmallImage.ts'
/* Headings for a half the admin didn't title. */ /* Headings for a half the admin didn't title. */
const DEFAULTS = { const DEFAULTS = {
@ -36,14 +37,14 @@ const DEFAULTS = {
const EXCERPT_CHARS = 180 const EXCERPT_CHARS = 180
function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) { function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) {
const cover = mediaUrl(post.cover_image) const cover = useSmallImage(mediaUrl(post.cover_image))
const date = postDate(post.published_on) const date = postDate(post.published_on)
const authors = post.authors.map((author) => author.name).join(', ') const authors = post.authors.map((author) => author.name).join(', ')
return ( return (
<li className="relative flex flex-col overflow-hidden rounded-2xl border border-brand/15 bg-surface shadow-sm transition-shadow hover:shadow-lg"> <li className="relative flex flex-col overflow-hidden rounded-2xl border border-brand/15 bg-surface shadow-sm transition-shadow hover:shadow-lg">
{cover ? ( {!cover.failed ? (
<img src={cover} alt="" loading="lazy" className="aspect-video w-full object-cover" /> <img src={cover.src} alt="" loading="lazy" onError={cover.onError} className="aspect-video w-full object-cover" />
) : ( ) : (
<div className="aspect-video w-full bg-tint" /> <div className="aspect-video w-full bg-tint" />
)} )}

View file

@ -2,6 +2,7 @@ import { Link } from 'react-router-dom'
import { MONTH_LABELS, type PersonRef, type TimelineItem } from '../../../lib/timeline.ts' import { MONTH_LABELS, type PersonRef, type TimelineItem } from '../../../lib/timeline.ts'
import { hrefFor, logoSrc } from '../../../lib/timelineRefs.ts' import { hrefFor, logoSrc } from '../../../lib/timelineRefs.ts'
import { initials, mediaUrl } from '../../../lib/media.ts' import { initials, mediaUrl } from '../../../lib/media.ts'
import { useSmallImage } from '../../../lib/useSmallImage.ts'
const KIND_NAMES: Record<TimelineItem['kind'], string> = { const KIND_NAMES: Record<TimelineItem['kind'], string> = {
milestone: 'Milestone', milestone: 'Milestone',
@ -28,11 +29,11 @@ function fullMarker(item: TimelineItem): string {
} }
function PersonChip({ person }: { person: PersonRef }) { function PersonChip({ person }: { person: PersonRef }) {
const src = mediaUrl(person.photo) const img = useSmallImage(mediaUrl(person.photo))
return ( return (
<li className="ngu-tl__person"> <li className="ngu-tl__person">
{src ? ( {!img.failed ? (
<img className="ngu-tl__personPhoto" src={src} alt="" loading="lazy" /> <img className="ngu-tl__personPhoto" src={img.src} alt="" loading="lazy" onError={img.onError} />
) : ( ) : (
<span className="ngu-tl__personPhoto ngu-tl__personPhoto--blank" aria-hidden="true"> <span className="ngu-tl__personPhoto ngu-tl__personPhoto--blank" aria-hidden="true">
{initials(person.name)} {initials(person.name)}

View file

@ -75,7 +75,7 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
return ( return (
<section <section
id="hero" id="hero"
className="relative isolate flex min-h-[92vh] items-center overflow-hidden pt-24 pb-16" className="relative isolate flex min-h-[92dvh] items-center overflow-hidden pt-24 pb-16"
style={{ background: DEEP }} style={{ background: DEEP }}
> >
{backdrop === 'photos' ? ( {backdrop === 'photos' ? (
@ -114,7 +114,6 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
/* ── The words ───────────────────────────────────────────────── */ /* ── The words ───────────────────────────────────────────────── */
function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) { function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) {
const words = hero.headline.split(/\s+/).filter(Boolean)
const live = feature === 'livestream' const live = feature === 'livestream'
const beside = feature !== 'none' const beside = feature !== 'none'
@ -153,27 +152,23 @@ function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) {
) )
)} )}
{/* One piece, not word by word: the headline is usually the
page's largest paint, and a staggered entrance held it back
by over a second. Sized so an admin's headline stays within
about two lines. */}
<h1 <h1
className={`font-display font-extrabold leading-[0.95] tracking-tight ${ className={`hp-rise font-display font-extrabold leading-[1.02] tracking-tight ${
beside ? 'text-5xl md:text-6xl' : 'text-6xl md:text-8xl' beside ? 'text-4xl md:text-5xl' : 'text-5xl md:text-6xl lg:text-7xl'
}`} }`}
style={{ animationDelay: '60ms' }}
> >
{words.map((word, index) => ( {hero.headline}
<span key={`${word}-${index}`}>
<span
className="hp-rise"
style={{ animationDelay: `${120 + index * 110}ms` }}
>
{word}
</span>{' '}
</span>
))}
</h1> </h1>
{hero.subhead && ( {hero.subhead && (
<p <p
className="hp-rise mt-8 max-w-2xl text-lg leading-relaxed text-white/75 md:text-xl" className="hp-rise mt-8 max-w-2xl text-lg leading-relaxed text-white/75 md:text-xl"
style={{ animationDelay: `${200 + words.length * 110}ms` }} style={{ animationDelay: '180ms' }}
> >
{hero.subhead} {hero.subhead}
</p> </p>
@ -182,7 +177,7 @@ function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) {
{(hero.primary || hero.secondary) && ( {(hero.primary || hero.secondary) && (
<div <div
className="hp-rise mt-10 flex flex-wrap gap-4" className="hp-rise mt-10 flex flex-wrap gap-4"
style={{ animationDelay: `${320 + words.length * 110}ms` }} style={{ animationDelay: '300ms' }}
> >
{hero.primary && ( {hero.primary && (
<HomeLink <HomeLink
@ -290,7 +285,13 @@ function PhotoBackdrop({ slides, seconds }: { slides: HeroSlide[]; seconds: numb
className={`hp-slide ${i === index ? 'hp-slide--on' : ''}`} className={`hp-slide ${i === index ? 'hp-slide--on' : ''}`}
aria-hidden={i !== index} aria-hidden={i !== index}
> >
<img src={mediaUrl(slide.media) ?? ''} alt={slide.alt ?? ''} loading={i === 0 ? 'eager' : 'lazy'} /> <img
src={mediaUrl(slide.media) ?? ''}
alt={slide.alt ?? ''}
loading={i === 0 ? 'eager' : 'lazy'}
fetchPriority={i === 0 ? 'high' : 'low'}
decoding="async"
/>
</div> </div>
))} ))}
<div <div

View file

@ -27,7 +27,10 @@ export default defineConfig({
}, },
}, },
build: { build: {
sourcemap: true, // Source maps are written for debugging a production error, but
// not linked from the bundle, so the site doesn't publish its
// source to every visitor's devtools.
sourcemap: 'hidden',
}, },
}) })