| 1 | import { data, redirect } from "react-router"; |
| 2 | |
| 3 | import type { Route } from "./+types/auth-sso-callback"; |
| 4 | import { cookie, readCookie, stateMatches } from "../lib/github"; |
| 5 | import { page } from "../lib/meta"; |
| 6 | import { SSO_STATE_COOKIE, afterSso } from "../lib/sso"; |
| 7 | import { sso } from "../lib/sso.server"; |
| 8 | import { sessionTokenOf } from "../lib/session.server"; |
| 9 | import { SsoProblem } from "./auth-sso"; |
| 10 | |
| 11 | export 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 | */ |
| 21 | export 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(refused === "access_denied" ? "The sign-in was cancelled at the identity provider." : `The identity provider refused the sign-in${said ? `: ${said}` : ` (${refused.slice(0, 60)})`}.`); |
| 34 | } |
| 35 | const code = url.searchParams.get("code"); |
| 36 | const state = url.searchParams.get("state"); |
| 37 | if (!code || !stateMatches(readCookie(request.headers.get("cookie"), SSO_STATE_COOKIE), state)) { |
| 38 | return failed("This sign-in did not start in this browser, or took too long. Start again."); |
| 39 | } |
| 40 | const token = sessionTokenOf(request); |
| 41 | if (!token) return failed("Sign in to g1t again, then start single sign-on again."); |
| 42 | const finished = await sso.finish({ slug: key, session_token: token, state: state!, code }); |
| 43 | if (!finished.ok) return failed(finished.error.message); |
| 44 | throw redirect(afterSso(finished.value), { headers: { "set-cookie": clear } }); |
| 45 | } |
| 46 | |
| 47 | export default function SsoCallback({ loaderData }: Route.ComponentProps) { |
| 48 | return <SsoProblem slug={loaderData.slug} error={loaderData.error} />; |
| 49 | } |