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