From b165e612c2f234a12b937f2cb4a4ecfc4e339d30 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Tue, 29 Sep 2026 02:11:57 -0500 Subject: [PATCH] Harden sign-in: __Host- session cookie and a per-email login lock - The session cookie is __Host-ngu_session when Secure (production), so a sibling subdomain can't set or overwrite it; plain ngu_session over local http. Every admin signs in again once after deploying. - Five wrong passwords for one email lock that email for 15 minutes, from any address; a correct password clears it. On top of the per-IP limit. - CLAUDE.md: noImplicitAny stays off on purpose. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/security-headers.md | 13 ++++++++++++ server/src/auth.js | 8 ++++++-- server/src/rateLimit.js | 42 +++++++++++++++++++++++++++++++++++++++ server/src/routes/auth.js | 23 +++++++++++++++++++-- 5 files changed, 83 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f9c3db2..051f5ee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,7 +15,7 @@ Website for NGU (Next Generation of Unity), a Unity movement organization with r Frontend (repo root): - `pnpm dev` / `pnpm build` / `pnpm preview`: Vite - `pnpm format`: oxfmt -- `pnpm exec tsc`: type-check (`noEmit`; there is no separate lint or typecheck script) +- `pnpm exec tsc`: type-check (`noEmit`; there is no separate lint or typecheck script). `noImplicitAny` is off on purpose: turning it on shows about 480 errors (untyped props and params, mostly in OrgList-Map, admin fields, EntityEdit, EventList-Cards). Decided 2026-09-29 not to fix them; don't turn it on or start typing files for it unless asked. New code should still type its props. - There is no test suite. Backend (`server/`, Node >= 22.13). The server reads `HOST` (default `127.0.0.1`), `PORT` (default `3001`), `DB_PATH` (default `./ngu.db`) and `UPLOADS_DIR` (default `./uploads`); locally, use `DB_PATH=./dev.db`: diff --git a/docs/security-headers.md b/docs/security-headers.md index 40b5081..997e0fa 100644 --- a/docs/security-headers.md +++ b/docs/security-headers.md @@ -43,6 +43,19 @@ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; Both lines are already in every proxied block in `nginx-dev` and in `docs/seo.md`. +## Sign-in + +- The session cookie is `__Host-ngu_session`: the browser only + accepts it Secure, on path `/`, with no Domain, so another + subdomain can't set or overwrite it. With `COOKIE_SECURE=false` + (plain-http local work) it's `ngu_session`, since the prefix needs + Secure. +- Logins are limited per IP where `/api/auth/login` is mounted (10 + per 15 minutes, `server/src/index.js`) and per email 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. + ## From nginx: HSTS nginx terminates TLS and serves files from disk (`/assets/`, diff --git a/server/src/auth.js b/server/src/auth.js index 7bcf47b..bfbc60c 100644 --- a/server/src/auth.js +++ b/server/src/auth.js @@ -23,8 +23,6 @@ import { } from "node:crypto"; import { getCookie, setCookie, deleteCookie } from "hono/cookie"; -export const COOKIE_NAME = "ngu_session"; - 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. @@ -35,6 +33,12 @@ 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"; +// __Host- makes the browser refuse the cookie unless it's Secure, on +// path /, with no Domain, so a sibling subdomain can't plant or +// overwrite it. Plain http (local work, COOKIE_SECURE=false) can't +// use the prefix, so it keeps the plain name. +export const COOKIE_NAME = SECURE_COOKIE ? "__Host-ngu_session" : "ngu_session"; + const IP_SALT = process.env.IP_SALT ?? randomBytes(16).toString("hex"); /* ── Passwords ───────────────────────────────────────────────── diff --git a/server/src/rateLimit.js b/server/src/rateLimit.js index ee881f7..6d677f6 100644 --- a/server/src/rateLimit.js +++ b/server/src/rateLimit.js @@ -48,3 +48,45 @@ export function rateLimit({ windowMs = 60_000, max = 10 } = {}) { await next(); }; } + +/* ── Failures per key ────────────────────────────────────────── + For login: count only failed attempts per account, so guessing + one person's password from many addresses still stops, and their + own successful sign-in clears it. Unknown emails are counted the + same way, so the limit says nothing about which accounts exist. + ponytail: in-memory like the IP limit (resets on restart, one + instance); a spray of random emails is swept each window. + ───────────────────────────────────────────────────────────── */ + +export function failureLimit({ windowMs = 15 * 60_000, max = 5 } = {}) { + const failures = new Map(); // key → { count, resetAt } + + setInterval(() => { + const now = Date.now(); + for (const [key, entry] of failures) { + if (entry.resetAt <= now) failures.delete(key); + } + }, windowMs).unref(); + + const live = (key) => { + const entry = failures.get(key); + if (entry && entry.resetAt <= Date.now()) failures.delete(key); + return failures.get(key); + }; + + return { + /** Seconds until the key may try again, or 0. */ + blockedFor(key) { + const entry = live(key); + return entry && entry.count >= max ? Math.ceil((entry.resetAt - Date.now()) / 1000) : 0; + }, + fail(key) { + const entry = live(key) ?? { count: 0, resetAt: Date.now() + windowMs }; + entry.count += 1; + failures.set(key, entry); + }, + clear(key) { + failures.delete(key); + }, + }; +} diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index 179452a..825f12c 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -11,8 +11,9 @@ Three deliberate choices: - Login is rate limited where it's mounted, and answers wrong - password and unknown account identically. Telling an attacker + Login is rate limited where it's mounted (per IP) and here (per + email, failures only), and answers wrong password and unknown + account identically. Telling an attacker which addresses exist is free reconnaissance. A failed login still runs a hash. Otherwise the response time @@ -39,6 +40,12 @@ import { verifyPassword, } from "../auth.js"; import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js"; +import { failureLimit } from "../rateLimit.js"; + +// On top of the per-IP limit where /login is mounted: five wrong +// passwords for one email in 15 minutes locks that email for the +// rest of the window, from anywhere. +const loginFailures = failureLimit({ windowMs: 15 * 60_000, max: 5 }); const auth = new Hono(); @@ -63,6 +70,16 @@ auth.post("/login", async (c) => { return c.json({ error: "Email and password are required." }, 400); } + const wait = loginFailures.blockedFor(email); + if (wait) { + console.warn(`login locked for ${email}`); + return c.json( + { error: "Too many wrong passwords for this account. Try again in a few minutes." }, + 429, + { "Retry-After": String(wait) }, + ); + } + const db = c.get("db"); const user = db @@ -79,10 +96,12 @@ auth.post("/login", async (c) => { : (verifyPassword(password, DUMMY_HASH), false); if (!ok) { + loginFailures.fail(email); console.warn(`login failed for ${email}`); return c.json({ error: "That email and password don't match." }, 401); } + loginFailures.clear(email); createSession(db, c, user.id); db.prepare("UPDATE admin_users SET last_login_at = datetime('now') WHERE id = ?").run(