forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionsSettings.tsx
More file actions
3463 lines (3344 loc) · 130 KB
/
Copy pathConnectionsSettings.tsx
File metadata and controls
3463 lines (3344 loc) · 130 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
ChevronsLeftRightEllipsisIcon,
PlusIcon,
QrCodeIcon,
RefreshCwIcon,
TerminalIcon,
} from "lucide-react";
import { useAtomValue } from "@effect/atom-react";
import { type ReactNode, memo, useCallback, useId, useMemo, useState } from "react";
import {
AuthAccessReadScope,
AuthAccessWriteScope,
AuthAdministrativeScopes,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthRelayReadScope,
AuthRelayWriteScope,
AuthReviewWriteScope,
AuthStandardClientScopes,
AuthTerminalOperateScope,
type AuthClientSession,
type AuthEnvironmentScope,
type AuthPairingLink,
type AdvertisedEndpoint,
type DesktopDiscoveredSshHost,
type DesktopSshEnvironmentTarget,
type DesktopServerExposureState,
type DesktopWslState,
type EnvironmentId,
} from "@t3tools/contracts";
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { cn } from "../../lib/utils";
import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";
import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
import {
applyWslEnableSelection,
isQrShareableEndpoint,
selectQrEndpointOption,
} from "./ConnectionsSettings.logic";
import {
SettingsPageContainer,
SettingsRow,
SettingsSection,
useRelativeTimeTick,
} from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
import { Input } from "../ui/input";
import { Checkbox } from "../ui/checkbox";
import {
Dialog,
DialogClose,
DialogFooter,
DialogDescription,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
DialogTrigger,
} from "../ui/dialog";
import { ScrollArea } from "../ui/scroll-area";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "../ui/alert-dialog";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { QRCodeSvg } from "../ui/qr-code";
import { Spinner } from "../ui/spinner";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { Button } from "../ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { AnimatedHeight } from "../AnimatedHeight";
import { Textarea } from "../ui/textarea";
import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "../../pairingUrl";
import { readHostedPairingRequest } from "../../hostedPairing";
import {
createServerPairingCredential,
revokeOtherServerClientSessions,
revokeServerClientSession,
revokeServerPairingLink,
isLoopbackHostname,
usePrimarySessionState,
type ServerClientSessionRecord,
type ServerPairingLinkRecord,
} from "~/environments/primary";
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
import { useUiStateStore } from "~/uiStateStore";
import {
resolveServerConfigVersionMismatch,
resolveServerSelfUpdateCapability,
} from "~/versionSkew";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
import { authEnvironment } from "~/state/auth";
import { environmentCatalog } from "~/connection/catalog";
import {
connectPairing as connectPairingAtom,
connectSshEnvironment as connectSshEnvironmentAtom,
} from "~/connection/onboarding";
import { useEnvironmentQuery } from "~/state/query";
import {
desktopNetworkAccessStateAtom,
refreshDesktopNetworkAccessState,
} from "~/state/desktopNetworkAccess";
import { desktopSshHostsStateAtom } from "~/state/desktopSshHosts";
import { desktopWslStateAtom, refreshDesktopWslState } from "~/state/desktopWslState";
import {
type EnvironmentPresentation,
useEnvironments,
usePrimaryEnvironment,
} from "~/state/environments";
import { useAtomCommand } from "../../state/use-atom-command";
import { serverEnvironment } from "~/state/server";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { ServerUpdateAction, ServerUpdateProgress } from "../ServerUpdateAction";
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
const EMPTY_DISCOVERED_SSH_HOSTS: ReadonlyArray<DesktopDiscoveredSshHost> = [];
// Sentinels for the consolidated WSL backend picker. The colon is
// rejected by DISTRO_NAME_PATTERN (validated on the desktop side) so
// neither can collide with a real distro name.
const BACKEND_VALUE_DEFAULT_WSL = "backend:default-wsl";
const BACKEND_VALUE_WSL_OFF = "backend:wsl-off";
const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, {
dateStyle: "medium",
timeStyle: "short",
});
function formatAccessTimestamp(value: string): string {
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) {
return value;
}
return accessTimestampFormatter.format(parsed);
}
const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{
readonly scope: AuthEnvironmentScope;
readonly title: string;
readonly description: string;
}> = [
{
scope: AuthOrchestrationReadScope,
title: "View environment",
description: "Read threads, status, diffs, and configuration.",
},
{
scope: AuthOrchestrationOperateScope,
title: "Operate tasks",
description: "Start tasks and perform changes in the environment.",
},
{
scope: AuthTerminalOperateScope,
title: "Use terminals",
description: "Create terminals and send input to running shells.",
},
{
scope: AuthReviewWriteScope,
title: "Write reviews",
description: "Create comments while reviewing changes.",
},
{
scope: AuthAccessReadScope,
title: "View access",
description: "Inspect pairing links and authorized clients.",
},
{
scope: AuthAccessWriteScope,
title: "Manage access",
description: "Issue and revoke credentials for other clients.",
},
{
scope: AuthRelayReadScope,
title: "View relay",
description: "Inspect managed relay connectivity.",
},
{
scope: AuthRelayWriteScope,
title: "Manage relay",
description: "Change managed tunnel connectivity.",
},
];
function AccessScopeSummary({
scopes,
label,
}: {
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
readonly label: string;
}) {
const scopeCountLabel = `${scopes.length} ${scopes.length === 1 ? "scope" : "scopes"}`;
return (
<Popover>
<PopoverTrigger
openOnHover
delay={250}
closeDelay={100}
render={
<button
type="button"
aria-label={`${label}: show ${scopeCountLabel}`}
className="cursor-help underline decoration-border underline-offset-2 outline-hidden hover:text-foreground focus-visible:text-foreground"
/>
}
>
{scopeCountLabel}
</PopoverTrigger>
<PopoverPopup
side="top"
align="start"
tooltipStyle
className="w-max max-w-80 whitespace-normal"
>
<p className="mb-1 font-medium">Granted scopes</p>
<div className="flex flex-col gap-0.5">
{scopes.map((scope) => (
<code key={scope} className="font-mono text-foreground/85">
{scope}
</code>
))}
</div>
</PopoverPopup>
</Popover>
);
}
function formatDesktopSshTarget(target: DesktopSshEnvironmentTarget): string {
const authority = target.username ? `${target.username}@${target.hostname}` : target.hostname;
return target.port ? `${authority}:${target.port}` : authority;
}
function parseManualDesktopSshTarget(input: {
readonly host: string;
readonly username: string;
readonly port: string;
}): DesktopSshEnvironmentTarget {
const rawHost = input.host.trim();
if (rawHost.length === 0) {
throw new Error("SSH host or alias is required.");
}
let hostname = rawHost;
let username = input.username.trim() || null;
let port: number | null = null;
const atIndex = hostname.lastIndexOf("@");
if (atIndex > 0) {
const inlineUsername = hostname.slice(0, atIndex).trim();
hostname = hostname.slice(atIndex + 1).trim();
if (!username && inlineUsername.length > 0) {
username = inlineUsername;
}
}
const bracketedHostMatch = /^\[([^\]]+)\](?::(\d+))?$/u.exec(hostname);
if (bracketedHostMatch) {
hostname = bracketedHostMatch[1]!.trim();
if (bracketedHostMatch[2]) {
port = Number.parseInt(bracketedHostMatch[2], 10);
}
} else {
const colonSegments = hostname.split(":");
if (colonSegments.length === 2 && /^\d+$/u.test(colonSegments[1] ?? "")) {
hostname = colonSegments[0]!.trim();
port = Number.parseInt(colonSegments[1]!, 10);
}
}
const rawPort = input.port.trim();
if (rawPort.length > 0) {
port = Number.parseInt(rawPort, 10);
}
if (hostname.length === 0) {
throw new Error("SSH host or alias is required.");
}
if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65_535)) {
throw new Error("SSH port must be between 1 and 65535.");
}
return {
alias: hostname,
hostname,
username,
port,
};
}
function parsePairingUrlFields(
input: string,
): { readonly host: string; readonly pairingCode: string } | null {
const trimmed = input.trim();
if (!trimmed) return null;
try {
const urlLikeInput =
/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//u.test(trimmed) || trimmed.startsWith("//")
? trimmed
: `https://${trimmed}`;
const url = new URL(urlLikeInput, window.location.origin);
const hostedPairingRequest = readHostedPairingRequest(url);
if (hostedPairingRequest) {
return {
host: hostedPairingRequest.host,
pairingCode: hostedPairingRequest.token,
};
}
const pairingCode = getPairingTokenFromUrl(url);
if (!pairingCode) return null;
return {
host: url.origin,
pairingCode,
};
} catch {
return null;
}
}
function parseRemotePairingFields(input: { readonly host: string; readonly pairingCode: string }): {
readonly host: string;
readonly pairingCode: string;
} {
const parsedPairingUrl = parsePairingUrlFields(input.host);
if (parsedPairingUrl) return parsedPairingUrl;
const host = input.host.trim();
const pairingCode = input.pairingCode.trim();
if (!host) {
throw new Error("Enter a backend host.");
}
if (!pairingCode) {
throw new Error("Enter a pairing code.");
}
return { host, pairingCode };
}
function formatDesktopSshConnectionError(error: unknown): string {
const fallback = "Failed to connect SSH host.";
const rawMessage = error instanceof Error ? error.message : fallback;
const withoutIpcPrefix = rawMessage.replace(
/^Error invoking remote method 'desktop:ensure-ssh-environment':\s*/u,
"",
);
const withoutTaggedErrorPrefix = withoutIpcPrefix.replace(/^Ssh[A-Za-z]+Error:\s*/u, "");
return withoutTaggedErrorPrefix.trim() || fallback;
}
const ENDPOINT_ROW_CLASSNAME = "rounded-xl px-3 py-2.5 sm:px-4";
type AccessSectionPresentation = "current" | "endpoint-rail";
function accessRowClassName(_presentation: AccessSectionPresentation) {
return ITEM_ROW_CLASSNAME;
}
function endpointRowClassName(presentation: AccessSectionPresentation, isAvailable: boolean) {
if (presentation === "endpoint-rail") {
return cn("relative rounded-xl px-3 py-3 sm:px-4", !isAvailable && "bg-muted/15");
}
return cn(ENDPOINT_ROW_CLASSNAME, !isAvailable && "bg-muted/24");
}
function sortDesktopPairingLinks(links: ReadonlyArray<ServerPairingLinkRecord>) {
return [...links].toSorted(
(left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(),
);
}
function sortDesktopClientSessions(sessions: ReadonlyArray<ServerClientSessionRecord>) {
return [...sessions].toSorted((left, right) => {
if (left.current !== right.current) {
return left.current ? -1 : 1;
}
if (left.connected !== right.connected) {
return left.connected ? -1 : 1;
}
return new Date(right.issuedAt).getTime() - new Date(left.issuedAt).getTime();
});
}
function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairingLinkRecord {
return {
...pairingLink,
createdAt: DateTime.formatIso(pairingLink.createdAt),
expiresAt: DateTime.formatIso(pairingLink.expiresAt),
};
}
function toDesktopClientSessionRecord(clientSession: AuthClientSession): ServerClientSessionRecord {
return {
...clientSession,
issuedAt: DateTime.formatIso(clientSession.issuedAt),
expiresAt: DateTime.formatIso(clientSession.expiresAt),
lastConnectedAt:
clientSession.lastConnectedAt === null
? null
: DateTime.formatIso(clientSession.lastConnectedAt),
};
}
function selectPairingEndpoint(
endpoints: ReadonlyArray<AdvertisedEndpoint>,
defaultEndpointKey?: string | null,
): AdvertisedEndpoint | null {
const availableEndpoints = endpoints.filter((endpoint) => endpoint.status !== "unavailable");
if (defaultEndpointKey) {
const selectedEndpoint = availableEndpoints.find(
(endpoint) => endpointDefaultPreferenceKey(endpoint) === defaultEndpointKey,
);
if (selectedEndpoint) {
return selectedEndpoint;
}
}
return (
availableEndpoints.find((endpoint) => endpoint.isDefault) ??
availableEndpoints.find((endpoint) => endpoint.reachability !== "loopback") ??
availableEndpoints.find((endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible") ??
null
);
}
function isTailscaleHttpsEndpoint(endpoint: AdvertisedEndpoint): boolean {
return endpoint.id.startsWith("tailscale-magicdns:");
}
function endpointDefaultPreferenceKey(endpoint: AdvertisedEndpoint): string {
if (endpoint.id.startsWith("desktop-loopback:")) {
return "desktop-core:loopback:http";
}
if (endpoint.id.startsWith("desktop-lan:")) {
return "desktop-core:lan:http";
}
if (endpoint.id.startsWith("tailscale-ip:")) {
return "tailscale:ip:http";
}
if (isTailscaleHttpsEndpoint(endpoint)) {
return "tailscale:magicdns:https";
}
let scheme = "unknown";
try {
scheme = new URL(endpoint.httpBaseUrl).protocol.replace(/:$/u, "");
} catch {
// Keep the stored preference stable even if a custom endpoint is malformed.
}
return `${endpoint.provider.id}:${endpoint.reachability}:${scheme}:${endpoint.label}`;
}
function resolveAdvertisedEndpointPairingUrl(
endpoint: AdvertisedEndpoint,
credential: string,
): string {
if (endpoint.compatibility.hostedHttpsApp === "compatible") {
return (
resolveHostedPairingUrl(endpoint.httpBaseUrl, credential) ??
resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential)
);
}
return resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential);
}
function resolveCurrentOriginPairingUrl(credential: string): string {
const url = new URL("/pair", window.location.href);
return setPairingTokenOnUrl(url, credential).toString();
}
function isHostedAppPairingUrl(value: string): boolean {
try {
const url = new URL(value);
return url.pathname === "/pair" && url.searchParams.has("host");
} catch {
return false;
}
}
function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): string {
if (isHostedAppPairingUrl(url)) {
return "Opens the hosted app, no install needed";
}
switch (endpoint.reachability) {
case "lan":
return "Devices on the same network";
case "private-network":
return "Devices on your private network";
case "public":
return "Reachable from anywhere";
case "loopback":
return "Clients on this machine";
}
}
type PairingLinkListRowProps = {
pairingLink: ServerPairingLinkRecord;
endpointUrl: string | null | undefined;
endpoints: ReadonlyArray<AdvertisedEndpoint>;
defaultEndpointKey: string | null;
presentation?: AccessSectionPresentation;
revokingPairingLinkId: string | null;
onRevoke: (id: string) => void;
};
const PairingLinkListRow = memo(function PairingLinkListRow({
pairingLink,
endpointUrl,
endpoints,
defaultEndpointKey,
presentation = "current",
revokingPairingLinkId,
onRevoke,
}: PairingLinkListRowProps) {
const nowMs = useRelativeTimeTick(1_000);
const expiresAtMs = useMemo(
() => new Date(pairingLink.expiresAt).getTime(),
[pairingLink.expiresAt],
);
const [isRevealDialogOpen, setIsRevealDialogOpen] = useState(false);
const [isQrPanelOpen, setIsQrPanelOpen] = useState(false);
// Ephemeral per-row choice of which endpoint the QR encodes (AdvertisedEndpoint.id);
// null falls back to the saved default endpoint.
const [qrEndpointId, setQrEndpointId] = useState<string | null>(null);
const qrPanelId = useId();
const currentOriginPairingUrl = useMemo(
() => resolveCurrentOriginPairingUrl(pairingLink.credential),
[pairingLink.credential],
);
const hostedPairingUrl = useMemo(
() =>
endpointUrl != null && endpointUrl !== ""
? resolveHostedPairingUrl(endpointUrl, pairingLink.credential)
: null,
[endpointUrl, pairingLink.credential],
);
const endpointPairingUrl = useMemo(() => {
const endpoint = selectPairingEndpoint(endpoints, defaultEndpointKey);
return endpoint ? resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential) : null;
}, [defaultEndpointKey, endpoints, pairingLink.credential]);
const endpointCopyOptions = useMemo(() => {
const options: Array<{
readonly id: string;
readonly preferenceKey: string;
readonly label: string;
readonly url: string;
readonly detail: string;
readonly qrShareable: boolean;
}> = [];
for (const endpoint of endpoints) {
if (endpoint.status === "unavailable") {
continue;
}
const url = resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential);
options.push({
id: endpoint.id,
preferenceKey: endpointDefaultPreferenceKey(endpoint),
label: endpoint.label,
url,
detail: endpointShareHint(endpoint, url),
qrShareable: isQrShareableEndpoint(endpoint),
});
}
return options;
}, [endpoints, pairingLink.credential]);
const shareablePairingUrl =
endpointPairingUrl ??
(endpointUrl != null && endpointUrl !== ""
? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential))
: isLoopbackHostname(window.location.hostname)
? null
: currentOriginPairingUrl);
// Value of the copy attempt that last failed. The clipboard-failure reveal
// dialog must show exactly what failed to copy, not the row's default URL.
const [failedCopyValue, setFailedCopyValue] = useState<string | null>(null);
const revealValue = failedCopyValue ?? shareablePairingUrl ?? pairingLink.credential;
const isRevealValueUrl = revealValue !== pairingLink.credential;
const isRevealValueHostedAppPairingUrl = isRevealValueUrl && isHostedAppPairingUrl(revealValue);
// Never render a QR for a loopback URL, even in the manual-copy fallback.
const isRevealValueQrShareable =
endpointCopyOptions.find((option) => option.url === revealValue)?.qrShareable ?? true;
const canCopyToClipboard =
typeof window !== "undefined" &&
window.isSecureContext &&
navigator.clipboard?.writeText != null;
const { copyToClipboard } = useCopyToClipboard<{
value: string;
kind: "code" | "hosted-link" | "link";
}>({
onCopy: ({ kind }) => {
toastManager.add({
type: "success",
title:
kind === "hosted-link"
? "Hosted app link copied"
: kind === "link"
? "Pairing URL copied"
: "Pairing code copied",
description:
kind === "hosted-link"
? "Open it in the browser on the device you want to connect."
: kind === "link"
? "Open it in the client you want to pair to this environment."
: "Paste it into another client to finish pairing.",
});
},
onError: (error, { value, kind }) => {
// Captured per attempt so concurrent copies cannot make the dialog
// reveal a different value than the one that failed.
setFailedCopyValue(value);
setIsRevealDialogOpen(true);
toastManager.add(
stackedThreadToast({
type: "error",
title: canCopyToClipboard
? kind === "hosted-link"
? "Could not copy hosted app link"
: kind === "link"
? "Could not copy pairing URL"
: "Could not copy pairing code"
: "Clipboard copy unavailable",
description: canCopyToClipboard ? error.message : "Showing the full value instead.",
}),
);
},
});
const copyPairingValue = useCallback(
(value: string, kind: "code" | "hosted-link" | "link") => {
copyToClipboard(value, { value, kind });
},
[copyToClipboard],
);
const copyKindForUrl = useCallback(
(url: string): "hosted-link" | "link" => (isHostedAppPairingUrl(url) ? "hosted-link" : "link"),
[],
);
const handleCopyCode = useCallback(() => {
copyPairingValue(pairingLink.credential, "code");
}, [copyPairingValue, pairingLink.credential]);
const expiresAbsolute = formatAccessTimestamp(pairingLink.expiresAt);
const primaryLabel = pairingLink.label ?? "Pairing link";
const selectedQrOption = selectQrEndpointOption(
endpointCopyOptions,
qrEndpointId,
defaultEndpointKey,
);
const qrPairingUrl = selectedQrOption?.url ?? shareablePairingUrl;
// With no endpoint list the fallback is never loopback: selectPairingEndpoint
// skips loopback and the current-origin fallback is guarded by
// isLoopbackHostname, so only an explicit loopback selection hides the QR.
const canRenderQrForSelection = selectedQrOption?.qrShareable ?? true;
if (expiresAtMs <= nowMs) {
return null;
}
return (
<div className={accessRowClassName(presentation)}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex min-h-5 items-center gap-1.5">
<ConnectionStatusDot
tooltipText={`Link created at ${formatAccessTimestamp(pairingLink.createdAt)}`}
dotClassName="bg-amber-400"
/>
<h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
</div>
<p className="text-xs text-muted-foreground">
<Tooltip>
<TooltipTrigger render={<span />}>
{formatExpiresInLabel(pairingLink.expiresAt, nowMs)}
</TooltipTrigger>
<TooltipPopup side="top">{expiresAbsolute}</TooltipPopup>
</Tooltip>
<span aria-hidden> · </span>
<AccessScopeSummary scopes={pairingLink.scopes} label="Pairing link scopes" />
</p>
{shareablePairingUrl === null ? (
<p className="text-[11px] text-muted-foreground/70">
Copy the token and pair from another client using this backend's reachable host.
</p>
) : null}
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
{shareablePairingUrl && canCopyToClipboard ? (
<Button
size="xs"
variant="outline"
aria-expanded={isQrPanelOpen}
aria-controls={qrPanelId}
onClick={() => setIsQrPanelOpen((open) => !open)}
>
<QrCodeIcon aria-hidden />
Share
</Button>
) : null}
<Dialog
open={isRevealDialogOpen}
onOpenChange={(open) => {
setIsRevealDialogOpen(open);
if (!open) setFailedCopyValue(null);
}}
>
{canCopyToClipboard ? (
shareablePairingUrl ? null : (
<Button size="xs" variant="outline" onClick={handleCopyCode}>
Copy code
</Button>
)
) : (
<DialogTrigger render={<Button size="xs" variant="outline" />}>
{shareablePairingUrl ? "Show link" : "Show code"}
</DialogTrigger>
)}
<DialogPopup className="max-w-md">
<DialogHeader>
<DialogTitle>
{isRevealValueUrl
? isRevealValueHostedAppPairingUrl
? "Hosted app pairing link"
: "Pairing link"
: "Pairing code"}
</DialogTitle>
<DialogDescription>
{isRevealValueUrl
? isRevealValueHostedAppPairingUrl
? "Clipboard copy is unavailable here. Open or manually copy this hosted app link on the device you want to connect."
: "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect."
: "Clipboard copy is unavailable here. Manually copy this code into another client."}
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-4">
<Textarea
readOnly
value={revealValue}
rows={isRevealValueUrl ? 4 : 3}
className="text-xs leading-relaxed"
onFocus={(event) => event.currentTarget.select()}
onClick={(event) => event.currentTarget.select()}
/>
{isRevealValueUrl && isRevealValueQrShareable ? (
<div className="flex justify-center rounded-xl border border-border/60 bg-muted/30 p-4">
<QRCodeSvg
value={revealValue}
size={132}
level="M"
marginSize={2}
title="Pairing link — scan to open on another device"
/>
</div>
) : null}
</DialogPanel>
<DialogFooter variant="bare">
<Button variant="outline" onClick={() => setIsRevealDialogOpen(false)}>
Done
</Button>
{canCopyToClipboard ? (
<Button variant="outline" size="xs" onClick={handleCopyCode}>
Copy code
</Button>
) : null}
</DialogFooter>
</DialogPopup>
</Dialog>
<Button
size="xs"
variant="destructive-outline"
disabled={revokingPairingLinkId === pairingLink.id}
onClick={() => void onRevoke(pairingLink.id)}
>
{revokingPairingLinkId === pairingLink.id ? "Revoking…" : "Revoke"}
</Button>
</div>
</div>
{isQrPanelOpen && qrPairingUrl !== null ? (
<div
id={qrPanelId}
className="mt-3 flex flex-col gap-4 border-t border-border/50 pt-3 sm:flex-row sm:items-start sm:justify-between"
>
<div className="min-w-0 flex-1 space-y-3">
{endpointCopyOptions.length > 1 ? (
<div
className="space-y-1.5"
role="radiogroup"
aria-label="Endpoint the pairing QR code and URL use"
>
<p className="text-[11px] text-muted-foreground/70">Reach this machine via</p>
{endpointCopyOptions.map((option) => {
const isSelected = option.id === selectedQrOption?.id;
return (
<button
key={option.id}
type="button"
role="radio"
aria-checked={isSelected}
className={cn(
"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-ring",
isSelected
? "border-foreground/60 bg-muted/30"
: "border-border/50 hover:bg-muted/20",
)}
onClick={() => setQrEndpointId(option.id)}
>
<span
className={cn(
"text-xs font-medium",
isSelected ? "text-foreground" : "text-muted-foreground",
)}
>
{option.label}
</span>
<span className="min-w-0 truncate text-[11px] text-muted-foreground/70">
{option.detail}
</span>
</button>
);
})}
</div>
) : null}
<div className="flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-2.5 py-1.5">
<Tooltip>
<TooltipTrigger
render={
<code className="min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground">
{qrPairingUrl}
</code>
}
/>
<TooltipPopup side="top" className="max-w-80 break-all">
{qrPairingUrl}
</TooltipPopup>
</Tooltip>
<Button
size="xs"
variant="ghost"
className="shrink-0"
onClick={() => copyPairingValue(qrPairingUrl, copyKindForUrl(qrPairingUrl))}
>
Copy link
</Button>
</div>
<Button size="xs" variant="ghost" onClick={handleCopyCode}>
Copy code only
</Button>
</div>
{canRenderQrForSelection ? (
<div className="w-fit shrink-0 self-center rounded-xl bg-white p-3 sm:self-start">
<QRCodeSvg
value={qrPairingUrl}
size={168}
level="M"
marginSize={1}
title="Pairing link — scan to open on another device"
/>
</div>
) : (
<div className="flex size-[192px] shrink-0 items-center justify-center self-center rounded-xl border border-border/50 p-4 sm:self-start">
<p className="text-center text-[11px] text-muted-foreground/70">
No QR for this endpoint. Another device scanning a loopback link would dial itself;
copy the URL for use on this machine instead.
</p>
</div>
)}
</div>
) : null}
</div>
);
});
type ConnectedClientListRowProps = {
clientSession: ServerClientSessionRecord;
presentation?: AccessSectionPresentation;
revokingClientSessionId: string | null;
onRevokeSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
};
const ConnectedClientListRow = memo(function ConnectedClientListRow({
clientSession,
presentation = "current",
revokingClientSessionId,
onRevokeSession,
}: ConnectedClientListRowProps) {
const nowMs = useRelativeTimeTick(1_000);
const isLive = clientSession.current || clientSession.connected;
const lastConnectedAt = clientSession.lastConnectedAt;
const statusTooltip = isLive
? lastConnectedAt
? `Connected for ${formatElapsedDurationLabel(lastConnectedAt, nowMs)}`
: "Connected"
: lastConnectedAt
? `Last connected at ${formatAccessTimestamp(lastConnectedAt)}`
: "Not connected yet.";
const deviceInfoBits = [
clientSession.client.deviceType !== "unknown"
? clientSession.client.deviceType[0]?.toUpperCase() + clientSession.client.deviceType.slice(1)
: null,
clientSession.client.os ?? null,
clientSession.client.browser ?? null,
clientSession.client.ipAddress ?? null,
].filter((value): value is string => value !== null);
const primaryLabel =
clientSession.client.label ??
([clientSession.client.os, clientSession.client.browser].filter(Boolean).join(" · ") ||
clientSession.subject);
return (
<div className={accessRowClassName(presentation)}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex min-h-5 items-center gap-1.5">
<ConnectionStatusDot
tooltipText={statusTooltip}
dotClassName={isLive ? "bg-success" : "bg-muted-foreground/30"}
pingClassName={isLive ? "bg-success/60 duration-2000" : null}
/>
<h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
{clientSession.current ? (
<span className="text-[10px] text-muted-foreground/80 rounded-md border border-border/50 bg-muted/50 px-1 py-0.5">
This device
</span>
) : null}
</div>
<p className="text-xs text-muted-foreground">
{deviceInfoBits.length > 0 ? (
<>
{deviceInfoBits.join(" · ")}
<span aria-hidden> · </span>
</>
) : null}
<AccessScopeSummary scopes={clientSession.scopes} label="Client scopes" />
</p>
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
{!clientSession.current ? (
<Button
size="xs"
variant="destructive-outline"
disabled={revokingClientSessionId === clientSession.sessionId}
onClick={() => void onRevokeSession(clientSession.sessionId)}
>
{revokingClientSessionId === clientSession.sessionId ? "Revoking…" : "Revoke"}
</Button>
) : null}
</div>
</div>
</div>
);
});
type AuthorizedClientsHeaderActionProps = {
clientSessions: ReadonlyArray<ServerClientSessionRecord>;
isRevokingOtherClients: boolean;
onRevokeOtherClients: () => void;
};
const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({
clientSessions,
isRevokingOtherClients,
onRevokeOtherClients,
}: AuthorizedClientsHeaderActionProps) {
const [dialogOpen, setDialogOpen] = useState(false);
const [pairingLabel, setPairingLabel] = useState("");
const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthEnvironmentScope>>([
...AuthStandardClientScopes,
]);
const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false);
const handleCreatePairingLink = useCallback(async () => {
setIsCreatingPairingLink(true);
try {
await createServerPairingCredential({ label: pairingLabel, scopes: pairingScopes });
setPairingLabel("");
setPairingScopes([...AuthStandardClientScopes]);