diff --git a/CLAUDE.md b/CLAUDE.md index 32e5a12..acb20d0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,6 +33,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Never run commands against the production server or database unless explicitly asked. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html). nginx setup: `docs/seo.md`. +- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.md`. ## Git workflow - Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`. diff --git a/docs/google-sign-in.md b/docs/google-sign-in.md new file mode 100644 index 0000000..607f868 --- /dev/null +++ b/docs/google-sign-in.md @@ -0,0 +1,67 @@ +# Google sign-in + +The admin login offers "Sign in with Google" for +@nextgenerationofunity.org accounts, alongside email and password. It's +off until the service has an OAuth client ID and secret. + +## Who gets in + +Only accounts that already exist. Create them as before with +`admin-cli.js add ` (the password it asks for stays as a way in +if Google is ever unavailable). The first time that person signs in with +Google, their Google account is linked to the admin account with the +same email; after that it matches by the link, even if the email later +changes. `admin-cli.js list` shows which accounts are linked. + +Refused, with a message on the login page: no admin account for that +email, an email already linked to a different Google account, a +disabled account, any account outside the Workspace domain (checked by +Google's `hd` claim, not just the email), an unverified email. + +Code: `server/src/googleAuth.js` (the Google side) and +`server/src/routes/auth.js` (matching and linking accounts). + +## Setting up the OAuth client + +In [Google Cloud Console](https://console.cloud.google.com/), signed in +as a Workspace admin for nextgenerationofunity.org: + +1. **Create or pick a project**, eg. "NGU Website". +2. **APIs & Services → OAuth consent screen** (Google Auth Platform → + Branding / Audience): + - User type / audience: **Internal**. Only accounts in the Workspace + can use it, and Google doesn't need to review the app. + - App name: NGU Admin. Support email: yours. + - Scopes: `openid`, `email`, `profile` (nothing else is needed). +3. **APIs & Services → Credentials → Create credentials → OAuth client + ID** (Google Auth Platform → Clients): + - Application type: **Web application**. Name: NGU admin. + - Authorized redirect URIs: + - `https://nextgenerationofunity.org/api/auth/google/callback` + - for local work, also the dev address, eg. + `http://localhost:5174/api/auth/google/callback` + - No JavaScript origins are needed: the browser never talks to Google + directly. +4. Copy the **Client ID** and **Client secret**. + +## Turning it on + +On the server, add them to the `ngu-api` unit (`systemctl edit ngu-api`) +and restart. Never commit the secret or paste it into the repo: + +```ini +[Service] +Environment=GOOGLE_CLIENT_ID= +Environment=GOOGLE_CLIENT_SECRET= +``` + +Optional: + +| Variable | Default | +| --- | --- | +| `GOOGLE_REDIRECT_URI` | `/api/auth/google/callback`. Set it for local work, eg. `http://localhost:5174/api/auth/google/callback`, and add the same URI in step 3. | +| `GOOGLE_ALLOWED_DOMAIN` | `nextgenerationofunity.org` | + +The login page asks `/api/auth/providers` whether Google is set up, so +the button appears as soon as the service restarts with both values. +Locally, also set `COOKIE_SECURE=false` when working over plain http. diff --git a/server/src/admin-cli.js b/server/src/admin-cli.js index b294a69..7c907f3 100644 --- a/server/src/admin-cli.js +++ b/server/src/admin-cli.js @@ -209,6 +209,7 @@ function list(db) { const rows = db .prepare( `SELECT u.email, u.name, u.role, u.is_active, u.last_login_at, + u.google_sub IS NOT NULL AS google, (SELECT COUNT(*) FROM sessions s WHERE s.user_id = u.id AND s.expires_at > datetime('now')) AS sessions FROM admin_users u @@ -228,7 +229,8 @@ function list(db) { const state = r.is_active ? r.role : `${r.role} (disabled)`; const seen = r.last_login_at ?? "never"; console.log( - `${r.email.padEnd(32)} ${state.padEnd(22)} last login ${seen.padEnd(20)} ${r.sessions} session(s)`, + `${r.email.padEnd(32)} ${state.padEnd(22)} last login ${seen.padEnd(20)} ${r.sessions} session(s)` + + (r.google ? " google linked" : ""), ); } } diff --git a/server/src/auth.js b/server/src/auth.js index 9a8a181..d1eed5a 100644 --- a/server/src/auth.js +++ b/server/src/auth.js @@ -31,7 +31,7 @@ const SESSION_DAYS = 30; const REFRESH_WITHIN_DAYS = 7; // Off only for plain-http local work. Production is behind TLS. -const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false"; +export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false"; const IP_SALT = process.env.IP_SALT ?? randomBytes(16).toString("hex"); diff --git a/server/src/googleAuth.js b/server/src/googleAuth.js new file mode 100644 index 0000000..8f59943 --- /dev/null +++ b/server/src/googleAuth.js @@ -0,0 +1,143 @@ +/* ═══════════════════════════════════════════════════════════════ + GOOGLE SIGN-IN + + The OAuth 2.0 authorization-code flow with PKCE, done on the + server, for @nextgenerationofunity.org accounts. The routes are + in routes/auth.js; this is the part that talks to Google and + decides whether an answer is good enough. + + Configured by the service environment: + + GOOGLE_CLIENT_ID from Google Cloud Console + GOOGLE_CLIENT_SECRET the same; never in the repo + GOOGLE_REDIRECT_URI default /api/auth/google/callback + GOOGLE_ALLOWED_DOMAIN default nextgenerationofunity.org + + With no client id or secret it's off: the login page doesn't + offer it and the routes answer 404. Setup: docs/google-sign-in.md. + + ── Why the ID token isn't signature-checked ── + The token comes straight from Google's token endpoint, over TLS, + in answer to a request this server made with its own secret. + Google's documentation says a token received that way can be + trusted without verifying its signature. Everything else is + checked: issuer, audience (our client id), expiry, a verified + email, and the Workspace domain in the `hd` claim, which only + Google sets, not just the email's suffix. + + Nothing here creates an account. A Google login is only let in + if admin-cli has already made one for that email (see auth.js + routes), and is linked to it on first use. + ═══════════════════════════════════════════════════════════════ */ + +import { createHash, randomBytes } from "node:crypto"; + +import { loadSite } from "./pageMeta.js"; + +const AUTHORIZE = "https://accounts.google.com/o/oauth2/v2/auth"; +const TOKEN = "https://oauth2.googleapis.com/token"; +const ISSUERS = new Set(["accounts.google.com", "https://accounts.google.com"]); + +const base64url = (buf) => buf.toString("base64url"); + +export function googleConfig() { + const clientId = process.env.GOOGLE_CLIENT_ID; + const clientSecret = process.env.GOOGLE_CLIENT_SECRET; + if (!clientId || !clientSecret) return null; + + let redirectUri = process.env.GOOGLE_REDIRECT_URI; + if (!redirectUri) { + const origin = (loadSite().url ?? "").replace(/\/$/, ""); + redirectUri = `${origin}/api/auth/google/callback`; + } + + return { + clientId, + clientSecret, + redirectUri, + domain: (process.env.GOOGLE_ALLOWED_DOMAIN ?? "nextgenerationofunity.org").toLowerCase(), + }; +} + +/* The first leg: where to send the browser, and the state and PKCE + verifier to keep (in a short-lived cookie) until it comes back. */ +export function startLogin(config) { + const state = base64url(randomBytes(24)); + const verifier = base64url(randomBytes(48)); + const challenge = base64url(createHash("sha256").update(verifier).digest()); + + const url = new URL(AUTHORIZE); + url.search = new URLSearchParams({ + client_id: config.clientId, + redirect_uri: config.redirectUri, + response_type: "code", + scope: "openid email profile", + state, + code_challenge: challenge, + code_challenge_method: "S256", + // Only a hint to Google's account chooser; the hd claim is what's + // actually checked on the way back. + hd: config.domain, + prompt: "select_account", + }); + + return { url: url.toString(), state, verifier }; +} + +export class GoogleLoginError extends Error { + constructor(code, message) { + super(message); + this.code = code; // shown to the login page as ?error= + } +} + +/* The second leg: trade the code for tokens and check the identity. + Returns { sub, email, name } or throws GoogleLoginError. */ +export async function finishLogin(config, code, verifier) { + let res; + try { + res = await fetch(TOKEN, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + code, + client_id: config.clientId, + client_secret: config.clientSecret, + redirect_uri: config.redirectUri, + grant_type: "authorization_code", + code_verifier: verifier, + }), + signal: AbortSignal.timeout(10_000), + }); + } catch { + throw new GoogleLoginError("google_unreachable", "Couldn't reach Google."); + } + + const body = await res.json().catch(() => ({})); + if (!res.ok || !body.id_token) { + console.warn(`google token exchange failed: ${res.status} ${body.error ?? ""}`); + throw new GoogleLoginError("google_failed", "Google didn't accept the sign-in."); + } + + let claims; + try { + claims = JSON.parse(Buffer.from(body.id_token.split(".")[1], "base64url").toString("utf8")); + } catch { + throw new GoogleLoginError("google_failed", "Google's answer couldn't be read."); + } + + const now = Math.floor(Date.now() / 1000); + if (!ISSUERS.has(claims.iss) || claims.aud !== config.clientId || !(claims.exp > now)) { + throw new GoogleLoginError("google_failed", "Google's answer didn't check out."); + } + + const email = String(claims.email ?? "").toLowerCase(); + if (!claims.email_verified || !email) { + throw new GoogleLoginError("unverified", "That Google account's email isn't verified."); + } + if (String(claims.hd ?? "").toLowerCase() !== config.domain || !email.endsWith(`@${config.domain}`)) { + throw new GoogleLoginError("wrong_domain", `Use your @${config.domain} account.`); + } + + return { sub: String(claims.sub), email, name: claims.name ?? null }; +} diff --git a/server/src/index.js b/server/src/index.js index 8f8cd31..0c9a45f 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -76,6 +76,9 @@ app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 })); app.route("/api/feedback", feedback); app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 })); +// Looser than a password guess: each Google sign-in is two requests, +// and Google has already checked the person by the second. +app.use("/api/auth/google/*", rateLimit({ windowMs: 15 * 60_000, max: 40 })); app.route("/api/admin/panel", panel); app.route("/api/auth", auth); app.route("/api/admin", admin); diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index b84eba8..e2100f9 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -4,6 +4,10 @@ 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: @@ -14,18 +18,27 @@ A failed login still runs a hash. Otherwise the response time itself says whether the account exists. - Nothing here creates accounts. See admin-cli.js. + Nothing here creates accounts. See admin-cli.js. 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, createSession, destroySession, currentUser, hashPassword, verifyPassword, } from "../auth.js"; +import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js"; const auth = new Hono(); @@ -96,4 +109,103 @@ auth.get("/me", (c) => { 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. +const OAUTH_COOKIE = "ngu_oauth"; +const OAUTH_COOKIE_OPTIONS = { + httpOnly: true, + secure: SECURE_COOKIE, + sameSite: "Lax", + path: "/api/auth/google", +}; + +// 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); + + 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, "cancelled"); + + 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`; + let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub); + + if (!user) { + const byEmail = db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email); + if (!byEmail) { + console.warn(`google login: no account for ${identity.email}`); + return backToLogin(c, "no_account"); + } + if (byEmail.google_sub) { + console.warn(`google login: ${identity.email} is linked to another Google account`); + return backToLogin(c, "linked_elsewhere"); + } + // 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; + } + + 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)`); + + return c.redirect(saved.next ?? "/admin/home", 302); +}); + export default auth; diff --git a/src/pages/admin/AdminLogin.tsx b/src/pages/admin/AdminLogin.tsx index 69c70a5..d03b6cf 100644 --- a/src/pages/admin/AdminLogin.tsx +++ b/src/pages/admin/AdminLogin.tsx @@ -5,18 +5,35 @@ page of the website; it's the door to the back office, and it shouldn't carry a banner, a subnav, or a footer site map. - The Google button is stubbed and disabled until the OAuth - routes exist. It's here so the layout doesn't change when it - starts working. + Google first, when the server has it set up (/auth/providers + says so; it's off until GOOGLE_CLIENT_ID and _SECRET are on the + service). It's a plain link: the server sends the browser to + Google and back, and a refusal comes back here as ?error=, + worded below. Email and password stay underneath as the way in + if Google is ever unavailable. ═══════════════════════════════════════════════════════════════ */ -import { useState } from "react"; -import { useLocation, useNavigate } from "react-router-dom"; +import { useEffect, useState } from "react"; +import { useLocation, useNavigate, useSearchParams } from "react-router-dom"; import { useAuth } from "../../lib/auth.tsx"; -import { ApiError } from "../../lib/api.ts"; +import { ApiError, get } from "../../lib/api.ts"; -const GOOGLE_ENABLED = false; +/* What a ?error= from the Google callback means, in the words the + person at the login page needs. */ +const GOOGLE_ERRORS: Record = { + cancelled: "Google sign-in was cancelled.", + expired: "That sign-in took too long or was already used. Try again.", + no_account: + "There's no admin account for that Google account. Ask a superadmin to add your email.", + linked_elsewhere: + "That email's admin account is linked to a different Google account.", + disabled: "That account has been disabled.", + wrong_domain: "Use your @nextgenerationofunity.org Google account.", + unverified: "That Google account's email isn't verified.", + google_unreachable: "Couldn't reach Google. Try again in a moment.", + google_failed: "Google sign-in didn't work. Try again, or use your password.", +}; const fieldClass = "w-full rounded-xl border border-[#4a6b72]/25 bg-white px-4 py-3 text-[#26454c] " + @@ -27,9 +44,21 @@ export default function AdminLogin() { const navigate = useNavigate(); const location = useLocation(); + const [searchParams] = useSearchParams(); + const googleError = searchParams.get("error"); + const [google, setGoogle] = useState(false); + + useEffect(() => { + get("/auth/providers", { ttl: 0 }) + .then((data) => setGoogle(Boolean(data.google))) + .catch(() => setGoogle(false)); + }, []); + const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); - const [error, setError] = useState(null); + const [error, setError] = useState( + googleError ? (GOOGLE_ERRORS[googleError] ?? GOOGLE_ERRORS.google_failed) : null, + ); const [busy, setBusy] = useState(false); const destination = location.state?.from?.pathname ?? "/admin/home"; @@ -60,7 +89,7 @@ export default function AdminLogin() {

NGU admin

- Sign in to read and triage site feedback. + Sign in to edit the site.

+ {google && ( + <> + + + Sign in with Google + +
+ + or with a password + +
+ + )} +