NGU-Web/server/src/googleAuth.js
Zaldimmar e932ee3007 Show Google sign-in even when site.json isn't deployed
/api/auth/providers read site.json to build Google's return address,
and the deploy copies server/ into /srv/ngu-api without site.json, so
it threw and the login page hid the button. Whether Google is on now
depends only on the client id and secret; a missing return address is
logged when a sign-in starts, naming GOOGLE_REDIRECT_URI and
SITE_CONFIG. The docs say how the server is actually deployed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 21:51:40 -05:00

153 lines
5.9 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
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;
set it when the server is deployed
without site.json (SITE_CONFIG)
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;
// Whether Google is on depends only on the id and secret. The
// return address can come from site.json, which a deploy of the
// server alone may not have; that's reported where it's needed
// (the sign-in routes), rather than hiding the button.
let redirectUri = process.env.GOOGLE_REDIRECT_URI ?? null;
if (!redirectUri) {
try {
const origin = (loadSite().url ?? "").replace(/\/$/, "");
if (origin) redirectUri = `${origin}/api/auth/google/callback`;
} catch {
redirectUri = null;
}
}
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 };
}