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

ConnectionsSettings.logic.ts

422 lines13.4 KB

1import * as DateTime from "effect/DateTime";
2​
3import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
4import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "../../pairingUrl";
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 isWslSettingsRowVisible(input: {
71 readonly state: DesktopWslState | null;
72 readonly error: string | null;
73}): boolean {
74 const { state, error } = input;
75 return state ? state.available || state.enabled || state.wslOnly : error !== null;
77​
78/**
79 * Once client/server versions match, this passive Version label follows the sidebar update action,
80 * including retryable failures. Rechecks retain downloaded-update labels; `state` is null outside desktop.
81 */
82export function resolveLocalVersionStatusLabel(state: DesktopUpdateState | null): string {
83 if (!state) return "Up to date";
84 if (state.status === "downloading") {
85 return state.availableVersion
86 ? `Downloading update ${state.availableVersion}`
87 : "Downloading update";
88 }
89 const action = resolveDesktopUpdateButtonAction(state);
90 if (
91 action === "install" ||
92 state.status === "downloaded" ||
93 (state.status === "checking" && state.downloadedVersion !== null)
94 ) {
95 const version = getDesktopUpdateDownloadedVersion(state);
96 return version ? `Update ${version} downloaded` : "Update downloaded";
97 }
98 if (action === "download") {
99 return state.availableVersion
100 ? `Update ${state.availableVersion} available`
101 : "Update available";
102 }
103 return "Up to date";
105​
106export type QrEndpointOption = {
107 readonly id: string;
108 /** Stable per endpoint type, not unique; used only to match the saved default. */
109 readonly preferenceKey: string;
110 readonly qrShareable: boolean;
111};
112​
113export function selectQrEndpointOption<T extends QrEndpointOption>(
114 options: ReadonlyArray<T>,
115 selectedId: string | null,
116 defaultPreferenceKey: string | null,
117): T | null {
118 return (
119 (selectedId !== null ? options.find((option) => option.id === selectedId) : undefined) ??
120 (defaultPreferenceKey !== null
121 ? options.find((option) => option.preferenceKey === defaultPreferenceKey)
122 : undefined) ??
123 options.find((option) => option.qrShareable) ??
124 options[0] ??
125 null
126 );
128​
129export async function applyWslEnableSelection(input: {
130 readonly bridge: WslEnableBridge;
131 readonly mode: "both" | "wsl-only";
132 readonly nextDistro: string | null;
133 readonly persistedDistro: string | null;
134}): Promise<DesktopWslState> {
135 const { bridge, mode, nextDistro, persistedDistro } = input;
136​
137 // Stage preferences before enabling; only the final call should relaunch WSL with the complete selection.
138 await bridge.setWslOnly(mode === "wsl-only");
139 if (persistedDistro !== nextDistro) {
140 await bridge.setWslDistro(nextDistro);
141 }
142 return await bridge.setWslBackendEnabled(true);
144​
145const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, {
146 dateStyle: "medium",
147 timeStyle: "short",
148});
149​
150export function formatAccessTimestamp(value: string): string {
151 const parsed = new Date(value);
152 if (Number.isNaN(parsed.getTime())) {
153 return value;
154 }
155 return accessTimestampFormatter.format(parsed);
157​
158export function parseManualDesktopSshTarget(input: {
159 readonly host: string;
160 readonly username: string;
161 readonly port: string;
162}): DesktopSshEnvironmentTarget {
163 const rawHost = input.host.trim();
164 if (rawHost.length === 0) {
165 throw new Error("SSH host or alias is required.");
166 }
167​
168 let hostname = rawHost;
169 let username = input.username.trim() || null;
170 let port: number | null = null;
171​
172 const atIndex = hostname.lastIndexOf("@");
173 if (atIndex > 0) {
174 const inlineUsername = hostname.slice(0, atIndex).trim();
175 hostname = hostname.slice(atIndex + 1).trim();
176 if (!username && inlineUsername.length > 0) {
177 username = inlineUsername;
178 }
179 }
180​
181 const bracketedHostMatch = /^\[([^\]]+)\](?::(\d+))?$/u.exec(hostname);
182 if (bracketedHostMatch) {
183 hostname = bracketedHostMatch[1]!.trim();
184 if (bracketedHostMatch[2]) {
185 port = Number.parseInt(bracketedHostMatch[2], 10);
186 }
187 } else {
188 const colonSegments = hostname.split(":");
189 if (colonSegments.length === 2 && /^\d+$/u.test(colonSegments[1] ?? "")) {
190 hostname = colonSegments[0]!.trim();
191 port = Number.parseInt(colonSegments[1]!, 10);
192 }
193 }
194​
195 const rawPort = input.port.trim();
196 if (rawPort.length > 0) {
197 port = Number.parseInt(rawPort, 10);
198 }
199​
200 if (hostname.length === 0) {
201 throw new Error("SSH host or alias is required.");
202 }
203​
204 if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65_535)) {
205 throw new Error("SSH port must be between 1 and 65535.");
206 }
207​
208 return {
209 alias: hostname,
210 hostname,
211 username,
212 port,
213 };
215​
216export function parsePairingUrlFields(
217 input: string,
218): { readonly host: string; readonly pairingCode: string } | null {
219 const trimmed = input.trim();
220 if (!trimmed) return null;
221​
222 try {
223 const urlLikeInput =
224 /^[a-zA-Z][a-zA-Z\d+.-]*:\/\//u.test(trimmed) || trimmed.startsWith("//")
225 ? trimmed
226 : `https://${trimmed}`;
227 const url = new URL(urlLikeInput, window.location.origin);
228 const hostedPairingRequest = readHostedPairingRequest(url);
229 if (hostedPairingRequest) {
230 return {
231 host: hostedPairingRequest.host,
232 pairingCode: hostedPairingRequest.token,
233 };
234 }
235​
236 const pairingCode = getPairingTokenFromUrl(url);
237 if (!pairingCode) return null;
238 return {
239 host: url.origin,
240 pairingCode,
241 };
242 } catch {
243 return null;
244 }
246​
247export function parseRemotePairingFields(input: {
248 readonly host: string;
249 readonly pairingCode: string;
250}): {
251 readonly host: string;
252 readonly pairingCode: string;
253} {
254 const parsedPairingUrl = parsePairingUrlFields(input.host);
255 if (parsedPairingUrl) return parsedPairingUrl;
256​
257 const host = input.host.trim();
258 const pairingCode = input.pairingCode.trim();
259 if (!host) {
260 throw new Error("Enter a backend host.");
261 }
262 if (!pairingCode) {
263 throw new Error("Enter a pairing code.");
264 }
265 return { host, pairingCode };
267​
268export function formatDesktopSshConnectionError(error: unknown): string {
269 const fallback = "Failed to connect SSH host.";
270 const rawMessage = error instanceof Error ? error.message : fallback;
271 const withoutIpcPrefix = rawMessage.replace(
272 /^Error invoking remote method 'desktop:ensure-ssh-environment':\s*/u,
273 "",
274 );
275 const withoutTaggedErrorPrefix = withoutIpcPrefix.replace(/^Ssh[A-Za-z]+Error:\s*/u, "");
276 return withoutTaggedErrorPrefix.trim() || fallback;
278​
279export function sortDesktopPairingLinks(links: ReadonlyArray<ServerPairingLinkRecord>) {
280 return [...links].toSorted(
281 (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(),
282 );
284​
285export function summarizeAuthorizedClients(
286 sessions: ReadonlyArray<ServerClientSessionRecord>,
287 links: ReadonlyArray<ServerPairingLinkRecord>,
288): string {
289 const parts = [
290 `${sessions.length} ${sessions.length === 1 ? "client" : "clients"}`,
291 links.length > 0
292 ? `${links.length} ${links.length === 1 ? "pairing link" : "pairing links"}`
293 : null,
294 ];
295 return parts.filter((part): part is string => part !== null).join(" · ");
297​
298export function sortDesktopClientSessions(sessions: ReadonlyArray<ServerClientSessionRecord>) {
299 return [...sessions].toSorted((left, right) => {
300 if (left.current !== right.current) {
301 return left.current ? -1 : 1;
302 }
303 if (left.connected !== right.connected) {
304 return left.connected ? -1 : 1;
305 }
306 return new Date(right.issuedAt).getTime() - new Date(left.issuedAt).getTime();
307 });
309​
310export function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairingLinkRecord {
311 return {
312 ...pairingLink,
313 scopes: pairingLink.permissions ?? pairingLink.scopes,
314 createdAt: DateTime.formatIso(pairingLink.createdAt),
315 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
316 };
318​
319export function toDesktopClientSessionRecord(
320 clientSession: AuthClientSession,
321): ServerClientSessionRecord {
322 return {
323 ...clientSession,
324 scopes: clientSession.permissions ?? clientSession.scopes,
325 issuedAt: DateTime.formatIso(clientSession.issuedAt),
326 expiresAt: DateTime.formatIso(clientSession.expiresAt),
327 lastConnectedAt:
328 clientSession.lastConnectedAt === null
329 ? null
330 : DateTime.formatIso(clientSession.lastConnectedAt),
331 };
333​
334export function selectPairingEndpoint(
335 endpoints: ReadonlyArray<AdvertisedEndpoint>,
336 defaultEndpointKey?: string | null,
337): AdvertisedEndpoint | null {
338 const availableEndpoints = endpoints.filter((endpoint) => endpoint.status !== "unavailable");
339 if (defaultEndpointKey) {
340 const selectedEndpoint = availableEndpoints.find(
341 (endpoint) => endpointDefaultPreferenceKey(endpoint) === defaultEndpointKey,
342 );
343 if (selectedEndpoint) {
344 return selectedEndpoint;
345 }
346 }
347 return (
348 availableEndpoints.find((endpoint) => endpoint.isDefault) ??
349 availableEndpoints.find((endpoint) => endpoint.reachability !== "loopback") ??
350 availableEndpoints.find((endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible") ??
351 null
352 );
354​
355export function isTailscaleHttpsEndpoint(endpoint: AdvertisedEndpoint): boolean {
356 return endpoint.id.startsWith("tailscale-magicdns:");
358​
359export function endpointDefaultPreferenceKey(endpoint: AdvertisedEndpoint): string {
360 if (endpoint.id.startsWith("desktop-loopback:")) {
361 return "desktop-core:loopback:http";
362 }
363 if (endpoint.id.startsWith("desktop-lan:")) {
364 return "desktop-core:lan:http";
365 }
366 if (endpoint.id.startsWith("tailscale-ip:")) {
367 return "tailscale:ip:http";
368 }
369 if (isTailscaleHttpsEndpoint(endpoint)) {
370 return "tailscale:magicdns:https";
371 }
372​
373 let scheme = "unknown";
374 try {
375 scheme = new URL(endpoint.httpBaseUrl).protocol.replace(/:$/u, "");
376 } catch {}
377​
378 return `${endpoint.provider.id}:${endpoint.reachability}:${scheme}:${endpoint.label}`;
380​
381export function resolveAdvertisedEndpointPairingUrl(
382 endpoint: AdvertisedEndpoint,
383 credential: string,
384): string {
385 if (endpoint.compatibility.hostedHttpsApp === "compatible") {
386 return (
387 resolveHostedPairingUrl(endpoint.httpBaseUrl, credential) ??
388 resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential)
389 );
390 }
391 return resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential);
393​
394export function resolveCurrentOriginPairingUrl(credential: string): string {
395 const url = new URL("/pair", window.location.href);
396 return setPairingTokenOnUrl(url, credential).toString();
398​
399export function isHostedAppPairingUrl(value: string): boolean {
400 try {
401 const url = new URL(value);
402 return url.pathname === "/pair" && url.searchParams.has("host");
403 } catch {
404 return false;
405 }
407​
408export function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): string {
409 if (isHostedAppPairingUrl(url)) {
410 return "Opens the hosted app, no install needed";
411 }
412 switch (endpoint.reachability) {
413 case "lan":
414 return "Devices on the same network";
415 case "private-network":
416 return "Devices on your private network";
417 case "public":
418 return "Reachable from anywhere";
419 case "loopback":
420 return "Clients on this machine";
421 }