Add Google sign-in for @nextgenerationofunity.org admin accounts
The login page offers "Sign in with Google" above email and password, once GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET are set on the service. It's the server-side authorization-code flow with PKCE; the ID token comes straight from Google's token endpoint and is checked for issuer, audience, expiry, a verified email and the Workspace domain (Google's hd claim). Only accounts admin-cli has made get in. The first Google sign-in links the account with the same email; later ones match by the link. A disabled account, one linked to another Google account, or a missing account is refused, with a message on the login page, and a refused sign-in never changes the account. admin-cli list shows which accounts are linked. Setup is in docs/google-sign-in.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
64cb2ec56a
commit
d4b39251d9
8 changed files with 392 additions and 28 deletions
|
|
@ -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" : ""),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
||||
|
|
|
|||
143
server/src/googleAuth.js
Normal file
143
server/src/googleAuth.js
Normal file
|
|
@ -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 <site.json url>/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=<code>
|
||||
}
|
||||
}
|
||||
|
||||
/* 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 };
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue