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