Functional Weave
Code in TypeScript

auth.oauth-sign-in@1.0.0

adapters/typescript/github.ts

3,376 bytes · the TypeScript implementation · view raw

import { io, requireEnv } from "./funeio.ts";
import type { SignedInUser } from "./auth_oauth_sign_in_types.ts";

const AUTHORIZE = "https://github.com/login/oauth/authorize";
const TOKEN = "https://github.com/login/oauth/access_token";
const API = "https://api.github.com";

function githubEncode(pairs: [string, string][]): string {
  return pairs.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
}

/** GitHub's authorisation URL, asking for the profile and email addresses, with PKCE. */
export async function githubAuthorizeUrl(p: { redirectUri: string; state: string; nonce: string; challenge: string }): Promise<string> {
  const clientId = requireEnv("GITHUB_CLIENT_ID");
  return `${AUTHORIZE}?${githubEncode([
    ["client_id", clientId],
    ["redirect_uri", p.redirectUri],
    ["scope", "read:user user:email"],
    ["state", p.state],
    ["code_challenge", p.challenge],
    ["code_challenge_method", "S256"],
  ])}`;
}

async function githubGet(path: string, token: string): Promise<unknown> {
  const res = await io().http({
    method: "GET",
    url: `${API}${path}`,
    headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "user-agent": "fune-auth-oauth-sign-in", "x-github-api-version": "2022-11-28" },
  });
  if (res.status !== 200) throw new Error(`github: ${path} answered ${res.status}`);
  return JSON.parse(res.body);
}

/**
 * Exchange the code for a token (GitHub answers an error with status 200 and
 * an "error" field), then read the user and their primary verified email.
 */
export async function githubExchange(p: { code: string; verifier: string; redirectUri: string; nonce: string }): Promise<SignedInUser> {
  const clientId = requireEnv("GITHUB_CLIENT_ID");
  const secret = requireEnv("GITHUB_CLIENT_SECRET");
  const res = await io().http({
    method: "POST",
    url: TOKEN,
    headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
    body: githubEncode([
      ["client_id", clientId],
      ["client_secret", secret],
      ["code", p.code],
      ["redirect_uri", p.redirectUri],
      ["code_verifier", p.verifier],
    ]),
  });
  let tokens: Record<string, unknown> = {};
  try {
    tokens = JSON.parse(res.body);
  } catch {
    tokens = {};
  }
  if (res.status !== 200 || tokens.error || typeof tokens.access_token !== "string") {
    throw new Error(`github: the token endpoint refused the code (${res.status}${tokens.error ? ` ${String(tokens.error)}` : ""})${tokens.error_description ? `: ${String(tokens.error_description)}` : ""}`);
  }
  const user = (await githubGet("/user", tokens.access_token)) as Record<string, unknown>;
  if (typeof user.id !== "number") throw new Error("github: /user has no id");
  const emails = (await githubGet("/user/emails", tokens.access_token)) as Record<string, unknown>[];
  const list = Array.isArray(emails) ? emails : [];
  const chosen = list.find((e) => e.primary === true && e.verified === true) ?? list.find((e) => e.verified === true) ?? null;
  return {
    provider: "github",
    subject: String(user.id),
    email: chosen && typeof chosen.email === "string" ? chosen.email : null,
    emailVerified: Boolean(chosen),
    name: typeof user.name === "string" && user.name ? user.name : typeof user.login === "string" ? user.login : null,
    returnTo: null,
  };
}