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 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-28 21:56:49 -05:00
parent 693dd84b6e
commit 4066e9ec61
11 changed files with 143 additions and 42 deletions

9
.gitignore vendored
View file

@ -13,15 +13,22 @@ build/
# local databases # local databases
*.db *.db
*.db-journal *.db-journal
*.db-wal
*.db-shm
# editor and OS files # editor and OS files
.vscode/* .vscode/*
!.vscode/extensions.json !.vscode/extensions.json
.DS_Store .DS_Store
Thumbs.db Thumbs.db
nginx-dev
# plain txt files # plain txt files
.txt *.txt
# uploaded media (local dev) # uploaded media (local dev)
server/uploads/ server/uploads/
server/clips/ server/clips/
# skills
graphify-out/

View file

@ -478,6 +478,7 @@ const people = {
key: "private", key: "private",
table: "person_private", table: "person_private",
idColumn: "person_id", 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 touch: true, // has its own updated_at with no trigger behind it
columns: [ columns: [
date("birth_date"), date("birth_date"),

View file

@ -29,6 +29,8 @@ const SESSION_DAYS = 30;
// Re-issue the expiry when a session is used with less than this // Re-issue the expiry when a session is used with less than this
// left, so an active person is never signed out mid-task. // left, so an active person is never signed out mid-task.
const REFRESH_WITHIN_DAYS = 7; 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. // Off only for plain-http local work. Production is behind TLS.
export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false"; export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false";
@ -95,9 +97,11 @@ export function hashIp(ip) {
} }
export function clientIp(c) { export function clientIp(c) {
// Trustworthy only because this service binds to 127.0.0.1 and // The last X-Forwarded-For entry is the one nginx (or Vite in dev)
// nginx is the only thing that can reach it. // added from the connection itself; anything before it is whatever
return c.req.header("x-forwarded-for")?.split(",")[0].trim() ?? null; // 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 ────────────────────────────────────────────────── */ /* ── Sessions ────────────────────────────────────────────────── */
@ -160,9 +164,10 @@ export function currentUser(db, c) {
JOIN admin_users u ON u.id = s.user_id JOIN admin_users u ON u.id = s.user_id
WHERE s.token_hash = ? WHERE s.token_hash = ?
AND s.expires_at > datetime('now') AND s.expires_at > datetime('now')
AND s.created_at > datetime('now', ?)
AND u.is_active = 1`, AND u.is_active = 1`,
) )
.get(tokenHash); .get(tokenHash, `-${MAX_SESSION_DAYS} days`);
if (!row) return null; if (!row) return null;

View file

