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";
16
17/**
18 * A saved environment can hold several routes: T3 Connect, direct URLs (LAN,
19 * tailnet, other VPNs, public), and SSH. The client connects over the first route in
20 * preference order that answers as the expected environment, and moves back
21 * to a better one when it becomes reachable again.
22 */
23
24export type ConnectionRouteKind =
25 | "relay"
26 | "loopback"
27 | "lan"
28 | "tailnet"
29 | "vpn"
30 | "public"
31 | "ssh";
32
33/** An environment has at most one T3 Connect route, so it needs no per-route id. */
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
48/** Every route of an entry, preferred first. */
49export function connectionRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {
50 return [{ target: entry.target, profile: entry.profile }, ...(entry.alternateRoutes ?? [])];
51}
52
53/** Builds an entry whose preferred route is the first of `routes`, which must not be empty. */
54export function entryWithRoutes(
55 entry: ConnectionCatalogEntry,
56 routes: ReadonlyArray<ConnectionRoute>,
57): ConnectionCatalogEntry {
58 const [first, ...rest] = routes;
59 if (first === undefined) {
60 throw new Error("A saved environment needs at least one route.");
61 }
62 const { alternateRoutes: _previous, ...base } = entry;
63 return {
64 ...base,
65 target: first.target,
66 profile: first.profile,
67 ...(rest.length === 0 ? {} : { alternateRoutes: rest }),
68 };
69}
70
71/** The entry a single route connects with. */
72export function routeEntry(
73 entry: ConnectionCatalogEntry,
74 route: ConnectionRoute,
75): ConnectionCatalogEntry {
76 return entryWithRoutes(entry, [route]);
77}
78
79/** The base URL of a direct route, or null for T3 Connect and SSH. */
80export function routeHttpBaseUrl(route: ConnectionRoute): string | null {
81 if (route.target._tag === "PrimaryConnectionTarget") return route.target.httpBaseUrl;
82 const profile = Option.getOrNull(route.profile);
83 return profile?._tag === "BearerConnectionProfile" ? profile.httpBaseUrl : null;
84}
85
86function routeHostname(route: ConnectionRoute): string | null {
87 const httpBaseUrl = routeHttpBaseUrl(route);
88 if (httpBaseUrl === null) return null;
89 try {
90 return new URL(httpBaseUrl).hostname;
91 } catch {
92 return null;
93 }
94}
95
96export function connectionRouteKind(route: ConnectionRoute): ConnectionRouteKind {
97 switch (route.target._tag) {
98 case "RelayConnectionTarget":
99 return "relay";
100 case "SshConnectionTarget":
101 return "ssh";
102 case "PrimaryConnectionTarget":
103 case "BearerConnectionTarget": {
104 const hostname = routeHostname(route);
105 if (hostname === null) return "public";
106 if (isLocalLoopbackHost(hostname)) return "loopback";
107 const profile = Option.getOrNull(route.profile);
108 const tailscale =
109 profile?._tag === "BearerConnectionProfile" && profile.network === "tailscale";
110 if (tailscale || isTailnetHost(hostname)) return "tailnet";
111 if (isSharedAddressSpaceHost(hostname)) return "vpn";
112 return isPrivateNetworkHost(hostname) ? "lan" : "public";
113 }
114 }
115}
116
117const ROUTE_KIND_RANK: Record<ConnectionRouteKind, number> = {
118 loopback: 0,
119 lan: 1,
120 tailnet: 2,
121 vpn: 2,
122 public: 3,
123 ssh: 4,
124 relay: 5,
125};
126
127/**
128 * Where a newly added route goes: after every saved route of the same or a
129 * faster kind, so LAN lands ahead of tailnet and both ahead of T3 Connect.
130 * Users can reorder afterwards; this only picks a sensible starting point.
131 */
132export function insertRoute(
133 routes: ReadonlyArray<ConnectionRoute>,
134 route: ConnectionRoute,
135): ReadonlyArray<ConnectionRoute> {
136 const rank = ROUTE_KIND_RANK[connectionRouteKind(route)];
137 const index = routes.findIndex(
138 (existing) => ROUTE_KIND_RANK[connectionRouteKind(existing)] > rank,
139 );
140 return index === -1
141 ? [...routes, route]
142 : [...routes.slice(0, index), route, ...routes.slice(index)];
143}
144
145/** Replaces the route with the same id in place, or inserts it by kind. */
146export function upsertRoute(
147 routes: ReadonlyArray<ConnectionRoute>,
148 route: ConnectionRoute,
149): ReadonlyArray<ConnectionRoute> {
150 const id = connectionRouteId(route.target);
151 return routes.some((existing) => connectionRouteId(existing.target) === id)
152 ? routes.map((existing) => (connectionRouteId(existing.target) === id ? route : existing))
153 : insertRoute(routes, route);
154}
155
156/**
157 * A saved route that reaches the same address as `route`: the same bearer
158 * URL, or the same SSH target (alias, host, user, and port, as desktop keys
159 * its tunnels). Registering it again replaces that route, even when it was
160 * saved under another id.
161 */
162export function findRouteToSameAddress(
163 routes: ReadonlyArray<ConnectionRoute>,
164 route: ConnectionRoute,
165): ConnectionRoute | undefined {
166 const key = routeAddressKey(route);
167 return key === null ? undefined : routes.find((existing) => routeAddressKey(existing) === key);
168}
169
170function routeAddressKey(route: ConnectionRoute): string | null {
171 const profile = Option.getOrNull(route.profile);
172 switch (profile?._tag) {
173 case "BearerConnectionProfile":
174 return `bearer:${profile.httpBaseUrl.replace(/\/+$/, "")}`;
175 case "SshConnectionProfile":
176 return `ssh:${sshTargetKey(profile.target)}`;
177 default:
178 return null;
179 }
180}
181
182/** Short user-facing route description: "LAN", "Tailscale", "VPN", "T3 Connect", a URL, or an SSH host. */
183export function connectionRouteLabel(route: ConnectionRoute): string {
184 switch (connectionRouteKind(route)) {
185 case "relay":
186 return "T3 Connect";
187 case "loopback":
188 return "This device";
189 case "lan":
190 return "LAN";
191 case "tailnet":
192 return "Tailscale";
193 case "vpn":
194 return "VPN";
195 case "ssh": {
196 const profile = Option.getOrNull(route.profile);
197 return profile?._tag === "SshConnectionProfile"
198 ? `SSH ${profile.target.username ? `${profile.target.username}@` : ""}${profile.target.hostname}`
199 : "SSH";
200 }
201 case "public":
202 return routeHostname(route) ?? "Remote link";
203 }
204}
205
206/** The address shown under a route, or null for T3 Connect. */
207export function connectionRouteAddress(route: ConnectionRoute): string | null {
208 if (route.target._tag === "SshConnectionTarget") {
209 const profile = Option.getOrNull(route.profile);
210 return profile?._tag === "SshConnectionProfile" ? profile.target.alias : null;
211 }
212 return routeHttpBaseUrl(route);
213}
214
215/** Whether the environment can be reached through T3 Connect. */
216export function hasRelayRoute(
217 entry: Pick<ConnectionCatalogEntry, "target" | "alternateRoutes">,
218): boolean {
219 return [entry.target, ...(entry.alternateRoutes ?? []).map((route) => route.target)].some(
220 (target) => target._tag === "RelayConnectionTarget",
221 );
222}
223
224/**
225 * The routes after the server reports where it listens. Each newly reported
226 * address becomes a learned route that authenticates the same way as the route
227 * in use: the paired token for a bearer route, the T3 Connect credential for
228 * relay. A learned route the server still reports keeps its place, so the
229 * user's order holds; one it no longer reports is dropped, so a changed LAN
230 * address replaces the old one. Routes the user saved are never removed or
231 * moved, and an address already saved is not learned twice. Any direct route
232 * the server reports is marked as Tailscale while the server finds it on its
233 * Tailscale interface, so a route paired by its numeric Tailscale address keeps
234 * that label.
235 */
236export function mergeLearnedRoutes(input: {
237 readonly entry: ConnectionCatalogEntry;
238 readonly activeRoute: ConnectionRoute;
239 readonly reported: ReadonlyArray<ReportedEndpoint>;
240 /** Plain HTTP routes are unusable from an HTTPS page (mixed content). */
241 readonly allowInsecure: boolean;
242}): ReadonlyArray<ConnectionRoute> | null {
243 const { entry } = input;
244 const active = input.activeRoute.target;
245 const saved = connectionRoutes(entry);
246 // The primary and SSH routes have no credential a learned route could reuse.
247 if (active._tag !== "RelayConnectionTarget" && active._tag !== "BearerConnectionTarget") {
248 return null;
249 }
250 // A route learned over another learned route inherits what that one uses:
251 // the T3 Connect credential, or the paired token it borrows.
252 const activeProfile = Option.getOrNull(input.activeRoute.profile);
253 const authorization =
254 active._tag === "RelayConnectionTarget" ||
255 (activeProfile?._tag === "BearerConnectionProfile" &&
256 activeProfile.authorization === "t3-connect")
257 ? ("t3-connect" as const)
258 : undefined;
259 const sharedCredential =
260 authorization === undefined && active._tag === "BearerConnectionTarget"
261 ? credentialConnectionId(active.connectionId)
262 : undefined;
263
264 // Usable reported addresses, by origin.
265 const reported = new Map<string, URL>();
266 const tailscaleOrigins = new Set<string>();
267 for (const endpoint of input.reported) {
268 let url: URL;
269 try {
270 url = new URL(endpoint.httpBaseUrl);
271 } catch {
272 continue;
273 }
274 if (url.protocol !== "http:" && url.protocol !== "https:") continue;
275 if (url.protocol === "http:" && !input.allowInsecure) continue;
276 // A loopback address names whichever device opens it, never the server.
277 if (isLocalLoopbackHost(url.hostname)) continue;
278 reported.set(url.origin, url);
279 if (endpoint.kind === "tailnet") tailscaleOrigins.add(url.origin);
280 }
281 const normalized = (url: string) => url.replace(/\/+$/, "");
282 const known = new Set(
283 saved.flatMap((route) => {
284 const url = routeHttpBaseUrl(route);
285 return url === null || isLearned(route) ? [] : [normalized(url)];
286 }),
287 );
288 const kept = saved.flatMap((route): ReadonlyArray<ConnectionRoute> => {
289 const url = routeHttpBaseUrl(route);
290 if (!isLearned(route)) {
291 return [
292 url === null || !reported.has(normalized(url))
293 ? route
294 : withNetwork(route, tailscaleOrigins.has(normalized(url))),
295 ];
296 }
297 if (url === null || !reported.has(normalized(url)) || known.has(normalized(url))) return [];
298 known.add(normalized(url));
299 return [withNetwork(route, tailscaleOrigins.has(normalized(url)))];
300 });
301 let next: ReadonlyArray<ConnectionRoute> = kept;
302 for (const url of reported.values()) {
303 if (known.has(url.origin)) continue;
304 const httpBaseUrl = `${url.origin}/`;
305 const connectionId = learnedConnectionId(
306 entry.target.environmentId,
307 url.origin,
308 sharedCredential,
309 );
310 next = insertRoute(next, {
311 target: new BearerConnectionTarget({
312 environmentId: entry.target.environmentId,
313 label: entry.target.label,
314 connectionId,
315 }),
316 profile: Option.some(
317 new BearerConnectionProfile({
318 connectionId,
319 environmentId: entry.target.environmentId,
320 label: entry.target.label,
321 httpBaseUrl,
322 wsBaseUrl: `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}/`,
323 learned: true,
324 ...(authorization === undefined ? {} : { authorization }),
325 ...(tailscaleOrigins.has(url.origin) ? { network: "tailscale" as const } : {}),
326 }),
327 ),
328 });
329 }
330 // Compare addresses too: a scheme or port change keeps no id stable.
331 const signature = (routes: ReadonlyArray<ConnectionRoute>) =>
332 routes
333 .map(
334 (route) =>
335 `${connectionRouteId(route.target)} ${routeHttpBaseUrl(route) ?? ""} ${connectionRouteKind(route)}`,
336 )
337 .join("\n");
338 return signature(saved) === signature(next) ? null : next;
339}
340
341/** A direct address the server reports, as `ServerDirectEndpoint`. */
342export interface ReportedEndpoint {
343 readonly httpBaseUrl: string;
344 readonly kind?: string;
345}
346
347/** The direct route with its Tailscale mark set or cleared; the same route when unchanged. */
348function withNetwork(route: ConnectionRoute, tailscale: boolean): ConnectionRoute {
349 const profile = Option.getOrNull(route.profile);
350 if (profile?._tag !== "BearerConnectionProfile") return route;
351 if ((profile.network === "tailscale") === tailscale) return route;
352 return {
353 target: route.target,
354 profile: Option.some(
355 new BearerConnectionProfile({
356 connectionId: profile.connectionId,
357 environmentId: profile.environmentId,
358 label: profile.label,
359 httpBaseUrl: profile.httpBaseUrl,
360 wsBaseUrl: profile.wsBaseUrl,
361 ...(profile.learned === undefined ? {} : { learned: profile.learned }),
362 ...(profile.authorization === undefined ? {} : { authorization: profile.authorization }),
363 ...(tailscale ? { network: "tailscale" as const } : {}),
364 }),
365 ),
366 };
367}
368
369/**
370 * A learned bearer route borrows the credential of the route it was learned
371 * from, so its id points back at that credential's owner.
372 */
373function learnedConnectionId(
374 environmentId: string,
375 origin: string,
376 sharedCredential: string | undefined,
377): string {
378 return sharedCredential === undefined
379 ? `learned:${environmentId}:${origin}`
380 : `learned:${environmentId}:${origin}@${sharedCredential}`;
381}
382
383/** The connection id whose stored credential a bearer route uses. */
384export function credentialConnectionId(connectionId: string): string {
385 // The borrowed id follows the first "@"; neither an environment id nor an
386 // origin contains one.
387 const at = connectionId.indexOf("@");
388 return connectionId.startsWith("learned:") && at !== -1
389 ? connectionId.slice(at + 1)
390 : connectionId;
391}
392
393export function isLearned(route: ConnectionRoute): boolean {
394 const profile = Option.getOrNull(route.profile);
395 return profile?._tag === "BearerConnectionProfile" && profile.learned === true;
396}
397
398/**
399 * Routes left after the user removes one. A learned route borrows the
400 * credential of the route it was learned over, so it cannot outlive that
401 * route: removing T3 Connect also removes routes learned through it, and
402 * removing a paired address removes routes that borrow its token.
403 */
404export function routesAfterRemoving(
405 routes: ReadonlyArray<ConnectionRoute>,
406 removedId: string,
407): ReadonlyArray<ConnectionRoute> {
408 const removed = routes.find((route) => connectionRouteId(route.target) === removedId);
409 if (removed === undefined) return routes;
410 return routes.filter((route) => {
411 if (route === removed) return false;
412 if (!isLearned(route)) return true;
413 const profile = Option.getOrNull(route.profile);
414 if (profile?._tag === "BearerConnectionProfile" && profile.authorization === "t3-connect") {
415 return removed.target._tag !== "RelayConnectionTarget";
416 }
417 return credentialConnectionId(connectionRouteId(route.target)) !== removedId;
418 });
419}
420
421/**
422 * Whether removing T3 Connect leaves the environment no route, so signing out
423 * removes it entirely. Routes learned through T3 Connect go with it.
424 */
425export function removedWithRelay(entry: ConnectionCatalogEntry): boolean {
426 return routesAfterRemoving(connectionRoutes(entry), RELAY_ROUTE_ID).length === 0;
427}
428
429/** One SSH target, as desktop keys its tunnels: alias, host, user, and port. */
430export function sshTargetKey(target: DesktopSshEnvironmentTarget): string {
431 return JSON.stringify([target.alias, target.hostname, target.username, target.port]);
432}