g1t/apps/web/app/routes/oauth-authorize.tsx

186 lines7,116 bytesCodeBlame
1import { CircleX, KeyRound } from "lucide-react";
2import { Form, redirect } from "react-router";
3
4import { decodeOAuthClient, isRegisteredRedirect } from "@g1t/contracts";
5
6import type { Route } from "./+types/oauth-authorize";
7import { page } from "../lib/meta";
8import { ErrorText, SubmitButton, usePending } from "../components/ui";
9import { ScopeChecklist } from "../components/token-scopes";
10import { identity } from "../lib/services.server";
11import { addresses } from "../lib/addresses.server";
12import { consentedScopes, requestedScopes } from "../lib/token-scopes";
13import { assertSameOrigin, requireUser } from "../lib/session.server";
14
15export function meta(args: Route.MetaArgs) {
16 return page(args, { title: "Sign in to an application · g1t" });
17}
18
19type Checked =
20 | { ok: false; problem: string }
21 | {
22 ok: true;
23 clientId: string;
24 clientName: string;
25 redirectUri: string;
26 codeChallenge: string;
27 state: string;
28 };
29
30/**
31 * Checks an authorization request. A request that names a client or a
32 * redirect address we cannot vouch for is never redirected anywhere; the
33 * person is told instead.
34 */
35function check(params: URLSearchParams | FormData): Checked {
36 const get = (key: string) => String(params.get(key) ?? "");
37 const client = decodeOAuthClient(get("client_id"));
38 if (!client) {
39 return { ok: false, problem: "This sign-in link names an application g1t does not recognise." };
40 }
41 const redirectUri = get("redirect_uri") || client.redirectUris[0];
42 if (!isRegisteredRedirect(client, redirectUri)) {
43 return {
44 ok: false,
45 problem: "This sign-in link would send you somewhere the application did not register.",
46 };
47 }
48 if (get("response_type") !== "code") {
49 return { ok: false, problem: "This sign-in link asks for a kind of access g1t does not offer." };
50 }
51 if (!get("code_challenge") || get("code_challenge_method") !== "S256") {
52 return {
53 ok: false,
54 problem: "This application did not protect its sign-in with PKCE (S256), which g1t requires.",
55 };
56 }
57 return {
58 ok: true,
59 clientId: get("client_id"),
60 clientName: client.name,
61 redirectUri,
62 codeChallenge: get("code_challenge"),
63 state: get("state"),
64 };
65}
66
67/** The application's redirect address with the outcome added to it. */
68function callback(redirectUri: string, params: Record<string, string>): string {
69 const url = new URL(redirectUri);
70 for (const [key, value] of Object.entries(params)) {
71 if (value) url.searchParams.set(key, value);
72 }
73 return url.toString();
74}
75
76/** Where an application sends a person to approve its sign-in. */
77export function loader({ request, context }: Route.LoaderArgs) {
78 const user = requireUser(context, request);
79 const { searchParams } = new URL(request.url);
80 return {
81 user,
82 request: check(searchParams),
83 // What the application asked for; nothing usable means the default set.
84 requested: requestedScopes(searchParams.get("scope")),
85 // Sent back unchanged when the person decides.
86 query: Object.fromEntries(searchParams),
87 };
88}
89
90export async function action({ request, context }: Route.ActionArgs) {
91 assertSameOrigin(request);
92 const user = requireUser(context, request);
93 const form = await request.formData();
94 const checked = check(form);
95 if (!checked.ok) return null;
96 if (form.get("decision") !== "approve") {
97 throw redirect(
98 callback(checked.redirectUri, { error: "access_denied", state: checked.state }),
99 );
100 }
101 // Only what the application asked for, never more, whatever the form says.
102 const scopes = consentedScopes(form, requestedScopes(String(form.get("scope") ?? "")));
103 if (scopes.length === 0) {
104 return { error: "Leave at least one box ticked, or deny." };
105 }
106 const { code } = await identity.oauthAuthorize(user, {
107 clientId: checked.clientId,
108 clientName: checked.clientName,
109 redirectUri: checked.redirectUri,
110 codeChallenge: checked.codeChallenge,
111 scopes,
112 });
113 // `iss` is the API's origin, the issuer its metadata names (RFC 9207).
114 throw redirect(
115 callback(checked.redirectUri, { code, state: checked.state, iss: addresses().api }),
116 );
117}
118
119export default function Authorize({ loaderData, actionData }: Route.ComponentProps) {
120 const { user, request, requested, query } = loaderData;
121 // Either answer turns both buttons off until it is in.
122 const deciding = usePending();
123
124 if (!request.ok) {
125 return (
126 <main className="mx-auto max-w-md px-4 py-32 text-center">
127 <CircleX size={40} className="mx-auto text-muted" />
128 <h1 className="mt-6 text-2xl font-semibold tracking-tight">This link cannot be used</h1>
129 <p className="mt-2 text-muted">{request.problem}</p>
130 <p className="mt-2 text-sm text-faint">Nothing was given access to your account.</p>
131 </main>
132 );
133 }
134
135 const destination = new URL(request.redirectUri);
136 return (
137 <main className="mx-auto max-w-md px-4 py-24">
138 <KeyRound size={36} className="text-accent" />
139 <h1 className="mt-6 text-2xl font-semibold tracking-tight">
140 Sign in to {request.clientName}
141 </h1>
142 <p className="mt-2 text-muted">
143 <span className="font-medium text-fg">{request.clientName}</span> wants to act as{" "}
144 <span className="font-mono font-medium text-fg">{user.username}</span> on g1t.
145 </p>
146
147 <Form method="post" className="mt-6 space-y-6">
148 {Object.entries(query).map(([name, value]) => (
149 <input key={name} type="hidden" name={name} value={value} />
150 ))}
151 <section>
152 <h2 className="text-sm font-medium">It will be able to</h2>
153 <p className="mt-0.5 text-xs text-faint">
154 Everywhere you can, as you. Untick anything you would rather it could not do.
155 </p>
156 <div className="mt-3">
157 <ScopeChecklist initial={requested} only={requested} allowFull={false} />
158 </div>
159 </section>
160 <dl className="rounded-xl border border-line bg-surface p-4 text-sm">
161 <dt className="text-xs text-faint">You will be sent back to</dt>
162 <dd className="mt-0.5 font-mono text-[0.8125rem] break-all">
163 {destination.protocol === "https:" || destination.protocol === "http:"
164 ? destination.host + destination.pathname
165 : request.redirectUri}
166 </dd>
167 </dl>
168 <div>
169 <p className="text-xs text-faint">
170 Approve only if you started this from {request.clientName} yourself. You can change
171 what it may do, or sign it out, in Settings.
172 </p>
173 <ErrorText>{actionData?.error}</ErrorText>
174 <div className="mt-4 flex gap-2">
175 <SubmitButton variant="accent" name="decision" value="approve" pending="Approving…" disabled={deciding}>
176 Approve
177 </SubmitButton>
178 <SubmitButton variant="quiet" name="decision" value="deny" pending="Denying…" disabled={deciding}>
179 Deny
180 </SubmitButton>
181 </div>
182 </div>
183 </Form>
184 </main>
185 );
186}