// Shared by the Node backend and browser SPA. Requires Web Crypto (HTTPS or localhost). const base64url = (bytes) => btoa(String.fromCharCode(...bytes)) .replaceAll("+", "-") .replaceAll("/", "_") .replace(/=+$/, ""); const decode = (s) => Uint8Array.from(atob(s.replaceAll("-", "+").replaceAll("_", "/")), (c) => c.charCodeAt(0)); const random = () => base64url(crypto.getRandomValues(new Uint8Array(32))); export async function metadata(issuer) { const u = new URL(issuer); if ( u.origin !== issuer || (u.protocol !== "https:" && !(u.protocol === "http:" && ["localhost", "127.0.0.1"].includes(u.hostname))) ) throw Error("Invalid issuer"); const md = await json(issuer + "/.well-known/openid-configuration"); if ( md.issuer !== issuer || ["authorization_endpoint", "token_endpoint", "userinfo_endpoint", "jwks_uri"].some( (k) => new URL(md[k]).origin !== issuer, ) ) throw Error("Invalid discovery"); return md; } async function json(url, opts = {}) { const r = await fetch(url, { ...opts, credentials: "omit", redirect: "error", cache: "no-store", signal: AbortSignal.timeout(7000), }); if (!r.ok) throw Error("OIDC HTTP " + r.status); return r.json(); } export async function begin(md, client_id, redirect_uri, ui_locales = "en") { const state = random(), nonce = random(), verifier = random(); const code_challenge = base64url( new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))), ); const q = new URLSearchParams({ client_id, redirect_uri, state, nonce, code_challenge, scope: "openid profile email", response_type: "code", code_challenge_method: "S256", ui_locales, }); return { url: md.authorization_endpoint + "?" + q, transaction: { issuer: md.issuer, state, nonce, verifier, client_id, redirect_uri, expires: Date.now() + 600000 }, }; } export async function finish(md, query, tx, secret) { if ( !tx || tx.expires < Date.now() || query.get("state") !== tx.state || tx.issuer !== md.issuer || query.getAll("iss").length !== 1 || query.get("iss") !== tx.issuer || query.has("error") || !query.get("code") ) throw Error("Invalid login transaction"); const body = new URLSearchParams({ grant_type: "authorization_code", redirect_uri: tx.redirect_uri, code_verifier: tx.verifier, code: query.get("code"), }); const headers = {}; const encode = (s) => new URLSearchParams({ x: s }).toString().slice(2); if (secret) headers.Authorization = "Basic " + btoa(encode(tx.client_id) + ":" + encode(secret)); else body.set("client_id", tx.client_id); const tokens = await json(md.token_endpoint, { method: "POST", body, headers }); const parts = tokens.id_token.split("."); if (parts.length !== 3) throw Error("Malformed ID token"); const parse = (s) => JSON.parse(new TextDecoder().decode(decode(s))); const h = parse(parts[0]), claims = parse(parts[1]); const jwks = await json(md.jwks_uri); const jwk = jwks.keys.find((k) => k.kid === h.kid && k.kty === "RSA" && k.alg === "RS256"); if (!jwk || h.alg !== "RS256") throw Error("Unknown signing key"); const key = await crypto.subtle.importKey( "jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"], ); const valid = await crypto.subtle.verify( "RSASSA-PKCS1-v1_5", key, decode(parts[2]), new TextEncoder().encode(parts[0] + "." + parts[1]), ); const now = Date.now() / 1000; if ( !valid || claims.iss !== md.issuer || claims.aud !== tx.client_id || claims.nonce !== tx.nonce || !Number.isFinite(claims.exp) || claims.exp <= now || !Number.isFinite(claims.iat) || claims.iat > now + 60 || typeof claims.sub !== "string" || !claims.sub ) throw Error("Invalid ID token claims"); await profile(md, tokens.access_token, claims.sub); return { access: tokens.access_token, sub: claims.sub }; } export async function profile(md, access, sub) { const info = await json(md.userinfo_endpoint, { headers: { Authorization: "Bearer " + access } }); if (info.sub !== sub) throw Error("UserInfo subject changed"); return info; }