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

AuthorizedClientsSettings.tsx

1,057 lines38.7 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, useRef, 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 { Button } from "../ui/button";
55import { Textarea } from "../ui/textarea";
56import {
57 type ServerClientSessionRecord,
58 type ServerPairingLinkRecord,
59} from "~/environments/primary";
60import { authEnvironment } from "~/state/auth";
61import { readEnvironmentScope } from "~/state/session";
62import { useManagedPolicy, usePrimaryManagedPolicy } from "~/state/managedPolicy";
63import { useAtomCommand } from "~/state/use-atom-command";
64import { ManagedControl } from "../ManagedPolicy";
65import { openUseInAnotherApp } from "../mcp/UseInAnotherAppDialog";
66import { ConnectionStatusDot } from "../ConnectionStatusDot";
67import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
68import {
69 formatAccessTimestamp,
70 selectPairingEndpoint,
71 isTailscaleHttpsEndpoint,
72 endpointDefaultPreferenceKey,
73 resolveAdvertisedEndpointPairingUrl,
74 resolveCurrentOriginPairingUrl,
75 isHostedAppPairingUrl,
76 endpointShareHint,
77} from "./ConnectionsSettings.logic";
78import { SharedTooltipTrigger } from "../ui/shared-tooltip";
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 <SharedTooltipTrigger render={<span />} label={expiresAbsolute}>
291 {formatExpiresInLabel(pairingLink.expiresAt, nowMs, m)}
292 </SharedTooltipTrigger>
293 <span aria-hidden> · </span>
294 <AccessScopeSummary scopes={pairingLink.scopes} label={gt("Pairing link scopes")} />
295 </p>
296 {!credential ? (
297 <p className="text-2xs text-muted-foreground/70">
298 <T>Create a new link to share from this client.</T>
299 </p>
300 ) : shareablePairingUrl === null ? (
301 <p className="text-2xs text-muted-foreground/70">
302 <T>
303 Copy the token and pair from another client using this backend&apos;s reachable
304 host.
305 </T>
306 </p>
307 ) : null}
308 </div>
309 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
310 {shareablePairingUrl && canCopyToClipboard ? (
311 <Button
312 size="xs"
313 variant="outline"
314 aria-expanded={isQrPanelOpen}
315 aria-controls={qrPanelId}
316 onClick={() => setIsQrPanelOpen((open) => !open)}
317 >
318 <QrCodeIcon aria-hidden />
319 <T>Share</T>
320 </Button>
321 ) : null}
322 <Dialog
323 open={credential !== undefined && isRevealDialogOpen}
324 onOpenChange={(open) => {
325 setIsRevealDialogOpen(open);
326 if (!open) setFailedCopyValue(null);
327 }}
328 >
329 {!credential ? null : canCopyToClipboard ? (
330 shareablePairingUrl ? null : (
331 <Button size="xs" variant="outline" onClick={handleCopyCode}>
332 <T>Copy code</T>
333 </Button>
334 )
335 ) : (
336 <DialogTrigger render={<Button size="xs" variant="outline" />}>
337 {shareablePairingUrl ? gt("Show link") : gt("Show code")}
338 </DialogTrigger>
339 )}
340 <DialogPopup className="max-w-md">
341 <DialogHeader>
342 <DialogTitle>
343 {isRevealValueUrl
344 ? isRevealValueHostedAppPairingUrl
345 ? gt("Hosted app pairing link")
346 : gt("Pairing link")
347 : gt("Pairing code")}
348 </DialogTitle>
349 <DialogDescription>
350 {isRevealValueUrl
351 ? isRevealValueHostedAppPairingUrl
352 ? gt(
353 "Clipboard copy is unavailable here. Open or manually copy this hosted app link on the device you want to connect.",
354 )
355 : gt(
356 "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect.",
357 )
358 : gt(
359 "Clipboard copy is unavailable here. Manually copy this code into another client.",
360 )}
361 </DialogDescription>
362 </DialogHeader>
363 <DialogPanel>
364 <Textarea
365 readOnly
366 value={revealValue}
367 rows={isRevealValueUrl ? 4 : 3}
368 onFocus={(event) => event.currentTarget.select()}
369 onClick={(event) => event.currentTarget.select()}
370 />
371 {isRevealValueUrl && isRevealValueQrShareable ? (
372 <div className="flex justify-center rounded-xl border border-border/60 bg-muted/30 p-4">
373 <QRCodeSvg
374 value={revealValue}
375 size={132}
376 level="M"
377 marginSize={2}
378 title={gt("Pairing link. Scan to open on another device")}
379 />
380 </div>
381 ) : null}
382 </DialogPanel>
383 <DialogFooter variant="bare">
384 <Button variant="outline" onClick={() => setIsRevealDialogOpen(false)}>
385 <T>Done</T>
386 </Button>
387 {canCopyToClipboard ? (
388 <Button variant="outline" onClick={handleCopyCode}>
389 <T>Copy code</T>
390 </Button>
391 ) : null}
392 </DialogFooter>
393 </DialogPopup>
394 </Dialog>
395 <Button
396 size="xs"
397 variant="destructive-outline"
398 disabled={!canRevoke || revokingPairingLinkId === pairingLink.id}
399 onClick={() => void onRevoke(pairingLink.id)}
400 >
401 {revokingPairingLinkId === pairingLink.id ? gt("Revoking…") : gt("Revoke")}
402 </Button>
403 </div>
404 </div>
405 {isQrPanelOpen && qrPairingUrl !== null ? (
406 <div
407 id={qrPanelId}
408 className="mt-3 flex flex-col gap-4 border-t border-border/50 pt-3 sm:flex-row sm:items-start sm:justify-between"
409 >
410 <div className="min-w-0 flex-1 space-y-3">
411 {endpointCopyOptions.length > 1 ? (
412 <div
413 className="space-y-1.5"
414 role="radiogroup"
415 aria-label={gt("Endpoint the pairing QR code and URL use")}
416 >
417 <p className="text-2xs text-muted-foreground/70">
418 <T>Reach this machine via</T>
419 </p>
420 {endpointCopyOptions.map((option) => {
421 const isSelected = option.id === selectedQrOption?.id;
422 return (
423 <button
424 key={option.id}
425 type="button"
426 role="radio"
427 aria-checked={isSelected}
428 className={cn(
429 "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",
430 isSelected
431 ? "border-foreground/60 bg-muted/30"
432 : "border-border/50 hover:bg-muted/20",
433 )}
434 onClick={() => setQrEndpointId(option.id)}
435 >
436 <span
437 className={cn(
438 "text-xs font-medium",
439 isSelected ? "text-foreground" : "text-muted-foreground",
440 )}
441 >
442 {option.label}
443 </span>
444 <span className="min-w-0 truncate text-2xs text-muted-foreground/70">
445 {option.detail}
446 </span>
447 </button>
448 );
449 })}
450 </div>
451 ) : null}
452 <div className="flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-2.5 py-1.5">
453 <SharedTooltipTrigger
454 render={
455 <code className="min-w-0 flex-1 truncate font-mono text-2xs text-muted-foreground">
456 {qrPairingUrl}
457 </code>
458 }
459 label={qrPairingUrl}
460 />
461 <Button
462 size="xs"
463 variant="ghost"
464 className="shrink-0"
465 onClick={() => copyPairingValue(qrPairingUrl, copyKindForUrl(qrPairingUrl))}
466 >
467 <T>Copy link</T>
468 </Button>
469 </div>
470 <Button size="xs" variant="ghost" onClick={handleCopyCode}>
471 <T>Copy code only</T>
472 </Button>
473 </div>
474 {canRenderQrForSelection ? (
475 <div className="w-fit shrink-0 self-center rounded-xl bg-white p-3 sm:self-start">
476 <QRCodeSvg
477 value={qrPairingUrl}
478 size={168}
479 level="M"
480 marginSize={1}
481 title={gt("Pairing link. Scan to open on another device")}
482 />
483 </div>
484 ) : (
485 <div className="flex size-[192px] shrink-0 items-center justify-center self-center rounded-xl border border-border/50 p-4 sm:self-start">
486 <p className="text-center text-2xs text-muted-foreground/70">
487 <T>
488 No QR for this endpoint. Another device scanning a loopback link would dial
489 itself; copy the URL for use on this machine instead.
490 </T>
491 </p>
492 </div>
493 )}
494 </div>
495 ) : null}
496 </div>
497 );
498});
499​
500type ConnectedClientListRowProps = {
501 clientSession: ServerClientSessionRecord;
502 revokingClientSessionId: string | null;
503 onRevokeSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
504 canRevoke: boolean;
505};
506​
507const ConnectedClientListRow = memo(function ConnectedClientListRow({
508 clientSession,
509 revokingClientSessionId,
510 onRevokeSession,
511 canRevoke,
512}: ConnectedClientListRowProps) {
513 const gt = useGT();
514 const m = useMessages();
515 const nowMs = useNowSecond();
516 const isLive = clientSession.current || clientSession.connected;
517 const lastConnectedAt = clientSession.lastConnectedAt;
518 const statusTooltip = isLive
519 ? lastConnectedAt
520 ? gt("Connected for {duration}", {
521 duration: formatElapsedDurationLabel(lastConnectedAt, nowMs, m),
522 })
523 : gt("Connected")
524 : lastConnectedAt
525 ? gt("Last connected at {time}", { time: formatAccessTimestamp(lastConnectedAt) })
526 : gt("Not connected yet.");
527 const deviceInfoBits = [
528 clientSession.client.deviceType !== "unknown"
529 ? clientSession.client.deviceType[0]?.toUpperCase() + clientSession.client.deviceType.slice(1)
530 : null,
531 clientSession.client.os ?? null,
532 clientSession.client.browser ?? null,
533 clientSession.client.ipAddress ?? null,
534 ].filter((value): value is string => value !== null);
535 const primaryLabel =
536 clientSession.client.label ??
537 ([clientSession.client.os, clientSession.client.browser].filter(Boolean).join(" · ") ||
538 clientSession.subject);
539​
540 return (
541 <div className={ITEM_ROW_CLASSNAME}>
542 <div className={ITEM_ROW_INNER_CLASSNAME}>
543 <div className="min-w-0 flex-1 space-y-1">
544 <div className="flex min-h-5 items-center gap-1.5">
545 <ConnectionStatusDot
546 tooltipText={statusTooltip}
547 dotClassName={isLive ? "bg-success" : "bg-muted-foreground/30"}
548 pingClassName={isLive ? "bg-success/60 duration-2000" : null}
549 />
550 <h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
551 {clientSession.current ? (
552 <span className="text-3xs text-muted-foreground/80 rounded-md border border-border/50 bg-muted/50 px-1 py-0.5">
553 <T>This device</T>
554 </span>
555 ) : null}
556 </div>
557 <p className="text-xs text-muted-foreground">
558 {deviceInfoBits.length > 0 ? (
559 <>
560 {deviceInfoBits.join(" · ")}
561 <span aria-hidden> · </span>
562 </>
563 ) : null}
564 <AccessScopeSummary scopes={clientSession.scopes} label={gt("Client scopes")} />
565 </p>
566 </div>
567 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
568 {!clientSession.current ? (
569 <Button
570 size="xs"
571 variant="destructive-outline"
572 disabled={!canRevoke || revokingClientSessionId === clientSession.sessionId}
573 onClick={() => void onRevokeSession(clientSession.sessionId)}
574 >
575 {revokingClientSessionId === clientSession.sessionId ? gt("Revoking…") : gt("Revoke")}
576 </Button>
577 ) : null}
578 </div>
579 </div>
580 </div>
581 );
582});
583​
584type AuthorizedClientsHeaderActionProps = {
585 environmentId: EnvironmentId;
586 onPairingLinkCreated: (result: AuthPairingCredentialResult) => void;
587 clientSessions: ReadonlyArray<ServerClientSessionRecord> | null;
588 isRevokingOtherClients: boolean;
589 onRevokeOtherClients: () => void;
590 delegatableScopes: ReadonlyArray<AuthEnvironmentScope>;
591};
592​
593export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({
594 environmentId,
595 onPairingLinkCreated,
596 clientSessions,
597 isRevokingOtherClients,
598 onRevokeOtherClients,
599 delegatableScopes,
600}: AuthorizedClientsHeaderActionProps) {
601 const gt = useGT();
602 const m = useMessages();
603 const pairingDenial = managedCapabilityDenial(
604 useManagedPolicy(environmentId),
605 "remoteClients",
606 m,
607 );
608 const createPairingCredential = useAtomCommand(authEnvironment.createPairingCredential, {
609 reportFailure: false,
610 });
611 const [dialogOpen, setDialogOpen] = useState(false);
612 const pairingDialogSessionRef = useRef(0);
613 const [pairingLabel, setPairingLabel] = useState("");
614 const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthGrantScope>>([
615 ...AuthStandardClientScopes,
616 ]);
617 const selectedScopes = pairingScopes.filter((scope) => delegatableScopes.includes(scope));
618 const terminalSelected = selectedScopes.includes(AuthTerminalOperateScope);
619 const relayAdminSelected = selectedScopes.includes(AuthRelayConfigureScope);
620 const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false);
621​
622 const handlePairingDialogOpenChange = (open: boolean) => {
623 setDialogOpen(open);
624 if (!open) {
625 pairingDialogSessionRef.current += 1;
626 setPairingLabel("");
627 setPairingScopes(
628 AuthStandardClientScopes.filter((scope) => delegatableScopes.includes(scope)),
629 );
630 }
631 };
632​
633 const handleCreatePairingLink = async () => {
634 if (
635 selectedScopes.length === 0 ||
636 !readEnvironmentScope(environmentId, AuthAccessWriteScope) ||
637 !selectedScopes.every((scope) => readEnvironmentScope(environmentId, scope))
638 )
639 return;
640 const dialogSession = pairingDialogSessionRef.current;
641 setIsCreatingPairingLink(true);
642 const trimmedLabel = pairingLabel.trim();
643 const result = await createPairingCredential({
644 environmentId,
645 input: { ...(trimmedLabel ? { label: trimmedLabel } : {}), scopes: selectedScopes },
646 });
647 if (result._tag === "Success") {
648 onPairingLinkCreated(result.value);
649 if (dialogSession === pairingDialogSessionRef.current) {
650 handlePairingDialogOpenChange(false);
651 }
652 } else if (!isAtomCommandInterrupted(result)) {
653 const error = squashAtomCommandFailure(result);
654 const message =
655 error instanceof Error
656 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
657 : gt("Failed to create pairing URL.");
658 toastManager.add(
659 stackedThreadToast({
660 type: "error",
661 title: gt("Could not create pairing URL"),
662 description: message,
663 }),
664 );
665 }
666 setIsCreatingPairingLink(false);
667 };
668​
669 const togglePairingScope = (scope: AuthGrantScope, checked: boolean) => {
670 setPairingScopes((current) => togglePairingScopeSelection(current, scope, checked));
671 };
672​
673 return (
674 <div className="flex flex-wrap items-center justify-end gap-2">
675 <Button size="xs" variant="outline" onClick={() => openUseInAnotherApp(environmentId)}>
676 <PlugIcon className="size-3" />
677 <T>Use in another app (MCP)</T>
678 </Button>
679 <Button
680 size="xs"
681 variant="destructive-outline"
682 disabled={isRevokingOtherClients || !canRevokeOtherClients(clientSessions)}
683 onClick={() => void onRevokeOtherClients()}
684 >
685 {isRevokingOtherClients ? gt("Revoking…") : gt("Revoke others")}
686 </Button>
687 {pairingDenial !== undefined ? (
688 <ManagedControl reason={pairingDenial}>
689 <Button size="xs" variant="default" disabled>
690 <PlusIcon className="size-3" />
691 <T>Create link</T>
692 </Button>
693 </ManagedControl>
694 ) : null}
695 <Dialog
696 open={dialogOpen && pairingDenial === undefined}
697 onOpenChange={handlePairingDialogOpenChange}
698 >
699 {pairingDenial === undefined ? (
700 <DialogTrigger
701 render={
702 <Button size="xs" variant="default">
703 <PlusIcon className="size-3" />
704 <T>Create link</T>
705 </Button>
706 }
707 />
708 ) : null}
709 <DialogPopup className="max-w-md">
710 <DialogHeader>
711 <DialogTitle>
712 <T>Create pairing link</T>
713 </DialogTitle>
714 <DialogDescription>
715 <T>
716 Generate a one-time link that another device can use to pair with this backend as an
717 authorized client.
718 </T>
719 </DialogDescription>
720 </DialogHeader>
721 <DialogPanel>
722 <label className="block">
723 <span className="mb-1.5 block text-xs font-medium text-foreground">
724 <T>Client label (optional)</T>
725 </span>
726 <Input
727 value={pairingLabel}
728 onChange={(event) => setPairingLabel(event.target.value)}
729 placeholder={gt("e.g. Living room iPad")}
730 disabled={isCreatingPairingLink}
731 autoFocus
732 />
733 </label>
734 <section className="space-y-3">
735 <div className="flex items-center justify-between gap-3">
736 <div>
737 <h3 className="text-xs font-medium text-foreground">
738 <T>Permissions</T>
739 </h3>
740 <p className="text-xs text-muted-foreground">
741 <T>Limit what the paired client can do.</T>
742 </p>
743 </div>
744 <div className="flex gap-1">
745 <Button
746 size="xs"
747 variant="outline"
748 disabled={isCreatingPairingLink}
749 onClick={() =>
750 setPairingScopes(
751 [
752 AuthOrchestrationReadScope,
753 AuthFilesystemReadScope,
754 AuthDiagnosticsReadScope,
755 AuthTerminalReadScope,
756 ].filter((scope) => delegatableScopes.includes(scope)),
757 )
758 }
759 >
760 <T>Read only</T>
761 </Button>
762 <Button
763 size="xs"
764 variant="outline"
765 disabled={isCreatingPairingLink}
766 onClick={() =>
767 setPairingScopes(
768 AuthStandardClientScopes.filter((scope) =>
769 delegatableScopes.includes(scope),
770 ),
771 )
772 }
773 >
774 {gt("Standard", { $context: "standard permission preset" })}
775 </Button>
776 </div>
777 </div>
778 <div className="divide-y divide-border/60 rounded-lg border border-input bg-muted/25">
779 {PAIRING_SCOPE_OPTIONS.filter(({ scope }) => delegatableScopes.includes(scope)).map(
780 ({ scope, title, description }) => (
781 <label
782 key={scope}
783 className="flex cursor-pointer items-start gap-3 px-3 py-2.5 transition-colors hover:bg-muted/40"
784 >
785 <Checkbox
786 className="mt-0.5"
787 checked={pairingScopes.includes(scope)}
788 disabled={isCreatingPairingLink}
789 onCheckedChange={(checked) => togglePairingScope(scope, checked === true)}
790 />
791 <span className="min-w-0">
792 <span className="block text-xs font-medium text-foreground">
793 {m(title)}
794 </span>
795 <span className="block text-xs leading-snug text-muted-foreground">
796 {m(description)}
797 </span>
798 {terminalSelected && scope === AuthTerminalOperateScope ? (
799 <span className="block text-xs text-warning">
800 {gt(
801 "Terminal commands can read or change files within the server account’s permissions.",
802 )}
803 </span>
804 ) : null}
805 {relayAdminSelected && scope === AuthRelayConfigureScope ? (
806 <span className="block text-xs text-warning">
807 {gt("This client can change who can issue pairing credentials.")}
808 </span>
809 ) : null}
810 </span>
811 </label>
812 ),
813 )}
814 </div>
815 {selectedScopes.length === 0 ? (
816 <p className="text-xs text-destructive">
817 <T>Select at least one permission.</T>
818 </p>
819 ) : selectedScopes.includes(AuthAccessWriteScope) ? (
820 <p className="text-xs text-warning">
821 <T>This client can create or revoke access for other devices.</T>
822 </p>
823 ) : null}
824 </section>
825 </DialogPanel>
826 <DialogFooter variant="bare">
827 <Button
828 variant="outline"
829 disabled={isCreatingPairingLink}
830 onClick={() => setDialogOpen(false)}
831 >
832 <T>Cancel</T>
833 </Button>
834 <Button
835 disabled={isCreatingPairingLink || selectedScopes.length === 0}
836 onClick={() => void handleCreatePairingLink()}
837 >
838 {isCreatingPairingLink ? gt("Creating…") : gt("Create link")}
839 </Button>
840 </DialogFooter>
841 </DialogPopup>
842 </Dialog>
843 </div>
844 );
845});
846​
847type PairingClientsListProps = {
848 servedByEnvironment: boolean;
849 endpointUrl: string | null | undefined;
850 endpoints: ReadonlyArray<AdvertisedEndpoint>;
851 defaultEndpointKey: string | null;
852 isLoading: boolean;
853 pairingLinks: ReadonlyArray<ServerPairingLinkRecord>;
854 createdPairingCredentials: ReadonlyMap<string, string>;
855 sharedPairingLinkId: string | null;
856 clientSessions: ReadonlyArray<ServerClientSessionRecord>;
857 revokingPairingLinkId: string | null;
858 revokingClientSessionId: string | null;
859 onRevokePairingLink: (id: string) => void;
860 onRevokeClientSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
861 canRevoke: boolean;
862};
863​
864export const PairingClientsList = memo(function PairingClientsList({
865 servedByEnvironment,
866 endpointUrl,
867 endpoints,
868 defaultEndpointKey,
869 isLoading,
870 pairingLinks,
871 createdPairingCredentials,
872 sharedPairingLinkId,
873 clientSessions,
874 revokingPairingLinkId,
875 revokingClientSessionId,
876 onRevokePairingLink,
877 onRevokeClientSession,
878 canRevoke,
879}: PairingClientsListProps) {
880 return (
881 <>
882 {pairingLinks.map((pairingLink) => (
883 <PairingLinkListRow
884 key={pairingLink.id}
885 pairingLink={pairingLink}
886 credential={createdPairingCredentials.get(pairingLink.id)}
887 defaultShareOpen={pairingLink.id === sharedPairingLinkId}
888 servedByEnvironment={servedByEnvironment}
889 endpointUrl={endpointUrl}
890 endpoints={endpoints}
891 defaultEndpointKey={defaultEndpointKey}
892 revokingPairingLinkId={revokingPairingLinkId}
893 onRevoke={onRevokePairingLink}
894 canRevoke={canRevoke}
895 />
896 ))}
897​
898 {clientSessions.map((clientSession) => (
899 <ConnectedClientListRow
900 key={clientSession.sessionId}
901 clientSession={clientSession}
902 revokingClientSessionId={revokingClientSessionId}
903 onRevokeSession={onRevokeClientSession}
904 canRevoke={canRevoke}
905 />
906 ))}
907​
908 {pairingLinks.length === 0 && clientSessions.length === 0 && !isLoading ? (
909 <div className={ITEM_ROW_CLASSNAME}>
910 <p className="text-xs text-muted-foreground/60">
911 <T>No pairing links or client sessions.</T>
912 </p>
913 </div>
914 ) : null}
915 </>
916 );
917});
918​
919type AdvertisedEndpointListRowProps = {
920 endpoint: AdvertisedEndpoint;
921 isDefault: boolean;
922 onSetDefault: (endpoint: AdvertisedEndpoint) => void;
923 onSetupTailscaleServe: (endpoint: AdvertisedEndpoint) => void;
924 onDisableTailscaleServe: (endpoint: AdvertisedEndpoint) => void;
925 isUpdatingTailscaleServe: boolean;
926};
927​
928export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow({
929 endpoint,
930 isDefault,
931 onSetDefault,
932 onSetupTailscaleServe,
933 onDisableTailscaleServe,
934 isUpdatingTailscaleServe,
935}: AdvertisedEndpointListRowProps) {
936 const gt = useGT();
937 const isAvailable = endpoint.status === "available";
938 const needsTailscaleSetup = isTailscaleHttpsEndpoint(endpoint) && endpoint.status !== "available";
939 const canDisableTailscaleServe =
940 isTailscaleHttpsEndpoint(endpoint) && endpoint.status === "available";
941 const shouldShowEndpointUrl = !needsTailscaleSetup;
942 const m = useMessages();
943 const remoteDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "remoteClients", m);
944 return (
945 <div className={endpointRowClassName(isAvailable)}>
946 {isDefault ? (
947 <span className="absolute inset-y-2 left-0 w-1 rounded-r-full bg-primary" aria-hidden />
948 ) : null}
949 <div className="flex min-h-7 min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
950 <div className="flex min-h-7 min-w-0 flex-1 items-center gap-3">
951 <h3 className="shrink-0 text-sm leading-5 font-medium text-foreground">
952 {endpoint.label}
953 </h3>
954 {shouldShowEndpointUrl ? (
955 <SharedTooltipTrigger
956 render={
957 <p className="min-w-0 truncate text-xs leading-5 text-muted-foreground">
958 {endpoint.httpBaseUrl}
959 </p>
960 }
961 label={endpoint.httpBaseUrl}
962 />
963 ) : null}
964 {!isAvailable ? (
965 <span className="inline-flex h-6 shrink-0 items-center rounded-md border border-border/70 px-1.5 text-3xs text-muted-foreground">
966 <T>Setup required</T>
967 </span>
968 ) : null}
969 </div>
970 <div className="ml-auto flex min-h-7 shrink-0 items-center justify-end gap-2">
971 {isDefault ? (
972 <span className="inline-flex h-6 items-center rounded-md border border-primary/30 bg-primary/10 px-1.5 text-3xs text-primary">
973 {gt("Default", { $context: "default endpoint badge" })}
974 </span>
975 ) : null}
976 {needsTailscaleSetup ? (
977 <ManagedControl reason={remoteDenial}>
978 <Button
979 size="xs"
980 variant="outline"
981 onClick={() => onSetupTailscaleServe(endpoint)}
982 disabled={isUpdatingTailscaleServe || remoteDenial !== undefined}
983 >
984 {isUpdatingTailscaleServe ? gt("Restarting…") : gt("Setup", { $context: "verb" })}
985 </Button>
986 </ManagedControl>
987 ) : null}
988 {canDisableTailscaleServe ? (
989 <Button
990 size="xs"
991 variant="destructive-outline"
992 onClick={() => onDisableTailscaleServe(endpoint)}
993 disabled={isUpdatingTailscaleServe}
994 >
995 {isUpdatingTailscaleServe ? gt("Restarting…") : gt("Disable")}
996 </Button>
997 ) : null}
998 {!needsTailscaleSetup && !isDefault ? (
999 <Button size="xs" variant="outline" onClick={() => onSetDefault(endpoint)}>
1000 <T>Set as default</T>
1001 </Button>
1002 ) : null}
1003 </div>
1004 </div>
1005 </div>
1006 );
1007});
1008​
1009export function NetworkAccessDescription({
1010 endpoint,
1011 hiddenEndpointCount,
1012 expanded,
1013 onToggleExpanded,
1014 fallback,
1015}: {
1016 endpoint: AdvertisedEndpoint | null;
1017 hiddenEndpointCount: number;
1018 expanded: boolean;
1019 onToggleExpanded: () => void;
1020 fallback: ReactNode;
1021}) {
1022 const gt = useGT();
1023 if (!endpoint) {
1024 return fallback;
1026​
1027 const summary = (
1028 <>
1029 <span className="min-w-0 truncate">{endpoint.httpBaseUrl}</span>
1030 {hiddenEndpointCount > 0 ? (
1031 <span className="shrink-0 text-xs font-medium">
1032 {expanded ? gt("Hide") : `+${hiddenEndpointCount}`}
1033 </span>
1034 ) : null}
1035 </>
1036 );
1037​
1038 return (
1039 <span className="inline-flex min-w-0 max-w-full items-baseline gap-1">
1040 <span className="shrink-0">
1041 <T>Reachable at</T>
1042 </span>
1043 {hiddenEndpointCount > 0 ? (
1044 <button
1045 type="button"
1046 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"
1047 onClick={onToggleExpanded}
1048 aria-expanded={expanded}
1050 {summary}
1051 </button>
1052 ) : (
1053 <span className="inline-flex min-w-0 max-w-full items-baseline gap-2">{summary}</span>
1054 )}
1055 </span>
1056 );