diff --git a/.gitignore b/.gitignore index 383815b..a8ec6a0 100644 --- a/.gitignore +++ b/.gitignore @@ -13,15 +13,22 @@ build/ # local databases *.db *.db-journal +*.db-wal +*.db-shm # editor and OS files .vscode/* !.vscode/extensions.json .DS_Store Thumbs.db +nginx-dev # plain txt files -.txt +*.txt + # uploaded media (local dev) server/uploads/ server/clips/ + +# skills +graphify-out/ \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md index bcbe152..753ad45 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ Website for NGU (Next Generation of Unity), a Unity movement organization with r ## Stack - Frontend: React, TypeScript, Tailwind CSS, React Router, Vite (in `src/`) -- Backend: Hono on Node.js, SQLite (WAL mode, STRICT tables) via better-sqlite3 / node:sqlite (in `server/`) +- Backend: Hono on Node.js, SQLite (WAL mode, STRICT tables) via node:sqlite (in `server/`) - Package manager: pnpm only (never npm or yarn) ## Commands @@ -18,7 +18,7 @@ Frontend (repo root): - `pnpm exec tsc`: type-check (`noEmit`; there is no separate lint or typecheck script) - There is no test suite. -Backend (`server/`, Node >= 22). The server reads `HOST` (default `127.0.0.1`), `PORT` (default `3001`), `DB_PATH` (default `./ngu.db`) and `UPLOADS_DIR` (default `./uploads`); locally, use `DB_PATH=./dev.db`: +Backend (`server/`, Node >= 22.13). The server reads `HOST` (default `127.0.0.1`), `PORT` (default `3001`), `DB_PATH` (default `./ngu.db`) and `UPLOADS_DIR` (default `./uploads`); locally, use `DB_PATH=./dev.db`: - `DB_PATH=./dev.db pnpm dev`: run with `node --watch` - `DB_PATH=./dev.db pnpm migrate`: apply migrations without starting the server - `DB_PATH=./dev.db node src/admin-cli.js add|list|passwd|role|disable|enable ...`: the only way accounts are created @@ -54,11 +54,11 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu ## Project layout - All pages use `PageShell.tsx` as the wrapper unless explicitly noted otherwise. - Pages live in `src/pages/`; section-level components go in `src/pages/sections/`. -- `src/data/` holds only hardcoded data shared across multiple section files (e.g. `historyDecades.ts`, map grid). Everything else comes from SQLite. +- `src/data/` holds only hardcoded data shared across multiple section files (e.g. `historyDecades.ts`, map grid). Everything else comes from SQLite, through hooks in `src/lib/`. - `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages). - `api.ts` is the shared caching client used by frontend data hooks. - `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content. -- Images: every record image (logos, photos, backgrounds, block images) is an upload. A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. The `` component hides itself on load error. +- Images: every record image (logos, photos, backgrounds, block images) is an upload. A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`). ## Rules and gotchas - **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs. @@ -69,7 +69,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - **Admin editor text:** blank select options read `Default: …` (what blank means), examples in help text start with `eg.`, and record ids are called "URL ID". Cut-off preview text uses `preview()` from `src/lib/text.ts`, which ends it with an ellipsis. See `docs/updating-data-in-code.md`. ## Admin CRUD engine -Descriptor-driven: `server/admin-crud.js` and `admin-schema.js` (server) and `adminSchema.ts` (client) generate SQL and form fields from declarative entity configs. Adding an entity should mean adding a descriptor, not new CRUD code. +Descriptor-driven: `server/src/admin-crud.js` and `server/src/admin-schema.js` (server) and `adminSchema.ts` (client) generate SQL and form fields from declarative entity configs. Adding an entity should mean adding a descriptor, not new CRUD code. - Child collections are deleted and reinserted wholesale. Unsafe for entities referenced by foreign keys elsewhere. - `reindex: false` prevents cross-entity sort order collisions. - The `OMIT` sentinel distinguishes unsent fields from deliberate clears. @@ -83,4 +83,14 @@ Descriptor-driven: `server/admin-crud.js` and `admin-schema.js` (server) and `ad - The runner turns foreign keys off around every migration (it can't be done inside the file's transaction) and runs `PRAGMA foreign_key_check` before committing, so a table rebuild needs no `PRAGMA foreign_keys` of its own. When views or triggers name the table being rebuilt, wrap the drop-and-rename in `PRAGMA legacy_alter_table = ON` ... `OFF`, then recreate the rebuilt table's own indexes and triggers. ## Integrations -- Church Center (ngu.churchcenteronline.com): Planning Center embeds for giving and the calendar. \ No newline at end of file +- Church Center (ngu.churchcenteronline.com): Planning Center embeds for giving. + +## graphify + +This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships. + +Rules: +- For codebase questions, first run `graphify query ""` when graphify-out/graph.json exists. Use `graphify path "" ""` for relationships and `graphify explain ""` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output. +- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing. +- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context. +- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost). diff --git a/README.md b/README.md index 5a78d25..655d467 100644 --- a/README.md +++ b/README.md @@ -1 +1,8 @@ -Test line added by Claude Code. +# NGU-Web + +Website for NGU (Next Generation of Unity): a public site and a role-based admin panel. + +- Frontend: React, TypeScript, Tailwind, Vite (`src/`). `pnpm dev`, `pnpm build`. +- API: Hono on Node 22.13+, SQLite (`server/`). `DB_PATH=./dev.db pnpm dev`. +- Accounts are made with `server/src/admin-cli.js`. +- Deployment and setup notes are in `docs/`; working notes for contributors are in `CLAUDE.md`. diff --git a/index.html b/index.html index 2eedec2..d51965e 100644 --- a/index.html +++ b/index.html @@ -5,7 +5,6 @@ <!-- site:title --> - diff --git a/server/package.json b/server/package.json index 9f206bf..886bbb6 100644 --- a/server/package.json +++ b/server/package.json @@ -4,7 +4,7 @@ "private": true, "type": "module", "engines": { - "node": ">=22" + "node": ">=22.13" }, "scripts": { "dev": "node --watch src/index.js", diff --git a/server/src/admin-cli.js b/server/src/admin-cli.js index 7c907f3..8153a8d 100644 --- a/server/src/admin-cli.js +++ b/server/src/admin-cli.js @@ -28,7 +28,7 @@ The list comes from auth.js rather than being repeated here, so the CLI can't drift from what requireRole will actually accept. - This is also how the first superadmin is made — there's no + This is also how the first superadmin is made, there's no bootstrap path in the web interface, on purpose: node src/admin-cli.js role you@ngu.org superadmin @@ -82,7 +82,7 @@ async function readPassword() { if (first === "") { const generated = randomBytes(12).toString("base64url"); console.log(`\nGenerated password: ${generated}`); - console.log("Copy it now — it isn't stored anywhere readable.\n"); + console.log("Copy it now, it isn't stored anywhere readable.\n"); return generated; } @@ -116,7 +116,7 @@ function checkRole(role) { return role; } -/* Printed, never enforced — see the note at the top of the file. +/* Printed, never enforced, see the note at the top of the file. Worth saying out loud, because the person doing it is usually tidying up accounts rather than thinking about lockouts. */ function warnIfLastSuper(db, user) { @@ -183,7 +183,7 @@ function setRole(db, email, role) { db.prepare("UPDATE admin_users SET role = ? WHERE id = ?").run(role, user.id); // The session they're holding was issued against the old role. - // Every check reads the row fresh, so it isn't a security hole — + // Every check reads the row fresh, so it isn't a security hole, // but their open tab would keep drawing buttons that now 403. destroyAllSessionsFor(db, user.id); diff --git a/server/src/admin-crud.js b/server/src/admin-crud.js index 6fa3164..a56f75d 100644 --- a/server/src/admin-crud.js +++ b/server/src/admin-crud.js @@ -304,7 +304,7 @@ export function createRow(db, entity, payload) { ) .run(...Object.values(values)) : db.prepare(`INSERT INTO ${entity.table} DEFAULT VALUES`).run(); - // better-sqlite3 and node:sqlite disagree about BigInt here. + // node:sqlite may hand back a BigInt here. newId = Number(result.lastInsertRowid); } else { const names = [entity.idColumn, ...Object.keys(values)]; diff --git a/server/src/admin-schema-sync.js b/server/src/admin-schema-sync.js index 6487d0c..3dd7c6a 100644 --- a/server/src/admin-schema-sync.js +++ b/server/src/admin-schema-sync.js @@ -18,7 +18,7 @@ ever set it, so every insert through the admin will fail. The first is a silent repair. The other two are deployment bugs, - so with { strict: true } they stop the service starting rather + so they stop the service starting rather than waiting to surface one row at a time. ═══════════════════════════════════════════════════════════════ */ @@ -84,7 +84,7 @@ function collectGroups(entity) { return groups; } -export function syncDescriptorsWithSchema(db, entities, { strict = true } = {}) { +export function syncDescriptorsWithSchema(db, entities) { const list = Array.isArray(entities) ? entities.map((e) => [e.name ?? e.table, e]) : Object.entries(entities); const inferred = []; @@ -136,8 +136,7 @@ export function syncDescriptorsWithSchema(db, entities, { strict = true } = {}) if (problems.length) { const report = `[admin-schema] descriptor does not match the database:\n ${problems.join("\n ")}`; - if (strict) throw new Error(report); - console.error(report); + throw new Error(report); } return { inferred, problems }; diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index 9e85beb..18ec7ab 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -206,6 +206,7 @@ const blocksChild = (ownerKind) => ({ text("person_id"), text("description"), text("media"), + text("media_alt"), text("map"), ], }, @@ -478,6 +479,7 @@ const people = { key: "private", table: "person_private", idColumn: "person_id", + readRole: "editor", // viewers don't see birth dates, addresses, phones touch: true, // has its own updated_at with no trigger behind it columns: [ date("birth_date"), @@ -839,6 +841,7 @@ const blogPosts = { text("title", { required: true }), text("excerpt"), text("cover_image"), + text("cover_alt"), date("published_on"), text("tags"), text("guest_author"), diff --git a/server/src/auth.js b/server/src/auth.js index ca7d977..7bcf47b 100644 --- a/server/src/auth.js +++ b/server/src/auth.js @@ -29,6 +29,8 @@ const SESSION_DAYS = 30; // Re-issue the expiry when a session is used with less than this // left, so an active person is never signed out mid-task. const REFRESH_WITHIN_DAYS = 7; +// However active, a session ends this long after sign-in. +const MAX_SESSION_DAYS = 90; // Off only for plain-http local work. Production is behind TLS. export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false"; @@ -95,9 +97,11 @@ export function hashIp(ip) { } export function clientIp(c) { - // Trustworthy only because this service binds to 127.0.0.1 and - // nginx is the only thing that can reach it. - return c.req.header("x-forwarded-for")?.split(",")[0].trim() ?? null; + // The last X-Forwarded-For entry is the one nginx (or Vite in dev) + // added from the connection itself; anything before it is whatever + // the client sent. Trustworthy only because this service binds to + // 127.0.0.1 and nginx is the only thing that can reach it. + return c.req.header("x-forwarded-for")?.split(",").at(-1).trim() || null; } /* ── Sessions ────────────────────────────────────────────────── */ @@ -160,9 +164,10 @@ export function currentUser(db, c) { JOIN admin_users u ON u.id = s.user_id WHERE s.token_hash = ? AND s.expires_at > datetime('now') + AND s.created_at > datetime('now', ?) AND u.is_active = 1`, ) - .get(tokenHash); + .get(tokenHash, `-${MAX_SESSION_DAYS} days`); if (!row) return null; diff --git a/server/src/clips.js b/server/src/clips.js index fc0a228..ea4f7ac 100644 --- a/server/src/clips.js +++ b/server/src/clips.js @@ -291,8 +291,9 @@ async function download(db, job) { await run( YTDLP, [ + // Our options only: no yt-dlp.conf on the box changes them. + "--ignore-config", ...cookies.args, - job.source_url, // YouTube needs a JavaScript runtime to list formats; the one // running this server will do. "--js-runtimes", @@ -319,6 +320,9 @@ async function download(db, job) { ...(process.env.FFMPEG_PATH ? ["--ffmpeg-location", process.env.FFMPEG_PATH] : []), "-o", template, + // Last, after --, so the link can never be read as an option. + "--", + job.source_url, ], { onLine: (line) => { diff --git a/server/src/db.js b/server/src/db.js index d5c926c..e7c5f3d 100644 --- a/server/src/db.js +++ b/server/src/db.js @@ -2,15 +2,12 @@ DATABASE One SQLite file, opened once at boot and held for the life of - the process. Node's own sqlite module is used when it's there - (Node 24+), better-sqlite3 otherwise. Their APIs overlap enough - that everything below works against either, as long as you: + the process, through Node's own node:sqlite (Node 22.13+). + House rules: • use positional ? parameters, never named ones • pass 0/1 for booleans, never true/false - • use tx() rather than db.transaction() - - Those three rules are the whole compatibility story. + • use tx(): node:sqlite has no db.transaction() ═══════════════════════════════════════════════════════════════ */ import { readdirSync, readFileSync } from "node:fs"; @@ -20,18 +17,6 @@ import { fileURLToPath } from "node:url"; const HERE = dirname(fileURLToPath(import.meta.url)); const MIGRATIONS_DIR = join(HERE, "migrations"); -/* ── Driver selection ──────────────────────────────────────── */ - -async function loadDriver() { - try { - const { DatabaseSync } = await import("node:sqlite"); - return { Driver: DatabaseSync, name: "node:sqlite" }; - } catch { - const { default: BetterSqlite3 } = await import("better-sqlite3"); - return { Driver: BetterSqlite3, name: "better-sqlite3" }; - } -} - /* ── Open ────────────────────────────────────────────────────── WAL readers never block the writer, which matters the moment a feedback POST lands mid page-load @@ -42,15 +27,15 @@ async function loadDriver() { ───────────────────────────────────────────────────────────── */ export async function openDatabase(path) { - const { Driver, name } = await loadDriver(); - const db = new Driver(path); + const { DatabaseSync } = await import("node:sqlite"); + const db = new DatabaseSync(path); db.exec("PRAGMA journal_mode = WAL"); db.exec("PRAGMA foreign_keys = ON"); db.exec("PRAGMA synchronous = NORMAL"); db.exec("PRAGMA busy_timeout = 5000"); - db.driverName = name; + db.driverName = "node:sqlite"; return db; } diff --git a/server/src/index.js b/server/src/index.js index 30218c8..ed72ec4 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -3,7 +3,7 @@ Binds to localhost only. nginx is the only thing that talks to it, which is what lets the routes trust X-Forwarded-For and skip - CORS entirely — in production the API and the site share an + CORS entirely, in production the API and the site share an origin, and in development Vite proxies /api so they share one there too. ═══════════════════════════════════════════════════════════════ */ @@ -13,7 +13,9 @@ import { mkdir } from "node:fs/promises"; import { serve } from "@hono/node-server"; import { serveStatic } from "@hono/node-server/serve-static"; import { Hono } from "hono"; +import { csrf } from "hono/csrf"; import { logger } from "hono/logger"; +import { secureHeaders } from "hono/secure-headers"; import { openDatabase, migrate } from "./db.js"; import { rateLimit } from "./rateLimit.js"; @@ -57,6 +59,39 @@ const app = new Hono(); app.use("*", logger()); +/* Headers for every response. Referrer kept to the origin (YouTube + embeds refuse to play without one); HSTS without includeSubDomains + so a plain-http dev subdomain keeps working. No CSP yet: pages carry + an inline window.__NGU_SITE__ script and YouTube, Facebook and Maps + iframes, so one needs trying in Report-Only first. */ +app.use( + "*", + secureHeaders({ + referrerPolicy: "strict-origin-when-cross-origin", + strictTransportSecurity: "max-age=31536000", + }), +); + +/* Refuse a form-style write (text/plain, form or multipart body) + that another site sent, including a sibling subdomain, which + SameSite=Lax cookies don't stop. Browsers mark their own requests + Sec-Fetch-Site: same-origin; older ones fall back to Origin, judged + by host because nginx speaks plain http to this service. JSON + bodies can't be sent cross-origin without a CORS preflight, which + this API never answers. */ +app.use( + "/api/*", + csrf({ + origin: (origin, c) => { + try { + return new URL(origin).host === c.req.header("host"); + } catch { + return false; + } + }, + }), +); + app.use("*", async (c, next) => { c.set("db", db); await next(); @@ -139,7 +174,7 @@ const server = serve({ fetch: app.fetch, hostname: HOST, port: PORT }, (info) => for (const signal of ["SIGTERM", "SIGINT"]) { process.on(signal, () => { - console.log(`${signal} — shutting down`); + console.log(`${signal}, shutting down`); server.close(() => { try { db.close(); diff --git a/server/src/linkPreview.js b/server/src/linkPreview.js index 64e0f65..769c120 100644 --- a/server/src/linkPreview.js +++ b/server/src/linkPreview.js @@ -40,35 +40,24 @@ const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)"; /* ── Address checks ────────────────────────────────────────── */ -function ipv4Blocked(ip) { - const [a, b] = ip.split(".").map(Number); - return ( - a === 0 || - a === 10 || - a === 127 || - (a === 100 && b >= 64 && b <= 127) || - (a === 169 && b === 254) || - (a === 172 && b >= 16 && b <= 31) || - (a === 192 && b === 168) || - (a === 192 && b === 0) || - (a === 198 && (b === 18 || b === 19)) || - a >= 224 - ); -} +/* Private, loopback, link-local, shared, benchmark, multicast and + reserved ranges. BlockList also judges an IPv4-mapped IPv6 address + (::ffff:7f00:1, however it's written) by the IPv4 inside it. The + IPv6 ranges that embed an IPv4 some other way (NAT64, 6to4, the + old compatible form) are refused outright. */ +const BLOCKED = new net.BlockList(); +for (const [ip, bits] of [ + ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], + ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.168.0.0", 16], + ["198.18.0.0", 15], ["224.0.0.0", 3], +]) BLOCKED.addSubnet(ip, bits, "ipv4"); +for (const [ip, bits] of [ + ["::", 96], ["::1", 128], ["64:ff9b::", 96], ["64:ff9b:1::", 48], ["2002::", 16], + ["fc00::", 7], ["fe80::", 10], ["ff00::", 8], +]) BLOCKED.addSubnet(ip, bits, "ipv6"); function ipBlocked(ip) { - if (net.isIPv4(ip)) return ipv4Blocked(ip); - const lower = ip.toLowerCase(); - // An IPv4 address written as IPv6 is judged as the IPv4 it is. - const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/); - if (mapped) return ipv4Blocked(mapped[1]); - return ( - lower === "::" || - lower === "::1" || - /^f[cd]/.test(lower) || // fc00::/7 unique local - /^fe[89ab]/.test(lower) || // fe80::/10 link-local - /^ff/.test(lower) // multicast - ); + return BLOCKED.check(ip, net.isIPv4(ip) ? "ipv4" : "ipv6"); } async function vet(raw) { diff --git a/server/src/migrations/023_schema.sql b/server/src/migrations/023_schema.sql index 71e0565..56dbee4 100644 --- a/server/src/migrations/023_schema.sql +++ b/server/src/migrations/023_schema.sql @@ -180,7 +180,7 @@ CREATE TABLE event_scopes ( -- an every-other-week series is "on", which day -- of the month a monthly one keeps, and the -- weekday used when none is ticked --- ends_on when set, the last day it can meet — which +-- ends_on when set, the last day it can meet, which -- also keeps effective_status right -- series_count when set, stops it after that many meetings, -- whichever comes first @@ -297,7 +297,7 @@ CREATE UNIQUE INDEX event_hosts_person_uniq -- -- Public by design. Everything in this table can appear on a card, -- and is_published = 0 is the only thing between a row and the open --- web — hence the default of 0, unlike organizations. Anything that +-- web, hence the default of 0, unlike organizations. Anything that -- must never be served lives in person_private, so a careless -- SELECT * can't leak it. Bios and pages go in content_blocks, -- socials in links. People sort by sort_name; there is no @@ -306,7 +306,7 @@ CREATE UNIQUE INDEX event_hosts_person_uniq CREATE TABLE people ( id TEXT PRIMARY KEY, -- slug: 'jane-doe' display_name TEXT NOT NULL, -- 'Jane Doe' - sort_name TEXT, -- 'Doe, Jane' — list ordering + sort_name TEXT, -- 'Doe, Jane', list ordering pronouns TEXT, -- 'she/her' tagline TEXT, -- fallback when no title applies photo TEXT, -- filename in public/people/ @@ -346,7 +346,7 @@ CREATE TABLE person_private ( -- A team belongs to exactly one organization: NGU national has a -- Board and a Leadership Team, a region or chapter can have its own. -- UNIQUE (id, org_id) looks redundant against the primary key, and --- is — except that it gives affiliations a composite foreign key to +-- is, except that it gives affiliations a composite foreign key to -- point at, which stops someone filing a person under a team -- belonging to a different organization. CREATE TABLE teams ( @@ -548,7 +548,7 @@ CREATE TABLE timeline_entries ( -- Null inherits from the referenced row: an event's starts_on. A -- hand-authored entry has to supply its own, which the descriptor - -- can't require conditionally — the read layer reports an entry + -- can't require conditionally, the read layer reports an entry -- with neither rather than the table refusing it. occurred_on TEXT, @@ -604,9 +604,9 @@ CREATE INDEX timeline_entry_people_person_idx -- FRONT PAGE -- ═══════════════════════════════════════════════════════════════ -- --- The home page's editable half. One row in front_page — the CHECK +-- The home page's editable half. One row in front_page, the CHECK -- on id makes a second one impossible, and the admin engine treats --- it as a singleton — and ordered collections hanging off it, each +-- it as a singleton, and ordered collections hanging off it, each -- replaced wholesale on save. Nothing has a foreign key into them, -- which is what makes that safe. -- @@ -759,7 +759,7 @@ CREATE TABLE admin_users ( -- password at all. A row with both can use either route in. password_hash TEXT, - -- Google's stable subject id. Nullable, unique when present — + -- Google's stable subject id. Nullable, unique when present, -- SQLite allows any number of NULLs in a unique index. google_sub TEXT UNIQUE, @@ -935,7 +935,7 @@ SELECT tm.name AS team_name, -- Whether the referenced record is itself visible. An entry must not - -- outlive the thing it points at being unpublished — a draft event + -- outlive the thing it points at being unpublished, a draft event -- would otherwise leak its title and date onto a public page. Null -- for a standalone milestone, which answers to nothing but its own -- is_published. @@ -964,7 +964,7 @@ LEFT JOIN person_awards pa ON t.ref_kind = 'award' AND pa.award_id = t.re -- ═══════════════════════════════════════════════════════════════ -- -- What a new database needs before anyone signs in: the scopes an --- event can be filed under, and the front page as it ships — every +-- event can be filed under, and the front page as it ships, every -- section, the stats that need no typing, and the Church Center -- forms sorted into paths. Everything else comes in through the -- admin. diff --git a/server/src/migrations/037_leadership_published_orgs.sql b/server/src/migrations/037_leadership_published_orgs.sql new file mode 100644 index 0000000..cd3a3cf --- /dev/null +++ b/server/src/migrations/037_leadership_published_orgs.sql @@ -0,0 +1,39 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 037 LEADERSHIP VIEW: PUBLISHED HOME ORGS ONLY +-- +-- v_org_leadership named a person's primary organization even when +-- that organization was unpublished, so a draft org's name could +-- show on a public leadership list. It now joins published ones +-- only; an unpublished one reads as no primary org. +-- ═══════════════════════════════════════════════════════════════ + +DROP VIEW v_org_leadership; + +CREATE VIEW v_org_leadership AS +SELECT + a.org_id, + a.team_id, + t.name AS team_name, + t.sort_order AS team_sort_order, + a.person_id, + a.title, + a.role, + a.is_owner, + a.sort_order, + p.display_name, + p.sort_name, + p.pronouns, + p.tagline, + p.photo, + p.public_email, + p.location_label, + p.bio, + o.id AS primary_org_id, + o.name AS primary_org_name +FROM affiliations a +JOIN people p ON p.id = a.person_id AND p.is_published = 1 +LEFT JOIN teams t ON t.id = a.team_id +LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1 +WHERE a.is_public = 1 + AND a.ended_on IS NULL +ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name; diff --git a/server/src/migrations/038_image_alt_text.sql b/server/src/migrations/038_image_alt_text.sql new file mode 100644 index 0000000..cff6a0d --- /dev/null +++ b/server/src/migrations/038_image_alt_text.sql @@ -0,0 +1,13 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 038 ALT TEXT FOR BLOG COVERS AND SCHEDULE GRAPHICS +-- +-- Both images can carry information (a flyer, a site map, a cover +-- photo that sets the scene), so each gets its own description for +-- screen readers. Blank means decorative: the image is skipped. +-- +-- blog_posts.cover_alt the cover image's description +-- content_block_items.media_alt a schedule entry graphic's +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE blog_posts ADD COLUMN cover_alt TEXT; +ALTER TABLE content_block_items ADD COLUMN media_alt TEXT; diff --git a/server/src/pageMeta.js b/server/src/pageMeta.js index ae7bd08..5eb85ba 100644 --- a/server/src/pageMeta.js +++ b/server/src/pageMeta.js @@ -450,7 +450,8 @@ export function renderPage(html, meta) { tags.splice(2, 0, ``); } - return out.replace(/<\/head>/i, ` ${tags.join("\n ")}\n `); + // A function, so a $& or $` in record text isn't read as a pattern. + return out.replace(/<\/head>/i, () => ` ${tags.join("\n ")}\n `); } /* ── Sitemap ───────────────────────────────────────────────── */ diff --git a/server/src/rateLimit.js b/server/src/rateLimit.js index 5b35773..ee881f7 100644 --- a/server/src/rateLimit.js +++ b/server/src/rateLimit.js @@ -5,11 +5,13 @@ the service restarts and it doesn't survive a second instance, both of which are fine for one systemd unit on one box. - The client IP comes from X-Forwarded-For, which nginx sets. That - header is only trustworthy because nothing but nginx can reach - this port — it binds to 127.0.0.1. Don't expose the port. + The client IP comes from clientIp() in auth.js (the entry nginx + adds to X-Forwarded-For). That is only trustworthy because + nothing but nginx can reach this port, it binds to 127.0.0.1. Don't expose the port. ═══════════════════════════════════════════════════════════════ */ +import { clientIp } from "./auth.js"; + export function rateLimit({ windowMs = 60_000, max = 10 } = {}) { const hits = new Map(); // ip → { count, resetAt } @@ -22,8 +24,7 @@ export function rateLimit({ windowMs = 60_000, max = 10 } = {}) { }, windowMs).unref(); return async (c, next) => { - const ip = - c.req.header("x-forwarded-for")?.split(",")[0].trim() ?? "unknown"; + const ip = clientIp(c) ?? "unknown"; const now = Date.now(); let entry = hits.get(ip); diff --git a/server/src/routes/admin-entities.js b/server/src/routes/admin-entities.js index f50c64b..8ff5e3b 100644 --- a/server/src/routes/admin-entities.js +++ b/server/src/routes/admin-entities.js @@ -52,6 +52,16 @@ function entityForWrite(c) { return entity; } +/* An extension can ask for more than a sign-in to be read + (readRole): a person's private details need editor. Blanked on + every row sent back, so a write's reply can't leak it either. */ +function visible(c, entity, row) { + for (const ext of entity.extensions ?? []) { + if (ext.readRole && !hasRole(c.get("user"), ext.readRole)) row[ext.key] = null; + } + return row; +} + /* Everything the select inputs need, in one request. Small enough that paging it would cost more than it saves. */ entities.get("/options", (c) => { @@ -71,12 +81,12 @@ entities.get("/:entity", (c) => { entities.get("/:entity/:id", (c) => { const entity = entityOr404(c); - return c.json({ row: readRow(c.get("db"), entity, c.req.param("id")) }, 200, NO_STORE); + return c.json({ row: visible(c, entity, readRow(c.get("db"), entity, c.req.param("id"))) }, 200, NO_STORE); }); entities.post("/:entity", requireRole("editor"), async (c) => { const entity = entityForWrite(c); - const row = createRow(c.get("db"), entity, await json(c)); + const row = visible(c, entity, createRow(c.get("db"), entity, await json(c))); console.log(`${entity.key} ${row[entity.idColumn]} created by ${c.get("user").email}`); return c.json({ row }, 201, NO_STORE); }); @@ -84,7 +94,7 @@ entities.post("/:entity", requireRole("editor"), async (c) => { entities.patch("/:entity/:id", requireRole("editor"), async (c) => { const entity = entityForWrite(c); const id = c.req.param("id"); - const row = updateRow(c.get("db"), entity, id, await json(c)); + const row = visible(c, entity, updateRow(c.get("db"), entity, id, await json(c))); console.log(`${entity.key} ${id} updated by ${c.get("user").email}`); return c.json({ row }, 200, NO_STORE); }); diff --git a/server/src/routes/blog.js b/server/src/routes/blog.js index 835de5f..04d6061 100644 --- a/server/src/routes/blog.js +++ b/server/src/routes/blog.js @@ -24,7 +24,7 @@ import { Hono } from "hono"; -import { asBool, loadBlocks, loadFeaturedCards, paragraphs } from "../shape.js"; +import { asBool, loadBlocks, marks, loadFeaturedCards, paragraphs } from "../shape.js"; import { readFeeds } from "../feeds.js"; const blog = new Hono(); @@ -33,7 +33,6 @@ const CACHE = "public, max-age=60, stale-while-revalidate=300"; const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); -const marks = (n) => Array(n).fill("?").join(","); const PAGE_ID = "community"; @@ -104,6 +103,7 @@ blog.get("/blog/:id", (c) => { title: row.title, excerpt: row.excerpt, cover_image: row.cover_image, + cover_alt: row.cover_alt, published_on: row.published_on, tags: splitTags(row.tags), authors, diff --git a/server/src/routes/content.js b/server/src/routes/content.js index 1e56055..a8dd3f6 100644 --- a/server/src/routes/content.js +++ b/server/src/routes/content.js @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - CONTENT ROUTES — read-only, mounted under /api + CONTENT ROUTES: read-only, mounted under /api GET /events list + the event scopes GET /events/:id one event, full body, people @@ -12,7 +12,7 @@ Organizations are one table, so they're one endpoint. A region and a chapter differ by a handful of fields, which arrive under - `details` rather than as separate routes — that's what lets a + `details` rather than as separate routes, that's what lets a list component be written once and pointed at any kind. The lists leave out unlisted records (is_listed = 0); the @@ -32,7 +32,7 @@ every event. An event's hosts are a list, in billing order, and each one is - either an organization or a person — `kind` says which, and + either an organization or a person, `kind` says which, and `org_kind` is there for the three organization routes. The first is the one the colour and logo fell back to, which is why order is data and not a display choice. @@ -56,6 +56,7 @@ import { asBool, loadBlocks, loadLinks, + marks, paragraphs, shapeSeries, splitLinks, @@ -72,7 +73,6 @@ const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); const ORG_KINDS = ["national", "region", "chapter", "partner"]; -const marks = (n) => Array(n).fill("?").join(","); /* ── Loaders ───────────────────────────────────────────────── */ @@ -83,7 +83,7 @@ const marks = (n) => Array(n).fill("?").join(","); Unpublished hosts are dropped here rather than in the view: the admin reads the same view and needs to see them. An event whose only host is unpublished comes back with an empty list, which is - the right answer — there is nobody to name and nowhere to link. */ + the right answer, there is nobody to name and nowhere to link. */ function loadHosts(db, ids) { const byEvent = new Map(); if (ids.length === 0) return byEvent; @@ -230,8 +230,8 @@ function shapeTeam(row, links, cardBlocks) { }; } -/* awards.org_id is nullable — an award can predate any decision - about which organization owns it — so `org` genuinely can be +/* awards.org_id is nullable, an award can predate any decision + about which organization owns it, so `org` genuinely can be null, and is also null when the awarding org is unpublished. */ function shapeAward(row) { return { @@ -372,7 +372,7 @@ function attachLeadership(db, orgs) { /* Every team this organization has, including ones with nobody currently filed under them. `leadership` already carries team_id - and team_name, so the page can group people without this — but + and team_name, so the page can group people without this, but grouping alone would make an empty team invisible rather than listed, which is the wrong answer for a team that exists. */ function attachTeams(db, orgs) { diff --git a/server/src/routes/feedback.js b/server/src/routes/feedback.js index 6a09822..25fb7f2 100644 --- a/server/src/routes/feedback.js +++ b/server/src/routes/feedback.js @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - FEEDBACK ROUTE — the only public write on the site + FEEDBACK ROUTE: the only public write on the site Everything hostile that will ever reach this service arrives here, so the defences live here rather than being sprinkled @@ -10,13 +10,12 @@ length caps rejected before anything touches the database no HTML stored verbatim, escaped at render time - The write is a single INSERT with positional parameters, so it - works on node:sqlite and better-sqlite3 alike. No transaction: - one statement is already atomic. + The write is a single INSERT. No transaction: one statement is + already atomic. ═══════════════════════════════════════════════════════════════ */ import { Hono } from "hono"; -import { createHash, randomBytes } from "node:crypto"; +import { clientIp, hashIp } from "../auth.js"; const feedback = new Hono(); @@ -31,29 +30,10 @@ const LIMITS = { const MIN_MESSAGE = 10; // Must match FEEDBACK_TYPES in src/pages/sections/FeedbackForm.jsx. -// Anything else falls back to 'general' rather than being rejected — +// Anything else falls back to 'general' rather than being rejected, // a renamed option shouldn't lose someone's submission. const TYPES = ["broken", "confusing", "outdated", "request", "praise", "other"]; -/* ── IP hashing ──────────────────────────────────────────────── - Stored so repeat abuse from one source is visible during - triage, hashed so the table never holds an address. Without - IP_SALT the salt is regenerated each boot, which makes hashes - incomparable across restarts — fine for dev, set it in - /etc/ngu/api.env for production. - ───────────────────────────────────────────────────────────── */ - -const IP_SALT = process.env.IP_SALT ?? randomBytes(16).toString("hex"); - -if (!process.env.IP_SALT) { - console.warn("IP_SALT unset — feedback ip_hash values reset on restart"); -} - -function hashIp(ip) { - if (!ip) return null; - return createHash("sha256").update(`${IP_SALT}:${ip}`).digest("hex").slice(0, 32); -} - /* ── Input cleaning ──────────────────────────────────────────── */ function clean(value, max) { @@ -118,7 +98,7 @@ feedback.post("/", async (c) => { pagePath || null, sectionId || null, clean(c.req.header("user-agent"), 500) || null, - hashIp(c.req.header("x-forwarded-for")?.split(",")[0].trim()), + hashIp(clientIp(c)), ); // created_at and status come from column defaults. diff --git a/server/src/routes/history.js b/server/src/routes/history.js index e7beca1..8641ed0 100644 --- a/server/src/routes/history.js +++ b/server/src/routes/history.js @@ -1,5 +1,5 @@ /* ═══════════════════════════════════════════════════════════════ - HISTORY ROUTE — read-only, mounted under /api + HISTORY ROUTE: read-only, mounted under /api GET /history every published timeline entry @@ -17,7 +17,7 @@ queries doesn't grow with the number of entries. · precision that outruns the date. An entry can hold '2012' with - precision 'day' — the admin doesn't stop you. Trusting that + precision 'day', the admin doesn't stop you. Trusting that pair would put the entry in a month node built from a month that isn't there, so precision is capped at what the string actually carries. @@ -31,6 +31,7 @@ ═══════════════════════════════════════════════════════════════ */ import { Hono } from "hono"; +import { marks } from "../shape.js"; const history = new Hono(); @@ -38,7 +39,6 @@ const CACHE = "public, max-age=60, stale-while-revalidate=300"; const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); -const marks = (n) => Array(n).fill("?").join(","); /* 'YYYY' → year, 'YYYY-MM' → month, 'YYYY-MM-DD' → day. */ function precisionOfString(date) { @@ -115,7 +115,7 @@ history.get("/history", (c) => { ) .all(); - // How many entries exist but can't be placed. Worth knowing about — + // How many entries exist but can't be placed. Worth knowing about, // an entry nobody gave a date to is invisible, and silence is how it // stays that way. const undated = db @@ -153,7 +153,7 @@ function loadRosters(db, rows) { const teamIds = [...new Set(teamEntries.map((row) => row.ref_id))]; // v_org_leadership already decides who counts as current and - // public — affiliation still open, marked public, person + // public, affiliation still open, marked public, person // published. Restating those conditions here is how they drift. const members = db .prepare( diff --git a/server/src/routes/people.js b/server/src/routes/people.js index 8d094e9..e09288b 100644 --- a/server/src/routes/people.js +++ b/server/src/routes/people.js @@ -1,12 +1,12 @@ /* ═══════════════════════════════════════════════════════════════ - PEOPLE ROUTES — read-only, mounted under /api + PEOPLE ROUTES: read-only, mounted under /api GET /teams/:id/people current public members of a team GET /people?ids=a,b,c named people, any order GET /people/:id one person's page The team route reads v_org_leadership, which already decides who - counts as current and public — affiliation still open, marked + counts as current and public, affiliation still open, marked public, person published. Restating those conditions here is how they drift apart. @@ -21,7 +21,7 @@ import { Hono } from "hono"; -import { asBool, loadBlocks, loadLinks, paragraphs, splitLinks } from "../shape.js"; +import { asBool, loadBlocks, loadLinks, marks, paragraphs, splitLinks } from "../shape.js"; const people = new Hono(); @@ -29,7 +29,6 @@ const CACHE = "public, max-age=60, stale-while-revalidate=300"; const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE }); -const marks = (n) => Array(n).fill("?").join(","); /* How many slugs one request may name. Keeps the URL sane. */ const MAX_IDS = 50; @@ -55,7 +54,7 @@ function shapePerson(row) { } /* people.bio is one run of prose with blank lines between - paragraphs — unrelated to shape.js's paragraphs(), which turns + paragraphs, unrelated to shape.js's paragraphs(), which turns content_block rows into text. */ function splitParagraphs(text) { if (!text) return null; @@ -144,7 +143,7 @@ people.get("/people", (c) => { the same visibility rules its own page applies: a role needs a public affiliation and a published organization, an event must be published, an award must be published and the citation - public. A hidden team drops its name rather than the role — + public. A hidden team drops its name rather than the role, the seat is still real, it just has no page to link to. Roles are current and past. v_org_leadership only knows diff --git a/server/src/shape.js b/server/src/shape.js index 179d71c..c414511 100644 --- a/server/src/shape.js +++ b/server/src/shape.js @@ -3,7 +3,7 @@ Blocks and links are polymorphic: any organization, event, person or team can own them. Every list endpoint therefore needs the - same move — fetch the parent rows, then fetch all their children + same move, fetch the parent rows, then fetch all their children in one query each and stitch. The alternative is a query per row, which at a dozen events is @@ -99,7 +99,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { const itemRows = db .prepare( `SELECT i.block_id, i.text, i.detail, i.url, - i.day, i.time, i.location, i.description, i.media, i.map, + i.day, i.time, i.location, i.description, i.media, i.media_alt, i.map, p.id AS person_id, p.display_name AS person_name, p.photo AS person_photo, p.tagline AS person_tagline FROM content_block_items i @@ -122,6 +122,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { location: row.location, description: row.description, media: row.media, + media_alt: row.media_alt, map: row.map, person: row.person_id ? { @@ -139,7 +140,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { /* ── Card description ────────────────────────────────────────── The card slot is paragraphs by convention, so it collapses to - an array of strings — desc_a and desc_b become description[0] + an array of strings, desc_a and desc_b become description[0] and description[1]. A non-paragraph block in the card slot is ignored here; put it in the body slot instead. ───────────────────────────────────────────────────────────── */ @@ -172,7 +173,7 @@ export function splitLinks(links = []) { collapse from seven flags to a list of the ticked ones, Sunday first; an empty list means "starts_on's weekday", which the client resolves since it already holds starts_on. Occurrences - are not sent — they are derived, and the client derives them + are not sent, they are derived, and the client derives them against its own today. Shared by /events and /front-page. ───────────────────────────────────────────────────────────── */ const SERIES_WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; @@ -300,3 +301,6 @@ export function loadFeaturedCards(db, ownerKind, ownerId) { } export { asBool }; + +// "?,?,?" for an IN (...) list of n values. +export const marks = (n) => Array(n).fill("?").join(","); diff --git a/src/components/Banner.tsx b/src/components/Banner.tsx index f713b67..01841e7 100644 --- a/src/components/Banner.tsx +++ b/src/components/Banner.tsx @@ -12,7 +12,7 @@ export default function Banner() { try { if (!localStorage.getItem(storageKey)) setVisible(true); } catch { - setVisible(true); // storage blocked — show it anyway + setVisible(true); // storage blocked, show it anyway } }, [storageKey]); diff --git a/src/components/ContentBlocks.tsx b/src/components/ContentBlocks.tsx index 959dcd3..30d3199 100644 --- a/src/components/ContentBlocks.tsx +++ b/src/components/ContentBlocks.tsx @@ -43,7 +43,7 @@ const BODY = '#4a6b72' export default function ContentBlocks({ blocks, - accent = '#138ba0', + accent = '#0f7183', className = '', }: { blocks?: ContentBlock[] | null diff --git a/src/components/DoveMark.tsx b/src/components/DoveMark.tsx index 675a5a7..1c011b8 100644 --- a/src/components/DoveMark.tsx +++ b/src/components/DoveMark.tsx @@ -3,7 +3,7 @@ NGU's dove, lifted from the original home page. The path and its two transforms are the drawing as exported, untouched; only the - wrapper changed — sized by the caller, coloured by currentColor, + wrapper changed, sized by the caller, coloured by currentColor, and hidden from screen readers since it's decoration wherever it appears. diff --git a/src/components/FeaturedCards.tsx b/src/components/FeaturedCards.tsx index f6ddac3..2cbe00d 100644 --- a/src/components/FeaturedCards.tsx +++ b/src/components/FeaturedCards.tsx @@ -78,7 +78,7 @@ function Card({ card }: { card: FeaturedCard }) { const text = (
{card.eyebrow && ( -

{card.eyebrow}

+

{card.eyebrow}

)} {card.title && (

diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index d06455e..44e71d3 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -40,13 +40,13 @@ const Footer_Links = [ ]; const footerLinkClass = - "text-white/40 hover:text-[#aac992] text-sm transition-colors"; + "text-white/65 hover:text-[#aac992] text-sm transition-colors"; const pageLinkClass = "text-white/80 hover:text-[#aac992] text-sm font-semibold transition-colors"; const sectionLinkClass = - "text-white/45 hover:text-[#aac992] text-sm transition-colors"; + "text-white/65 hover:text-[#aac992] text-sm transition-colors"; const headingClass = "text-white/90 text-sm font-semibold mb-4"; @@ -67,7 +67,7 @@ export default function Footer() {
{Organization_Details.cityLine}
- ({Organization_Details.addressNote}) + ({Organization_Details.addressNote})

{Organization_Details.nonprofit} Tax ID: {Organization_Details.taxId}. @@ -111,7 +111,7 @@ export default function Footer() { target="_blank" rel="noopener noreferrer" className="inline-block mt-8 px-6 py-2.5 rounded-full text-sm font-bold text-white whitespace-nowrap transition-all duration-200 hover:scale-105" - style={{ background: "linear-gradient(135deg, #008fa8, #88b668)" }} + style={{ background: "#0f7183" }} > Support Us @@ -161,7 +161,7 @@ export default function Footer() {

-

© 2026 Next Generation of Unity. All rights reserved.

+

© 2026 Next Generation of Unity. All rights reserved.

{Footer_Links.map((link) => ( diff --git a/src/components/InlineText.tsx b/src/components/InlineText.tsx index 37338c0..380d987 100644 --- a/src/components/InlineText.tsx +++ b/src/components/InlineText.tsx @@ -39,6 +39,15 @@ export function Anchor({ className?: string style?: CSSProperties }) { + // A stored link with some other scheme (javascript:, data:) draws + // as plain text rather than a link. + if (isExternalUrl(href) && !SAFE_URL.test(href)) { + return ( + + {children} + + ) + } if (isExternalUrl(href)) { const app = /^(mailto|tel):/i.test(href) return ( diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx index d04bf59..94767b0 100644 --- a/src/components/Layout.tsx +++ b/src/components/Layout.tsx @@ -1,7 +1,7 @@ import { useState, useEffect, useRef } from "react"; import { NavLink, Link, Outlet, useLocation } from "react-router-dom"; import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts"; -import Banner from "./Banner.jsx"; +import Banner from "./Banner.tsx"; import nguLogo from "../assets/logos/NGU_Logo.svg"; import Footer from "./Footer.tsx"; @@ -25,7 +25,7 @@ const ACTION_VARIANTS: Record< }, fancy: { className: "font-bold text-white hover:scale-105", - style: { background: "linear-gradient(135deg, #008fa8, #88b668)" }, + style: { background: "#0f7183" }, }, }; @@ -73,6 +73,7 @@ export default function Layout() { const [activeSection, setActiveSection] = useState(null); const [headerHeight, setHeaderHeight] = useState(72); const headerRef = useRef(null); + const closeMenuRef = useRef(null); const location = useLocation(); const sections = PAGE_SECTIONS[location.pathname] ?? []; @@ -84,6 +85,16 @@ export default function Layout() { setActiveSection(null); }, [location.pathname]); + // The open menu is modal: focus starts on its close button, Escape + // shuts it, and everything behind it is inert (below). + useEffect(() => { + if (!mobileMenuOpen) return; + closeMenuRef.current?.focus(); + const onKey = (e: KeyboardEvent) => e.key === "Escape" && setMobileMenuOpen(false); + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [mobileMenuOpen]); + // The header grows and shrinks: the banner can be dismissed and the // subnav only exists on some pages. Measure it instead of guessing, // so the spacer below always matches. @@ -140,17 +151,24 @@ export default function Layout() { return (
+ + Skip to content + {/* ── NAV ─────────────────────────────────────────────── */}
- {/* Tier 0 — site-wide announcement */} + {/* Tier 0, site-wide announcement */} - {/* Tier 1 — site navigation */} + {/* Tier 1, site navigation */} - {/* Tier 2 — sections of the current page */} + {/* Tier 2, sections of the current page */} {sections.length > 0 && (