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

AuthorizedClientsSettings.tsx

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