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