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