3463 lines · 129.7 KB · TypeScript
RawDownload
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;  }} 

Lines 1–500 of 3463.