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

ConnectionsSettings.logic.ts

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