TypeScript
refactor(web): the connections page's pure helpers live in ConnectionsSettings.logic (#22683)
Julius Marminge9dc28a125a84
diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.tsindex 9e9f5be1b91..db5ba42ae7c 100644--- a/apps/web/src/components/settings/ConnectionsSettings.logic.ts+++ b/apps/web/src/components/settings/ConnectionsSettings.logic.ts@@ -1,10 +1,22 @@+import * as DateTime from "effect/DateTime";++import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";+import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "../../pairingUrl";+import { readHostedPairingRequest } from "../../hostedPairing";+import {+ type ServerClientSessionRecord,+ type ServerPairingLinkRecord,+} from "~/environments/primary";import {type AdvertisedEndpoint,+ type AuthClientSession,type AuthGrantScope,+ type AuthPairingLink,AuthTerminalOperateScope,AuthTerminalReadScope,type DesktopBridge,type DesktopServerExposureState,+ type DesktopSshEnvironmentTarget,type DesktopUpdateState,type DesktopWslState,} from "@t3tools/contracts";@@ -150,3 +162,282 @@ export async function applyWslEnableSelection(input: {}return await bridge.setWslBackendEnabled(true);}++const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, {+ dateStyle: "medium",+ timeStyle: "short",+});++export function formatAccessTimestamp(value: string): string {+ const parsed = new Date(value);+ if (Number.isNaN(parsed.getTime())) {+ return value;+ }+ return accessTimestampFormatter.format(parsed);+}++export 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,+ };+}++export 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;+ }+}++export 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 };+}++export 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;+}++export function sortDesktopPairingLinks(links: ReadonlyArray<ServerPairingLinkRecord>) {+ return [...links].toSorted(+ (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(),+ );+}++export function summarizeAuthorizedClients(+ sessions: ReadonlyArray<ServerClientSessionRecord>,+ links: ReadonlyArray<ServerPairingLinkRecord>,+): string {+ const parts = [+ `${sessions.length} ${sessions.length === 1 ? "client" : "clients"}`,+ links.length > 0+ ? `${links.length} ${links.length === 1 ? "pairing link" : "pairing links"}`+ : null,+ ];+ return parts.filter((part): part is string => part !== null).join(" · ");+}++export 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();+ });+}++export function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairingLinkRecord {+ return {+ ...pairingLink,+ scopes: pairingLink.permissions ?? pairingLink.scopes,+ createdAt: DateTime.formatIso(pairingLink.createdAt),+ expiresAt: DateTime.formatIso(pairingLink.expiresAt),+ };+}++export function toDesktopClientSessionRecord(+ clientSession: AuthClientSession,+): ServerClientSessionRecord {+ return {+ ...clientSession,+ scopes: clientSession.permissions ?? clientSession.scopes,+ issuedAt: DateTime.formatIso(clientSession.issuedAt),+ expiresAt: DateTime.formatIso(clientSession.expiresAt),+ lastConnectedAt:+ clientSession.lastConnectedAt === null+ ? null+ : DateTime.formatIso(clientSession.lastConnectedAt),+ };+}++export 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+ );+}++export function isTailscaleHttpsEndpoint(endpoint: AdvertisedEndpoint): boolean {+ return endpoint.id.startsWith("tailscale-magicdns:");+}++export 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 {}++ return `${endpoint.provider.id}:${endpoint.reachability}:${scheme}:${endpoint.label}`;+}++export 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);+}++export function resolveCurrentOriginPairingUrl(credential: string): string {+ const url = new URL("/pair", window.location.href);+ return setPairingTokenOnUrl(url, credential).toString();+}++export function isHostedAppPairingUrl(value: string): boolean {+ try {+ const url = new URL(value);+ return url.pathname === "/pair" && url.searchParams.has("host");+ } catch {+ return false;+ }+}++export 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";+ }+}diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsxindex bda517c4fe1..1156b568977 100644--- a/apps/web/src/components/settings/ConnectionsSettings.tsx+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx@@ -60,7 +60,6 @@ import {squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";import * as Cause from "effect/Cause";-import * as DateTime from "effect/DateTime";import * as Option from "effect/Option";import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";@@ -148,8 +147,6 @@ import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "..import { AnimatedHeight } from "../AnimatedHeight";import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";import { Textarea } from "../ui/textarea";-import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "../../pairingUrl";-import { readHostedPairingRequest } from "../../hostedPairing";import {createServerPairingCredential,revokeOtherServerClientSessions,@@ -218,6 +215,25 @@ import {threadJumpCommandForIndex,threadJumpIndexFromCommand,} from "../../keybindings";+import {+ formatAccessTimestamp,+ parseManualDesktopSshTarget,+ parsePairingUrlFields,+ parseRemotePairingFields,+ formatDesktopSshConnectionError,+ sortDesktopPairingLinks,+ summarizeAuthorizedClients,+ sortDesktopClientSessions,+ toDesktopPairingLinkRecord,+ toDesktopClientSessionRecord,+ selectPairingEndpoint,+ isTailscaleHttpsEndpoint,+ endpointDefaultPreferenceKey,+ resolveAdvertisedEndpointPairingUrl,+ resolveCurrentOriginPairingUrl,+ isHostedAppPairingUrl,+ endpointShareHint,+} from "./ConnectionsSettings.logic";const DEFAULT_TAILSCALE_SERVE_PORT = 443;const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];@@ -229,19 +245,6 @@ const EMPTY_DISCOVERED_SSH_HOSTS: ReadonlyArray<DesktopDiscoveredSshHost> = [];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);-}-function AccessScopeSummary({scopes,label,@@ -286,124 +289,6 @@ function AccessScopeSummary({);}-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 = "first:rounded-t-xl last:rounded-b-xl px-3 py-2.5 sm:px-4";type AccessSectionPresentation = "current" | "endpoint-rail";@@ -423,149 +308,6 @@ function endpointRowClassName(presentation: AccessSectionPresentation, isAvailabreturn 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 summarizeAuthorizedClients(- sessions: ReadonlyArray<ServerClientSessionRecord>,- links: ReadonlyArray<ServerPairingLinkRecord>,-): string {- const parts = [- `${sessions.length} ${sessions.length === 1 ? "client" : "clients"}`,- links.length > 0- ? `${links.length} ${links.length === 1 ? "pairing link" : "pairing links"}`- : null,- ];- return parts.filter((part): part is string => part !== null).join(" · ");-}--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,- scopes: pairingLink.permissions ?? pairingLink.scopes,- createdAt: DateTime.formatIso(pairingLink.createdAt),- expiresAt: DateTime.formatIso(pairingLink.expiresAt),- };-}--function toDesktopClientSessionRecord(clientSession: AuthClientSession): ServerClientSessionRecord {- return {- ...clientSession,- scopes: clientSession.permissions ?? clientSession.scopes,- 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 {}-- 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;credential: string | undefined;