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