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 return "Tailscale";
204 case "vpn":
205 return "VPN";
206 case "ssh": {
207 const profile = Option.getOrNull(route.profile);
208 return profile?._tag === "SshConnectionProfile"
209 ? `SSH ${profile.target.username ? `${profile.target.username}@` : ""}${profile.target.hostname}`
210 : "SSH";
211 }
212 case "public":
213 return routeHostname(route) ?? msg("Remote link");
214 }
215}
216
217/** @public */
218export function connectionRouteLabelText(
219 route: ConnectionRoute,
220 resolve: MFunctionType = mFallback,
221): string {
222 switch (connectionRouteKind(route)) {
223 case "loopback":
224 return resolve(msg("This device"));
225 case "public":
226 return routeHostname(route) ?? resolve(msg("Remote link"));
227 default:
228 return connectionRouteLabel(route);
229 }
230}
231
232export function connectionRouteAddress(route: ConnectionRoute): string | null {
233 if (route.target._tag === "SshConnectionTarget") {
234 const profile = Option.getOrNull(route.profile);
235 return profile?._tag === "SshConnectionProfile" ? profile.target.alias : null;
236 }
237 return routeHttpBaseUrl(route);
238}
239
240/** Learned routes alone must not make relay environments manually retryable. */
241export const hasSavedBearerRoute = (entry: ConnectionCatalogEntry) =>
242 connectionRoutes(entry).some((r) => !isLearned(r) && r.target._tag === "BearerConnectionTarget");
243
244export function hasRelayRoute(
245 entry: Pick<ConnectionCatalogEntry, "target" | "alternateRoutes">,
246): boolean {
247 return [entry.target, ...(entry.alternateRoutes ?? []).map((route) => route.target)].some(
248 (target) => target._tag === "RelayConnectionTarget",
249 );
250}
251
252export function mergeLearnedRoutes(input: {
253 readonly entry: ConnectionCatalogEntry;
254 readonly activeRoute: ConnectionRoute;
255 readonly reported: ReadonlyArray<ReportedEndpoint>;
256 /** Plain HTTP routes are unusable from an HTTPS page (mixed content). */
257 readonly allowInsecure: boolean;
258}): ReadonlyArray<ConnectionRoute> | null {
259 const { entry } = input;
260 const active = input.activeRoute.target;
261 const saved = connectionRoutes(entry);
262 if (active._tag !== "RelayConnectionTarget" && active._tag !== "BearerConnectionTarget") {
263 return null;
264 }
265 const activeProfile = Option.getOrNull(input.activeRoute.profile);
266 const authorization =
267 active._tag === "RelayConnectionTarget" ||
268 (activeProfile?._tag === "BearerConnectionProfile" &&
269 activeProfile.authorization === "t3-connect")
270 ? ("t3-connect" as const)
271 : undefined;
272 const sharedCredential =
273 authorization === undefined && active._tag === "BearerConnectionTarget"
274 ? credentialConnectionId(active.connectionId)
275 : undefined;
276 const reported = new Map<string, URL>();
277 const tailscaleOrigins = new Set<string>();
278 for (const endpoint of input.reported) {
279 let url: URL;
280 try {
281 url = new URL(endpoint.httpBaseUrl);
282 } catch {
283 continue;
284 }
285 if (url.protocol !== "http:" && url.protocol !== "https:") continue;
286 if (url.protocol === "http:" && !input.allowInsecure) continue;
287 // A loopback address names whichever device opens it, never the server.
288 if (isLocalLoopbackHost(url.hostname)) continue;
289 reported.set(url.origin, url);
290 if (endpoint.kind === "tailnet") tailscaleOrigins.add(url.origin);
291 }
292 const normalized = (url: string) => url.replace(/\/+$/, "");
293 const known = new Set(
294 saved.flatMap((route) => {
295 const url = routeHttpBaseUrl(route);
296 return url === null || isLearned(route) ? [] : [normalized(url)];
297 }),
298 );
299 const kept = saved.flatMap((route): ReadonlyArray<ConnectionRoute> => {
300 const url = routeHttpBaseUrl(route);
301 if (!isLearned(route)) {
302 return [
303 url === null || !reported.has(normalized(url))
304 ? route
305 : withNetwork(route, tailscaleOrigins.has(normalized(url))),
306 ];
307 }
308 if (url === null || !reported.has(normalized(url)) || known.has(normalized(url))) return [];
309 if (sendsTokenInClear(saved, route, tailscaleOrigins.has(normalized(url)))) return [];
310 known.add(normalized(url));
311 return [withNetwork(route, tailscaleOrigins.has(normalized(url)))];
312 });
313 let next: ReadonlyArray<ConnectionRoute> = kept;
314 for (const url of reported.values()) {
315 if (known.has(url.origin)) continue;
316 if (
317 url.protocol === "http:" &&
318 sharedCredential !== undefined &&
319 !tailscaleOrigins.has(url.origin) &&
320 !tokenAllowsPlainHttp(saved, sharedCredential)
321 ) {
322 continue;
323 }
324 const httpBaseUrl = `${url.origin}/`;
325 const connectionId = learnedConnectionId(
326 entry.target.environmentId,
327 url.origin,
328 sharedCredential,
329 );
330 next = insertRoute(next, {
331 target: new BearerConnectionTarget({
332 environmentId: entry.target.environmentId,
333 label: entry.target.label,
334 connectionId,
335 }),
336 profile: Option.some(
337 new BearerConnectionProfile({
338 connectionId,
339 environmentId: entry.target.environmentId,
340 label: entry.target.label,
341 httpBaseUrl,
342 wsBaseUrl: `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}/`,
343 learned: true,
344 ...(authorization === undefined ? {} : { authorization }),
345 ...(tailscaleOrigins.has(url.origin) ? { network: "tailscale" as const } : {}),
346 }),
347 ),
348 });
349 }
350 const signature = (routes: ReadonlyArray<ConnectionRoute>) =>
351 routes
352 .map(
353 (route) =>
354 `${connectionRouteId(route.target)} ${routeHttpBaseUrl(route) ?? ""} ${connectionRouteKind(route)}`,
355 )
356 .join("\n");
357 return signature(saved) === signature(next) ? null : next;
358}
359
360// A paired token goes to a plain HTTP address outside the tailnet only when
361// it was paired that way, so a token paired over HTTPS, loopback, or the
362// tailnet keeps to the transports it was issued for.
363function tokenAllowsPlainHttp(
364 routes: ReadonlyArray<ConnectionRoute>,
365 credentialId: string,
366): boolean {
367 const credentialRoute = routes.find((route) => connectionRouteId(route.target) === credentialId);
368 return (
369 credentialRoute !== undefined &&
370 routeHttpBaseUrl(credentialRoute)?.startsWith("http:") === true &&
371 (connectionRouteKind(credentialRoute) === "lan" ||
372 connectionRouteKind(credentialRoute) === "public")
373 );
374}
375
376/**
377 * Whether connecting over `route` would send a paired token over plain HTTP
378 * that it wasn't paired over. Checked against the token the route borrows,
379 * so a route learned before this rule existed is refused too.
380 */
381export function sendsTokenInClear(
382 routes: ReadonlyArray<ConnectionRoute>,
383 route: ConnectionRoute,
384 tailscale?: boolean,
385): boolean {
386 const profile = Option.getOrNull(route.profile);
387 if (profile?._tag !== "BearerConnectionProfile" || profile.authorization === "t3-connect") {
388 return false;
389 }
390 if ((tailscale ?? profile.network === "tailscale") || !profile.httpBaseUrl.startsWith("http:")) {
391 return false;
392 }
393 const credentialId = credentialConnectionId(connectionRouteId(route.target));
394 return (
395 credentialId !== connectionRouteId(route.target) && !tokenAllowsPlainHttp(routes, credentialId)
396 );
397}
398
399/** Routes a connect may use: none sends a paired token over plain HTTP it wasn't paired over. */
400export function usableRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {
401 const routes = connectionRoutes(entry);
402 return routes.filter((route) => !sendsTokenInClear(routes, route));
403}
404
405export interface ReportedEndpoint {
406 readonly httpBaseUrl: string;
407 readonly kind?: string;
408}
409
410function withNetwork(route: ConnectionRoute, tailscale: boolean): ConnectionRoute {
411 const profile = Option.getOrNull(route.profile);
412 if (profile?._tag !== "BearerConnectionProfile") return route;
413 if ((profile.network === "tailscale") === tailscale) return route;
414 return {
415 target: route.target,
416 profile: Option.some(
417 new BearerConnectionProfile({
418 connectionId: profile.connectionId,
419 environmentId: profile.environmentId,
420 label: profile.label,
421 httpBaseUrl: profile.httpBaseUrl,
422 wsBaseUrl: profile.wsBaseUrl,
423 ...(profile.learned === undefined ? {} : { learned: profile.learned }),
424 ...(profile.authorization === undefined ? {} : { authorization: profile.authorization }),
425 ...(tailscale ? { network: "tailscale" as const } : {}),
426 }),
427 ),
428 };
429}
430
431function learnedConnectionId(
432 environmentId: string,
433 origin: string,
434 sharedCredential: string | undefined,
435): string {
436 return sharedCredential === undefined
437 ? `learned:${environmentId}:${origin}`
438 : `learned:${environmentId}:${origin}@${sharedCredential}`;
439}
440
441export function credentialConnectionId(connectionId: string): string {
442 const at = connectionId.indexOf("@");
443 return connectionId.startsWith("learned:") && at !== -1
444 ? connectionId.slice(at + 1)
445 : connectionId;
446}
447
448export function isLearned(route: ConnectionRoute): boolean {
449 const profile = Option.getOrNull(route.profile);
450 return profile?._tag === "BearerConnectionProfile" && profile.learned === true;
451}
452
453/**
454 * A learned route borrows the credential of the route it was learned over, so
455 * it cannot outlive that route: removing T3 Connect also removes routes learned
456 * through it, and removing a paired address removes routes that borrow its
457 * token.
458 */
459export function routesAfterRemoving(
460 routes: ReadonlyArray<ConnectionRoute>,
461 removedId: string,
462): ReadonlyArray<ConnectionRoute> {
463 const removed = routes.find((route) => connectionRouteId(route.target) === removedId);
464 if (removed === undefined) return routes;
465 return routes.filter((route) => {
466 if (route === removed) return false;
467 if (!isLearned(route)) return true;
468 const profile = Option.getOrNull(route.profile);
469 if (profile?._tag === "BearerConnectionProfile" && profile.authorization === "t3-connect") {
470 return removed.target._tag !== "RelayConnectionTarget";
471 }
472 return credentialConnectionId(connectionRouteId(route.target)) !== removedId;
473 });
474}
475
476/**
477 * A dragged route order shows until the saved routes catch up with it. It is
478 * stale, and returns null, once the saved order matches it or the saved routes
479 * are no longer the same set: kept any longer, it would hide a route added
480 * later whenever the count happened to match again.
481 */
482export function pendingRouteOrder(
483 pending: ReadonlyArray<string> | null,
484 savedIds: ReadonlyArray<string>,
485): ReadonlyArray<string> | null {
486 if (pending === null || pending.length !== savedIds.length) return null;
487 const saved = new Set(savedIds);
488 if (!pending.every((id) => saved.has(id))) return null;
489 return pending.some((id, index) => id !== savedIds[index]) ? pending : null;
490}
491
492export function removedWithRelay(entry: ConnectionCatalogEntry): boolean {
493 return routesAfterRemoving(connectionRoutes(entry), RELAY_ROUTE_ID).length === 0;
494}
495
496export function sshTargetKey(target: DesktopSshEnvironmentTarget): string {
497 return JSON.stringify([target.alias, target.hostname, target.username, target.port]);
498}