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
17export type ConnectionRouteKind =
18 | "relay"
19 | "loopback"
20 | "lan"
21 | "tailnet"
22 | "vpn"
23 | "public"
24 | "ssh";
25
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
40export function connectionRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {
41 return [{ target: entry.target, profile: entry.profile }, ...(entry.alternateRoutes ?? [])];
42}
43
44export function entryWithRoutes(
45 entry: ConnectionCatalogEntry,
46 routes: ReadonlyArray<ConnectionRoute>,
47): ConnectionCatalogEntry {
48 const [first, ...rest] = routes;
49 if (first === undefined) {
50 throw new Error("A saved environment needs at least one route.");
51 }
52 const { alternateRoutes: _previous, ...base } = entry;
53 return {
54 ...base,
55 target: first.target,
56 profile: first.profile,
57 ...(rest.length === 0 ? {} : { alternateRoutes: rest }),
58 };
59}
60
61export function routeEntry(
62 entry: ConnectionCatalogEntry,
63 route: ConnectionRoute,
64): ConnectionCatalogEntry {
65 return entryWithRoutes(entry, [route]);
66}
67
68export function routeHttpBaseUrl(route: ConnectionRoute): string | null {
69 if (route.target._tag === "PrimaryConnectionTarget") return route.target.httpBaseUrl;
70 const profile = Option.getOrNull(route.profile);
71 return profile?._tag === "BearerConnectionProfile" ? profile.httpBaseUrl : null;
72}
73
74function routeHostname(route: ConnectionRoute): string | null {
75 const httpBaseUrl = routeHttpBaseUrl(route);
76 if (httpBaseUrl === null) return null;
77 try {
78 return new URL(httpBaseUrl).hostname;
79 } catch {
80 return null;
81 }
82}
83
84export function connectionRouteKind(route: ConnectionRoute): ConnectionRouteKind {
85 switch (route.target._tag) {
86 case "RelayConnectionTarget":
87 return "relay";
88 case "SshConnectionTarget":
89 return "ssh";
90 case "PrimaryConnectionTarget":
91 case "BearerConnectionTarget": {
92 const hostname = routeHostname(route);
93 if (hostname === null) return "public";
94 if (isLocalLoopbackHost(hostname)) return "loopback";
95 const profile = Option.getOrNull(route.profile);
96 const tailscale =
97 profile?._tag === "BearerConnectionProfile" && profile.network === "tailscale";
98 if (tailscale || isTailnetHost(hostname)) return "tailnet";
99 if (isSharedAddressSpaceHost(hostname)) return "vpn";
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 vpn: 2,
110 public: 3,
111 ssh: 4,
112 relay: 5,
113};
114
115export function insertRoute(
116 routes: ReadonlyArray<ConnectionRoute>,
117 route: ConnectionRoute,
118): ReadonlyArray<ConnectionRoute> {
119 const rank = ROUTE_KIND_RANK[connectionRouteKind(route)];
120 const index = routes.findIndex(
121 (existing) => ROUTE_KIND_RANK[connectionRouteKind(existing)] > rank,
122 );
123 return index === -1
124 ? [...routes, route]
125 : [...routes.slice(0, index), route, ...routes.slice(index)];
126}
127
128export function upsertRoute(
129 routes: ReadonlyArray<ConnectionRoute>,
130 route: ConnectionRoute,
131): ReadonlyArray<ConnectionRoute> {
132 const id = connectionRouteId(route.target);
133 return routes.some((existing) => connectionRouteId(existing.target) === id)
134 ? routes.map((existing) => (connectionRouteId(existing.target) === id ? route : existing))
135 : insertRoute(routes, route);
136}
137
138export function findRouteToSameAddress(
139 routes: ReadonlyArray<ConnectionRoute>,
140 route: ConnectionRoute,
141): ConnectionRoute | undefined {
142 const key = routeAddressKey(route);
143 return key === null ? undefined : routes.find((existing) => routeAddressKey(existing) === key);
144}
145
146function routeAddressKey(route: ConnectionRoute): string | null {
147 const profile = Option.getOrNull(route.profile);
148 switch (profile?._tag) {
149 case "BearerConnectionProfile":
150 return `bearer:${profile.httpBaseUrl.replace(/\/+$/, "")}`;
151 case "SshConnectionProfile":
152 return `ssh:${sshTargetKey(profile.target)}`;
153 default:
154 return null;
155 }
156}
157
158export function connectionRouteLabel(route: ConnectionRoute): string {
159 switch (connectionRouteKind(route)) {
160 case "relay":
161 return "T3 Connect";
162 case "loopback":
163 return "This device";
164 case "lan":
165 return "LAN";
166 case "tailnet":
167 return "Tailscale";
168 case "vpn":
169 return "VPN";
170 case "ssh": {
171 const profile = Option.getOrNull(route.profile);
172 return profile?._tag === "SshConnectionProfile"
173 ? `SSH ${profile.target.username ? `${profile.target.username}@` : ""}${profile.target.hostname}`
174 : "SSH";
175 }
176 case "public":
177 return routeHostname(route) ?? "Remote link";
178 }
179}
180
181export function connectionRouteAddress(route: ConnectionRoute): string | null {
182 if (route.target._tag === "SshConnectionTarget") {
183 const profile = Option.getOrNull(route.profile);
184 return profile?._tag === "SshConnectionProfile" ? profile.target.alias : null;
185 }
186 return routeHttpBaseUrl(route);
187}
188
189export function hasRelayRoute(
190 entry: Pick<ConnectionCatalogEntry, "target" | "alternateRoutes">,
191): boolean {
192 return [entry.target, ...(entry.alternateRoutes ?? []).map((route) => route.target)].some(
193 (target) => target._tag === "RelayConnectionTarget",
194 );
195}
196
197export function mergeLearnedRoutes(input: {
198 readonly entry: ConnectionCatalogEntry;
199 readonly activeRoute: ConnectionRoute;
200 readonly reported: ReadonlyArray<ReportedEndpoint>;
201 /** Plain HTTP routes are unusable from an HTTPS page (mixed content). */
202 readonly allowInsecure: boolean;
203}): ReadonlyArray<ConnectionRoute> | null {
204 const { entry } = input;
205 const active = input.activeRoute.target;
206 const saved = connectionRoutes(entry);
207 if (active._tag !== "RelayConnectionTarget" && active._tag !== "BearerConnectionTarget") {
208 return null;
209 }
210 const activeProfile = Option.getOrNull(input.activeRoute.profile);
211 const authorization =
212 active._tag === "RelayConnectionTarget" ||
213 (activeProfile?._tag === "BearerConnectionProfile" &&
214 activeProfile.authorization === "t3-connect")
215 ? ("t3-connect" as const)
216 : undefined;
217 const sharedCredential =
218 authorization === undefined && active._tag === "BearerConnectionTarget"
219 ? credentialConnectionId(active.connectionId)
220 : undefined;
221
222 const reported = new Map<string, URL>();
223 const tailscaleOrigins = new Set<string>();
224 for (const endpoint of input.reported) {
225 let url: URL;
226 try {
227 url = new URL(endpoint.httpBaseUrl);
228 } catch {
229 continue;
230 }
231 if (url.protocol !== "http:" && url.protocol !== "https:") continue;
232 if (url.protocol === "http:" && !input.allowInsecure) continue;
233 // A loopback address names whichever device opens it, never the server.
234 if (isLocalLoopbackHost(url.hostname)) continue;
235 reported.set(url.origin, url);
236 if (endpoint.kind === "tailnet") tailscaleOrigins.add(url.origin);
237 }
238 const normalized = (url: string) => url.replace(/\/+$/, "");
239 const known = new Set(
240 saved.flatMap((route) => {
241 const url = routeHttpBaseUrl(route);
242 return url === null || isLearned(route) ? [] : [normalized(url)];
243 }),
244 );
245 const kept = saved.flatMap((route): ReadonlyArray<ConnectionRoute> => {
246 const url = routeHttpBaseUrl(route);
247 if (!isLearned(route)) {
248 return [
249 url === null || !reported.has(normalized(url))
250 ? route
251 : withNetwork(route, tailscaleOrigins.has(normalized(url))),
252 ];
253 }
254 if (url === null || !reported.has(normalized(url)) || known.has(normalized(url))) return [];
255 known.add(normalized(url));
256 return [withNetwork(route, tailscaleOrigins.has(normalized(url)))];
257 });
258 let next: ReadonlyArray<ConnectionRoute> = kept;
259 for (const url of reported.values()) {
260 if (known.has(url.origin)) continue;
261 const httpBaseUrl = `${url.origin}/`;
262 const connectionId = learnedConnectionId(
263 entry.target.environmentId,
264 url.origin,
265 sharedCredential,
266 );
267 next = insertRoute(next, {
268 target: new BearerConnectionTarget({
269 environmentId: entry.target.environmentId,
270 label: entry.target.label,
271 connectionId,
272 }),
273 profile: Option.some(
274 new BearerConnectionProfile({
275 connectionId,
276 environmentId: entry.target.environmentId,
277 label: entry.target.label,
278 httpBaseUrl,
279 wsBaseUrl: `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}/`,
280 learned: true,
281 ...(authorization === undefined ? {} : { authorization }),
282 ...(tailscaleOrigins.has(url.origin) ? { network: "tailscale" as const } : {}),
283 }),
284 ),
285 });
286 }
287 const signature = (routes: ReadonlyArray<ConnectionRoute>) =>
288 routes
289 .map(
290 (route) =>
291 `${connectionRouteId(route.target)} ${routeHttpBaseUrl(route) ?? ""} ${connectionRouteKind(route)}`,
292 )
293 .join("\n");
294 return signature(saved) === signature(next) ? null : next;
295}
296
297export interface ReportedEndpoint {
298 readonly httpBaseUrl: string;
299 readonly kind?: string;
300}
301
302function withNetwork(route: ConnectionRoute, tailscale: boolean): ConnectionRoute {
303 const profile = Option.getOrNull(route.profile);
304 if (profile?._tag !== "BearerConnectionProfile") return route;
305 if ((profile.network === "tailscale") === tailscale) return route;
306 return {
307 target: route.target,
308 profile: Option.some(
309 new BearerConnectionProfile({
310 connectionId: profile.connectionId,
311 environmentId: profile.environmentId,
312 label: profile.label,
313 httpBaseUrl: profile.httpBaseUrl,
314 wsBaseUrl: profile.wsBaseUrl,
315 ...(profile.learned === undefined ? {} : { learned: profile.learned }),
316 ...(profile.authorization === undefined ? {} : { authorization: profile.authorization }),
317 ...(tailscale ? { network: "tailscale" as const } : {}),
318 }),
319 ),
320 };
321}
322
323function learnedConnectionId(
324 environmentId: string,
325 origin: string,
326 sharedCredential: string | undefined,
327): string {
328 return sharedCredential === undefined
329 ? `learned:${environmentId}:${origin}`
330 : `learned:${environmentId}:${origin}@${sharedCredential}`;
331}
332
333export function credentialConnectionId(connectionId: string): string {
334 const at = connectionId.indexOf("@");
335 return connectionId.startsWith("learned:") && at !== -1
336 ? connectionId.slice(at + 1)
337 : connectionId;
338}
339
340export function isLearned(route: ConnectionRoute): boolean {
341 const profile = Option.getOrNull(route.profile);
342 return profile?._tag === "BearerConnectionProfile" && profile.learned === true;
343}
344
345/**
346 * A learned route borrows the credential of the route it was learned over, so
347 * it cannot outlive that route: removing T3 Connect also removes routes learned
348 * through it, and removing a paired address removes routes that borrow its
349 * token.
350 */
351export function routesAfterRemoving(
352 routes: ReadonlyArray<ConnectionRoute>,
353 removedId: string,
354): ReadonlyArray<ConnectionRoute> {
355 const removed = routes.find((route) => connectionRouteId(route.target) === removedId);
356 if (removed === undefined) return routes;
357 return routes.filter((route) => {
358 if (route === removed) return false;
359 if (!isLearned(route)) return true;
360 const profile = Option.getOrNull(route.profile);
361 if (profile?._tag === "BearerConnectionProfile" && profile.authorization === "t3-connect") {
362 return removed.target._tag !== "RelayConnectionTarget";
363 }
364 return credentialConnectionId(connectionRouteId(route.target)) !== removedId;
365 });
366}
367
368export function removedWithRelay(entry: ConnectionCatalogEntry): boolean {
369 return routesAfterRemoving(connectionRoutes(entry), RELAY_ROUTE_ID).length === 0;
370}
371
372export function sshTargetKey(target: DesktopSshEnvironmentTarget): string {
373 return JSON.stringify([target.alias, target.hostname, target.username, target.port]);
374}