@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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