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
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 };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue