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

ConnectionsSettings.logic.ts

541 lines17.5 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import * as DateTime from "effect/DateTime";
3import type { TimestampFormat } from "@t3tools/contracts/settings";
4import { msg, plural, part as gtPart } from "gt-react";
5​
6import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
7import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "@t3tools/shared/remote";
8import { readHostedPairingRequest } from "../../hostedPairing";
9import { m, type MessageResolver } from "../../i18n/messages";
10import { formatDateTimeTimestamp } from "../../timestampFormat";
11import {
12 isLoopbackHostname,
13 type ServerClientSessionRecord,
14 type ServerPairingLinkRecord,
15} from "~/environments/primary";
16import {
17 type AdvertisedEndpoint,
18 type AuthClientMetadata,
19 type AuthClientSession,
20 type AuthGrantScope,
21 type AuthPairingLink,
22 AuthTerminalOperateScope,
23 AuthTerminalReadScope,
24 type DesktopBridge,
25 type DesktopServerExposureState,
26 type DesktopSshEnvironmentTarget,
27 type DesktopUpdateState,
28 type DesktopWslState,
29 type EnvironmentId,
30 type ServerAuthPolicy,
31 type ServerDirectEndpoint,
32} from "@t3tools/contracts";
33import {
34 getDesktopUpdateDownloadedVersion,
35 resolveDesktopUpdateButtonAction,
36} from "../desktopUpdate.logic";
37​
38/** Keep terminal:read with terminal:operate to avoid creating unseen shells on every script run. */
39export function togglePairingScopeSelection(
40 current: ReadonlyArray<AuthGrantScope>,
41 scope: AuthGrantScope,
42 checked: boolean,
43): ReadonlyArray<AuthGrantScope> {
44 const without = (scopes: ReadonlyArray<AuthGrantScope>) =>
45 scopes.filter((currentScope) => currentScope !== scope);
46 if (!checked) {
47 return scope === AuthTerminalReadScope
48 ? without(current).filter((currentScope) => currentScope !== AuthTerminalOperateScope)
49 : without(current);
50 }
51 const next = [...without(current), scope];
52 return scope === AuthTerminalOperateScope && !next.includes(AuthTerminalReadScope)
53 ? [...next, AuthTerminalReadScope]
54 : next;
56​
57export function canRevokeOtherClients(
58 clientSessions: ReadonlyArray<{ readonly current: boolean }> | null,
59): boolean {
60 return clientSessions === null || clientSessions.some((session) => !session.current);
62​
63type WslEnableBridge = Pick<DesktopBridge, "setWslBackendEnabled" | "setWslDistro" | "setWslOnly">;
64​
65/** Never offer loopback URLs as QR targets; scanning devices would connect to themselves. */
66export function isQrShareableEndpoint(endpoint: AdvertisedEndpoint): boolean {
67 return endpoint.status !== "unavailable" && endpoint.reachability !== "loopback";
69​
70/** Desktop skips Tailscale probing until network/Serve is enabled to avoid macOS prompts; absence then
71 * means unchecked. */
72export function missingTailscaleEndpointDescription(
73 state: Pick<DesktopServerExposureState, "mode" | "tailscaleServeEnabled"> | null,
74 resolve: MessageResolver = m,
75): string {
76 return state && state.mode !== "network-accessible" && !state.tailscaleServeEnabled
77 ? resolve(msg("Turn on Network access to detect Tailscale."))
78 : resolve(msg("Start Tailscale to set up HTTPS access through MagicDNS."));
80​
81export function resolveTailscaleServeBaseUrl(
82 endpoint: Pick<AdvertisedEndpoint, "httpBaseUrl"> | null,
83 port: number,
84 isPortValid: boolean,
85): string | null {
86 if (!endpoint) return null;
87 if (!isPortValid) return endpoint.httpBaseUrl;
88 try {
89 const url = new URL(endpoint.httpBaseUrl);
90 url.port = String(port);
91 return url.toString().replace(/\/$/u, "");
92 } catch {
93 return endpoint.httpBaseUrl;
94 }
96​
97export function isWslSettingsRowVisible(input: {
98 readonly state: DesktopWslState | null;
99 readonly error: string | null;
100}): boolean {
101 const { state, error } = input;
102 return state ? state.available || state.enabled || state.wslOnly : error !== null;
104​
105/**
106 * Once client/server versions match, this passive Version label follows the sidebar update action,
107 * including retryable failures. Rechecks retain downloaded-update labels; `state` is null outside desktop.
108 */
109export function resolveLocalVersionStatusLabel(
110 state: DesktopUpdateState | null,
111 resolve: MessageResolver = m,
112): string {
113 if (!state) return resolve(msg("Up to date"));
114 if (state.status === "downloading") {
115 return state.availableVersion
116 ? resolve(msg`Downloading update ${{ version: state.availableVersion }}`)
117 : resolve(msg("Downloading update"));
118 }
119 const action = resolveDesktopUpdateButtonAction(state);
120 if (
121 action === "install" ||
122 state.status === "downloaded" ||
123 (state.status === "checking" && state.downloadedVersion !== null)
124 ) {
125 const version = getDesktopUpdateDownloadedVersion(state);
126 return version
127 ? resolve(msg`Update ${{ version }} downloaded`)
128 : resolve(msg("Update downloaded"));
129 }
130 if (action === "download") {
131 return state.availableVersion
132 ? resolve(msg`Update ${{ version: state.availableVersion }} available`)
133 : resolve(msg("Update available"));
134 }
135 return resolve(msg("Up to date"));
137​
138export type QrEndpointOption = {
139 readonly id: string;
140 /** Unique for VPN addresses, shared by type otherwise; used only to match the saved default. */
141 readonly preferenceKey: string;
142 readonly qrShareable: boolean;
143};
144​
145export function selectQrEndpointOption<T extends QrEndpointOption>(
146 options: ReadonlyArray<T>,
147 selectedId: string | null,
148 defaultPreferenceKey: string | null,
149): T | null {
150 return (
151 (selectedId !== null ? options.find((option) => option.id === selectedId) : undefined) ??
152 (defaultPreferenceKey !== null
153 ? options.find((option) => option.preferenceKey === defaultPreferenceKey)
154 : undefined) ??
155 options.find((option) => option.qrShareable) ??
156 options[0] ??
157 null
158 );
160​
161export async function applyWslEnableSelection(input: {
162 readonly bridge: WslEnableBridge;
163 readonly mode: "both" | "wsl-only";
164 readonly nextDistro: string | null;
165 readonly persistedDistro: string | null;
166}): Promise<DesktopWslState> {
167 const { bridge, mode, nextDistro, persistedDistro } = input;
168​
169 // Stage preferences before enabling; only the final call should relaunch WSL with the complete selection.
170 await bridge.setWslOnly(mode === "wsl-only");
171 if (persistedDistro !== nextDistro) {
172 await bridge.setWslDistro(nextDistro);
173 }
174 return await bridge.setWslBackendEnabled(true);
176​
177export function formatAccessTimestamp(value: string, timestampFormat: TimestampFormat): string {
178 return formatDateTimeTimestamp(value, timestampFormat) || value;
180​
181export function parseManualDesktopSshTarget(
182 input: {
183 readonly host: string;
184 readonly username: string;
185 readonly port: string;
186 },
187 resolve: MessageResolver = m,
188): DesktopSshEnvironmentTarget {
189 const rawHost = input.host.trim();
190 if (rawHost.length === 0) {
191 throw new Error(resolve(msg("SSH host or alias is required.")));
192 }
193​
194 let hostname = rawHost;
195 let username = input.username.trim() || null;
196 let port: number | null = null;
197​
198 const atIndex = hostname.lastIndexOf("@");
199 if (atIndex > 0) {
200 const inlineUsername = hostname.slice(0, atIndex).trim();
201 hostname = hostname.slice(atIndex + 1).trim();
202 if (!username && inlineUsername.length > 0) {
203 username = inlineUsername;
204 }
205 }
206​
207 const bracketedHostMatch = /^\[([^\]]+)\](?::(\d+))?$/u.exec(hostname);
208 if (bracketedHostMatch) {
209 hostname = bracketedHostMatch[1]!.trim();
210 if (bracketedHostMatch[2]) {
211 port = Number.parseInt(bracketedHostMatch[2], 10);
212 }
213 } else {
214 const colonSegments = hostname.split(":");
215 if (colonSegments.length === 2 && /^\d+$/u.test(colonSegments[1] ?? "")) {
216 hostname = colonSegments[0]!.trim();
217 port = Number.parseInt(colonSegments[1]!, 10);
218 }
219 }
220​
221 const rawPort = input.port.trim();
222 if (rawPort.length > 0) {
223 port = /^\d+$/u.test(rawPort) ? Number.parseInt(rawPort, 10) : Number.NaN;
224 }
225​
226 if (hostname.length === 0) {
227 throw new Error(resolve(msg("SSH host or alias is required.")));
228 }
229​
230 if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65_535)) {
231 throw new Error(resolve(msg("SSH port must be between 1 and 65535.")));
232 }
233​
234 return {
235 alias: hostname,
236 hostname,
237 username,
238 port,
239 };
241​
242export function parsePairingUrlFields(
243 input: string,
244): { readonly host: string; readonly pairingCode: string } | null {
245 const trimmed = input.trim();
246 if (!trimmed) return null;
247​
248 try {
249 const urlLikeInput =
250 /^[a-zA-Z][a-zA-Z\d+.-]*:\/\//u.test(trimmed) || trimmed.startsWith("//")
251 ? trimmed
252 : `https://${trimmed}`;
253 const url = new URL(urlLikeInput, window.location.origin);
254 const hostedPairingRequest = readHostedPairingRequest(url);
255 if (hostedPairingRequest) {
256 return {
257 host: hostedPairingRequest.host,
258 pairingCode: hostedPairingRequest.token,
259 };
260 }
261​
262 const pairingCode = getPairingTokenFromUrl(url);
263 if (!pairingCode) return null;
264 return {
265 host: url.origin,
266 pairingCode,
267 };
268 } catch {
269 return null;
270 }
272​
273export function parseRemotePairingFields(
274 input: {
275 readonly host: string;
276 readonly pairingCode: string;
277 },
278 resolve: MessageResolver = m,
279): {
280 readonly host: string;
281 readonly pairingCode: string;
282} {
283 const parsedPairingUrl = parsePairingUrlFields(input.host);
284 if (parsedPairingUrl) return parsedPairingUrl;
285​
286 const host = input.host.trim();
287 const pairingCode = input.pairingCode.trim();
288 if (!host) {
289 throw new Error(resolve(msg("Enter a backend host.")));
290 }
291 if (!pairingCode) {
292 throw new Error(resolve(msg("Enter a pairing code.")));
293 }
294 return { host, pairingCode };
296​
297export function formatDesktopSshConnectionError(
298 error: unknown,
299 resolve: MessageResolver = m,
300): string {
301 const fallback = resolve(msg("Failed to connect SSH host."));
302 const rawMessage =
303 error instanceof Error ? (thrownErrorMessage(error, m) ?? error.message) : fallback;
304 const withoutIpcPrefix = rawMessage.replace(
305 /^Error invoking remote method 'desktop:ensure-ssh-environment':\s*/u,
306 "",
307 );
308 const withoutTaggedErrorPrefix = withoutIpcPrefix.replace(/^Ssh[A-Za-z]+Error:\s*/u, "");
309 return withoutTaggedErrorPrefix.trim() || fallback;
311​
312export function sortDesktopPairingLinks(links: ReadonlyArray<ServerPairingLinkRecord>) {
313 return [...links].toSorted(
314 (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(),
315 );
317​
318export function summarizeAuthorizedClients(
319 sessions: ReadonlyArray<ServerClientSessionRecord>,
320 links: ReadonlyArray<ServerPairingLinkRecord>,
321 resolve: MessageResolver = m,
322): string {
323 const parts = [
324 resolve(
325 msg`${plural(
326 { count: sessions.length },
327 {
328 one: gtPart`${{ count: sessions.length }} client`,
329 other: gtPart`${{ count: sessions.length }} clients`,
330 },
331 )}`,
332 ),
333 links.length > 0
334 ? resolve(
335 msg`${plural(
336 { count: links.length },
337 {
338 one: gtPart`${{ count: links.length }} pairing link`,
339 other: gtPart`${{ count: links.length }} pairing links`,
340 },
341 )}`,
342 )
343 : null,
344 ];
345 return parts.filter((part): part is string => part !== null).join(" · ");
347​
348export function sortDesktopClientSessions(sessions: ReadonlyArray<ServerClientSessionRecord>) {
349 return [...sessions].toSorted((left, right) => {
350 if (left.current !== right.current) {
351 return left.current ? -1 : 1;
352 }
353 if (left.connected !== right.connected) {
354 return left.connected ? -1 : 1;
355 }
356 return new Date(right.issuedAt).getTime() - new Date(left.issuedAt).getTime();
357 });
359​
360export function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairingLinkRecord {
361 return {
362 ...pairingLink,
363 scopes: pairingLink.permissions ?? pairingLink.scopes,
364 createdAt: DateTime.formatIso(pairingLink.createdAt),
365 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
366 };
368​
369export function toDesktopClientSessionRecord(
370 clientSession: AuthClientSession,
371): ServerClientSessionRecord {
372 return {
373 ...clientSession,
374 scopes: clientSession.permissions ?? clientSession.scopes,
375 issuedAt: DateTime.formatIso(clientSession.issuedAt),
376 expiresAt: DateTime.formatIso(clientSession.expiresAt),
377 lastConnectedAt:
378 clientSession.lastConnectedAt === null
379 ? null
380 : DateTime.formatIso(clientSession.lastConnectedAt),
381 };
383​
384export function selectPairingEndpoint(
385 endpoints: ReadonlyArray<AdvertisedEndpoint>,
386 defaultEndpointKey?: string | null,
387): AdvertisedEndpoint | null {
388 const availableEndpoints = endpoints.filter((endpoint) => endpoint.status !== "unavailable");
389 if (defaultEndpointKey) {
390 const selectedEndpoint = availableEndpoints.find(
391 (endpoint) => endpointDefaultPreferenceKey(endpoint) === defaultEndpointKey,
392 );
393 if (selectedEndpoint) {
394 return selectedEndpoint;
395 }
396 }
397 return (
398 availableEndpoints.find((endpoint) => endpoint.isDefault) ??
399 availableEndpoints.find((endpoint) => endpoint.reachability !== "loopback") ??
400 availableEndpoints.find((endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible") ??
401 null
402 );
404​
405/** A loopback server advertises a direct endpoint only once its Tailscale Serve URL answers. */
406export function isServerNetworkAccessible(input: {
407 readonly authPolicy: ServerAuthPolicy | null;
408 readonly directEndpoints: ReadonlyArray<ServerDirectEndpoint> | undefined;
409}): boolean {
410 if (input.authPolicy === "remote-reachable") return true;
411 return input.authPolicy === "loopback-browser" && (input.directEndpoints?.length ?? 0) > 0;
413​
414export function isTailscaleHttpsEndpoint(endpoint: AdvertisedEndpoint): boolean {
415 return endpoint.id.startsWith("tailscale-magicdns:");
417​
418export function endpointDefaultPreferenceKey(endpoint: AdvertisedEndpoint): string {
419 if (endpoint.id.startsWith("desktop-loopback:")) {
420 return "desktop-core:loopback:http";
421 }
422 if (endpoint.id.startsWith("desktop-lan:")) {
423 return "desktop-core:lan:http";
424 }
425 if (endpoint.id.startsWith("tailscale-ip:")) {
426 return "tailscale:ip:http";
427 }
428 if (endpoint.id.startsWith("vpn-ip:")) {
429 return endpoint.id;
430 }
431 if (isTailscaleHttpsEndpoint(endpoint)) {
432 return "tailscale:magicdns:https";
433 }
434​
435 let scheme = "unknown";
436 try {
437 scheme = new URL(endpoint.httpBaseUrl).protocol.replace(/:$/u, "");
438 } catch {}
439​
440 return `${endpoint.provider.id}:${endpoint.reachability}:${scheme}:${endpoint.label}`;
442​
443export function resolveAdvertisedEndpointPairingUrl(
444 endpoint: AdvertisedEndpoint,
445 credential: string,
446): string {
447 if (endpoint.compatibility.hostedHttpsApp === "compatible") {
448 return (
449 resolveHostedPairingUrl(endpoint.httpBaseUrl, credential) ??
450 resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential)
451 );
452 }
453 return resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential);
455​
456export function resolveCurrentOriginPairingUrl(
457 credential: string,
458 currentHref: string = window.location.href,
459): string | null {
460 const url = new URL("/pair", currentHref);
461 // The packaged desktop window loads from t3code://app, which no other device can open.
462 if ((url.protocol !== "http:" && url.protocol !== "https:") || isLoopbackHostname(url.hostname)) {
463 return null;
464 }
465 return setPairingTokenOnUrl(url, credential).toString();
467​
468export function isHostedAppPairingUrl(value: string): boolean {
469 try {
470 const url = new URL(value);
471 return url.pathname === "/pair" && url.searchParams.has("host");
472 } catch {
473 return false;
474 }
476​
477export function endpointShareHint(
478 endpoint: AdvertisedEndpoint,
479 url: string,
480 resolve: MessageResolver = m,
481): string {
482 if (isHostedAppPairingUrl(url)) {
483 return resolve(msg("Opens the hosted app, no install needed"));
484 }
485 switch (endpoint.reachability) {
486 case "lan":
487 return resolve(msg("Devices on the same network"));
488 case "private-network":
489 return resolve(msg("Devices on your private network"));
490 case "public":
491 return resolve(msg("Reachable from anywhere"));
492 case "loopback":
493 return resolve(msg("Clients on this machine"));
494 }
496​
497/** An explicit choice while it is listed, else the primary, else a connected environment. */
498export function resolveAccessEnvironmentId(input: {
499 readonly primaryEnvironmentId: EnvironmentId | null;
500 readonly environments: ReadonlyArray<{
501 readonly environmentId: EnvironmentId;
502 readonly connected: boolean;
503 }>;
504 readonly selected: EnvironmentId | null;
505}): EnvironmentId | null {
506 const isListed = (environmentId: EnvironmentId | null) =>
507 input.environments.some((environment) => environment.environmentId === environmentId);
508 if (isListed(input.selected)) return input.selected;
509 if (isListed(input.primaryEnvironmentId)) return input.primaryEnvironmentId;
510 return (
511 (input.environments.find((environment) => environment.connected) ?? input.environments[0])
512 ?.environmentId ?? null
513 );
515​
516/** A short name for a T3 Connect device: its label, or what it runs on. */
517export function connectDeviceName(
518 {
519 client,
520 }: {
521 readonly client?: AuthClientMetadata | undefined;
522 },
523 resolve: MessageResolver = m,
524): string {
525 return client?.label ?? client?.os ?? client?.browser ?? resolve(msg("this device"));
527​
528/** How a T3 Connect device describes itself. It can say anything, so the code is what to trust. */
529export function describeConnectDeviceClient(
530 {
531 client,
532 }: {
533 readonly client?: AuthClientMetadata | undefined;
534 },
535 resolve: MessageResolver = m,
536): string {
537 const bits = [client?.label, client?.os, client?.browser, client?.ipAddress].filter(
538 (value): value is string => typeof value === "string" && value.length > 0,
539 );
540 return bits.length > 0 ? [...new Set(bits)].join(" · ") : resolve(msg("Unknown device"));