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 <noreply@anthropic.com>
This commit is contained in:
parent
d1a6332a45
commit
b165e612c2
5 changed files with 83 additions and 5 deletions
|
|
@ -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`:
|
||||
|
|
|
|||
|
|
@ -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/`,
|
||||
|
|
|
|||
|
|
@ -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 ─────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue