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

ConnectionsSettings.logic.ts

458 lines14.7 KB

1import * as DateTime from "effect/DateTime";
2​
3import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
4import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "@t3tools/shared/remote";
5import { readHostedPairingRequest } from "../../hostedPairing";
6import {
7 type ServerClientSessionRecord,
8 type ServerPairingLinkRecord,
9} from "~/environments/primary";
10import {
11 type AdvertisedEndpoint,
12 type AuthClientSession,
13 type AuthGrantScope,
14 type AuthPairingLink,
15 AuthTerminalOperateScope,
16 AuthTerminalReadScope,
17 type DesktopBridge,
18 type DesktopServerExposureState,
19 type DesktopSshEnvironmentTarget,
20 type DesktopUpdateState,
21 type DesktopWslState,
22 type EnvironmentId,
23} from "@t3tools/contracts";
24import {
25 getDesktopUpdateDownloadedVersion,
26 resolveDesktopUpdateButtonAction,
27} from "../desktopUpdate.logic";
28​
29/** Keep terminal:read with terminal:operate to avoid creating unseen shells on every script run. */
30export function togglePairingScopeSelection(
31 current: ReadonlyArray<AuthGrantScope>,
32 scope: AuthGrantScope,
33 checked: boolean,
34): ReadonlyArray<AuthGrantScope> {
35 const without = (scopes: ReadonlyArray<AuthGrantScope>) =>
36 scopes.filter((currentScope) => currentScope !== scope);
37 if (!checked) {
38 return scope === AuthTerminalReadScope
39 ? without(current).filter((currentScope) => currentScope !== AuthTerminalOperateScope)
40 : without(current);
41 }
42 const next = [...without(current), scope];
43 return scope === AuthTerminalOperateScope && !next.includes(AuthTerminalReadScope)
44 ? [...next, AuthTerminalReadScope]
45 : next;
47​
48export function canRevokeOtherClients(
49 clientSessions: ReadonlyArray<{ readonly current: boolean }> | null,
50): boolean {
51 return clientSessions === null || clientSessions.some((session) => !session.current);
53​
54type WslEnableBridge = Pick<DesktopBridge, "setWslBackendEnabled" | "setWslDistro" | "setWslOnly">;
55​
56/** Never offer loopback URLs as QR targets; scanning devices would connect to themselves. */
57export function isQrShareableEndpoint(endpoint: AdvertisedEndpoint): boolean {
58 return endpoint.status !== "unavailable" && endpoint.reachability !== "loopback";
60​
61/** Desktop skips Tailscale probing until network/Serve is enabled to avoid macOS prompts; absence then
62 * means unchecked. */
63export function missingTailscaleEndpointDescription(
64 state: Pick<DesktopServerExposureState, "mode" | "tailscaleServeEnabled"> | null,
65): string {
66 return state && state.mode !== "network-accessible" && !state.tailscaleServeEnabled
67 ? "Turn on Network access to detect Tailscale."
68 : "Start Tailscale to set up HTTPS access through MagicDNS.";
70​
71export function resolveTailscaleServeBaseUrl(
72 endpoint: Pick<AdvertisedEndpoint, "httpBaseUrl"> | null,
73 port: number,
74 isPortValid: boolean,
75): string | null {
76 if (!endpoint) return null;
77 if (!isPortValid) return endpoint.httpBaseUrl;
78 try {
79 const url = new URL(endpoint.httpBaseUrl);
80 url.port = String(port);
81 return url.toString().replace(/\/$/u, "");
82 } catch {
83 return endpoint.httpBaseUrl;
84 }
86​
87export function isWslSettingsRowVisible(input: {
88 readonly state: DesktopWslState | null;
89 readonly error: string | null;
90}): boolean {
91 const { state, error } = input;
92 return state ? state.available || state.enabled || state.wslOnly : error !== null;
94​
95/**
96 * Once client/server versions match, this passive Version label follows the sidebar update action,
97 * including retryable failures. Rechecks retain downloaded-update labels; `state` is null outside desktop.
98 */
99export function resolveLocalVersionStatusLabel(state: DesktopUpdateState | null): string {
100 if (!state) return "Up to date";
101 if (state.status === "downloading") {
102 return state.availableVersion
103 ? `Downloading update ${state.availableVersion}`
104 : "Downloading update";
105 }
106 const action = resolveDesktopUpdateButtonAction(state);
107 if (
108 action === "install" ||
109 state.status === "downloaded" ||
110 (state.status === "checking" && state.downloadedVersion !== null)
111 ) {
112 const version = getDesktopUpdateDownloadedVersion(state);
113 return version ? `Update ${version} downloaded` : "Update downloaded";
114 }
115 if (action === "download") {
116 return state.availableVersion
117 ? `Update ${state.availableVersion} available`
118 : "Update available";
119 }
120 return "Up to date";
122​
123export type QrEndpointOption = {
124 readonly id: string;
125 /** Stable per endpoint type, not unique; used only to match the saved default. */
126 readonly preferenceKey: string;
127 readonly qrShareable: boolean;
128};
129​
130export function selectQrEndpointOption<T extends QrEndpointOption>(
131 options: ReadonlyArray<T>,
132 selectedId: string | null,
133 defaultPreferenceKey: string | null,
134): T | null {
135 return (
136 (selectedId !== null ? options.find((option) => option.id === selectedId) : undefined) ??
137 (defaultPreferenceKey !== null
138 ? options.find((option) => option.preferenceKey === defaultPreferenceKey)
139 : undefined) ??
140 options.find((option) => option.qrShareable) ??
141 options[0] ??
142 null
143 );
145​
146export async function applyWslEnableSelection(input: {
147 readonly bridge: WslEnableBridge;
148 readonly mode: "both" | "wsl-only";
149 readonly nextDistro: string | null;
150 readonly persistedDistro: string | null;
151}): Promise<DesktopWslState> {
152 const { bridge, mode, nextDistro, persistedDistro } = input;
153​
154 // Stage preferences before enabling; only the final call should relaunch WSL with the complete selection.
155 await bridge.setWslOnly(mode === "wsl-only");
156 if (persistedDistro !== nextDistro) {
157 await bridge.setWslDistro(nextDistro);
158 }
159 return await bridge.setWslBackendEnabled(true);
161​
162const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, {
163 dateStyle: "medium",
164 timeStyle: "short",
165});
166​
167export function formatAccessTimestamp(value: string): string {
168 const parsed = new Date(value);
169 if (Number.isNaN(parsed.getTime())) {
170 return value;
171 }
172 return accessTimestampFormatter.format(parsed);
174​
175export function parseManualDesktopSshTarget(input: {
176 readonly host: string;
177 readonly username: string;
178 readonly port: string;
179}): DesktopSshEnvironmentTarget {
180 const rawHost = input.host.trim();
181 if (rawHost.length === 0) {
182 throw new Error("SSH host or alias is required.");
183 }
184​
185 let hostname = rawHost;
186 let username = input.username.trim() || null;
187 let port: number | null = null;
188​
189 const atIndex = hostname.lastIndexOf("@");
190 if (atIndex > 0) {
191 const inlineUsername = hostname.slice(0, atIndex).trim();
192 hostname = hostname.slice(atIndex + 1).trim();
193 if (!username && inlineUsername.length > 0) {
194 username = inlineUsername;
195 }
196 }
197​
198 const bracketedHostMatch = /^\[([^\]]+)\](?::(\d+))?$/u.exec(hostname);
199 if (bracketedHostMatch) {
200 hostname = bracketedHostMatch[1]!.trim();
201 if (bracketedHostMatch[2]) {
202 port = Number.parseInt(bracketedHostMatch[2], 10);
203 }
204 } else {
205 const colonSegments = hostname.split(":");
206 if (colonSegments.length === 2 && /^\d+$/u.test(colonSegments[1] ?? "")) {
207 hostname = colonSegments[0]!.trim();
208 port = Number.parseInt(colonSegments[1]!, 10);
209 }
210 }
211​
212 const rawPort = input.port.trim();
213 if (rawPort.length > 0) {
214 port = Number.parseInt(rawPort, 10);
215 }
216​
217 if (hostname.length === 0) {
218 throw new Error("SSH host or alias is required.");
219 }
220​
221 if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65_535)) {
222 throw new Error("SSH port must be between 1 and 65535.");
223 }
224​
225 return {
226 alias: hostname,
227 hostname,
228 username,
229 port,
230 };
232​
233export function parsePairingUrlFields(
234 input: string,
235): { readonly host: string; readonly pairingCode: string } | null {
236 const trimmed = input.trim();
237 if (!trimmed) return null;
238​
239 try {
240 const urlLikeInput =
241 /^[a-zA-Z][a-zA-Z\d+.-]*:\/\//u.test(trimmed) || trimmed.startsWith("//")
242 ? trimmed
243 : `https://${trimmed}`;
244 const url = new URL(urlLikeInput, window.location.origin);
245 const hostedPairingRequest = readHostedPairingRequest(url);
246 if (hostedPairingRequest) {
247 return {
248 host: hostedPairingRequest.host,
249 pairingCode: hostedPairingRequest.token,
250 };
251 }
252​
253 const pairingCode = getPairingTokenFromUrl(url);
254 if (!pairingCode) return null;
255 return {
256 host: url.origin,
257 pairingCode,
258 };
259 } catch {
260 return null;
261 }
263​
264export function parseRemotePairingFields(input: {
265 readonly host: string;
266 readonly pairingCode: string;
267}): {
268 readonly host: string;
269 readonly pairingCode: string;
270} {
271 const parsedPairingUrl = parsePairingUrlFields(input.host);
272 if (parsedPairingUrl) return parsedPairingUrl;
273​
274 const host = input.host.trim();
275 const pairingCode = input.pairingCode.trim();
276 if (!host) {
277 throw new Error("Enter a backend host.");
278 }
279 if (!pairingCode) {
280 throw new Error("Enter a pairing code.");
281 }
282 return { host, pairingCode };
284​
285export function formatDesktopSshConnectionError(error: unknown): string {
286 const fallback = "Failed to connect SSH host.";
287 const rawMessage = error instanceof Error ? error.message : fallback;
288 const withoutIpcPrefix = rawMessage.replace(
289 /^Error invoking remote method 'desktop:ensure-ssh-environment':\s*/u,
290 "",
291 );
292 const withoutTaggedErrorPrefix = withoutIpcPrefix.replace(/^Ssh[A-Za-z]+Error:\s*/u, "");
293 return withoutTaggedErrorPrefix.trim() || fallback;
295​
296export function sortDesktopPairingLinks(links: ReadonlyArray<ServerPairingLinkRecord>) {
297 return [...links].toSorted(
298 (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(),
299 );
301​
302export function summarizeAuthorizedClients(
303 sessions: ReadonlyArray<ServerClientSessionRecord>,
304 links: ReadonlyArray<ServerPairingLinkRecord>,
305): string {
306 const parts = [
307 `${sessions.length} ${sessions.length === 1 ? "client" : "clients"}`,
308 links.length > 0
309 ? `${links.length} ${links.length === 1 ? "pairing link" : "pairing links"}`
310 : null,
311 ];
312 return parts.filter((part): part is string => part !== null).join(" · ");
314​
315export function sortDesktopClientSessions(sessions: ReadonlyArray<ServerClientSessionRecord>) {
316 return [...sessions].toSorted((left, right) => {
317 if (left.current !== right.current) {
318 return left.current ? -1 : 1;
319 }
320 if (left.connected !== right.connected) {
321 return left.connected ? -1 : 1;
322 }
323 return new Date(right.issuedAt).getTime() - new Date(left.issuedAt).getTime();
324 });
326​
327export function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairingLinkRecord {
328 return {
329 ...pairingLink,
330 scopes: pairingLink.permissions ?? pairingLink.scopes,
331 createdAt: DateTime.formatIso(pairingLink.createdAt),
332 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
333 };
335​
336export function toDesktopClientSessionRecord(
337 clientSession: AuthClientSession,
338): ServerClientSessionRecord {
339 return {
340 ...clientSession,
341 scopes: clientSession.permissions ?? clientSession.scopes,
342 issuedAt: DateTime.formatIso(clientSession.issuedAt),
343 expiresAt: DateTime.formatIso(clientSession.expiresAt),
344 lastConnectedAt:
345 clientSession.lastConnectedAt === null
346 ? null
347 : DateTime.formatIso(clientSession.lastConnectedAt),
348 };
350​
351export function selectPairingEndpoint(
352 endpoints: ReadonlyArray<AdvertisedEndpoint>,
353 defaultEndpointKey?: string | null,
354): AdvertisedEndpoint | null {
355 const availableEndpoints = endpoints.filter((endpoint) => endpoint.status !== "unavailable");
356 if (defaultEndpointKey) {
357 const selectedEndpoint = availableEndpoints.find(
358 (endpoint) => endpointDefaultPreferenceKey(endpoint) === defaultEndpointKey,
359 );
360 if (selectedEndpoint) {
361 return selectedEndpoint;
362 }
363 }
364 return (
365 availableEndpoints.find((endpoint) => endpoint.isDefault) ??
366 availableEndpoints.find((endpoint) => endpoint.reachability !== "loopback") ??
367 availableEndpoints.find((endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible") ??
368 null
369 );
371​
372export function isTailscaleHttpsEndpoint(endpoint: AdvertisedEndpoint): boolean {
373 return endpoint.id.startsWith("tailscale-magicdns:");
375​
376export function endpointDefaultPreferenceKey(endpoint: AdvertisedEndpoint): string {
377 if (endpoint.id.startsWith("desktop-loopback:")) {
378 return "desktop-core:loopback:http";
379 }
380 if (endpoint.id.startsWith("desktop-lan:")) {
381 return "desktop-core:lan:http";
382 }
383 if (endpoint.id.startsWith("tailscale-ip:")) {
384 return "tailscale:ip:http";
385 }
386 if (isTailscaleHttpsEndpoint(endpoint)) {
387 return "tailscale:magicdns:https";
388 }
389​
390 let scheme = "unknown";
391 try {
392 scheme = new URL(endpoint.httpBaseUrl).protocol.replace(/:$/u, "");
393 } catch {}
394​
395 return `${endpoint.provider.id}:${endpoint.reachability}:${scheme}:${endpoint.label}`;
397​
398export function resolveAdvertisedEndpointPairingUrl(
399 endpoint: AdvertisedEndpoint,
400 credential: string,
401): string {
402 if (endpoint.compatibility.hostedHttpsApp === "compatible") {
403 return (
404 resolveHostedPairingUrl(endpoint.httpBaseUrl, credential) ??
405 resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential)
406 );
407 }
408 return resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential);
410​
411export function resolveCurrentOriginPairingUrl(credential: string): string {
412 const url = new URL("/pair", window.location.href);
413 return setPairingTokenOnUrl(url, credential).toString();
415​
416export function isHostedAppPairingUrl(value: string): boolean {
417 try {
418 const url = new URL(value);
419 return url.pathname === "/pair" && url.searchParams.has("host");
420 } catch {
421 return false;
422 }
424​
425export function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): string {
426 if (isHostedAppPairingUrl(url)) {
427 return "Opens the hosted app, no install needed";
428 }
429 switch (endpoint.reachability) {
430 case "lan":
431 return "Devices on the same network";
432 case "private-network":
433 return "Devices on your private network";
434 case "public":
435 return "Reachable from anywhere";
436 case "loopback":
437 return "Clients on this machine";
438 }
440​
441/** An explicit choice while it is listed, else the primary, else a connected environment. */
442export function resolveAccessEnvironmentId(input: {
443 readonly primaryEnvironmentId: EnvironmentId | null;
444 readonly environments: ReadonlyArray<{
445 readonly environmentId: EnvironmentId;
446 readonly connected: boolean;
447 }>;
448 readonly selected: EnvironmentId | null;
449}): EnvironmentId | null {
450 const isListed = (environmentId: EnvironmentId | null) =>
451 input.environments.some((environment) => environment.environmentId === environmentId);
452 if (isListed(input.selected)) return input.selected;
453 if (isListed(input.primaryEnvironmentId)) return input.primaryEnvironmentId;
454 return (
455 (input.environments.find((environment) => environment.connected) ?? input.environments[0])
456 ?.environmentId ?? null
457 );