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