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