Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AuthorizedClientsSettings.tsx

986 lines35.9 KB

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