Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

53 linesCodeBlameRaw
1import { data, redirect } from "react-router";
2
3import type { Route } from "./+types/auth-sso-callback";
4import { cookie, readCookie, stateMatches } from "../lib/github";
5import { page } from "../lib/meta";
6import { SSO_STATE_COOKIE, afterSso } from "../lib/sso";
7import { sso } from "../lib/sso.server";
8import { sessionTokenOf } from "../lib/session.server";
9import { SsoProblem } from "./auth-sso";
10
11export function meta({ params, ...args }: Route.MetaArgs) {
12 return page(args, { title: `Single sign-on · ${args.loaderData?.slug ?? params.owner} · g1t` });
13}
14
15/**
16 * Where a workspace's provider returns over OpenID Connect or OAuth 2.0.
17 * The state must match this browser's cookie, and the session must be the
18 * one that set off; identity then spends the state once, exchanges the
19 * code, and links, admits and marks the session.
20 */
21export async function loader({ request, params }: Route.LoaderArgs) {
22 // The provider sends people back to the workspace's id.
23 const key = params.owner.toLowerCase();
24 const url = new URL(request.url);
25 const clear = cookie(SSO_STATE_COOKIE, "", 0);
26 const failed = async (error: string) => {
27 const named = await sso.summary(key).catch(() => null);
28 return data({ slug: named?.slug || key, error }, { headers: { "set-cookie": clear } });
29 };
30 const refused = url.searchParams.get("error");
31 if (refused) {
32 const said = url.searchParams.get("error_description")?.slice(0, 300);
33 return failed(
34 refused === "access_denied"
35 ? "The sign-in was cancelled at the identity provider."
36 : `The identity provider refused the sign-in${said ? `: ${said}` : ` (${refused.slice(0, 60)})`}.`,
37 );
38 }
39 const code = url.searchParams.get("code");
40 const state = url.searchParams.get("state");
41 if (!code || !stateMatches(readCookie(request.headers.get("cookie"), SSO_STATE_COOKIE), state)) {
42 return failed("This sign-in did not start in this browser, or took too long. Start again.");
43 }
44 const token = sessionTokenOf(request);
45 if (!token) return failed("Sign in to g1t again, then start single sign-on again.");
46 const finished = await sso.finish({ slug: key, session_token: token, state: state!, code });
47 if (!finished.ok) return failed(finished.error.message);
48 throw redirect(afterSso(finished.value), { headers: { "set-cookie": clear } });
49}
50
51export default function SsoCallback({ loaderData }: Route.ComponentProps) {
52 return <SsoProblem slug={loaderData.slug} error={loaderData.error} />;
53}