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

AuthorizedClientsSettings.tsx

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