Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderAuthenticationSection.tsx

472 lines17.7 KB

1import {
2 isAtomCommandInterrupted,
3 squashAtomCommandFailure,
4 type AtomCommandResult,
5} from "@t3tools/client-runtime/state/runtime";
6import type {
7 EnvironmentId,
8 ProviderAuthRespondInput,
9 ProviderAuthResponse,
10 ProviderInstanceId,
11 ServerProvider,
12} from "@t3tools/contracts";
13import { lazy, Suspense, useRef, useState } from "react";
14import { CopyIcon } from "lucide-react";
15​
16import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";
17import { ensureLocalApi } from "../../localApi";
18import { useEnvironmentQuery } from "../../state/query";
19import { serverEnvironment } from "../../state/server";
20import { useAtomCommand } from "../../state/use-atom-command";
21import { Button } from "../ui/button";
22import { Input } from "../ui/input";
23import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
24import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
25import { SettingsRow } from "./settingsLayout";
26import { RedactedSensitiveText } from "./RedactedSensitiveText";
27​
28const ProviderAuthTerminal = lazy(() => import("./ProviderAuthTerminal"));
29​
30export function ProviderAuthenticationSection({
31 environmentId,
32 environmentLabel,
33 instanceId,
34 provider,
35 readOnly,
36}: {
37 readonly environmentId: EnvironmentId;
38 readonly environmentLabel: string;
39 readonly instanceId: ProviderInstanceId;
40 readonly provider: ServerProvider;
41 readonly readOnly: boolean;
42}) {
43 const target = { environmentId, input: { instanceId } };
44 const query = useEnvironmentQuery(serverEnvironment.providerAuthState(target));
45 const commands = { reportFailure: false, reportDefect: false };
46 const start = useAtomCommand(serverEnvironment.startProviderAuth, commands);
47 const respond = useAtomCommand(serverEnvironment.respondProviderAuth, commands);
48 const complete = useAtomCommand(serverEnvironment.completeProviderAuth, commands);
49 const cancel = useAtomCommand(serverEnvironment.cancelProviderAuth, commands);
50 const logout = useAtomCommand(serverEnvironment.logoutProviderAuth, commands);
51 const [methodId, setMethodId] = useState("");
52 const [draft, setDraft] = useState({ id: "", values: {} as Record<string, string> });
53 const [error, setError] = useState<string | null>(null);
54 const [pending, setPending] = useState(false);
55 const pendingRef = useRef(false);
56 const terminalQueue = useRef<ProviderAuthRespondInput[]>([]);
57 const terminalSending = useRef(false);
58 const auth = query.data;
59 const interaction = auth?.interaction;
60 const active =
61 auth?.phase === "starting" || auth?.phase === "waiting" || auth?.phase === "verifying";
62 const signedIn =
63 provider.auth.status === "authenticated" ||
64 (provider.auth.status === "unknown" && auth?.phase === "succeeded");
65 const isDiscovering =
66 provider.driver === "acpRegistry" &&
67 !active &&
68 !signedIn &&
69 !query.error &&
70 auth?.methods === undefined;
71 const needsExternalSetup =
72 !active &&
73 !signedIn &&
74 (provider.setup?.canAuthenticate === false ||
75 (provider.driver === "acpRegistry" && auth?.methods?.length === 0));
76 const accountDescription = active
77 ? auth?.phase === "starting"
78 ? (auth.message ?? "Starting sign-in…")
79 : auth?.phase === "verifying"
80 ? "Checking your account…"
81 : interaction?.type === "terminal"
82 ? "Complete sign-in in the terminal below."
83 : interaction?.type === "credentials"
84 ? "Enter your credentials below."
85 : "Finish signing in in your browser."
86 : signedIn
87 ? "Signed in."
88 : isDiscovering
89 ? "Discovering sign-in methods…"
90 : needsExternalSetup
91 ? "No in-app sign-in advertised. Follow the provider's docs to finish setup."
92 : `Sign in on ${environmentLabel}.`;
93 const statusMessage = auth?.phase === "failed" ? auth.message : null;
94 const disabled = readOnly || pending || query.error !== null || isDiscovering;
95 const draftId = `${auth?.flowId ?? ""}:${interaction?.id ?? ""}`;
96 const values = draft.id === draftId ? draft.values : {};
97 const url =
98 interaction?.type === "browser" || interaction?.type === "deviceCode"
99 ? interaction.url
100 : auth?.authorizationUrl;
101​
102 async function run(command: () => Promise<AtomCommandResult<unknown, unknown>>) {
103 if (pendingRef.current) return false;
104 pendingRef.current = true;
105 setPending(true);
106 setError(null);
107 let succeeded = false;
108 try {
109 const result = await command();
110 if (result._tag === "Success") succeeded = true;
111 else if (!isAtomCommandInterrupted(result)) {
112 const failure = squashAtomCommandFailure(result);
113 setError(
114 failure instanceof Error ? failure.message : "Provider sign-in failed. Try again.",
115 );
116 }
117 } catch {
118 setError("Provider sign-in failed. Try again.");
119 }
120 pendingRef.current = false;
121 setPending(false);
122 return succeeded;
123 }
124​
125 async function send(response: ProviderAuthResponse) {
126 if (!auth?.flowId || !interaction) return false;
127 return run(() =>
128 respond({
129 environmentId,
130 input: { instanceId, flowId: auth.flowId!, interactionId: interaction.id, response },
131 }),
132 );
133 }
134​
135 async function openBrowser() {
136 if (!url || readOnly) return;
137 const requiresConsent = interaction?.type === "browser" && interaction.requiresConsent;
138 // Reserve tabs before awaiting consent; browsers block later opens.
139 const pending = requiresConsent && !window.desktopBridge ? window.open("", "_blank") : null;
140 if (pending) pending.opener = null;
141 try {
142 if (requiresConsent && !(await send({ type: "browser", action: "accept" }))) {
143 pending?.close();
144 return;
145 }
146 if (pending) pending.location.href = url;
147 else await ensureLocalApi().shell.openExternal(url);
148 setError(null);
149 } catch {
150 pending?.close();
151 setError("Could not open the sign-in page. Copy the link and open it in your browser.");
152 }
153 }
154​
155 function updateDraft(name: string, value: string) {
156 setDraft({ id: draftId, values: { ...values, [name]: value } });
157 }
158​
159 return (
160 <SettingsRow
161 title="Account"
162 description={
163 signedIn && !active && provider.auth.email?.trim() ? (
164 <span>
165 Signed in as{" "}
166 <RedactedSensitiveText
167 key={provider.auth.email}
168 value={provider.auth.email}
169 ariaLabel="Toggle account email visibility"
170 revealTooltip="Click to reveal email"
171 hideTooltip="Click to hide email"
172 className="max-w-full truncate"
173 />
174 </span>
175 ) : (
176 <span role="status">{accountDescription}</span>
177 )
178 }
179 status={
180 statusMessage ? (
181 <p role="status" className="[overflow-wrap:anywhere]">
182 {statusMessage}
183 </p>
184 ) : undefined
185 }
186 control={
187 <div className="flex min-w-0 flex-wrap items-center gap-1.5">
188 {!active && (auth?.methods?.length ?? 0) > 1 ? (
189 <Select
190 value={auth?.methods?.some((method) => method.id === methodId) ? methodId : ""}
191 disabled={disabled}
192 onValueChange={(value) => setMethodId(value ?? "")}
193 >
194 <SelectTrigger size="sm" aria-label="Sign-in method" className="w-44">
195 <SelectValue>
196 {auth?.methods?.find((method) => method.id === methodId)?.name ??
197 "Provider default"}
198 </SelectValue>
199 </SelectTrigger>
200 <SelectPopup>
201 <SelectItem value="">Provider default</SelectItem>
202 {auth?.methods?.map((method) => (
203 <SelectItem key={method.id} value={method.id}>
204 {method.name}
205 </SelectItem>
206 ))}
207 </SelectPopup>
208 </Select>
209 ) : null}
210 {url ? (
211 <>
212 <Button
213 size="sm"
214 variant="outline"
215 disabled={disabled}
216 onClick={() => void openBrowser()}
217 >
218 Open browser
219 </Button>
220 <Tooltip>
221 <TooltipTrigger
222 render={
223 <Button
224 aria-label="Copy sign-in link"
225 size="icon-sm"
226 variant="ghost-muted"
227 disabled={disabled}
228 onClick={() => {
229 // Copy during the click to retain clipboard activation; consent must still be
230 // recorded before use.
231 const copied = writeTextToClipboard(url, "Provider sign-in link");
232 void (async () => {
233 await copied;
234 if (interaction?.type === "browser" && interaction.requiresConsent)
235 await send({ type: "browser", action: "accept" });
236 })().catch(() => setError("Could not copy the sign-in link."));
237 }}
238 >
239 <CopyIcon />
240 </Button>
241 }
242 />
243 <TooltipPopup>Copy sign-in link</TooltipPopup>
244 </Tooltip>
245 </>
246 ) : null}
247 <>
248 {needsExternalSetup && provider.setup?.documentationUrl ? (
249 <Button
250 size="sm"
251 variant="outline"
252 render={
253 <a href={provider.setup.documentationUrl} target="_blank" rel="noreferrer" />
254 }
255 >
256 Open docs
257 </Button>
258 ) : active && auth?.flowId ? (
259 <Button
260 size="sm"
261 variant="ghost-muted"
262 aria-label="Cancel sign-in"
263 disabled={disabled}
264 onClick={() =>
265 void run(() =>
266 cancel({ environmentId, input: { instanceId, flowId: auth.flowId! } }),
267 )
268 }
269 >
270 Cancel
271 </Button>
272 ) : !active && !needsExternalSetup && provider.setup?.canAuthenticate !== false ? (
273 <Button
274 size="sm"
275 variant="outline"
276 disabled={disabled || !provider.enabled || !provider.installed || !auth}
277 onClick={() =>
278 void run(() =>
279 start({
280 environmentId,
281 input: {
282 instanceId,
283 ...(methodId && auth?.methods?.some((method) => method.id === methodId)
284 ? { methodId }
285 : {}),
286 },
287 }),
288 )
289 }
290 >
291 {signedIn
292 ? "Change account"
293 : auth?.phase === "failed" || auth?.phase === "cancelled"
294 ? "Retry sign-in"
295 : "Sign in"}
296 </Button>
297 ) : null}
298 {!active && signedIn && (provider.auth.canLogout ?? provider.setup?.canAuthenticate) ? (
299 <Button
300 size="sm"
301 variant="ghost"
302 disabled={disabled || !auth}
303 onClick={() => {
304 void ensureLocalApi()
305 .dialogs.confirm(
306 `Sign out of ${provider.displayName ?? provider.driver} on ${environmentLabel}? This stops running threads that share this sign-in. Thread history is kept.`,
307 )
308 .then((confirmed) => {
309 if (confirmed) void run(() => logout(target));
310 });
311 }}
312 >
313 Sign out
314 </Button>
315 ) : null}
316 </>
317 </div>
318 }
319 >
320 {interaction?.type === "terminal" ||
321 interaction?.type === "credentials" ||
322 interaction?.type === "deviceCode" ||
323 (url && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction)) ||
324 error ||
325 query.error ? (
326 <>
327 {interaction?.type === "deviceCode" ? (
328 <p className="py-2 text-sm text-muted-foreground">
329 Enter code{" "}
330 <code className="select-all font-mono text-foreground">{interaction.userCode}</code>{" "}
331 in your browser.
332 </p>
333 ) : null}
334 {interaction?.type === "terminal" ? (
335 <div className="py-2">
336 <Suspense
337 fallback={
338 <p className="text-xs text-muted-foreground">Loading sign-in terminal…</p>
339 }
340 >
341 <ProviderAuthTerminal
342 key={`${auth?.flowId}:${interaction.id}`}
343 output={interaction.output}
344 outputOffset={interaction.outputOffset}
345 onResponse={(response) => {
346 if (readOnly || !auth?.flowId) return;
347 for (
348 let offset = 0;
349 offset < Math.max(1, response.data.length);
350 offset += 4_096
351 ) {
352 terminalQueue.current.push({
353 instanceId,
354 flowId: auth.flowId,
355 interactionId: interaction.id,
356 response: {
357 ...response,
358 data: response.data.slice(offset, offset + 4_096),
359 },
360 });
361 }
362 if (terminalSending.current) return;
363 terminalSending.current = true;
364 void (async () => {
365 while (terminalQueue.current.length > 0) {
366 const input = terminalQueue.current.shift()!;
367 const result = await respond({ environmentId, input });
368 if (result._tag !== "Success") {
369 terminalQueue.current = [];
370 if (!isAtomCommandInterrupted(result))
371 setError("The provider sign-in terminal is no longer available.");
372 break;
373 }
374 }
375 })()
376 .catch(() => {
377 terminalQueue.current = [];
378 setError("Could not send input to the provider sign-in terminal.");
379 })
380 .finally(() => {
381 terminalSending.current = false;
382 });
383 }}
384 />
385 </Suspense>
386 </div>
387 ) : null}
388 {interaction?.type === "credentials" ? (
389 <form
390 className="grid gap-2 py-2 text-sm leading-normal"
391 onSubmit={(event) => {
392 event.preventDefault();
393 void send({ type: "credentials", values }).then((sent) => {
394 if (sent) setDraft({ id: "", values: {} });
395 });
396 }}
397 >
398 {interaction.fields.map((field) => (
399 <label key={field.name} className="grid gap-1">
400 {field.label}
401 <Input
402 size="sm"
403 type={field.secret ? "password" : "text"}
404 autoComplete="off"
405 value={values[field.name] ?? ""}
406 disabled={disabled}
407 maxLength={16_384}
408 onChange={(event) => updateDraft(field.name, event.target.value)}
409 />
410 </label>
411 ))}
412 <Button
413 type="submit"
414 size="sm"
415 variant="outline"
416 className="w-fit"
417 disabled={disabled}
418 >
419 Connect
420 </Button>
421 </form>
422 ) : null}
423 {url && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction) ? (
424 <form
425 className="grid gap-2 py-2 text-sm leading-normal"
426 onSubmit={(event) => {
427 event.preventDefault();
428 if (!auth?.flowId || !values.callback?.trim()) return;
429 void run(() =>
430 complete({
431 environmentId,
432 input: { instanceId, flowId: auth.flowId!, callbackUrl: values.callback! },
433 }),
434 ).then((sent) => {
435 if (sent) setDraft({ id: "", values: {} });
436 });
437 }}
438 >
439 <label className="grid gap-1">
440 If the final localhost page does not load, paste its full URL here.
441 <Input
442 size="sm"
443 id={`provider-callback-${instanceId}`}
444 type="url"
445 autoComplete="off"
446 value={values.callback ?? ""}
447 disabled={disabled}
448 maxLength={16_384}
449 onChange={(event) => updateDraft("callback", event.target.value)}
450 />
451 </label>
452 <Button
453 type="submit"
454 size="sm"
455 variant="outline"
456 className="w-fit"
457 disabled={disabled || !values.callback?.trim()}
458 >
459 Continue
460 </Button>
461 </form>
462 ) : null}
463 {error || query.error ? (
464 <p role="alert" className="py-2 text-xs text-destructive">
465 {error ?? query.error}
466 </p>
467 ) : null}
468 </>
469 ) : null}
470 </SettingsRow>
471 );