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