adapters/typescript/oidc.ts
5,287 bytes · the TypeScript implementation · view raw
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { io, requireEnv } from "./funeio.ts";
import type { SignedInUser } from "./auth_oauth_sign_in_types.ts";
import { base64UrlDecode } from "./encoding_base64.ts"; ← from encoding.base64 ^1.0.0 · built alongside by fune
import { utf8Decode } from "./encoding_utf8.ts"; ← from encoding.utf8 ^1.0.0 · built alongside by fune
type Discovery = { issuer: string; authorization_endpoint: string; token_endpoint: string };
// key=value pairs, percent-encoded, for a query string or a form body.
function oidcEncode(pairs: [string, string][]): string {
return pairs.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
}
// OIDC_ISSUER without a trailing slash, as issuers compare.
function oidcIssuer(): string {
return requireEnv("OIDC_ISSUER").replace(/\/+$/, "");
}
/** The issuer's discovery document (OpenID Connect Discovery 1.0), checked. */
async function oidcDiscover(): Promise<Discovery> {
const issuer = oidcIssuer();
const url = `${issuer}/.well-known/openid-configuration`;
const res = await io().http({ method: "GET", url, headers: { accept: "application/json" } });
if (res.status !== 200) throw new Error(`oidc: ${url} answered ${res.status}; is OIDC_ISSUER right?`);
let doc: Record<string, unknown>;
try {
doc = JSON.parse(res.body);
} catch {
throw new Error(`oidc: ${url} is not JSON`);
}
for (const key of ["issuer", "authorization_endpoint", "token_endpoint"]) {
if (typeof doc[key] !== "string") throw new Error(`oidc: the discovery document has no ${key}`);
}
if (String(doc.issuer).replace(/\/+$/, "") !== issuer) throw new Error(`oidc: the discovery document is for issuer ${String(doc.issuer)}, not OIDC_ISSUER ${issuer}`);
return doc as unknown as Discovery;
}
/** The issuer's authorisation URL, with PKCE (S256) and a nonce. */
export async function oidcAuthorizeUrl(p: { redirectUri: string; state: string; nonce: string; challenge: string }): Promise<string> {
const clientId = requireEnv("OIDC_CLIENT_ID");
const scopes = io().env("OIDC_SCOPES") ?? "openid email profile";
if (!scopes.split(/\s+/).includes("openid")) throw new Error(`OIDC_SCOPES is "${scopes}"; it must include openid`);
const doc = await oidcDiscover();
const query = oidcEncode([
["response_type", "code"],
["client_id", clientId],
["redirect_uri", p.redirectUri],
["scope", scopes],
["state", p.state],
["nonce", p.nonce],
["code_challenge", p.challenge],
["code_challenge_method", "S256"],
]);
return `${doc.authorization_endpoint}${doc.authorization_endpoint.includes("?") ? "&" : "?"}${query}`;
}
/**
* Exchange the code at the token endpoint and read the id_token's claims.
* The token comes straight from the issuer over TLS, so its claims are
* checked (issuer, audience, nonce, expiry) and its signature need not be
* (OpenID Connect Core 1.0, 3.1.3.7).
*/
export async function oidcExchange(p: { code: string; verifier: string; redirectUri: string; nonce: string }): Promise<SignedInUser> {
const clientId = requireEnv("OIDC_CLIENT_ID");
const secret = io().env("OIDC_CLIENT_SECRET");
const doc = await oidcDiscover();
const form: [string, string][] = [
["grant_type", "authorization_code"],
["code", p.code],
["redirect_uri", p.redirectUri],
["client_id", clientId],
["code_verifier", p.verifier],
];
if (secret) form.push(["client_secret", secret]);
const res = await io().http({
method: "POST",
url: doc.token_endpoint,
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
body: oidcEncode(form),
});
let tokens: Record<string, unknown> = {};
try {
tokens = JSON.parse(res.body);
} catch {
tokens = {};
}
if (res.status !== 200 || tokens.error) {
throw new Error(`oidc: the token endpoint refused the code (${res.status}${tokens.error ? ` ${String(tokens.error)}` : ""})${tokens.error_description ? `: ${String(tokens.error_description)}` : ""}`);
}
if (typeof tokens.id_token !== "string") throw new Error("oidc: the token response has no id_token; OIDC_SCOPES must include openid");
const parts = tokens.id_token.split(".");
let claims: Record<string, unknown>;
try {
claims = JSON.parse(utf8Decode(base64UrlDecode(parts[1] ?? "")));
} catch {
throw new Error("oidc: the id_token is not a JWT");
}
const issuer = String(doc.issuer).replace(/\/+$/, "");
if (String(claims.iss ?? "").replace(/\/+$/, "") !== issuer) throw new Error(`oidc: the id_token was issued by ${String(claims.iss)}, not ${issuer}`);
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
if (!aud.includes(clientId)) throw new Error("oidc: the id_token is not for OIDC_CLIENT_ID (aud)");
if (claims.nonce !== p.nonce) throw new Error("oidc: the id_token's nonce does not match this sign-in");
if (typeof claims.exp !== "number" || claims.exp * 1000 <= io().now()) throw new Error("oidc: the id_token has expired");
if (typeof claims.sub !== "string" || !claims.sub) throw new Error("oidc: the id_token has no subject");
return {
provider: "oidc",
subject: claims.sub,
email: typeof claims.email === "string" ? claims.email : null,
emailVerified: claims.email_verified === true || claims.email_verified === "true",
name: typeof claims.name === "string" ? claims.name : null,
returnTo: null,
};
}