Open History to see the last commit
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/**
29 * Operating terminals without being able to list them leaves a client
30 * allocating a fresh shell for every script run it cannot see, so the pairing
31 * form keeps `terminal:read` alongside `terminal:operate`.
32 */
33export function togglePairingScopeSelection(
34 current: ReadonlyArray<AuthGrantScope>,
35 scope: AuthGrantScope,
36 checked: boolean,
37): ReadonlyArray<AuthGrantScope> {
38 const without = (scopes: ReadonlyArray<AuthGrantScope>) =>
39 scopes.filter((currentScope) => currentScope !== scope);
40 if (!checked) {
41 return scope === AuthTerminalReadScope
42 ? without(current).filter((currentScope) => currentScope !== AuthTerminalOperateScope)
43 : without(current);
44 }
45 const next = [...without(current), scope];
46 return scope === AuthTerminalOperateScope && !next.includes(AuthTerminalReadScope)
47 ? [...next, AuthTerminalReadScope]
48 : next;
49}
50
51export function canRevokeOtherClients(
52 clientSessions: ReadonlyArray<{ readonly current: boolean }> | null,
53): boolean {
54 return clientSessions === null || clientSessions.some((session) => !session.current);
55}
56
57type WslEnableBridge = Pick<DesktopBridge, "setWslBackendEnabled" | "setWslDistro" | "setWslOnly">;
58
59/**
60 * A QR code encoding a loopback URL makes the scanning device dial itself, so
61 * loopback endpoints stay copyable from the endpoint menu but are never
62 * offered as QR targets.
63 */
64export function isQrShareableEndpoint(endpoint: AdvertisedEndpoint): boolean {
65 return endpoint.status !== "unavailable" && endpoint.reachability !== "loopback";
66}
67
68/**
69 * Copy for the Tailscale HTTPS row when no Tailscale endpoint is advertised.
70 * The desktop skips the Tailscale probe until Network access or Tailscale
71 * Serve is on (it can trigger a macOS privacy prompt), so a missing endpoint
72 * then means "not checked", not "not running".
73 */
74export function missingTailscaleEndpointDescription(
75 state: Pick<DesktopServerExposureState, "mode" | "tailscaleServeEnabled"> | null,
76): string {
77 return state && state.mode !== "network-accessible" && !state.tailscaleServeEnabled
78 ? "Turn on Network access to detect Tailscale."
79 : "Start Tailscale to set up HTTPS access through MagicDNS.";
80}
81
82export function isWslSettingsRowVisible(input: {
83 readonly state: DesktopWslState | null;
84 readonly error: string | null;
85}): boolean {
86 const { state, error } = input;
87 return state ? state.available || state.enabled || state.wslOnly : error !== null;
88}
89
90/**
91 * Passive label for this machine's Version row once client and server versions
92 * match. The desktop bundles its server, so a pending app update is the only
93 * way it falls behind. Pending states follow the sidebar update control's
94 * action, including retryable failures, so the two never disagree; the sidebar
95 * is where to act. A recheck keeps a downloaded update while `checking`, so it
96 * keeps its label too. `state` is null outside the desktop app.
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";
120}
121
122export type QrEndpointOption = {
123 readonly id: string;
124 /**
125 * Stable per endpoint *type* (endpointDefaultPreferenceKey). Multiple
126 * endpoints can share one, so it is only used to match the saved default.
127 */
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 every preference before enabling. The desktop only relaunches for
157 // mode/distro changes while WSL is active, so the final enable observes the
158 // complete selection and is the only call that may relaunch.
159 await bridge.setWslOnly(mode === "wsl-only");
160 if (persistedDistro !== nextDistro) {
161 await bridge.setWslDistro(nextDistro);
162 }
163 return await bridge.setWslBackendEnabled(true);
164}
165
166const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, {
167 dateStyle: "medium",
168 timeStyle: "short",
169});
170
171export function formatAccessTimestamp(value: string): string {
172 const parsed = new Date(value);
173 if (Number.isNaN(parsed.getTime())) {
174 return value;
175 }
176 return accessTimestampFormatter.format(parsed);
177}
178
179export function parseManualDesktopSshTarget(input: {
180 readonly host: string;
181 readonly username: string;
182 readonly port: string;
183}): DesktopSshEnvironmentTarget {
184 const rawHost = input.host.trim();
185 if (rawHost.length === 0) {
186 throw new Error("SSH host or alias is required.");
187 }
188
189 let hostname = rawHost;
190 let username = input.username.trim() || null;
191 let port: number | null = null;
192
193 const atIndex = hostname.lastIndexOf("@");
194 if (atIndex > 0) {
195 const inlineUsername = hostname.slice(0, atIndex).trim();
196 hostname = hostname.slice(atIndex + 1).trim();
197 if (!username && inlineUsername.length > 0) {
198 username = inlineUsername;
199 }
200 }
201
202 const bracketedHostMatch = /^\[([^\]]+)\](?::(\d+))?$/u.exec(hostname);
203 if (bracketedHostMatch) {
204 hostname = bracketedHostMatch[1]!.trim();
205 if (bracketedHostMatch[2]) {
206 port = Number.parseInt(bracketedHostMatch[2], 10);
207 }
208 } else {
209 const colonSegments = hostname.split(":");
210 if (colonSegments.length === 2 && /^\d+$/u.test(colonSegments[1] ?? "")) {
211 hostname = colonSegments[0]!.trim();
212 port = Number.parseInt(colonSegments[1]!, 10);
213 }
214 }
215
216 const rawPort = input.port.trim();
217 if (rawPort.length > 0) {
218 port = Number.parseInt(rawPort, 10);
219 }
220
221 if (hostname.length === 0) {
222 throw new Error("SSH host or alias is required.");
223 }
224
225 if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65_535)) {
226 throw new Error("SSH port must be between 1 and 65535.");
227 }
228
229 return {
230 alias: hostname,
231 hostname,
232 username,
233 port,
234 };
235}
236
237export function parsePairingUrlFields(
238 input: string,
239): { readonly host: string; readonly pairingCode: string } | null {
240 const trimmed = input.trim();
241 if (!trimmed) return null;
242
243 try {
244 const urlLikeInput =
245 /^[a-zA-Z][a-zA-Z\d+.-]*:\/\//u.test(trimmed) || trimmed.startsWith("//")
246 ? trimmed
247 : `https://${trimmed}`;
248 const url = new URL(urlLikeInput, window.location.origin);
249 const hostedPairingRequest = readHostedPairingRequest(url);
250 if (hostedPairingRequest) {
251 return {
252 host: hostedPairingRequest.host,
253 pairingCode: hostedPairingRequest.token,
254 };
255 }
256
257 const pairingCode = getPairingTokenFromUrl(url);
258 if (!pairingCode) return null;
259 return {
260 host: url.origin,
261 pairingCode,
262 };
263 } catch {
264 return null;
265 }
266}
267
268export function parseRemotePairingFields(input: {
269 readonly host: string;
270 readonly pairingCode: string;
271}): {
272 readonly host: string;
273 readonly pairingCode: string;
274} {
275 const parsedPairingUrl = parsePairingUrlFields(input.host);
276 if (parsedPairingUrl) return parsedPairingUrl;
277
278 const host = input.host.trim();
279 const pairingCode = input.pairingCode.trim();
280 if (!host) {
281 throw new Error("Enter a backend host.");
282 }
283 if (!pairingCode) {
284 throw new Error("Enter a pairing code.");
285 }
286 return { host, pairingCode };
287}
288
289export function formatDesktopSshConnectionError(error: unknown): string {
290 const fallback = "Failed to connect SSH host.";
291 const rawMessage = error instanceof Error ? error.message : fallback;
292 const withoutIpcPrefix = rawMessage.replace(
293 /^Error invoking remote method 'desktop:ensure-ssh-environment':\s*/u,
294 "",
295 );
296 const withoutTaggedErrorPrefix = withoutIpcPrefix.replace(/^Ssh[A-Za-z]+Error:\s*/u, "");
297 return withoutTaggedErrorPrefix.trim() || fallback;
298}
299
300export function sortDesktopPairingLinks(links: ReadonlyArray<ServerPairingLinkRecord>) {
301 return [...links].toSorted(
302 (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(),
303 );
304}
305
306export function summarizeAuthorizedClients(
307 sessions: ReadonlyArray<ServerClientSessionRecord>,
308 links: ReadonlyArray<ServerPairingLinkRecord>,
309): string {
310 const parts = [
311 `${sessions.length} ${sessions.length === 1 ? "client" : "clients"}`,
312 links.length > 0
313 ? `${links.length} ${links.length === 1 ? "pairing link" : "pairing links"}`
314 : null,
315 ];
316 return parts.filter((part): part is string => part !== null).join(" · ");
317}
318
319export function sortDesktopClientSessions(sessions: ReadonlyArray<ServerClientSessionRecord>) {
320 return [...sessions].toSorted((left, right) => {
321 if (left.current !== right.current) {
322 return left.current ? -1 : 1;
323 }
324 if (left.connected !== right.connected) {
325 return left.connected ? -1 : 1;
326 }
327 return new Date(right.issuedAt).getTime() - new Date(left.issuedAt).getTime();
328 });
329}
330
331export function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairingLinkRecord {
332 return {
333 ...pairingLink,
334 scopes: pairingLink.permissions ?? pairingLink.scopes,
335 createdAt: DateTime.formatIso(pairingLink.createdAt),
336 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
337 };
338}
339
340export function toDesktopClientSessionRecord(
341 clientSession: AuthClientSession,
342): ServerClientSessionRecord {
343 return {
344 ...clientSession,
345 scopes: clientSession.permissions ?? clientSession.scopes,
346 issuedAt: DateTime.formatIso(clientSession.issuedAt),
347 expiresAt: DateTime.formatIso(clientSession.expiresAt),
348 lastConnectedAt:
349 clientSession.lastConnectedAt === null
350 ? null
351 : DateTime.formatIso(clientSession.lastConnectedAt),
352 };
353}
354
355export function selectPairingEndpoint(
356 endpoints: ReadonlyArray<AdvertisedEndpoint>,
357 defaultEndpointKey?: string | null,
358): AdvertisedEndpoint | null {
359 const availableEndpoints = endpoints.filter((endpoint) => endpoint.status !== "unavailable");
360 if (defaultEndpointKey) {
361 const selectedEndpoint = availableEndpoints.find(
362 (endpoint) => endpointDefaultPreferenceKey(endpoint) === defaultEndpointKey,
363 );
364 if (selectedEndpoint) {
365 return selectedEndpoint;
366 }
367 }
368 return (
369 availableEndpoints.find((endpoint) => endpoint.isDefault) ??
370 availableEndpoints.find((endpoint) => endpoint.reachability !== "loopback") ??
371 availableEndpoints.find((endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible") ??
372 null
373 );
374}
375
376export function isTailscaleHttpsEndpoint(endpoint: AdvertisedEndpoint): boolean {
377 return endpoint.id.startsWith("tailscale-magicdns:");
378}
379
380export function endpointDefaultPreferenceKey(endpoint: AdvertisedEndpoint): string {
381 if (endpoint.id.startsWith("desktop-loopback:")) {
382 return "desktop-core:loopback:http";
383 }
384 if (endpoint.id.startsWith("desktop-lan:")) {
385 return "desktop-core:lan:http";
386 }
387 if (endpoint.id.startsWith("tailscale-ip:")) {
388 return "tailscale:ip:http";
389 }
390 if (isTailscaleHttpsEndpoint(endpoint)) {
391 return "tailscale:magicdns:https";
392 }
393
394 let scheme = "unknown";
395 try {
396 scheme = new URL(endpoint.httpBaseUrl).protocol.replace(/:$/u, "");
397 } catch {}
398
399 return `${endpoint.provider.id}:${endpoint.reachability}:${scheme}:${endpoint.label}`;
400}
401
402export function resolveAdvertisedEndpointPairingUrl(
403 endpoint: AdvertisedEndpoint,
404 credential: string,
405): string {
406 if (endpoint.compatibility.hostedHttpsApp === "compatible") {
407 return (
408 resolveHostedPairingUrl(endpoint.httpBaseUrl, credential) ??
409 resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential)
410 );
411 }
412 return resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential);
413}
414
415export function resolveCurrentOriginPairingUrl(credential: string): string {
416 const url = new URL("/pair", window.location.href);
417 return setPairingTokenOnUrl(url, credential).toString();
418}
419
420export function isHostedAppPairingUrl(value: string): boolean {
421 try {
422 const url = new URL(value);
423 return url.pathname === "/pair" && url.searchParams.has("host");
424 } catch {
425 return false;
426 }
427}
428
429export function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): string {
430 if (isHostedAppPairingUrl(url)) {
431 return "Opens the hosted app, no install needed";
432 }
433 switch (endpoint.reachability) {
434 case "lan":
435 return "Devices on the same network";
436 case "private-network":
437 return "Devices on your private network";
438 case "public":
439 return "Reachable from anywhere";
440 case "loopback":
441 return "Clients on this machine";
442 }
443}