From 693dd84b6e51805474a75307dfd78bbd68f1c2c7 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Mon, 28 Sep 2026 21:53:46 -0500 Subject: [PATCH 1/6] Fix bugs found in the audit - People tiles resolve a bare photo filename to /uploads, via personPhoto - api.ts keeps the Accept header when a request sets its own headers - Feedback hashes IPs with auth.js's salt and client IP helper - Drop the better-sqlite3 fallback (not installed); require Node 22.13+ Co-Authored-By: Claude Opus 5.5 --- server/package.json | 2 +- server/src/admin-crud.js | 2 +- server/src/db.js | 27 ++++++--------------------- server/src/routes/feedback.js | 28 ++++------------------------ src/components/PeopleTiles.tsx | 10 ++-------- src/lib/api.ts | 2 +- 6 files changed, 15 insertions(+), 56 deletions(-) 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-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/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/routes/feedback.js b/server/src/routes/feedback.js index 6a09822..beb5335 100644 --- a/server/src/routes/feedback.js +++ b/server/src/routes/feedback.js @@ -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(); @@ -35,25 +34,6 @@ const MIN_MESSAGE = 10; // 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/src/components/PeopleTiles.tsx b/src/components/PeopleTiles.tsx index ab1b12d..5a89801 100644 --- a/src/components/PeopleTiles.tsx +++ b/src/components/PeopleTiles.tsx @@ -12,6 +12,7 @@ import { Link } from "react-router-dom"; import { get } from "../lib/api.ts"; import { isBadId, personHref } from "../lib/hrefs.ts"; +import { personPhoto } from "../lib/media.ts"; import "./PeopleTiles.css"; /** @@ -547,7 +548,7 @@ function Tile({ const content = ( - + {person.name} @@ -760,13 +761,6 @@ function hasDetails(person: Person): boolean { ); } -/* Database rows carry a bare filename; a hand-written entry may - give a path or a full URL. Both should work. */ -function photoSrc(photo?: string | null): string | null { - if (!photo) return null; - if (/^(https?:|\/|data:)/.test(photo)) return photo; - return `/people/${photo}`; -} function initials(name = ""): string { return name diff --git a/src/lib/api.ts b/src/lib/api.ts index 5eeca0a..9d3c693 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -38,8 +38,8 @@ export class ApiError extends Error { async function request(path, options: RequestInit = {}) { const response = await fetch(`${BASE}${path}`, { - headers: { Accept: "application/json", ...options.headers }, ...options, + headers: { Accept: "application/json", ...options.headers }, }); if (response.status === 204) return null; From 4066e9ec615f709fdbb39556429d16986ecb7e4e Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Mon, 28 Sep 2026 21:56:49 -0500 Subject: [PATCH 2/6] Harden security found in the audit - Rate limits and IP hashes use the X-Forwarded-For entry nginx adds, not the client-supplied first one - Link preview and feed fetches block IPv4-mapped and other embedded IPv6 forms of private addresses (net.BlockList) - CSRF check on /api writes; security headers and HSTS on every response - Viewers no longer receive a person's private details (readRole) - Sessions end 90 days after sign-in however active - yt-dlp ignores config files and takes the link after -- - Meta tag insert no longer expands $ patterns from record text - Links with an unsafe scheme draw as text - Migration 037: leadership lists name published home orgs only - Ignore *.db-wal, *.db-shm and *.txt Co-Authored-By: Claude Opus 5.5 --- .gitignore | 9 +++- server/src/admin-schema.js | 1 + server/src/auth.js | 13 ++++-- server/src/clips.js | 6 ++- server/src/index.js | 35 +++++++++++++++ server/src/linkPreview.js | 43 +++++++------------ .../037_leadership_published_orgs.sql | 39 +++++++++++++++++ server/src/pageMeta.js | 3 +- server/src/rateLimit.js | 11 ++--- server/src/routes/admin-entities.js | 16 +++++-- src/components/InlineText.tsx | 9 ++++ 11 files changed, 143 insertions(+), 42 deletions(-) create mode 100644 server/src/migrations/037_leadership_published_orgs.sql 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/server/src/admin-schema.js b/server/src/admin-schema.js index 9e85beb..03953c9 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -478,6 +478,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"), 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/index.js b/server/src/index.js index 30218c8..4c47ee6 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -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(); 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/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/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..5c46744 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/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 ( From 5274e09571a4d37b95ad3591bd397c6917d637fb Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Mon, 28 Sep 2026 22:02:03 -0500 Subject: [PATCH 3/6] Clean up code found in the audit - Replace every em-dash in src and server/src with a colon, comma or hyphen - Give every relative import its file extension (.jsx imports of .tsx fixed) - Delete old-historyMock.ts, unused exports, unused CSS utilities, the unused @ alias and the fallback option nothing passed - One copy each of initials, capitalize, byName and the server's marks() - Move the organization, chapter and event hooks from src/data to src/lib - Schema sync always throws on a mismatch (strict was never turned off) - Replace the placeholder README Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +- server/src/admin-cli.js | 8 +- server/src/admin-schema-sync.js | 7 +- server/src/index.js | 4 +- server/src/migrations/023_schema.sql | 20 +- server/src/rateLimit.js | 2 +- server/src/routes/blog.js | 3 +- server/src/routes/content.js | 16 +- server/src/routes/feedback.js | 4 +- server/src/routes/history.js | 10 +- server/src/routes/people.js | 11 +- server/src/shape.js | 9 +- src/components/Banner.tsx | 2 +- src/components/DoveMark.tsx | 2 +- src/components/Layout.tsx | 8 +- src/components/PageShell.tsx | 8 +- src/components/PageState.tsx | 4 +- src/components/PeopleTiles.css | 2 +- src/components/PeopleTiles.tsx | 27 +- src/data/bannerConfig.ts | 2 +- src/data/feedbackTypes.ts | 2 +- src/data/historyDecades.ts | 4 +- src/data/mapGrid.ts | 17 +- src/data/old-historyMock.ts | 299 ------------------ src/index.css | 27 -- src/lib/api.ts | 20 +- src/lib/auth.tsx | 4 +- src/{data => lib}/chapters.ts | 12 +- src/{data => lib}/eventData.ts | 12 +- src/lib/eventSeries.ts | 4 +- src/lib/eventTypes.ts | 8 +- src/lib/hrefs.ts | 22 +- src/lib/media.ts | 4 - src/{data => lib}/organizations.ts | 7 +- src/lib/sections.tsx | 2 +- src/lib/site.ts | 2 - src/lib/text.ts | 3 + src/lib/timeline.ts | 16 +- src/lib/timelineRefs.ts | 12 +- src/lib/useContent.ts | 12 +- src/lib/useHistory.ts | 10 +- src/lib/useRecord.ts | 8 +- src/lib/useResource.ts | 23 +- src/lib/version.ts | 2 +- src/main.tsx | 2 +- src/pages/AwardDetail.tsx | 6 +- src/pages/EventDetail.tsx | 16 +- src/pages/Feedback.tsx | 6 +- src/pages/History.tsx | 12 +- src/pages/Home.tsx | 6 +- src/pages/OrganizationDetail.tsx | 12 +- src/pages/PersonDetail.tsx | 5 +- src/pages/Privacy.tsx | 2 +- src/pages/Resources.tsx | 2 +- src/pages/Retreats.tsx | 6 +- src/pages/TeamDetail.tsx | 2 +- src/pages/Terms.tsx | 2 +- src/pages/sections/EventCalendar.tsx | 4 +- src/pages/sections/EventList-Cards.tsx | 40 +-- src/pages/sections/FeedbackForm.tsx | 6 +- src/pages/sections/OrgList-Card.tsx | 14 +- src/pages/sections/OrgList-Map.tsx | 32 +- src/pages/sections/OrgList-Vertical.tsx | 14 +- .../sections/history/HistoryTimeline.tsx | 6 +- src/pages/sections/history/TimelineDecade.tsx | 6 +- src/pages/sections/history/TimelineEntry.tsx | 17 +- .../sections/history/TimelineUpcoming.tsx | 6 +- src/pages/sections/history/TimelineYear.tsx | 6 +- src/pages/sections/history/timeline.css | 26 +- src/pages/sections/home/CalendarBand.tsx | 4 +- .../sections/home/FeaturedTimelineRail.tsx | 6 +- .../sections/home/NextEventCountdown.tsx | 2 +- src/pages/sections/home/Pathfinder.tsx | 2 +- tsconfig.json | 4 - vite.config.ts | 6 - 75 files changed, 282 insertions(+), 688 deletions(-) delete mode 100644 src/data/old-historyMock.ts rename src/{data => lib}/chapters.ts (95%) rename src/{data => lib}/eventData.ts (91%) rename src/{data => lib}/organizations.ts (95%) 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/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-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/index.js b/server/src/index.js index 4c47ee6..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. ═══════════════════════════════════════════════════════════════ */ @@ -174,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/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/rateLimit.js b/server/src/rateLimit.js index 5c46744..ee881f7 100644 --- a/server/src/rateLimit.js +++ b/server/src/rateLimit.js @@ -7,7 +7,7 @@ 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. + nothing but nginx can reach this port, it binds to 127.0.0.1. Don't expose the port. ═══════════════════════════════════════════════════════════════ */ import { clientIp } from "./auth.js"; diff --git a/server/src/routes/blog.js b/server/src/routes/blog.js index 835de5f..3a6e665 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"; 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 beb5335..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 @@ -30,7 +30,7 @@ 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"]; 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..970cec9 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 @@ -139,7 +139,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 +172,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 +300,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/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/Layout.tsx b/src/components/Layout.tsx index d04bf59..82b00e8 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"; @@ -147,10 +147,10 @@ export default function Layout() { className="fixed top-0 left-0 right-0 z-50 backdrop-blur-md" > - {/* 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 && (