@ -291,8 +291,9 @@ async function download(db, job) {
await run( await run(
YTDLP, YTDLP,
[ [
// Our options only: no yt-dlp.conf on the box changes them.
"--ignore-config",
...cookies.args, ...cookies.args,
job.source_url,
// YouTube needs a JavaScript runtime to list formats; the one // YouTube needs a JavaScript runtime to list formats; the one
// running this server will do. // running this server will do.
"--js-runtimes", "--js-runtimes",
@ -319,6 +320,9 @@ async function download(db, job) {
...(process.env.FFMPEG_PATH ? ["--ffmpeg-location", process.env.FFMPEG_PATH] : []), ...(process.env.FFMPEG_PATH ? ["--ffmpeg-location", process.env.FFMPEG_PATH] : []),
"-o", "-o",
template, template,
// Last, after --, so the link can never be read as an option.
"--",
job.source_url,
], ],
{ {
onLine: (line) => { onLine: (line) => {

View file

@ -13,7 +13,9 @@ import { mkdir } from "node:fs/promises";
import { serve } from "@hono/node-server"; import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static"; import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono"; import { Hono } from "hono";
import { csrf } from "hono/csrf";
import { logger } from "hono/logger"; import { logger } from "hono/logger";
import { secureHeaders } from "hono/secure-headers";
import { openDatabase, migrate } from "./db.js"; import { openDatabase, migrate } from "./db.js";
import { rateLimit } from "./rateLimit.js"; import { rateLimit } from "./rateLimit.js";
@ -57,6 +59,39 @@ const app = new Hono();
app.use("*", logger()); 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) => { app.use("*", async (c, next) => {
c.set("db", db); c.set("db", db);
await next(); await next();

View file

@ -40,35 +40,24 @@ const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)";
/* ── Address checks ────────────────────────────────────────── */ /* ── Address checks ────────────────────────────────────────── */
function ipv4Blocked(ip) { /* Private, loopback, link-local, shared, benchmark, multicast and
const [a, b] = ip.split(".").map(Number); reserved ranges. BlockList also judges an IPv4-mapped IPv6 address
return ( (::ffff:7f00:1, however it's written) by the IPv4 inside it. The
a === 0 || IPv6 ranges that embed an IPv4 some other way (NAT64, 6to4, the
a === 10 || old compatible form) are refused outright. */
a === 127 || const BLOCKED = new net.BlockList();
(a === 100 && b >= 64 && b <= 127) || for (const [ip, bits] of [
(a === 169 && b === 254) || ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8],
(a === 172 && b >= 16 && b <= 31) || ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.168.0.0", 16],
(a === 192 && b === 168) || ["198.18.0.0", 15], ["224.0.0.0", 3],
(a === 192 && b === 0) || ]) BLOCKED.addSubnet(ip, bits, "ipv4");
(a === 198 && (b === 18 || b === 19)) || for (const [ip, bits] of [
a >= 224 ["::", 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) { function ipBlocked(ip) {
if (net.isIPv4(ip)) return ipv4Blocked(ip); return BLOCKED.check(ip, net.isIPv4(ip) ? "ipv4" : "ipv6");
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
);
} }
async function vet(raw) { async function vet(raw) {

View file

@ -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;

View file

@ -450,7 +450,8 @@ export function renderPage(html, meta) {
tags.splice(2, 0, `<meta name="robots" content="noindex, nofollow">`); tags.splice(2, 0, `<meta name="robots" content="noindex, nofollow">`);
} }
return out.replace(/<\/head>/i, ` ${tags.join("\n ")}\n </head>`); // A function, so a $& or $` in record text isn't read as a pattern.
return out.replace(/<\/head>/i, () => ` ${tags.join("\n ")}\n </head>`);
} }
/* ── Sitemap ───────────────────────────────────────────────── */ /* ── Sitemap ───────────────────────────────────────────────── */

View file

@ -5,11 +5,13 @@
the service restarts and it doesn't survive a second instance, the service restarts and it doesn't survive a second instance,
both of which are fine for one systemd unit on one box. both of which are fine for one systemd unit on one box.
The client IP comes from X-Forwarded-For, which nginx sets. That The client IP comes from clientIp() in auth.js (the entry nginx
header is only trustworthy because nothing but nginx can reach adds to X-Forwarded-For). That is only trustworthy because
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";
export function rateLimit({ windowMs = 60_000, max = 10 } = {}) { export function rateLimit({ windowMs = 60_000, max = 10 } = {}) {
const hits = new Map(); // ip → { count, resetAt } const hits = new Map(); // ip → { count, resetAt }
@ -22,8 +24,7 @@ export function rateLimit({ windowMs = 60_000, max = 10 } = {}) {
}, windowMs).unref(); }, windowMs).unref();
return async (c, next) => { return async (c, next) => {
const ip = const ip = clientIp(c) ?? "unknown";
c.req.header("x-forwarded-for")?.split(",")[0].trim() ?? "unknown";
const now = Date.now(); const now = Date.now();
let entry = hits.get(ip); let entry = hits.get(ip);

View file

@ -52,6 +52,16 @@ function entityForWrite(c) {
return entity; 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 /* Everything the select inputs need, in one request. Small enough
that paging it would cost more than it saves. */ that paging it would cost more than it saves. */
entities.get("/options", (c) => { entities.get("/options", (c) => {
@ -71,12 +81,12 @@ entities.get("/:entity", (c) => {
entities.get("/:entity/:id", (c) => { entities.get("/:entity/:id", (c) => {
const entity = entityOr404(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) => { entities.post("/:entity", requireRole("editor"), async (c) => {
const entity = entityForWrite(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}`); console.log(`${entity.key} ${row[entity.idColumn]} created by ${c.get("user").email}`);
return c.json({ row }, 201, NO_STORE); 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) => { entities.patch("/:entity/:id", requireRole("editor"), async (c) => {
const entity = entityForWrite(c); const entity = entityForWrite(c);
const id = c.req.param("id"); 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}`); console.log(`${entity.key} ${id} updated by ${c.get("user").email}`);
return c.json({ row }, 200, NO_STORE); return c.json({ row }, 200, NO_STORE);
}); });

View file

@ -39,6 +39,15 @@ export function Anchor({
className?: string className?: string
style?: CSSProperties 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 (
<span className={className} style={style}>
{children}
</span>
)
}
if (isExternalUrl(href)) { if (isExternalUrl(href)) {
const app = /^(mailto|tel):/i.test(href) const app = /^(mailto|tel):/i.test(href)
return ( return (