Open History to see the last commit
1import {
2 isLocalLoopbackHost,
3 isPrivateNetworkHost,
4 isSharedAddressSpaceHost,
5 isTailnetHost,
6} from "@t3tools/shared/hostClassification";
7import type { DesktopSshEnvironmentTarget } from "@t3tools/contracts";
8import * as Option from "effect/Option";
9
10import {
11 BearerConnectionProfile,
12 type ConnectionCatalogEntry,
13 type ConnectionRoute,
14} from "./catalog.ts";
15import { BearerConnectionTarget, type ConnectionTarget } from "./model.ts";
16import { mFallback, msg } from "gt-i18n";
17import type { MFunctionType } from "gt-i18n/types";
18
19export type ConnectionRouteKind =
20 | "relay"
21 | "loopback"
22 | "lan"
23 | "tailnet"
24 | "vpn"
25 | "public"
26 | "ssh";
27
28export const RELAY_ROUTE_ID = "relay";
29
30export function connectionRouteId(target: ConnectionTarget): string {
31 switch (target._tag) {
32 case "PrimaryConnectionTarget":
33 return "primary";
34 case "RelayConnectionTarget":
35 return RELAY_ROUTE_ID;
36 case "BearerConnectionTarget":
37 case "SshConnectionTarget":
38 return target.connectionId;
39 }
40}
41
42export function connectionRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {
43 return [{ target: entry.target, profile: entry.profile }, ...(entry.alternateRoutes ?? [])];
44}
45
46export function entryWithRoutes(
47 entry: ConnectionCatalogEntry,
48 routes: ReadonlyArray<ConnectionRoute>,
49): ConnectionCatalogEntry {
50 const [first, ...rest] = routes;
51 if (first === undefined) {
52 throw new Error("A saved environment needs at least one route.");
53 }
54 const { alternateRoutes: _previous, ...base } = entry;
55 return {
56 ...base,
57 target: first.target,
58 profile: first.profile,
59 ...(rest.length === 0 ? {} : { alternateRoutes: rest }),
60 };
61}
62
63export function routeEntry(
64 entry: ConnectionCatalogEntry,
65 route: ConnectionRoute,
66): ConnectionCatalogEntry {
67 return entryWithRoutes(entry, [route]);
68}
69
70export function routeHttpBaseUrl(route: ConnectionRoute): string | null {
71 if (route.target._tag === "PrimaryConnectionTarget") return route.target.httpBaseUrl;
72 const profile = Option.getOrNull(route.profile);
73 return profile?._tag === "BearerConnectionProfile" ? profile.httpBaseUrl : null;
74}
75
76function routeHostname(route: ConnectionRoute): string | null {
77 const httpBaseUrl = routeHttpBaseUrl(route);
78 if (httpBaseUrl === null) return null;
79 try {
80 return new URL(httpBaseUrl).hostname;
81 } catch {
82 return null;
83 }
84}
85
86function directAddressKind(hostname: string, tailscale = false) {
87 if (isLocalLoopbackHost(hostname)) return "loopback";
88 if (tailscale || isTailnetHost(hostname)) return "tailnet";
89 if (isSharedAddressSpaceHost(hostname)) return "vpn";
90 return isPrivateNetworkHost(hostname) ? "lan" : "public";
91}
92
93export function connectionRouteKind(route: ConnectionRoute): ConnectionRouteKind {
94 switch (route.target._tag) {
95 case "RelayConnectionTarget":
96 return "relay";
97 case "SshConnectionTarget":
98 return "ssh";
99 case "PrimaryConnectionTarget":
100 case "BearerConnectionTarget": {
101 const hostname = routeHostname(route);
102 if (hostname === null) return "public";
103 const profile = Option.getOrNull(route.profile);
104 return directAddressKind(
105 hostname,
106 profile?._tag === "BearerConnectionProfile" && profile.network === "tailscale",
107 );
108 }
109 }
110}
111
112/**
113 * Whether the route's address reaches the same machine on every network: TLS
114 * proves who answers, and loopback cannot move. Any other plain http address,
115 * a tailnet one too once Tailscale is down, can belong to another machine after
116 * a network change, so an answer from it is not kept.
117 */
118export function routeKeepsItsHost(route: ConnectionRoute): boolean {
119 if (routeHttpBaseUrl(route)?.startsWith("https:") === true) return true;
120 return connectionRouteKind(route) === "loopback";
121}
122
123/** A loopback or LAN host answers within a few seconds or is not there. */
124export function isNearbyAddress(httpBaseUrl: string): boolean {
125 try {
126 const kind = directAddressKind(new URL(httpBaseUrl).hostname);
127 return kind === "loopback" || kind === "lan";
128 } catch {
129 return false;
130 }
131}
132
133const ROUTE_KIND_RANK: Record<ConnectionRouteKind, number> = {
134 loopback: 0,
135 lan: 1,
136 tailnet: 2,
137 vpn: 2,
138 public: 3,
139 ssh: 4,
140 relay: 5,
141};
142
143export function insertRoute(
144 routes: ReadonlyArray<ConnectionRoute>,
145 route: ConnectionRoute,
146 { aheadOfSameKind = false }: { readonly aheadOfSameKind?: boolean } = {},
147): ReadonlyArray<ConnectionRoute> {
148 const kind = connectionRouteKind(route);
149 const rank = ROUTE_KIND_RANK[kind];
150 const index = routes.findIndex((existing) => {
151 const existingKind = connectionRouteKind(existing);
152 return ROUTE_KIND_RANK[existingKind] > rank || (aheadOfSameKind && existingKind === kind);
153 });
154 return index === -1
155 ? [...routes, route]
156 : [...routes.slice(0, index), route, ...routes.slice(index)];
157}
158
159export function upsertRoute(
160 routes: ReadonlyArray<ConnectionRoute>,
161 route: ConnectionRoute,
162): ReadonlyArray<ConnectionRoute> {
163 const id = connectionRouteId(route.target);
164 return routes.some((existing) => connectionRouteId(existing.target) === id)
165 ? routes.map((existing) => (connectionRouteId(existing.target) === id ? route : existing))
166 : // A route paired at a new address, such as localhost beside a saved
167 // 127.0.0.1, goes first among its kind so its fresh credential connects.
168 insertRoute(routes, route, { aheadOfSameKind: true });
169}
170
171export function findRouteToSameAddress(
172 routes: ReadonlyArray<ConnectionRoute>,
173 route: ConnectionRoute,
174): ConnectionRoute | undefined {
175 const key = routeAddressKey(route);
176 return key === null ? undefined : routes.find((existing) => routeAddressKey(existing) === key);
177}
178
179function routeAddressKey(route: ConnectionRoute): string | null {
180 const profile = Option.getOrNull(route.profile);
181 switch (profile?._tag) {
182 case "BearerConnectionProfile":
183 return `bearer:${profile.httpBaseUrl.replace(/\/+$/, "")}`;
184 case "SshConnectionProfile":
185 return `ssh:${sshTargetKey(profile.target)}`;
186 default:
187 return null;
188 }
189}
190
191const T3_CONNECT_NAME = "T3 Connect";
192
193/** The route's label in English. Display sites use `connectionRouteLabelText`. */
194export function connectionRouteLabel(route: ConnectionRoute): string {
195 switch (connectionRouteKind(route)) {
196 case "relay":
197 return T3_CONNECT_NAME;
198 case "loopback":
199 return msg("This device");
200 case "lan":
201 return "LAN";
202 case "tailnet":
203 // Tailscale Serve answers over HTTPS on the machine's name; the same machine's
204 // plain address is another route, so the two are told apart.
205 return routeHttpBaseUrl(route)?.startsWith("https:") === true
206 ? msg("Tailscale HTTPS")
207 : "Tailscale";
208 case "vpn":
209 return "VPN";
210 case "ssh": {
211 const profile = Option.getOrNull(route.profile);
212 return profile?._tag === "SshConnectionProfile"
213 ? `SSH ${profile.target.username ? `${profile.target.username}@` : ""}${profile.target.hostname}`
214 : "SSH";
215 }
216 case "public":
217 return routeHostname(route) ?? msg("Remote link");
218 }
219}
220
221/** @public */
222export function connectionRouteLabelText(
223 route: ConnectionRoute,
224 resolve: MFunctionType = mFallback,
225): string {
226 switch (connectionRouteKind(route)) {
227 case "loopback":
228 return resolve(msg("This device"));
229 case "public":
230 return routeHostname(route) ?? resolve(msg("Remote link"));
231 default:
232 return connectionRouteLabel(route);
233 }
234}
235
236export function connectionRouteAddress(route: ConnectionRoute): string | null {
237 if (route.target._tag === "SshConnectionTarget") {
238 const profile = Option.getOrNull(route.profile);
239 return profile?._tag === "SshConnectionProfile" ? profile.target.alias : null;
240 }
241 return routeHttpBaseUrl(route);
242}
243
244/** Learned routes alone must not make relay environments manually retryable. */
245export const hasSavedBearerRoute = (entry: ConnectionCatalogEntry) =>
246 connectionRoutes(entry).some((r) => !isLearned(r) && r.target._tag === "BearerConnectionTarget");
247
248export function hasRelayRoute(
249 entry: Pick<ConnectionCatalogEntry, "target" | "alternateRoutes">,
250): boolean {
251 return [entry.target, ...(entry.alternateRoutes ?? []).map((route) => route.target)].some(
252 (target) => target._tag === "RelayConnectionTarget",
253 );
254}
255
256export function mergeLearnedRoutes(input: {
257 readonly entry: ConnectionCatalogEntry;
258 readonly activeRoute: ConnectionRoute;
259 readonly reported: ReadonlyArray<ReportedEndpoint>;
260 /** Plain HTTP routes are unusable from an HTTPS page (mixed content). */
261 readonly allowInsecure: boolean;
262}): ReadonlyArray<ConnectionRoute> | null {
263 const { entry } = input;
264 const active = input.activeRoute.target;
265 const saved = connectionRoutes(entry);
266 if (active._tag !== "RelayConnectionTarget" && active._tag !== "BearerConnectionTarget") {
267 return null;
268 }
269 const activeProfile = Option.getOrNull(input.activeRoute.profile);
270 const authorization =
271 active._tag === "RelayConnectionTarget" ||
272 (activeProfile?._tag === "BearerConnectionProfile" &&
273 activeProfile.authorization === "t3-connect")
274 ? ("t3-connect" as const)
275 : undefined;
276 const sharedCredential =
277 authorization === undefined && active._tag === "BearerConnectionTarget"
278 ? credentialConnectionId(active.connectionId)
279 : undefined;
280 const reported = new Map<string, URL>();
281 const tailscaleOrigins = new Set<string>();
282 for (const endpoint of input.reported) {
283 let url: URL;
284 try {
285 url = new URL(endpoint.httpBaseUrl);
286 } catch {
287 continue;
288 }
289 if (url.protocol !== "http:" && url.protocol !== "https:") continue;
290 if (url.protocol === "http:" && !input.allowInsecure) continue;
291 // A loopback address names whichever device opens it, never the server.
292 if (isLocalLoopbackHost(url.hostname)) continue;
293 reported.set(url.origin, url);
294 if (endpoint.kind === "tailnet") tailscaleOrigins.add(url.origin);
295 }
296 const normalized = (url: string) => url.replace(/\/+$/, "");
297 const known = new Set(
298 saved.flatMap((route) => {
299 const url = routeHttpBaseUrl(route);
300 return url === null || isLearned(route) ? [] : [normalized(url)];
301 }),
302 );
303 const kept = saved.flatMap((route): ReadonlyArray<ConnectionRoute> => {
304 const url = routeHttpBaseUrl(route);
305 if (!isLearned(route)) {
306 return [
307 url === null || !reported.has(normalized(url))
308 ? route
309 : withNetwork(route, tailscaleOrigins.has(normalized(url))),
310 ];
311 }
312 if (url === null || !reported.has(normalized(url)) || known.has(normalized(url))) return [];
313 if (sendsTokenInClear(saved, route, tailscaleOrigins.has(normalized(url)))) return [];
314 known.add(normalized(url));
315 return [withNetwork(route, tailscaleOrigins.has(normalized(url)))];
316 });
317 let next: ReadonlyArray<ConnectionRoute> = kept;
318 for (const url of reported.values()) {
319 if (known.has(url.origin)) continue;
320 if (
321 url.protocol === "http:" &&
322 sharedCredential !== undefined &&
323 !tailscaleOrigins.has(url.origin) &&
324 !tokenAllowsPlainHttp(saved, sharedCredential)
325 ) {
326 continue;
327 }
328 const httpBaseUrl = `${url.origin}/`;
329 const connectionId = learnedConnectionId(
330 entry.target.environmentId,
331 url.origin,
332 sharedCredential,
333 );
334 next = insertRoute(next, {
335 target: new BearerConnectionTarget({
336 environmentId: entry.target.environmentId,
337 label: entry.target.label,
338 connectionId,
339 }),
340 profile: Option.some(
341 new BearerConnectionProfile({
342 connectionId,
343 environmentId: entry.target.environmentId,
344 label: entry.target.label,
345 httpBaseUrl,
346 wsBaseUrl: `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}/`,
347 learned: true,
348 ...(authorization === undefined ? {} : { authorization }),
349 ...(tailscaleOrigins.has(url.origin) ? { network: "tailscale" as const } : {}),
350 }),
351 ),
352 });
353 }
354 const signature = (routes: ReadonlyArray<ConnectionRoute>) =>
355 routes
356 .map(
357 (route) =>
358 `${connectionRouteId(route.target)} ${routeHttpBaseUrl(route) ?? ""} ${connectionRouteKind(route)}`,
359 )
360 .join("\n");
361 return signature(saved) === signature(next) ? null : next;
362}
363
364// A paired token goes to a plain HTTP address outside the tailnet only when
365// it was paired that way, so a token paired over HTTPS, loopback, or the
366// tailnet keeps to the transports it was issued for.
367function tokenAllowsPlainHttp(
368 routes: ReadonlyArray<ConnectionRoute>,
369 credentialId: string,
370): boolean {
371 const credentialRoute = routes.find((route) => connectionRouteId(route.target) === credentialId);
372 return (
373 credentialRoute !== undefined &&
374 routeHttpBaseUrl(credentialRoute)?.startsWith("http:") === true &&
375 (connectionRouteKind(credentialRoute) === "lan" ||
376 connectionRouteKind(credentialRoute) === "public")
377 );
378}
379
380/**
381 * Whether connecting over `route` would send a paired token over plain HTTP
382 * that it wasn't paired over. Checked against the token the route borrows,
383 * so a route learned before this rule existed is refused too.
384 */
385export function sendsTokenInClear(
386 routes: ReadonlyArray<ConnectionRoute>,
387 route: ConnectionRoute,
388 tailscale?: boolean,
389): boolean {
390 const profile = Option.getOrNull(route.profile);
391 if (profile?._tag !== "BearerConnectionProfile" || profile.authorization === "t3-connect") {
392 return false;
393 }
394 if ((tailscale ?? profile.network === "tailscale") || !profile.httpBaseUrl.startsWith("http:")) {
395 return false;
396 }
397 const credentialId = credentialConnectionId(connectionRouteId(route.target));
398 return (
399 credentialId !== connectionRouteId(route.target) && !tokenAllowsPlainHttp(routes, credentialId)
400 );
401}
402
403/** Routes a connect may use: none sends a paired token over plain HTTP it wasn't paired over. */
404export function usableRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {
405 const routes = connectionRoutes(entry);
406 return routes.filter((route) => !sendsTokenInClear(routes, route));
407}
408
409export interface ReportedEndpoint {
410 readonly httpBaseUrl: string;
411 readonly kind?: string;
412}
413
414function withNetwork(route: ConnectionRoute, tailscale: boolean): ConnectionRoute {
415 const profile = Option.getOrNull(route.profile);
416 if (profile?._tag !== "BearerConnectionProfile") return route;
417 if ((profile.network === "tailscale") === tailscale) return route;
418 return {
419 target: route.target,
420 profile: Option.some(
421 new BearerConnectionProfile({
422 connectionId: profile.connectionId,
423 environmentId: profile.environmentId,
424 label: profile.label,
425 httpBaseUrl: profile.httpBaseUrl,
426 wsBaseUrl: profile.wsBaseUrl,
427 ...(profile.learned === undefined ? {} : { learned: profile.learned }),
428 ...(profile.authorization === undefined ? {} : { authorization: profile.authorization }),
429 ...(tailscale ? { network: "tailscale" as const } : {}),
430 }),
431 ),
432 };
433}
434
435function learnedConnectionId(
436 environmentId: string,
437 origin: string,
438 sharedCredential: string | undefined,
439): string {
440 return sharedCredential === undefined
441 ? `learned:${environmentId}:${origin}`
442 : `learned:${environmentId}:${origin}@${sharedCredential}`;
443}
444
445export function credentialConnectionId(connectionId: string): string {
446 const at = connectionId.indexOf("@");
447 return connectionId.startsWith("learned:") && at !== -1
448 ? connectionId.slice(at + 1)
449 : connectionId;
450}
451
452export function isLearned(route: ConnectionRoute): boolean {
453 const profile = Option.getOrNull(route.profile);
454 return profile?._tag === "BearerConnectionProfile" && profile.learned === true;
455}
456
457/**
458 * A learned route borrows the credential of the route it was learned over, so
459 * it cannot outlive that route: removing T3 Connect also removes routes learned
460 * through it, and removing a paired address removes routes that borrow its
461 * token.
462 */
463export function routesAfterRemoving(
464 routes: ReadonlyArray<ConnectionRoute>,
465 removedId: string,
466): ReadonlyArray<ConnectionRoute> {
467 const removed = routes.find((route) => connectionRouteId(route.target) === removedId);
468 if (removed === undefined) return routes;
469 return routes.filter((route) => {
470 if (route === removed) return false;
471 if (!isLearned(route)) return true;
472 const profile = Option.getOrNull(route.profile);
473 if (profile?._tag === "BearerConnectionProfile" && profile.authorization === "t3-connect") {
474 return removed.target._tag !== "RelayConnectionTarget";
475 }
476 return credentialConnectionId(connectionRouteId(route.target)) !== removedId;
477 });
478}
479
480/**
481 * A route is offered for removal only when removing it leaves a route behind.
482 * A learned route would be learned again, and the last route a learned route
483 * borrows from would take the whole environment with it.
484 */
485export function canRemoveRoute(
486 routes: ReadonlyArray<ConnectionRoute>,
487 route: ConnectionRoute,
488): boolean {
489 return (
490 !isLearned(route) && routesAfterRemoving(routes, connectionRouteId(route.target)).length > 0
491 );
492}
493
494/**
495 * A dragged route order shows until the saved routes catch up with it. It is
496 * stale, and returns null, once the saved order matches it or the saved routes
497 * are no longer the same set: kept any longer, it would hide a route added
498 * later whenever the count happened to match again.
499 */
500export function pendingRouteOrder(
501 pending: ReadonlyArray<string> | null,
502 savedIds: ReadonlyArray<string>,
503): ReadonlyArray<string> | null {
504 if (pending === null || pending.length !== savedIds.length) return null;
505 const saved = new Set(savedIds);
506 if (!pending.every((id) => saved.has(id))) return null;
507 return pending.some((id, index) => id !== savedIds[index]) ? pending : null;
508}
509
510export function removedWithRelay(entry: ConnectionCatalogEntry): boolean {
511 return routesAfterRemoving(connectionRoutes(entry), RELAY_ROUTE_ID).length === 0;
512}
513
514export function sshTargetKey(target: DesktopSshEnvironmentTarget): string {
515 return JSON.stringify([target.alias, target.hostname, target.username, target.port]);
516}