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

AuthorizedClientsSettings.tsx

1,061 lines38.8 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { m as resolveMessage } from "~/i18n/messages";
3import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
4import { AUTH_SCOPE_OPTIONS as PAIRING_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
5import { PlugIcon, PlusIcon, QrCodeIcon } from "lucide-react";
6import { type ReactNode, memo, useId, useState } from "react";
7import { T, useGT, useMessages } from "gt-react";
8import {
9 AuthAccessWriteScope,
10 AuthDiagnosticsReadScope,
11 AuthOrchestrationReadScope,
12 AuthFilesystemReadScope,
13 AuthRelayConfigureScope,
14 AuthStandardClientScopes,
15 AuthTerminalOperateScope,
16 AuthTerminalReadScope,
17 type AuthEnvironmentScope,
18 type AuthGrantScope,
19 type AuthPairingCredentialResult,
20 type AdvertisedEndpoint,
21 type EnvironmentId,
22} from "@t3tools/contracts";
23import {
24 isAtomCommandInterrupted,
25 squashAtomCommandFailure,
26} from "@t3tools/client-runtime/state/runtime";
27​
28import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
29import { cn } from "../../lib/utils";
30import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";
31import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
32import {
33 canRevokeOtherClients,
34 isQrShareableEndpoint,
35 selectQrEndpointOption,
36 togglePairingScopeSelection,
37} from "./ConnectionsSettings.logic";
38import { useNowSecond } from "../../hooks/useNowSecond";
39import { Input } from "../ui/input";
40import { Checkbox } from "../ui/checkbox";
41import {
42 Dialog,
43 DialogFooter,
44 DialogDescription,
45 DialogHeader,
46 DialogPanel,
47 DialogPopup,
48 DialogTitle,
49 DialogTrigger,
50} from "../ui/dialog";
51import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
52import { QRCodeSvg } from "../ui/qr-code";
53import { stackedThreadToast, toastManager } from "../ui/toast";
54import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
55import { Button } from "../ui/button";
56import { Textarea } from "../ui/textarea";
57import {
58 type ServerClientSessionRecord,
59 type ServerPairingLinkRecord,
60} from "~/environments/primary";
61import { authEnvironment } from "~/state/auth";
62import { readEnvironmentScope } from "~/state/session";
63import { useManagedPolicy, usePrimaryManagedPolicy } from "~/state/managedPolicy";
64import { useAtomCommand } from "~/state/use-atom-command";
65import { ManagedControl } from "../ManagedPolicy";
66import { openUseInAnotherApp } from "../mcp/UseInAnotherAppDialog";
67import { ConnectionStatusDot } from "../ConnectionStatusDot";
68import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
69import {
70 formatAccessTimestamp,
71 selectPairingEndpoint,
72 isTailscaleHttpsEndpoint,
73 endpointDefaultPreferenceKey,
74 resolveAdvertisedEndpointPairingUrl,
75 resolveCurrentOriginPairingUrl,
76 isHostedAppPairingUrl,
77 endpointShareHint,
78} from "./ConnectionsSettings.logic";
79​
80function AccessScopeSummary({
81 scopes,
82 label,
83}: {
84 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
85 readonly label: string;
86}) {
87 const gt = useGT();
88 const scopeCountLabel = gt("{count, plural, one {{count} scope} other {{count} scopes}}", {
89 count: scopes.length,
90 });
91​
92 return (
93 <Popover>
94 <PopoverTrigger
95 openOnHover
96 delay={250}
97 closeDelay={100}
98 render={
99 <button
100 type="button"
101 aria-label={gt("{label}: show {scopes}", { label, scopes: scopeCountLabel })}
102 className="cursor-help underline decoration-border underline-offset-2 outline-hidden hover:text-foreground focus-visible:text-foreground"
103 />
104 }
105 >
106 {scopeCountLabel}
107 </PopoverTrigger>
108 <PopoverPopup
109 side="top"
110 align="start"
111 tooltipStyle
112 className="w-max max-w-80 whitespace-normal"
113 >
114 <p className="mb-1 font-medium">
115 <T>Granted scopes</T>
116 </p>
117 <div className="flex flex-col gap-0.5">
118 {scopes.map((scope) => (
119 <code key={scope} className="font-mono text-foreground/85">
120 {scope}
121 </code>
122 ))}
123 </div>
124 </PopoverPopup>
125 </Popover>
126 );
128​
129function endpointRowClassName(isAvailable: boolean) {
130 return cn(
131 "relative first:rounded-t-xl last:rounded-b-xl px-3 py-3 sm:px-4",
132 !isAvailable && "bg-muted/15",
133 );
135​
136type PairingLinkListRowProps = {
137 pairingLink: ServerPairingLinkRecord;
138 credential: string | undefined;
139 defaultShareOpen: boolean;
140 /** Whether this page is served by the environment the link pairs with. */
141 servedByEnvironment: boolean;
142 endpointUrl: string | null | undefined;
143 endpoints: ReadonlyArray<AdvertisedEndpoint>;
144 defaultEndpointKey: string | null;
145 revokingPairingLinkId: string | null;
146 onRevoke: (id: string) => void;
147 canRevoke: boolean;
148};
149​
150const PairingLinkListRow = memo(function PairingLinkListRow({
151 pairingLink,
152 credential,
153 defaultShareOpen,
154 servedByEnvironment,
155 endpointUrl,
156 endpoints,
157 defaultEndpointKey,
158 revokingPairingLinkId,
159 onRevoke,
160 canRevoke,
161}: PairingLinkListRowProps) {
162 const gt = useGT();
163 const m = useMessages();
164 const nowMs = useNowSecond();
165 const expiresAtMs = new Date(pairingLink.expiresAt).getTime();
166 const [isRevealDialogOpen, setIsRevealDialogOpen] = useState(false);
167 const [isQrPanelOpen, setIsQrPanelOpen] = useState(defaultShareOpen);
168 const [qrEndpointId, setQrEndpointId] = useState<string | null>(null);
169 const qrPanelId = useId();
170​
171 const currentOriginPairingUrl = credential ? resolveCurrentOriginPairingUrl(credential) : null;
172 const hostedPairingUrl =
173 credential && endpointUrl != null && endpointUrl !== ""
174 ? resolveHostedPairingUrl(endpointUrl, credential)
175 : null;
176 const endpointPairingUrl = (() => {
177 const endpoint = selectPairingEndpoint(endpoints, defaultEndpointKey);
178 return endpoint && credential
179 ? resolveAdvertisedEndpointPairingUrl(endpoint, credential)
180 : null;
181 })();
182 const endpointCopyOptions = (() => {
183 const options: Array<{
184 readonly id: string;
185 readonly preferenceKey: string;
186 readonly label: string;
187 readonly url: string;
188 readonly detail: string;
189 readonly qrShareable: boolean;
190 }> = [];
191 if (!credential) return options;
192 for (const endpoint of endpoints) {
193 if (endpoint.status === "unavailable") {
194 continue;
195 }
196 const url = resolveAdvertisedEndpointPairingUrl(endpoint, credential);
197 options.push({
198 id: endpoint.id,
199 preferenceKey: endpointDefaultPreferenceKey(endpoint),
200 label: endpoint.label,
201 url,
202 detail: endpointShareHint(endpoint, url, m),
203 qrShareable: isQrShareableEndpoint(endpoint),
204 });
205 }
206 return options;
207 })();
208 const shareablePairingUrl =
209 endpointPairingUrl ??
210 (credential && endpointUrl != null && endpointUrl !== ""
211 ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, credential))
212 : servedByEnvironment
213 ? currentOriginPairingUrl
214 : null);
215 const [failedCopyValue, setFailedCopyValue] = useState<string | null>(null);
216 const revealValue = failedCopyValue ?? shareablePairingUrl ?? credential ?? "";
217 const isRevealValueUrl = revealValue !== credential;
218 const isRevealValueHostedAppPairingUrl = isRevealValueUrl && isHostedAppPairingUrl(revealValue);
219 const isRevealValueQrShareable =
220 endpointCopyOptions.find((option) => option.url === revealValue)?.qrShareable ?? true;
221 const canCopyToClipboard =
222 typeof window !== "undefined" &&
223 window.isSecureContext &&
224 navigator.clipboard?.writeText != null;
225​
226 const { copyToClipboard } = useCopyToClipboard<{
227 value: string;
228 kind: "code" | "hosted-link" | "link";
229 }>({
230 onError: (error, { value, kind }) => {
231 // Captured per attempt so concurrent copies cannot make the dialog
232 // reveal a different value than the one that failed.
233 setFailedCopyValue(value);
234 setIsRevealDialogOpen(true);
235 toastManager.add(
236 stackedThreadToast({
237 type: "error",
238 title: canCopyToClipboard
239 ? kind === "hosted-link"
240 ? gt("Could not copy hosted app link")
241 : kind === "link"
242 ? gt("Could not copy pairing URL")
243 : gt("Could not copy pairing code")
244 : gt("Clipboard copy unavailable"),
245 description: canCopyToClipboard ? error.message : gt("Showing the full value instead."),
246 }),
247 );
248 },
249 });
250​
251 const copyPairingValue = (value: string, kind: "code" | "hosted-link" | "link") => {
252 copyToClipboard(value, { value, kind });
253 };
254​
255 const copyKindForUrl = (url: string): "hosted-link" | "link" =>
256 isHostedAppPairingUrl(url) ? "hosted-link" : "link";
257​
258 const handleCopyCode = () => {
259 if (credential) copyPairingValue(credential, "code");
260 };
261​
262 const expiresAbsolute = formatAccessTimestamp(pairingLink.expiresAt);
263​
264 const primaryLabel = pairingLink.label ?? gt("Pairing link");
265 const selectedQrOption = selectQrEndpointOption(
266 endpointCopyOptions,
267 qrEndpointId,
268 defaultEndpointKey,
269 );
270 const qrPairingUrl = selectedQrOption?.url ?? shareablePairingUrl;
271 const canRenderQrForSelection = selectedQrOption?.qrShareable ?? true;
272 if (expiresAtMs <= nowMs) {
273 return null;
274 }
275​
276 return (
277 <div className={ITEM_ROW_CLASSNAME}>
278 <div className={ITEM_ROW_INNER_CLASSNAME}>
279 <div className="min-w-0 flex-1 space-y-1">
280 <div className="flex min-h-5 items-center gap-1.5">
281 <ConnectionStatusDot
282 tooltipText={gt("Link created at {time}", {
283 time: formatAccessTimestamp(pairingLink.createdAt),
284 })}
285 dotClassName="bg-warning"
286 />
287 <h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
288 </div>
289 <p className="text-xs text-muted-foreground">
290 <Tooltip>
291 <TooltipTrigger render={<span />}>
292 {formatExpiresInLabel(pairingLink.expiresAt, nowMs, m)}
293 </TooltipTrigger>
294 <TooltipPopup side="top">{expiresAbsolute}</TooltipPopup>
295 </Tooltip>
296 <span aria-hidden> · </span>
297 <AccessScopeSummary scopes={pairingLink.scopes} label={gt("Pairing link scopes")} />
298 </p>
299 {!credential ? (
300 <p className="text-2xs text-muted-foreground/70">
301 <T>Create a new link to share from this client.</T>
302 </p>
303 ) : shareablePairingUrl === null ? (
304 <p className="text-2xs text-muted-foreground/70">
305 <T>
306 Copy the token and pair from another client using this backend&apos;s reachable
307 host.
308 </T>
309 </p>
310 ) : null}
311 </div>
312 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
313 {shareablePairingUrl && canCopyToClipboard ? (
314 <Button
315 size="xs"
316 variant="outline"
317 aria-expanded={isQrPanelOpen}
318 aria-controls={qrPanelId}
319 onClick={() => setIsQrPanelOpen((open) => !open)}
320 >
321 <QrCodeIcon aria-hidden />
322 <T>Share</T>
323 </Button>
324 ) : null}
325 <Dialog
326 open={credential !== undefined && isRevealDialogOpen}
327 onOpenChange={(open) => {
328 setIsRevealDialogOpen(open);
329 if (!open) setFailedCopyValue(null);
330 }}
331 >
332 {!credential ? null : canCopyToClipboard ? (
333 shareablePairingUrl ? null : (
334 <Button size="xs" variant="outline" onClick={handleCopyCode}>
335 <T>Copy code</T>
336 </Button>
337 )
338 ) : (
339 <DialogTrigger render={<Button size="xs" variant="outline" />}>
340 {shareablePairingUrl ? gt("Show link") : gt("Show code")}
341 </DialogTrigger>
342 )}
343 <DialogPopup className="max-w-md">
344 <DialogHeader>
345 <DialogTitle>
346 {isRevealValueUrl
347 ? isRevealValueHostedAppPairingUrl
348 ? gt("Hosted app pairing link")
349 : gt("Pairing link")
350 : gt("Pairing code")}
351 </DialogTitle>
352 <DialogDescription>
353 {isRevealValueUrl
354 ? isRevealValueHostedAppPairingUrl
355 ? gt(
356 "Clipboard copy is unavailable here. Open or manually copy this hosted app link on the device you want to connect.",
357 )
358 : gt(
359 "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect.",
360 )
361 : gt(
362 "Clipboard copy is unavailable here. Manually copy this code into another client.",
363 )}
364 </DialogDescription>
365 </DialogHeader>
366 <DialogPanel>
367 <Textarea
368 readOnly
369 value={revealValue}
370 rows={isRevealValueUrl ? 4 : 3}
371 onFocus={(event) => event.currentTarget.select()}
372 onClick={(event) => event.currentTarget.select()}
373 />
374 {isRevealValueUrl && isRevealValueQrShareable ? (
375 <div className="flex justify-center rounded-xl border border-border/60 bg-muted/30 p-4">
376 <QRCodeSvg
377 value={revealValue}
378 size={132}
379 level="M"
380 marginSize={2}
381 title={gt("Pairing link. Scan to open on another device")}
382 />
383 </div>
384 ) : null}
385 </DialogPanel>
386 <DialogFooter variant="bare">
387 <Button variant="outline" onClick={() => setIsRevealDialogOpen(false)}>
388 <T>Done</T>
389 </Button>
390 {canCopyToClipboard ? (
391 <Button variant="outline" onClick={handleCopyCode}>
392 <T>Copy code</T>
393 </Button>
394 ) : null}
395 </DialogFooter>
396 </DialogPopup>
397 </Dialog>
398 <Button
399 size="xs"
400 variant="destructive-outline"
401 disabled={!canRevoke || revokingPairingLinkId === pairingLink.id}
402 onClick={() => void onRevoke(pairingLink.id)}
403 >
404 {revokingPairingLinkId === pairingLink.id ? gt("Revoking…") : gt("Revoke")}
405 </Button>
406 </div>
407 </div>
408 {isQrPanelOpen && qrPairingUrl !== null ? (
409 <div
410 id={qrPanelId}
411 className="mt-3 flex flex-col gap-4 border-t border-border/50 pt-3 sm:flex-row sm:items-start sm:justify-between"
412 >
413 <div className="min-w-0 flex-1 space-y-3">
414 {endpointCopyOptions.length > 1 ? (
415 <div
416 className="space-y-1.5"
417 role="radiogroup"
418 aria-label={gt("Endpoint the pairing QR code and URL use")}
419 >
420 <p className="text-2xs text-muted-foreground/70">
421 <T>Reach this machine via</T>
422 </p>
423 {endpointCopyOptions.map((option) => {
424 const isSelected = option.id === selectedQrOption?.id;
425 return (
426 <button
427 key={option.id}
428 type="button"
429 role="radio"
430 aria-checked={isSelected}
431 className={cn(
432 "flex w-full items-baseline gap-2 rounded-lg border px-2.5 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
433 isSelected
434 ? "border-foreground/60 bg-muted/30"
435 : "border-border/50 hover:bg-muted/20",
436 )}
437 onClick={() => setQrEndpointId(option.id)}
438 >
439 <span
440 className={cn(
441 "text-xs font-medium",
442 isSelected ? "text-foreground" : "text-muted-foreground",
443 )}
444 >
445 {option.label}
446 </span>
447 <span className="min-w-0 truncate text-2xs text-muted-foreground/70">
448 {option.detail}
449 </span>
450 </button>
451 );
452 })}
453 </div>
454 ) : null}
455 <div className="flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-2.5 py-1.5">
456 <Tooltip>
457 <TooltipTrigger
458 render={
459 <code className="min-w-0 flex-1 truncate font-mono text-2xs text-muted-foreground">
460 {qrPairingUrl}
461 </code>
462 }
463 />
464 <TooltipPopup side="top">{qrPairingUrl}</TooltipPopup>
465 </Tooltip>
466 <Button
467 size="xs"
468 variant="ghost"
469 className="shrink-0"
470 onClick={() => copyPairingValue(qrPairingUrl, copyKindForUrl(qrPairingUrl))}
471 >
472 <T>Copy link</T>
473 </Button>
474 </div>
475 <Button size="xs" variant="ghost" onClick={handleCopyCode}>
476 <T>Copy code only</T>
477 </Button>
478 </div>
479 {canRenderQrForSelection ? (
480 <div className="w-fit shrink-0 self-center rounded-xl bg-white p-3 sm:self-start">
481 <QRCodeSvg
482 value={qrPairingUrl}
483 size={168}
484 level="M"
485 marginSize={1}
486 title={gt("Pairing link. Scan to open on another device")}
487 />
488 </div>
489 ) : (
490 <div className="flex size-[192px] shrink-0 items-center justify-center self-center rounded-xl border border-border/50 p-4 sm:self-start">
491 <p className="text-center text-2xs text-muted-foreground/70">
492 <T>
493 No QR for this endpoint. Another device scanning a loopback link would dial
494 itself; copy the URL for use on this machine instead.
495 </T>
496 </p>
497 </div>
498 )}
499 </div>
500 ) : null}
501 </div>
502 );
503});
504​
505type ConnectedClientListRowProps = {
506 clientSession: ServerClientSessionRecord;
507 revokingClientSessionId: string | null;
508 onRevokeSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
509 canRevoke: boolean;
510};
511​
512const ConnectedClientListRow = memo(function ConnectedClientListRow({
513 clientSession,
514 revokingClientSessionId,
515 onRevokeSession,
516 canRevoke,
517}: ConnectedClientListRowProps) {
518 const gt = useGT();
519 const m = useMessages();
520 const nowMs = useNowSecond();
521 const isLive = clientSession.current || clientSession.connected;
522 const lastConnectedAt = clientSession.lastConnectedAt;
523 const statusTooltip = isLive
524 ? lastConnectedAt
525 ? gt("Connected for {duration}", {
526 duration: formatElapsedDurationLabel(lastConnectedAt, nowMs, m),
527 })
528 : gt("Connected")
529 : lastConnectedAt
530 ? gt("Last connected at {time}", { time: formatAccessTimestamp(lastConnectedAt) })
531 : gt("Not connected yet.");
532 const deviceInfoBits = [
533 clientSession.client.deviceType !== "unknown"
534 ? clientSession.client.deviceType[0]?.toUpperCase() + clientSession.client.deviceType.slice(1)
535 : null,
536 clientSession.client.os ?? null,
537 clientSession.client.browser ?? null,
538 clientSession.client.ipAddress ?? null,
539 ].filter((value): value is string => value !== null);
540 const primaryLabel =
541 clientSession.client.label ??
542 ([clientSession.client.os, clientSession.client.browser].filter(Boolean).join(" · ") ||
543 clientSession.subject);
544​
545 return (
546 <div className={ITEM_ROW_CLASSNAME}>
547 <div className={ITEM_ROW_INNER_CLASSNAME}>
548 <div className="min-w-0 flex-1 space-y-1">
549 <div className="flex min-h-5 items-center gap-1.5">
550 <ConnectionStatusDot
551 tooltipText={statusTooltip}
552 dotClassName={isLive ? "bg-success" : "bg-muted-foreground/30"}
553 pingClassName={isLive ? "bg-success/60 duration-2000" : null}
554 />
555 <h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
556 {clientSession.current ? (
557 <span className="text-3xs text-muted-foreground/80 rounded-md border border-border/50 bg-muted/50 px-1 py-0.5">
558 <T>This device</T>
559 </span>
560 ) : null}
561 </div>
562 <p className="text-xs text-muted-foreground">
563 {deviceInfoBits.length > 0 ? (
564 <>
565 {deviceInfoBits.join(" · ")}
566 <span aria-hidden> · </span>
567 </>
568 ) : null}
569 <AccessScopeSummary scopes={clientSession.scopes} label={gt("Client scopes")} />
570 </p>
571 </div>
572 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
573 {!clientSession.current ? (
574 <Button
575 size="xs"
576 variant="destructive-outline"
577 disabled={!canRevoke || revokingClientSessionId === clientSession.sessionId}
578 onClick={() => void onRevokeSession(clientSession.sessionId)}
579 >
580 {revokingClientSessionId === clientSession.sessionId ? gt("Revoking…") : gt("Revoke")}
581 </Button>
582 ) : null}
583 </div>
584 </div>
585 </div>
586 );
587});
588​
589type AuthorizedClientsHeaderActionProps = {
590 environmentId: EnvironmentId;
591 onPairingLinkCreated: (result: AuthPairingCredentialResult) => void;
592 clientSessions: ReadonlyArray<ServerClientSessionRecord> | null;
593 isRevokingOtherClients: boolean;
594 onRevokeOtherClients: () => void;
595 delegatableScopes: ReadonlyArray<AuthEnvironmentScope>;
596};
597​
598export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({
599 environmentId,
600 onPairingLinkCreated,
601 clientSessions,
602 isRevokingOtherClients,
603 onRevokeOtherClients,
604 delegatableScopes,
605}: AuthorizedClientsHeaderActionProps) {
606 const gt = useGT();
607 const m = useMessages();
608 const pairingDenial = managedCapabilityDenial(
609 useManagedPolicy(environmentId),
610 "remoteClients",
611 m,
612 );
613 const createPairingCredential = useAtomCommand(authEnvironment.createPairingCredential, {
614 reportFailure: false,
615 });
616 const [dialogOpen, setDialogOpen] = useState(false);
617 const [pairingLabel, setPairingLabel] = useState("");
618 const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthGrantScope>>([
619 ...AuthStandardClientScopes,
620 ]);
621 const selectedScopes = pairingScopes.filter((scope) => delegatableScopes.includes(scope));
622 const terminalSelected = selectedScopes.includes(AuthTerminalOperateScope);
623 const relayAdminSelected = selectedScopes.includes(AuthRelayConfigureScope);
624 const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false);
625​
626 const handleCreatePairingLink = async () => {
627 if (
628 selectedScopes.length === 0 ||
629 !readEnvironmentScope(environmentId, AuthAccessWriteScope) ||
630 !selectedScopes.every((scope) => readEnvironmentScope(environmentId, scope))
631 )
632 return;
633 setIsCreatingPairingLink(true);
634 const trimmedLabel = pairingLabel.trim();
635 const result = await createPairingCredential({
636 environmentId,
637 input: { ...(trimmedLabel ? { label: trimmedLabel } : {}), scopes: selectedScopes },
638 });
639 if (result._tag === "Success") {
640 onPairingLinkCreated(result.value);
641 setPairingLabel("");
642 setPairingScopes(
643 AuthStandardClientScopes.filter((scope) => delegatableScopes.includes(scope)),
644 );
645 setDialogOpen(false);
646 } else if (!isAtomCommandInterrupted(result)) {
647 const error = squashAtomCommandFailure(result);
648 const message =
649 error instanceof Error
650 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
651 : gt("Failed to create pairing URL.");
652 toastManager.add(
653 stackedThreadToast({
654 type: "error",
655 title: gt("Could not create pairing URL"),
656 description: message,
657 }),
658 );
659 }
660 setIsCreatingPairingLink(false);
661 };
662​
663 const togglePairingScope = (scope: AuthGrantScope, checked: boolean) => {
664 setPairingScopes((current) => togglePairingScopeSelection(current, scope, checked));
665 };
666​
667 return (
668 <div className="flex flex-wrap items-center justify-end gap-2">
669 <Button size="xs" variant="outline" onClick={() => openUseInAnotherApp(environmentId)}>
670 <PlugIcon className="size-3" />
671 <T>Use in another app (MCP)</T>
672 </Button>
673 <Button
674 size="xs"
675 variant="destructive-outline"
676 disabled={isRevokingOtherClients || !canRevokeOtherClients(clientSessions)}
677 onClick={() => void onRevokeOtherClients()}
678 >
679 {isRevokingOtherClients ? gt("Revoking…") : gt("Revoke others")}
680 </Button>
681 {pairingDenial !== undefined ? (
682 <ManagedControl reason={pairingDenial}>
683 <Button size="xs" variant="default" disabled>
684 <PlusIcon className="size-3" />
685 <T>Create link</T>
686 </Button>
687 </ManagedControl>
688 ) : null}
689 <Dialog
690 open={dialogOpen && pairingDenial === undefined}
691 onOpenChange={(open) => {
692 setDialogOpen(open);
693 if (!open) {
694 setPairingLabel("");
695 setPairingScopes(
696 AuthStandardClientScopes.filter((scope) => delegatableScopes.includes(scope)),
697 );
698 }
699 }}
700 >
701 {pairingDenial === undefined ? (
702 <DialogTrigger
703 render={
704 <Button size="xs" variant="default">
705 <PlusIcon className="size-3" />
706 <T>Create link</T>
707 </Button>
708 }
709 />
710 ) : null}
711 <DialogPopup className="max-w-md">
712 <DialogHeader>
713 <DialogTitle>
714 <T>Create pairing link</T>
715 </DialogTitle>
716 <DialogDescription>
717 <T>
718 Generate a one-time link that another device can use to pair with this backend as an
719 authorized client.
720 </T>
721 </DialogDescription>
722 </DialogHeader>
723 <DialogPanel>
724 <label className="block">
725 <span className="mb-1.5 block text-xs font-medium text-foreground">
726 <T>Client label (optional)</T>
727 </span>
728 <Input
729 value={pairingLabel}
730 onChange={(event) => setPairingLabel(event.target.value)}
731 placeholder={gt("e.g. Living room iPad")}
732 disabled={isCreatingPairingLink}
733 autoFocus
734 />
735 </label>
736 <section className="space-y-3">
737 <div className="flex items-center justify-between gap-3">
738 <div>
739 <h3 className="text-xs font-medium text-foreground">
740 <T>Permissions</T>
741 </h3>
742 <p className="text-xs text-muted-foreground">
743 <T>Limit what the paired client can do.</T>
744 </p>
745 </div>
746 <div className="flex gap-1">
747 <Button
748 size="xs"
749 variant="outline"
750 disabled={isCreatingPairingLink}
751 onClick={() =>
752 setPairingScopes(
753 [
754 AuthOrchestrationReadScope,
755 AuthFilesystemReadScope,
756 AuthDiagnosticsReadScope,
757 AuthTerminalReadScope,
758 ].filter((scope) => delegatableScopes.includes(scope)),
759 )
760 }
761 >
762 <T>Read only</T>
763 </Button>
764 <Button
765 size="xs"
766 variant="outline"
767 disabled={isCreatingPairingLink}
768 onClick={() =>
769 setPairingScopes(
770 AuthStandardClientScopes.filter((scope) =>
771 delegatableScopes.includes(scope),
772 ),
773 )
774 }
775 >
776 {gt("Standard", { $context: "standard permission preset" })}
777 </Button>
778 </div>
779 </div>
780 <div className="divide-y divide-border/60 rounded-lg border border-input bg-muted/25">
781 {PAIRING_SCOPE_OPTIONS.filter(({ scope }) => delegatableScopes.includes(scope)).map(
782 ({ scope, title, description }) => (
783 <label
784 key={scope}
785 className="flex cursor-pointer items-start gap-3 px-3 py-2.5 transition-colors hover:bg-muted/40"
786 >
787 <Checkbox
788 className="mt-0.5"
789 checked={pairingScopes.includes(scope)}
790 disabled={isCreatingPairingLink}
791 onCheckedChange={(checked) => togglePairingScope(scope, checked === true)}
792 />
793 <span className="min-w-0">
794 <span className="block text-xs font-medium text-foreground">
795 {m(title)}
796 </span>
797 <span className="block text-xs leading-snug text-muted-foreground">
798 {m(description)}
799 </span>
800 {terminalSelected && scope === AuthTerminalOperateScope ? (
801 <span className="block text-xs text-warning">
802 {gt(
803 "Terminal commands can read or change files within the server account’s permissions.",
804 )}
805 </span>
806 ) : null}
807 {relayAdminSelected && scope === AuthRelayConfigureScope ? (
808 <span className="block text-xs text-warning">
809 {gt("This client can change who can issue pairing credentials.")}
810 </span>
811 ) : null}
812 </span>
813 </label>
814 ),
815 )}
816 </div>
817 {selectedScopes.length === 0 ? (
818 <p className="text-xs text-destructive">
819 <T>Select at least one permission.</T>
820 </p>
821 ) : selectedScopes.includes(AuthAccessWriteScope) ? (
822 <p className="text-xs text-warning">
823 <T>This client can create or revoke access for other devices.</T>
824 </p>
825 ) : null}
826 </section>
827 </DialogPanel>
828 <DialogFooter variant="bare">
829 <Button
830 variant="outline"
831 disabled={isCreatingPairingLink}
832 onClick={() => setDialogOpen(false)}
833 >
834 <T>Cancel</T>
835 </Button>
836 <Button
837 disabled={isCreatingPairingLink || selectedScopes.length === 0}
838 onClick={() => void handleCreatePairingLink()}
839 >
840 {isCreatingPairingLink ? gt("Creating…") : gt("Create link")}
841 </Button>
842 </DialogFooter>
843 </DialogPopup>
844 </Dialog>
845 </div>
846 );
847});
848​
849type PairingClientsListProps = {
850 servedByEnvironment: boolean;
851 endpointUrl: string | null | undefined;
852 endpoints: ReadonlyArray<AdvertisedEndpoint>;
853 defaultEndpointKey: string | null;
854 isLoading: boolean;
855 pairingLinks: ReadonlyArray<ServerPairingLinkRecord>;
856 createdPairingCredentials: ReadonlyMap<string, string>;
857 sharedPairingLinkId: string | null;
858 clientSessions: ReadonlyArray<ServerClientSessionRecord>;
859 revokingPairingLinkId: string | null;
860 revokingClientSessionId: string | null;
861 onRevokePairingLink: (id: string) => void;
862 onRevokeClientSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
863 canRevoke: boolean;
864};
865​
866export const PairingClientsList = memo(function PairingClientsList({
867 servedByEnvironment,
868 endpointUrl,
869 endpoints,
870 defaultEndpointKey,
871 isLoading,
872 pairingLinks,
873 createdPairingCredentials,
874 sharedPairingLinkId,
875 clientSessions,
876 revokingPairingLinkId,
877 revokingClientSessionId,
878 onRevokePairingLink,
879 onRevokeClientSession,
880 canRevoke,
881}: PairingClientsListProps) {
882 return (
883 <>
884 {pairingLinks.map((pairingLink) => (
885 <PairingLinkListRow
886 key={pairingLink.id}
887 pairingLink={pairingLink}
888 credential={createdPairingCredentials.get(pairingLink.id)}
889 defaultShareOpen={pairingLink.id === sharedPairingLinkId}
890 servedByEnvironment={servedByEnvironment}
891 endpointUrl={endpointUrl}
892 endpoints={endpoints}
893 defaultEndpointKey={defaultEndpointKey}
894 revokingPairingLinkId={revokingPairingLinkId}
895 onRevoke={onRevokePairingLink}
896 canRevoke={canRevoke}
897 />
898 ))}
899​
900 {clientSessions.map((clientSession) => (
901 <ConnectedClientListRow
902 key={clientSession.sessionId}
903 clientSession={clientSession}
904 revokingClientSessionId={revokingClientSessionId}
905 onRevokeSession={onRevokeClientSession}
906 canRevoke={canRevoke}
907 />
908 ))}
909​
910 {pairingLinks.length === 0 && clientSessions.length === 0 && !isLoading ? (
911 <div className={ITEM_ROW_CLASSNAME}>
912 <p className="text-xs text-muted-foreground/60">
913 <T>No pairing links or client sessions.</T>
914 </p>
915 </div>
916 ) : null}
917 </>
918 );
919});
920​
921type AdvertisedEndpointListRowProps = {
922 endpoint: AdvertisedEndpoint;
923 isDefault: boolean;
924 onSetDefault: (endpoint: AdvertisedEndpoint) => void;
925 onSetupTailscaleServe: (endpoint: AdvertisedEndpoint) => void;
926 onDisableTailscaleServe: (endpoint: AdvertisedEndpoint) => void;
927 isUpdatingTailscaleServe: boolean;
928};
929​
930export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow({
931 endpoint,
932 isDefault,
933 onSetDefault,
934 onSetupTailscaleServe,
935 onDisableTailscaleServe,
936 isUpdatingTailscaleServe,
937}: AdvertisedEndpointListRowProps) {
938 const gt = useGT();
939 const isAvailable = endpoint.status === "available";
940 const needsTailscaleSetup = isTailscaleHttpsEndpoint(endpoint) && endpoint.status !== "available";
941 const canDisableTailscaleServe =
942 isTailscaleHttpsEndpoint(endpoint) && endpoint.status === "available";
943 const shouldShowEndpointUrl = !needsTailscaleSetup;
944 const m = useMessages();
945 const remoteDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "remoteClients", m);
946 return (
947 <div className={endpointRowClassName(isAvailable)}>
948 {isDefault ? (
949 <span className="absolute inset-y-2 left-0 w-1 rounded-r-full bg-primary" aria-hidden />
950 ) : null}
951 <div className="flex min-h-7 min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
952 <div className="flex min-h-7 min-w-0 flex-1 items-center gap-3">
953 <h3 className="shrink-0 text-sm leading-5 font-medium text-foreground">
954 {endpoint.label}
955 </h3>
956 {shouldShowEndpointUrl ? (
957 <Tooltip>
958 <TooltipTrigger
959 render={
960 <p className="min-w-0 truncate text-xs leading-5 text-muted-foreground">
961 {endpoint.httpBaseUrl}
962 </p>
963 }
964 />
965 <TooltipPopup side="top">{endpoint.httpBaseUrl}</TooltipPopup>
966 </Tooltip>
967 ) : null}
968 {!isAvailable ? (
969 <span className="inline-flex h-6 shrink-0 items-center rounded-md border border-border/70 px-1.5 text-3xs text-muted-foreground">
970 <T>Setup required</T>
971 </span>
972 ) : null}
973 </div>
974 <div className="ml-auto flex min-h-7 shrink-0 items-center justify-end gap-2">
975 {isDefault ? (
976 <span className="inline-flex h-6 items-center rounded-md border border-primary/30 bg-primary/10 px-1.5 text-3xs text-primary">
977 {gt("Default", { $context: "default endpoint badge" })}
978 </span>
979 ) : null}
980 {needsTailscaleSetup ? (
981 <ManagedControl reason={remoteDenial}>
982 <Button
983 size="xs"
984 variant="outline"
985 onClick={() => onSetupTailscaleServe(endpoint)}
986 disabled={isUpdatingTailscaleServe || remoteDenial !== undefined}
987 >
988 {isUpdatingTailscaleServe ? gt("Restarting…") : gt("Setup", { $context: "verb" })}
989 </Button>
990 </ManagedControl>
991 ) : null}
992 {canDisableTailscaleServe ? (
993 <Button
994 size="xs"
995 variant="destructive-outline"
996 onClick={() => onDisableTailscaleServe(endpoint)}
997 disabled={isUpdatingTailscaleServe}
998 >
999 {isUpdatingTailscaleServe ? gt("Restarting…") : gt("Disable")}
1000 </Button>
1001 ) : null}
1002 {!needsTailscaleSetup && !isDefault ? (
1003 <Button size="xs" variant="outline" onClick={() => onSetDefault(endpoint)}>
1004 <T>Set as default</T>
1005 </Button>
1006 ) : null}
1007 </div>
1008 </div>
1009 </div>
1010 );
1011});
1012​
1013export function NetworkAccessDescription({
1014 endpoint,
1015 hiddenEndpointCount,
1016 expanded,
1017 onToggleExpanded,
1018 fallback,
1019}: {
1020 endpoint: AdvertisedEndpoint | null;
1021 hiddenEndpointCount: number;
1022 expanded: boolean;
1023 onToggleExpanded: () => void;
1024 fallback: ReactNode;
1025}) {
1026 const gt = useGT();
1027 if (!endpoint) {
1028 return fallback;
1030​
1031 const summary = (
1032 <>
1033 <span className="min-w-0 truncate">{endpoint.httpBaseUrl}</span>
1034 {hiddenEndpointCount > 0 ? (
1035 <span className="shrink-0 text-xs font-medium">
1036 {expanded ? gt("Hide") : `+${hiddenEndpointCount}`}
1037 </span>
1038 ) : null}
1039 </>
1040 );
1041​
1042 return (
1043 <span className="inline-flex min-w-0 max-w-full items-baseline gap-1">
1044 <span className="shrink-0">
1045 <T>Reachable at</T>
1046 </span>
1047 {hiddenEndpointCount > 0 ? (
1048 <button
1049 type="button"
1050 className="inline-flex min-w-0 max-w-full items-baseline gap-2 border-b border-dotted border-muted-foreground/60 text-left text-muted-foreground underline-offset-4 hover:border-foreground hover:text-foreground"
1051 onClick={onToggleExpanded}
1052 aria-expanded={expanded}
1054 {summary}
1055 </button>
1056 ) : (
1057 <span className="inline-flex min-w-0 max-w-full items-baseline gap-2">{summary}</span>
1058 )}
1059 </span>
1060 );