From be7e92417eb6014b06b63cd8123b5c0dad5ec4d3 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Tue, 29 Sep 2026 02:34:26 -0500 Subject: [PATCH 001/207] Fix the Panel account bug and harden what the second audit found - Panel: changing a role or disabling an account always failed (db.transaction doesn't exist on node:sqlite); it uses tx() now - Feeds and link previews are scanned with indexOf, not whole-document regexes, so a hostile feed or page can't freeze the server; entity decoding can't throw; escaped-HTML descriptions make clean excerpts - Feed reads share one fetch per feed and serve the stale copy while a refresh runs - Deliberate HTTP errors (the CSRF 403) keep their status instead of becoming logged 500s; a JSON null body is handled - url columns read the scheme the way the URL parser does, so control characters can't hide javascript: - Google sign-in state cookie is __Host- and its return page is checked again; more reserved ranges blocked for previews and feeds, and a 15 s cap on each whole fetch - Log lines from visitor text are made single-line and short; list limits can't go negative; entity names can't hit object prototypes - A clip title can't point the clip tool at another file - Uploads over 60 MP are refused before decoding; the Keep original help says a photo's location stays in it - admin-cli add defaults to the editor role Co-Authored-By: Claude Opus 5.5 --- docs/security-headers.md | 12 ++++ server/src/admin-cli.js | 6 +- server/src/admin-crud.js | 6 +- server/src/auth.js | 6 ++ server/src/clips.js | 11 +++- server/src/feeds.js | 86 +++++++++++++++++------- server/src/index.js | 9 ++- server/src/linkPreview.js | 94 ++++++++++++++++++++++++--- server/src/media.js | 10 ++- server/src/pageMeta.js | 3 + server/src/routes/admin-entities.js | 3 +- server/src/routes/admin.js | 5 +- server/src/routes/auth.js | 17 +++-- server/src/routes/feedback.js | 3 +- server/src/routes/media.js | 2 +- server/src/routes/panel.js | 8 ++- server/src/theme.js | 2 +- src/components/admin/MediaLibrary.tsx | 2 +- 18 files changed, 226 insertions(+), 59 deletions(-) diff --git a/docs/security-headers.md b/docs/security-headers.md index 997e0fa..d7c2baf 100644 --- a/docs/security-headers.md +++ b/docs/security-headers.md @@ -55,6 +55,18 @@ Both lines are already in every proxied block in `nginx-dev` and in `routes/auth.js`: five wrong passwords for one address lock it for the rest of 15 minutes, from anywhere; a correct one clears the count. Both are in memory and reset when the service restarts. +- The per-email lock is a trade-off: anyone who knows an admin's + address can keep password sign-in for it locked by guessing wrong + five times every 15 minutes. Google sign-in still works for that + account, and the lock clears on a restart. +- `clientIp` trusts the last `X-Forwarded-For` entry, the one nginx + adds. If a CDN or another proxy is ever put in front of nginx, that + entry becomes the proxy's address and every visitor shares one + rate-limit bucket: set nginx's `real_ip_header` and + `set_real_ip_from` for the proxy first. +- The Google sign-in state cookie is `__Host-ngu_oauth` (plain + `ngu_oauth` over local http), and the page it returns to is checked + again when the browser comes back. ## From nginx: HSTS diff --git a/server/src/admin-cli.js b/server/src/admin-cli.js index 8153a8d..8bbae19 100644 --- a/server/src/admin-cli.js +++ b/server/src/admin-cli.js @@ -21,8 +21,8 @@ admin + delete records superadmin + accounts, roles and sessions, via /admin/panel - add takes --role=editor, --name="Full Name". It defaults to - admin. Press enter at the password prompt and it generates one + add takes --role=admin, --name="Full Name". It defaults to + editor, the least that can change content; raise it on purpose. Press enter at the password prompt and it generates one and prints it once. The list comes from auth.js rather than being repeated here, so @@ -139,7 +139,7 @@ function warnIfLastSuper(db, user) { async function add(db, email, flags) { if (findUser(db, email)) fail(`${email} already exists. Use passwd to change it.`); - const role = checkRole(flags.role ?? "admin"); + const role = checkRole(flags.role ?? "editor"); const password = await readPassword(); diff --git a/server/src/admin-crud.js b/server/src/admin-crud.js index 0b899b0..f82a0b4 100644 --- a/server/src/admin-crud.js +++ b/server/src/admin-crud.js @@ -113,7 +113,9 @@ function coerceValue(column, raw, errors, prefix = "") { } case "url": { const value = String(raw).trim(); - const scheme = URL_SCHEME.exec(value)?.[1].toLowerCase(); + // The URL parser ignores control characters, spaces and tabs + // inside a scheme ("java\tscript:"), so read it the same way. + const scheme = URL_SCHEME.exec(value.replace(/[\u0000-\u0020\u007f]/g, ""))?.[1].toLowerCase(); if (scheme && !SAFE_SCHEMES.has(scheme)) { errors[key] = "Links must start with http://, https://, mailto: or tel:, or be a site path like /retreats."; return null; @@ -160,7 +162,7 @@ export function listRows(db, entity, query = {}) { params.push(...search.map(() => term)); } - const limit = Math.min(Number(query.limit) || 200, 500); + const limit = Math.max(1, Math.min(Number(query.limit) || 200, 500)); const rows = db .prepare( diff --git a/server/src/auth.js b/server/src/auth.js index bfbc60c..084d513 100644 --- a/server/src/auth.js +++ b/server/src/auth.js @@ -91,6 +91,12 @@ export function verifyPassword(password, stored) { return timingSafeEqual(candidate, expected); } +/* Text a visitor controls, made safe for one log line: control + characters (a newline would start a forged line) become "?", and + it's cut short. */ +export const logSafe = (value, max = 200) => + String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "?").slice(0, max); + /* ── Hashing helpers ─────────────────────────────────────────── */ const sha256 = (value) => createHash("sha256").update(value).digest("hex"); diff --git a/server/src/clips.js b/server/src/clips.js index ea4f7ac..bd56ee7 100644 --- a/server/src/clips.js +++ b/server/src/clips.js @@ -330,8 +330,17 @@ async function download(db, job) { if (percent) update(db, job.id, { progress: Math.min(0.99, Number(percent[1]) / 100) }); const t = line.match(/^TITLE (.+)$/); if (t) title = t[1].slice(0, 300); + // Only this job's own output file counts: a video title with + // a newline in it could print a "FILE ..." line of its own. const f = line.match(/^FILE (.+)$/); - if (f) file = f[1].trim(); + const candidate = f?.[1].trim(); + if ( + candidate && + path.resolve(path.dirname(candidate)) === path.resolve(CLIPS_DIR) && + path.basename(candidate).startsWith(`source-${job.id}.`) + ) { + file = candidate; + } }, }, ); diff --git a/server/src/feeds.js b/server/src/feeds.js index d5b2fb5..43f826a 100644 --- a/server/src/feeds.js +++ b/server/src/feeds.js @@ -18,7 +18,7 @@ image on the page. ═══════════════════════════════════════════════════════════════ */ -import { decodeEntities, safeGet } from "./linkPreview.js"; +import { decodeEntities, elements, innerOf, openTags, safeGet } from "./linkPreview.js"; const CACHE_MS = 30 * 60 * 1000; const MAX_FEED_BYTES = 3 * 1024 * 1024; @@ -34,24 +34,32 @@ function unwrap(text) { } /* The text inside the first …, CDATA unwrapped. Tag - names may carry a namespace prefix (content:encoded). */ + names may carry a namespace prefix (content:encoded). Scanned with + indexOf, not a regex: the feed is someone else's (see "Scanning + markup" in linkPreview.js). */ function inner(xml, tag) { - const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)`, "i")); - return match ? unwrap(match[1]) : null; + const text = innerOf(xml, tag); + return text == null ? null : unwrap(text); } function attrOf(xml, tag, name, where = () => true) { - for (const match of xml.matchAll(new RegExp(`<${tag}\\b[^>]*>`, "gi"))) { - const el = match[0]; + for (const el of openTags(xml, tag, 50)) { const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i")); if (value && where(el)) return value[2] ?? value[3]; } return null; } +// Enough of a body or summary to make an excerpt from, so the tag +// strip and entity decoding never see more than this. +const PLAIN_SCAN = 20_000; + function plain(html) { if (!html) return null; - const text = decodeEntities(html.replace(/<[^>]+>/g, " ")); + // Tags stripped both before and after decoding: a description is + // often HTML written as entities (<p>). + const strip = (s) => s.replace(/<[^>]*>/g, " "); + const text = decodeEntities(strip(decodeEntities(strip(html.slice(0, PLAIN_SCAN))))); if (!text) return null; return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text; } @@ -74,21 +82,34 @@ function isoDate(raw) { } function firstImage(html) { - return html?.match(/]*\bsrc\s*=\s*["']([^"']+)["']/i)?.[1] ?? null; + if (!html) return null; + for (const tag of openTags(html, "img", 20)) { + const src = tag.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1]; + if (src) return src; + } + return null; } function parseFeed(xml, feedUrl) { - const isAtom = /]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !//gi : //gi) ?? []; + // The root element is near the top; nothing needs the rest for this. + const top = xml.slice(0, 8192); + const root = openTags(top, "feed", 1)[0] ?? ""; + const isAtom = /xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(root) && openTags(top, "rss", 1).length === 0; + const tag = isAtom ? "entry" : "item"; + // The channel's own title is the one before the first item. + const firstItem = xml.toLowerCase().indexOf(`<${tag}`); + const channelTitle = decodeEntities( + inner(firstItem === -1 ? xml : xml.slice(0, firstItem), "title")?.slice(0, 1000) ?? "", + ); + const blocks = elements(xml, tag, MAX_ITEMS_PER_FEED); const items = []; - for (const block of blocks.slice(0, MAX_ITEMS_PER_FEED)) { + for (const block of blocks) { const link = isAtom ? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el)) : inner(block, "link"); const url = safeUrl(link?.trim(), feedUrl); - const title = decodeEntities(inner(block, "title") ?? ""); + const title = decodeEntities(inner(block, "title")?.slice(0, 1000) ?? ""); if (!url || !title) continue; const body = inner(block, "content:encoded") ?? inner(block, "content"); @@ -123,20 +144,37 @@ async function fetchFeed(url) { return parseFeed(result.body.toString("utf8"), result.url.toString()); } +/* One fetch at a time per feed, shared by everyone who asks while it + runs. A failure keeps the last good copy and waits 5 minutes before + trying again, rather than retrying on every request. */ +function refresh(url) { + const hit = cache.get(url); + if (hit?.pending) return hit.pending; + const pending = fetchFeed(url) + .then((feed) => { + cache.set(url, { at: Date.now(), feed }); + return feed; + }) + .catch((err) => { + console.warn(`feed ${url}: ${err.message}`); + const stale = hit?.feed ?? { title: null, items: [] }; + cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale }); + return stale; + }); + cache.set(url, { ...hit, pending }); + return pending; +} + +/* A fresh copy as it is; a stale one straight away while a refresh + runs behind it, so no visitor waits on someone else's server once + the feed has been read once. Only the very first read waits. */ async function readFeed(url) { const hit = cache.get(url); - if (hit && Date.now() - hit.at < CACHE_MS) return hit.feed; - try { - const feed = await fetchFeed(url); - cache.set(url, { at: Date.now(), feed }); - return feed; - } catch (err) { - console.warn(`feed ${url}: ${err.message}`); - // Serve the last good copy, and don't retry on every request. - const stale = hit?.feed ?? { title: null, items: [] }; - cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale }); - return stale; + if (hit?.feed) { + if (Date.now() - hit.at >= CACHE_MS) refresh(url); + return hit.feed; } + return refresh(url); } /* Every listed feed's items, newest first, each tagged with its diff --git a/server/src/index.js b/server/src/index.js index 5a5bf70..420b7b9 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -13,6 +13,7 @@ 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 { HTTPException } from "hono/http-exception"; import { csrf } from "hono/csrf"; import { logger } from "hono/logger"; import { secureHeaders } from "hono/secure-headers"; @@ -35,7 +36,7 @@ import media from "./routes/media.js"; import clips from "./routes/clips.js"; import { CLIPS_DIR, startClipWorker } from "./clips.js"; import { UPLOADS_DIR } from "./media.js"; -import { startSessionSweeper } from "./auth.js"; +import { logSafe, startSessionSweeper } from "./auth.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { ENTITIES } from "./admin-schema.js"; @@ -111,8 +112,9 @@ app.post("/api/csp-report", async (c) => { const text = (await c.req.text()).slice(0, 4000); try { const report = JSON.parse(text)["csp-report"] ?? {}; + const field = (name) => logSafe(report[name] ?? "?", 150); console.warn( - `csp ${report["violated-directive"] ?? "?"} blocked ${report["blocked-uri"] ?? "?"} on ${report["document-uri"] ?? "?"}`, + `csp ${field("violated-directive")} blocked ${field("blocked-uri")} on ${field("document-uri")}`, ); } catch { // Not a report; nothing to log. @@ -203,6 +205,9 @@ console.log(`clips ${CLIPS_DIR}`); app.notFound((c) => c.json({ error: "Not found" }, 404)); app.onError((err, c) => { + // A deliberate refusal (the CSRF check's 403, say) is an answer, + // not a crash: send it as it is and keep it out of the error log. + if (err instanceof HTTPException) return err.getResponse(); console.error(err); // Never leak internals to the browser. return c.json({ error: "Something went wrong." }, 500); diff --git a/server/src/linkPreview.js b/server/src/linkPreview.js index 769c120..6b554da 100644 --- a/server/src/linkPreview.js +++ b/server/src/linkPreview.js @@ -34,6 +34,8 @@ import net from "node:net"; import { MAX_UPLOAD_BYTES, MediaError } from "./media.js"; const TIMEOUT_MS = 8000; +// The whole request, however steadily the bytes trickle in. +const TOTAL_TIMEOUT_MS = 15000; const MAX_REDIRECTS = 4; const MAX_HTML_BYTES = 1024 * 1024; const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)"; @@ -48,12 +50,13 @@ const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)"; 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], + ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24], + ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24], + ["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], + ["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8], ["2001:db8::", 32], ]) BLOCKED.addSubnet(ip, bits, "ipv6"); function ipBlocked(ip) { @@ -146,6 +149,14 @@ function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) { }, ); req.on("timeout", () => req.destroy(new MediaError(504, "The site took too long to answer."))); + // `timeout` above only fires when the socket goes quiet; a server + // sending a byte every few seconds would hold the request open + // for hours. This caps the whole exchange. + const deadline = setTimeout( + () => req.destroy(new MediaError(504, "The site took too long to answer.")), + TOTAL_TIMEOUT_MS, + ); + req.on("close", () => clearTimeout(deadline)); req.on("error", (err) => reject(err instanceof MediaError ? err : new MediaError(400, "That site couldn't be reached.")), ); @@ -169,15 +180,82 @@ export async function safeGet(raw, options) { const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }; +// A code point past U+10FFFF would make fromCodePoint throw. +const codePoint = (n) => String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd); + export function decodeEntities(text) { return text - .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16))) - .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec))) + .replace(/&#x([0-9a-f]{1,6});/gi, (_, hex) => codePoint(parseInt(hex, 16))) + .replace(/&#(\d{1,7});/g, (_, dec) => codePoint(Number(dec))) .replace(/&([a-z]+);/gi, (whole, name) => ENTITIES[name.toLowerCase()] ?? whole) .replace(/\s+/g, " ") .trim(); } +/* ── Scanning markup ─────────────────────────────────────────── + Pages and feeds come from other people's servers, so nothing here + runs a regex over the whole document: a pattern like + /]*>/ restarts at every "", "/", " ", "\t", "\n", "\r"]); + +/* Where the next ) starts, or -1. */ +function tagStart(lower, name, from) { + for (let i = from; ; ) { + const at = lower.indexOf(name, i); + if (at === -1 || TAG_END.has(lower[at + name.length] ?? "")) return at; + i = at + name.length; + } +} + +/* Each opening in text, up to `limit` of them. */ +export function openTags(text, tag, limit = 200) { + const lower = text.toLowerCase(); + const name = `<${tag.toLowerCase()}`; + const out = []; + for (let i = 0; out.length < limit; ) { + const start = tagStart(lower, name, i); + if (start === -1) break; + const end = lower.indexOf(">", start); + if (end === -1) break; + out.push(text.slice(start, end + 1)); + i = end + 1; + } + return out; +} + +/* Each whole … in text, up to `limit` of them. */ +export function elements(text, tag, limit) { + const lower = text.toLowerCase(); + const name = `<${tag.toLowerCase()}`; + const close = ``; + const out = []; + for (let i = 0; out.length < limit; ) { + const start = tagStart(lower, name, i); + if (start === -1) break; + const end = lower.indexOf(close, start); + if (end === -1) break; + out.push(text.slice(start, end + close.length)); + i = end + close.length; + } + return out; +} + +/* What's between the first and its , or null. */ +export function innerOf(text, tag) { + const lower = text.toLowerCase(); + const start = tagStart(lower, `<${tag.toLowerCase()}`, 0); + if (start === -1) return null; + const open = lower.indexOf(">", start); + if (open === -1) return null; + const end = lower.indexOf(``, open); + return end === -1 ? null : text.slice(open + 1, end); +} + function attr(tag, name) { const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i")); return match ? (match[1] ?? match[2] ?? match[3] ?? "") : null; @@ -185,12 +263,12 @@ function attr(tag, name) { function readMeta(html) { const meta = {}; - for (const tag of html.match(/]*>/gi) ?? []) { + for (const tag of openTags(html, "meta")) { const key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase(); const content = attr(tag, "content"); - if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content); + if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content.slice(0, 2000)); } - const title = html.match(/]*>([\s\S]*?)<\/title>/i)?.[1]; + const title = innerOf(html, "title")?.slice(0, 1000); return { title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null, description: diff --git a/server/src/media.js b/server/src/media.js index 7427770..9c5b1fd 100644 --- a/server/src/media.js +++ b/server/src/media.js @@ -63,6 +63,10 @@ export const KEEP_MAX_BYTES = 10 * MB; /* Longest side after processing, in pixels. Wide enough for a full-bleed hero on a large screen. */ +// About 60 megapixels (eg. 9000 x 6700): past any camera an editor +// uses, and it stops one giant image eating the VPS's memory while +// it's decoded. sharp's own default is 268 MP. +const MAX_INPUT_PIXELS = 60_000_000; const MAX_EDGE = 2400; const WEBP_QUALITY = 82; @@ -141,7 +145,7 @@ export async function store(buf, { keepOriginal = false } = {}) { try { if (convert) { // animated keeps every frame of a GIF or an animated WebP. - const { data, info } = await sharp(buf, { animated: true }) + const { data, info } = await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS }) .rotate() .resize({ width: MAX_EDGE, height: MAX_EDGE, fit: "inside", withoutEnlargement: true }) .webp({ quality: WEBP_QUALITY }) @@ -152,7 +156,7 @@ export async function store(buf, { keepOriginal = false } = {}) { // An animated image reports the whole strip's height. height = info.pageHeight ?? info.height; } else if (kind !== "svg") { - const meta = await sharp(buf).metadata(); + const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); width = meta.width ?? null; height = meta.pageHeight ?? meta.height ?? null; } @@ -209,7 +213,7 @@ async function describe(filename) { let height = null; if (kind !== "svg") { try { - const meta = await sharp(buf).metadata(); + const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); width = meta.width ?? null; height = meta.pageHeight ?? meta.height ?? null; } catch { diff --git a/server/src/pageMeta.js b/server/src/pageMeta.js index 3c167af..aecca40 100644 --- a/server/src/pageMeta.js +++ b/server/src/pageMeta.js @@ -130,7 +130,10 @@ export function robotsTxt(site) { cut on a word near DESCRIPTION_CHARS. */ export function plainText(text) { if (!text) return null; + // A description is ~160 characters; reading far past that only + // gives the patterns below more to rescan on pathological text. const flat = String(text) + .slice(0, 2000) .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1") .replace(/\*\*(.+?)\*\*/g, "$1") .replace(/\*(.+?)\*/g, "$1") diff --git a/server/src/routes/admin-entities.js b/server/src/routes/admin-entities.js index 8ff5e3b..3a85687 100644 --- a/server/src/routes/admin-entities.js +++ b/server/src/routes/admin-entities.js @@ -36,7 +36,8 @@ entities.use("*", requireAuth); const NO_STORE = { "Cache-Control": "no-store" }; function entityOr404(c) { - const entity = ENTITIES[c.req.param("entity")]; + const name = c.req.param("entity"); + const entity = Object.hasOwn(ENTITIES, name) ? ENTITIES[name] : null; if (!entity) throw new HttpError(404, "Unknown entity."); return entity; } diff --git a/server/src/routes/admin.js b/server/src/routes/admin.js index 1479050..2b433b7 100644 --- a/server/src/routes/admin.js +++ b/server/src/routes/admin.js @@ -53,7 +53,7 @@ admin.get("/feedback", (c) => { params.push(Number(before)); } - const take = Math.min(Number(limit) || 50, MAX_LIMIT); + const take = Math.max(1, Math.min(Number(limit) || 50, MAX_LIMIT)); const rows = db .prepare( @@ -99,7 +99,8 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => { let body; try { - body = await c.req.json(); + // `?? {}`: a body of JSON null parses fine and has no fields. + body = (await c.req.json()) ?? {}; } catch { return c.json({ error: "Expected a JSON body." }, 400); } diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 825f12c..4bebca5 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -33,6 +33,7 @@ import { deleteCookie, getCookie, setCookie } from "hono/cookie"; import { SECURE_COOKIE, + logSafe, createSession, destroySession, currentUser, @@ -58,7 +59,8 @@ const NO_STORE = { "Cache-Control": "no-store" }; auth.post("/login", async (c) => { let body; try { - body = await c.req.json(); + // `?? {}`: a body of JSON null parses fine and has no fields. + body = (await c.req.json()) ?? {}; } catch { return c.json({ error: "Expected a JSON body." }, 400); } @@ -72,7 +74,7 @@ auth.post("/login", async (c) => { const wait = loginFailures.blockedFor(email); if (wait) { - console.warn(`login locked for ${email}`); + console.warn(`login locked for ${logSafe(email)}`); return c.json( { error: "Too many wrong passwords for this account. Try again in a few minutes." }, 429, @@ -97,7 +99,7 @@ auth.post("/login", async (c) => { if (!ok) { loginFailures.fail(email); - console.warn(`login failed for ${email}`); + console.warn(`login failed for ${logSafe(email)}`); return c.json({ error: "That email and password don't match." }, 401); } @@ -134,12 +136,14 @@ auth.get("/me", (c) => { // The state and PKCE verifier between the two legs. Scoped to the // Google routes and gone in ten minutes; Lax so it comes back on // the redirect from Google, which is a top-level navigation. -const OAUTH_COOKIE = "ngu_oauth"; +// __Host- (Secure, path /, no Domain) when over https, like the +// session cookie, so a sibling subdomain can't plant its own state. +const OAUTH_COOKIE = SECURE_COOKIE ? "__Host-ngu_oauth" : "ngu_oauth"; const OAUTH_COOKIE_OPTIONS = { httpOnly: true, secure: SECURE_COOKIE, sameSite: "Lax", - path: "/api/auth/google", + path: "/", }; // Where to land afterwards: an admin page, never anywhere else. @@ -232,7 +236,8 @@ auth.get("/google/callback", async (c) => { ).run(identity.name, user.id); console.log(`login ${user.email} (google)`); - return c.redirect(saved.next ?? "/admin/home", 302); + // Checked again: the cookie came back from the browser. + return c.redirect(safeNext(saved.next), 302); }); export default auth; diff --git a/server/src/routes/feedback.js b/server/src/routes/feedback.js index 0c377a4..885394e 100644 --- a/server/src/routes/feedback.js +++ b/server/src/routes/feedback.js @@ -52,7 +52,8 @@ function looksLikeEmail(value) { feedback.post("/", async (c) => { let body; try { - body = await c.req.json(); + // `?? {}`: a body of JSON null parses fine and has no fields. + body = (await c.req.json()) ?? {}; } catch { return c.json({ error: "Expected a JSON body." }, 400); } diff --git a/server/src/routes/media.js b/server/src/routes/media.js index 42d5d1a..6e39ad8 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -165,7 +165,7 @@ media.post("/link-preview", requireRole("editor"), async (c) => { const user = c.get("user"); let url; try { - ({ url } = await c.req.json()); + ({ url } = (await c.req.json()) ?? {}); } catch { return c.json({ error: "Expected a JSON body." }, 400); } diff --git a/server/src/routes/panel.js b/server/src/routes/panel.js index 8aefbce..4c13242 100644 --- a/server/src/routes/panel.js +++ b/server/src/routes/panel.js @@ -25,6 +25,7 @@ import { Hono } from "hono"; import { requireAuth, requireRole, ROLES } from "../auth.js"; +import { tx } from "../db.js"; const panel = new Hono(); @@ -116,7 +117,8 @@ panel.patch("/users/:id", async (c) => { let body; try { - body = await c.req.json(); + // `?? {}`: a body of JSON null parses fine and has no fields. + body = (await c.req.json()) ?? {}; } catch { return c.json({ error: "Expected a JSON body." }, 400); } @@ -154,7 +156,8 @@ panel.patch("/users/:id", async (c) => { if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400); - const tx = db.transaction(() => { + // tx(), not db.transaction(): node:sqlite has no transaction(). + tx(db, () => { db.prepare(`UPDATE admin_users SET ${sets.join(", ")} WHERE id = ?`).run( ...params, id, @@ -163,7 +166,6 @@ panel.patch("/users/:id", async (c) => { // matches the row. Make them sign in again. db.prepare("DELETE FROM sessions WHERE user_id = ?").run(id); }); - tx(); console.log( `account ${target.email} updated by ${me.email}: ${JSON.stringify(body)}`, diff --git a/server/src/theme.js b/server/src/theme.js index 789be80..bc55b39 100644 --- a/server/src/theme.js +++ b/server/src/theme.js @@ -48,7 +48,7 @@ function overrides(db) { .all(); // Checked again here, not only by the table's CHECK: this goes // straight into a `, ].filter(Boolean); diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index c86ce55..d798f87 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -138,7 +138,7 @@ auth.get("/me", (c) => { // the redirect from Google, which is a top-level navigation. // __Host- (Secure, path /, no Domain) when over https, like the // session cookie, so a sibling subdomain can't plant its own state. -const OAUTH_COOKIE = SECURE_COOKIE ? "__Host-ngu_oauth" : "ngu_oauth"; +const OAUTH_COOKIE = SECURE_COOKIE ? "__Host-site_oauth" : "site_oauth"; const OAUTH_COOKIE_OPTIONS = { httpOnly: true, secure: SECURE_COOKIE, diff --git a/src/App.tsx b/src/App.tsx index 8252b6c..2f20f98 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -25,7 +25,7 @@ import Home from "./pages/Home.tsx" /* A page's chunk can be missing when a deploy replaced the build while this tab still ran the old one. Reload once to pick up the new build; if that doesn't help, let the error surface. */ -const CHUNK_RELOAD = "ngu-chunk-reload" +const CHUNK_RELOAD = "site-chunk-reload" const lazyPage = (load) => lazy(() => load() diff --git a/src/components/Banner.tsx b/src/components/Banner.tsx index af1df71..e5d32e6 100644 --- a/src/components/Banner.tsx +++ b/src/components/Banner.tsx @@ -5,7 +5,7 @@ import { SITE_BANNER } from "../data/bannerConfig.ts"; export default function Banner() { const [visible, setVisible] = useState(false); - const storageKey = `ngu-banner-dismissed:${SITE_BANNER.id}`; + const storageKey = `site-banner-dismissed:${SITE_BANNER.id}`; useEffect(() => { if (!SITE_BANNER.enabled) return; diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index 41754f7..0c8e37f 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -1,6 +1,6 @@ import { Link } from "react-router-dom"; import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts"; -import nguLogo from "../assets/logos/NGU_Logo.svg"; +import siteLogo from "../assets/logos/NGU_Logo.svg"; import PlatformIcon from "./PlatformIcon.tsx"; const Social_Links = [ @@ -59,7 +59,7 @@ export default function Footer() { width below them. */}
- Next Generation of Unity + Next Generation of Unity
diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx index 057e0c6..3bbf9ae 100644 --- a/src/components/Layout.tsx +++ b/src/components/Layout.tsx @@ -3,7 +3,7 @@ import { Suspense, 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.tsx"; -import nguLogo from "../assets/logos/NGU_Logo.svg"; +import siteLogo from "../assets/logos/NGU_Logo.svg"; import Footer from "./Footer.tsx"; import PrivacyNotice from "./PrivacyNotice.tsx"; import ThemeToggle from "./ThemeToggle.tsx"; @@ -187,7 +187,7 @@ export default function Layout() { >
- Next Generation of Unity + Next Generation of Unity
diff --git a/src/components/PrivacyNotice.tsx b/src/components/PrivacyNotice.tsx index 32d9d16..9453846 100644 --- a/src/components/PrivacyNotice.tsx +++ b/src/components/PrivacyNotice.tsx @@ -16,7 +16,7 @@ import { useEffect, useState } from 'react' import { Link } from 'react-router-dom' -const STORAGE_KEY = 'ngu-privacy-notice-closed' +const STORAGE_KEY = 'site-privacy-notice-closed' export default function PrivacyNotice() { const [visible, setVisible] = useState(false) diff --git a/src/components/ThemeToggle.tsx b/src/components/ThemeToggle.tsx index f74db1f..de9937e 100644 --- a/src/components/ThemeToggle.tsx +++ b/src/components/ThemeToggle.tsx @@ -15,7 +15,7 @@ import { useEffect, useState } from 'react' type Theme = 'light' | 'dark' -export const THEME_STORAGE_KEY = 'ngu-theme' +export const THEME_STORAGE_KEY = 'site-theme' const current = (): Theme => document.documentElement.dataset.theme === 'dark' ? 'dark' : 'light' diff --git a/src/index.css b/src/index.css index 36a9abc..44734a7 100644 --- a/src/index.css +++ b/src/index.css @@ -188,13 +188,13 @@ iframe[src*="churchcenter"] { gap: 0.25rem 1.5rem; grid-template-columns: 2fr 1fr; grid-template-areas: - "ngu image" + "org image" "info image" "desc desc"; } -.ev-ngu { - grid-area: ngu; +.ev-org { + grid-area: org; } .ev-info { @@ -217,7 +217,7 @@ iframe[src*="churchcenter"] { .ev-grid { grid-template-columns: 1fr; grid-template-areas: - "ngu" + "org" "info" "desc"; } diff --git a/src/lib/site.ts b/src/lib/site.ts index 92fe60e..0c538d2 100644 --- a/src/lib/site.ts +++ b/src/lib/site.ts @@ -4,7 +4,7 @@ What the site says about itself, for the browser: /site.json, with the admin's Site settings (Panel) laid over it. The server merges the two and writes the result into each page's HTML as - window.__NGU_SITE__ (server/src/pageMeta.js), which is read here + window.__SITE__ (server/src/pageMeta.js), which is read here before the app renders, so there's no request and no flash of the old wording. In development, or if the API is down and nginx serves the plain index.html, it isn't there and site.json alone @@ -28,7 +28,7 @@ type SiteText = { title?: string; pages?: Record; privacyEmail /* What the server wrote into the page, if it did. */ const fromServer: SiteText = - (typeof window !== 'undefined' && (window as unknown as { __NGU_SITE__?: SiteText }).__NGU_SITE__) || {} + (typeof window !== 'undefined' && (window as unknown as { __SITE__?: SiteText }).__SITE__) || {} export const SITE_NAME: string = fromServer.title || siteConfiguration.title diff --git a/src/pages/admin/AdminLayout.tsx b/src/pages/admin/AdminLayout.tsx index 5f16632..c87506c 100644 --- a/src/pages/admin/AdminLayout.tsx +++ b/src/pages/admin/AdminLayout.tsx @@ -27,7 +27,7 @@ import { AdminTitleContext } from "../../lib/adminTitle.tsx"; import { AdminWidthContext } from "../../lib/adminWidth.tsx"; import { SITE_VERSION } from "../../lib/version.ts"; import { ROLE_LABELS, isSuper } from "../../lib/roles.ts"; -import nguLogo from "../../assets/logos/NGU_Logo.svg"; +import siteLogo from "../../assets/logos/NGU_Logo.svg"; import ThemeToggle from "../../components/ThemeToggle.tsx"; import { ADMIN_HOME, @@ -220,7 +220,7 @@ export default function AdminLayout() {