NGU-Web/server/src/routes/auth.js
Zaldimmar 2ad65cdc15 Write the site in US English
color, center, canceled, labeled, recognize and the rest, in UI
text, help text, comments, docs and names (ColorInput, QrCenter).
Migration 053 renames the two Site settings color CHECKs, whose
names are the messages the admin shows. Kept: events.status's
stored value 'cancelled' (shown as canceled), aria-labelledby,
schema.org's EventCancelled, and old migrations as they ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:24:11 -05:00

287 lines
10 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
AUTH ROUTES
POST /api/auth/login email + password → session cookie
POST /api/auth/logout deletes the session row and cookie
GET /api/auth/me who am I, or 401
GET /api/auth/providers which ways in are switched on
GET /api/auth/google off to Google's account chooser
GET /api/auth/google/callback back from it: sign in, or
back to the login page with ?error=
Three deliberate choices:
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
itself says whether the account exists.
Accounts come from admin-cli.js, with one exception: with access
groups set up (accessGroups.js), a Google sign-in by someone in
one makes a group account, whose role then follows the group.
Otherwise Google sign-in only lets in an account that already
exists: matched by its linked Google id, or on first use by its
email, which then links it. A matching email already linked to a
different Google account is refused rather than relinked.
googleAuth.js checks the identity itself.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import {
SECURE_COOKIE,
logSafe,
createSession,
destroySession,
currentUser,
hashPassword,
verifyPassword,
} from "../auth.js";
import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js";
import { accessEnabled, applyGroupRole, groupRole } from "../accessGroups.js";
import { failureLimit } from "../rateLimit.js";
import { NO_STORE } from "../shape.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();
// A real hash to compare against when the account doesn't exist,
// so both paths cost the same. Computed once at import.
const DUMMY_HASH = hashPassword("this password is never correct");
auth.post("/login", async (c) => {
let body;
try {
// `?? {}`: 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);
}
const email = String(body.email ?? "").trim().toLowerCase().slice(0, 254);
const password = String(body.password ?? "");
if (!email || !password) {
return c.json({ error: "Email and password are required." }, 400);
}
const wait = loginFailures.blockedFor(email);
if (wait) {
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,
{ "Retry-After": String(wait) },
);
}
const db = c.get("db");
const user = db
.prepare(
`SELECT id, email, name, role, password_hash, is_active
FROM admin_users
WHERE email = ?`,
)
.get(email);
const ok =
user && user.is_active === 1
? await verifyPassword(password, user.password_hash)
: (await verifyPassword(password, DUMMY_HASH), false);
if (!ok) {
loginFailures.fail(email);
console.warn(`login failed for ${logSafe(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(
user.id,
);
console.log(`login ${user.email}`);
return c.json(
{ user: { id: user.id, email: user.email, name: user.name, role: user.role } },
200,
NO_STORE,
);
});
auth.post("/logout", (c) => {
destroySession(c.get("db"), c);
return c.body(null, 204);
});
auth.get("/me", (c) => {
const user = currentUser(c.get("db"), c);
if (!user) return c.json({ error: "Not signed in." }, 401, NO_STORE);
return c.json({ user }, 200, NO_STORE);
});
/* ── Google ──────────────────────────────────────────────────── */
// 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.
// __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-site_oauth" : "site_oauth";
const OAUTH_COOKIE_OPTIONS = {
httpOnly: true,
secure: SECURE_COOKIE,
sameSite: "Lax",
path: "/",
};
// Where to land afterwards: an admin page, never anywhere else.
const safeNext = (value) =>
typeof value === "string" && /^\/admin(\/[\w\-/]*)?$/.test(value) ? value : "/admin/home";
const backToLogin = (c, code) => c.redirect(`/admin/login?error=${encodeURIComponent(code)}`, 302);
auth.get("/providers", (c) =>
c.json({ password: true, google: Boolean(googleConfig()) }, 200, NO_STORE),
);
auth.get("/google", (c) => {
const config = googleConfig();
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
if (!config.redirectUri) {
// Said in the log, where whoever runs the box will look; the
// person at the login page just learns it didn't work.
console.error(
"google login: no return address. Set GOOGLE_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.",
);
return backToLogin(c, "google_failed");
}
const { url, state, verifier } = startLogin(config);
setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, next: safeNext(c.req.query("next")) }), {
...OAUTH_COOKIE_OPTIONS,
maxAge: 600,
});
return c.redirect(url, 302);
});
auth.get("/google/callback", async (c) => {
const config = googleConfig();
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
let saved = null;
try {
saved = JSON.parse(getCookie(c, OAUTH_COOKIE) ?? "null");
} catch {
saved = null;
}
deleteCookie(c, OAUTH_COOKIE, OAUTH_COOKIE_OPTIONS);
// Pressing Cancel on Google's screen comes back as ?error=.
if (c.req.query("error")) return backToLogin(c, "canceled");
const code = c.req.query("code");
if (!saved?.state || !code || c.req.query("state") !== saved.state) {
return backToLogin(c, "expired");
}
let identity;
try {
identity = await finishLogin(config, code, saved.verifier);
} catch (err) {
if (err instanceof GoogleLoginError) {
console.warn(`google login refused: ${err.code}`);
return backToLogin(c, err.code);
}
throw err;
}
const db = c.get("db");
const columns = `id, email, name, role, is_active, google_sub, access_source, group_disabled`;
const byId = (id) => db.prepare(`SELECT ${columns} FROM admin_users WHERE id = ?`).get(id);
let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub);
// What the access groups give this person (accessGroups.js), asked
// only when it matters. Unanswerable is a refusal: a sign-in has to
// be shown to be allowed.
const roleFromGroups = async () => {
try {
return { role: await groupRole(db, identity.email) };
} catch (err) {
console.warn(`google login: groups unreadable for ${identity.email}: ${err.message}`);
return { failed: true };
}
};
if (!user) {
const byEmail = db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
if (!byEmail) {
if (!accessEnabled(db)) {
console.warn(`google login: no account for ${identity.email}`);
return backToLogin(c, "no_account");
}
// In an access group: the account is made now, Google only.
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
if (!found.role) {
console.warn(`google login: ${identity.email} is in no access group`);
return backToLogin(c, "not_in_group");
}
const id = db
.prepare(
`INSERT INTO admin_users (email, name, role, google_sub, access_source, groups_checked_at)
VALUES (?, ?, ?, ?, 'group', datetime('now'))`,
)
.run(identity.email, identity.name, found.role, identity.sub).lastInsertRowid;
console.log(`account ${identity.email} made from access group (${found.role})`);
user = byId(id);
} else if (byEmail.google_sub) {
console.warn(`google login: ${identity.email} is linked to another Google account`);
return backToLogin(c, "linked_elsewhere");
} else {
// Before linking: a refused sign-in mustn't change the account.
if (byEmail.is_active !== 1) return backToLogin(c, "disabled");
db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id);
console.log(`google account linked to ${byEmail.email}`);
user = byEmail;
}
}
// A group account's role follows its groups, checked every time.
// One a superadmin disabled stays disabled whatever its groups say.
if (user.access_source === "group" && user.role !== "superadmin" && accessEnabled(db)) {
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
applyGroupRole(db, user, found.role);
if (!found.role) return backToLogin(c, "not_in_group");
user = byId(user.id);
}
if (user.is_active !== 1) return backToLogin(c, "disabled");
createSession(db, c, user.id);
db.prepare(
`UPDATE admin_users SET last_login_at = datetime('now'), name = COALESCE(name, ?) WHERE id = ?`,
).run(identity.name, user.id);
console.log(`login ${user.email} (google)`);
// Checked again: the cookie came back from the browser.
return c.redirect(safeNext(saved.next), 302);
});
export default auth;