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 { aheadOfSameKind = false }: { readonly aheadOfSameKind?: boolean } = {},
119): ReadonlyArray<ConnectionRoute> {
120 const kind = connectionRouteKind(route);
121 const rank = ROUTE_KIND_RANK[kind];
122 const index = routes.findIndex((existing) => {
123 const existingKind = connectionRouteKind(existing);
124 return ROUTE_KIND_RANK[existingKind] > rank || (aheadOfSameKind && existingKind === kind);
125 });
126 return index === -1
127 ? [...routes, route]
128 : [...routes.slice(0, index), route, ...routes.slice(index)];
129}
130
131export function upsertRoute(
132 routes: ReadonlyArray<ConnectionRoute>,
133 route: ConnectionRoute,
134): ReadonlyArray<ConnectionRoute> {
135 const id = connectionRouteId(route.target);
136 return routes.some((existing) => connectionRouteId(existing.target) === id)
137 ? routes.map((existing) => (connectionRouteId(existing.target) === id ? route : existing))
138 : // A route paired at a new address, such as localhost beside a saved
139 // 127.0.0.1, goes first among its kind so its fresh credential connects.
140 insertRoute(routes, route, { aheadOfSameKind: true });
141}
142
143export function findRouteToSameAddress(
144 routes: ReadonlyArray<ConnectionRoute>,
145 route: ConnectionRoute,
146): ConnectionRoute | undefined {
147 const key = routeAddressKey(route);
148 return key === null ? undefined : routes.find((existing) => routeAddressKey(existing) === key);
149}
150
151function routeAddressKey(route: ConnectionRoute): string | null {
152 const profile = Option.getOrNull(route.profile);
153 switch (profile?._tag) {
154 case "BearerConnectionProfile":
155 return `bearer:${profile.httpBaseUrl.replace(/\/+$/, "")}`;
156 case "SshConnectionProfile":
157 return `ssh:${sshTargetKey(profile.target)}`;
158 default:
159 return null;
160 }
161}
162
163export function connectionRouteLabel(route: ConnectionRoute): string {
164 switch (connectionRouteKind(route)) {
165 case "relay":
166 return "T3 Connect";
167 case "loopback":
168 return "This device";
169 case "lan":
170 return "LAN";
171 case "tailnet":
172 return "Tailscale";
173 case "vpn":
174 return "VPN";
175 case "ssh": {
176 const profile = Option.getOrNull(route.profile);
177 return profile?._tag === "SshConnectionProfile"
178 ? `SSH ${profile.target.username ? `${profile.target.username}@` : ""}${profile.target.hostname}`
179 : "SSH";
180 }
181 case "public":
182 return routeHostname(route) ?? "Remote link";
183 }
184}
185
186export function connectionRouteAddress(route: ConnectionRoute): string | null {
187 if (route.target._tag === "SshConnectionTarget") {
188 const profile = Option.getOrNull(route.profile);
189 return profile?._tag === "SshConnectionProfile" ? profile.target.alias : null;
190 }
191 return routeHttpBaseUrl(route);
192}
193
194/** Learned routes alone must not make relay environments manually retryable. */
195export const hasSavedBearerRoute = (entry: ConnectionCatalogEntry) =>
196 connectionRoutes(entry).some((r) => !isLearned(r) && r.target._tag === "BearerConnectionTarget");
197
198export function hasRelayRoute(
199 entry: Pick<ConnectionCatalogEntry, "target" | "alternateRoutes">,
200): boolean {
201 return [entry.target, ...(entry.alternateRoutes ?? []).map((route) => route.target)].some(
202 (target) => target._tag === "RelayConnectionTarget",
203 );
204}
205
206export function mergeLearnedRoutes(input: {
207 readonly entry: ConnectionCatalogEntry;
208 readonly activeRoute: ConnectionRoute;
209 readonly reported: ReadonlyArray<ReportedEndpoint>;
210 /** Plain HTTP routes are unusable from an HTTPS page (mixed content). */
211 readonly allowInsecure: boolean;
212}): ReadonlyArray<ConnectionRoute> | null {
213 const { entry } = input;
214 const active = input.activeRoute.target;
215 const saved = connectionRoutes(entry);
216 if (active._tag !== "RelayConnectionTarget" && active._tag !== "BearerConnectionTarget") {
217 return null;
218 }
219 const activeProfile = Option.getOrNull(input.activeRoute.profile);
220 const authorization =
221 active._tag === "RelayConnectionTarget" ||
222 (activeProfile?._tag === "BearerConnectionProfile" &&
223 activeProfile.authorization === "t3-connect")
224 ? ("t3-connect" as const)
225 : undefined;
226 const sharedCredential =
227 authorization === undefined && active._tag === "BearerConnectionTarget"
228 ? credentialConnectionId(active.connectionId)
229 : undefined;
230 const reported = new Map<string, URL>();
231 const tailscaleOrigins = new Set<string>();
232 for (const endpoint of input.reported) {
233 let url: URL;
234 try {
235 url = new URL(endpoint.httpBaseUrl);
236 } catch {
237 continue;
238 }
239 if (url.protocol !== "http:" && url.protocol !== "https:") continue;
240 if (url.protocol === "http:" && !input.allowInsecure) continue;
241 // A loopback address names whichever device opens it, never the server.
242 if (isLocalLoopbackHost(url.hostname)) continue;
243 reported.set(url.origin, url);
244 if (endpoint.kind === "tailnet") tailscaleOrigins.add(url.origin);
245 }
246 const normalized = (url: string) => url.replace(/\/+$/, "");
247 const known = new Set(
248 saved.flatMap((route) => {
249 const url = routeHttpBaseUrl(route);
250 return url === null || isLearned(route) ? [] : [normalized(url)];
251 }),
252 );
253 const kept = saved.flatMap((route): ReadonlyArray<ConnectionRoute> => {
254 const url = routeHttpBaseUrl(route);
255 if (!isLearned(route)) {
256 return [
257 url === null || !reported.has(normalized(url))
258 ? route
259 : withNetwork(route, tailscaleOrigins.has(normalized(url))),
260 ];
261 }
262 if (url === null || !reported.has(normalized(url)) || known.has(normalized(url))) return [];
263 if (sendsTokenInClear(saved, route, tailscaleOrigins.has(normalized(url)))) return [];
264 known.add(normalized(url));
265 return [withNetwork(route, tailscaleOrigins.has(normalized(url)))];
266 });
267 let next: ReadonlyArray<ConnectionRoute> = kept;
268 for (const url of reported.values()) {
269 if (known.has(url.origin)) continue;
270 if (
271 url.protocol === "http:" &&
272 sharedCredential !== undefined &&
273 !tailscaleOrigins.has(url.origin) &&
274 !tokenAllowsPlainHttp(saved, sharedCredential)
275 ) {
276 continue;
277 }
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 ...(tailscaleOrigins.has(url.origin) ? { network: "tailscale" as const } : {}),
300 }),
301 ),
302 });
303 }
304 const signature = (routes: ReadonlyArray<ConnectionRoute>) =>
305 routes
306 .map(
307 (route) =>
308 `${connectionRouteId(route.target)} ${routeHttpBaseUrl(route) ?? ""} ${connectionRouteKind(route)}`,
309 )
310 .join("\n");
311 return signature(saved) === signature(next) ? null : next;
312}
313
314// A paired token goes to a plain HTTP address outside the tailnet only when
315// it was paired that way, so a token paired over HTTPS, loopback, or the
316// tailnet keeps to the transports it was issued for.
317function tokenAllowsPlainHttp(
318 routes: ReadonlyArray<ConnectionRoute>,
319 credentialId: string,
320): boolean {
321 const credentialRoute = routes.find((route) => connectionRouteId(route.target) === credentialId);
322 return (
323 credentialRoute !== undefined &&
324 routeHttpBaseUrl(credentialRoute)?.startsWith("http:") === true &&
325 (connectionRouteKind(credentialRoute) === "lan" ||
326 connectionRouteKind(credentialRoute) === "public")
327 );
328}
329
330/**
331 * Whether connecting over `route` would send a paired token over plain HTTP
332 * that it wasn't paired over. Checked against the token the route borrows,
333 * so a route learned before this rule existed is refused too.
334 */
335export function sendsTokenInClear(
336 routes: ReadonlyArray<ConnectionRoute>,
337 route: ConnectionRoute,
338 tailscale?: boolean,
339): boolean {
340 const profile = Option.getOrNull(route.profile);
341 if (profile?._tag !== "BearerConnectionProfile" || profile.authorization === "t3-connect") {
342 return false;
343 }
344 if ((tailscale ?? profile.network === "tailscale") || !profile.httpBaseUrl.startsWith("http:")) {
345 return false;
346 }
347 const credentialId = credentialConnectionId(connectionRouteId(route.target));
348 return (
349 credentialId !== connectionRouteId(route.target) && !tokenAllowsPlainHttp(routes, credentialId)
350 );
351}
352
353/** Routes a connect may use: none sends a paired token over plain HTTP it wasn't paired over. */
354export function usableRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {
355 const routes = connectionRoutes(entry);
356 return routes.filter((route) => !sendsTokenInClear(routes, route));
357}
358
359export interface ReportedEndpoint {
360 readonly httpBaseUrl: string;
361 readonly kind?: string;
362}
363
364function withNetwork(route: ConnectionRoute, tailscale: boolean): ConnectionRoute {
365 const profile = Option.getOrNull(route.profile);
366 if (profile?._tag !== "BearerConnectionProfile") return route;
367 if ((profile.network === "tailscale") === tailscale) return route;
368 return {
369 target: route.target,
370 profile: Option.some(
371 new BearerConnectionProfile({
372 connectionId: profile.connectionId,
373 environmentId: profile.environmentId,
374 label: profile.label,
375 httpBaseUrl: profile.httpBaseUrl,
376 wsBaseUrl: profile.wsBaseUrl,
377 ...(profile.learned === undefined ? {} : { learned: profile.learned }),
378 ...(profile.authorization === undefined ? {} : { authorization: profile.authorization }),
379 ...(tailscale ? { network: "tailscale" as const } : {}),
380 }),
381 ),
382 };
383}
384
385function learnedConnectionId(
386 environmentId: string,
387 origin: string,
388 sharedCredential: string | undefined,
389): string {
390 return sharedCredential === undefined
391 ? `learned:${environmentId}:${origin}`
392 : `learned:${environmentId}:${origin}@${sharedCredential}`;
393}
394
395export function credentialConnectionId(connectionId: string): string {
396 const at = connectionId.indexOf("@");
397 return connectionId.startsWith("learned:") && at !== -1
398 ? connectionId.slice(at + 1)
399 : connectionId;
400}
401
402export function isLearned(route: ConnectionRoute): boolean {
403 const profile = Option.getOrNull(route.profile);
404 return profile?._tag === "BearerConnectionProfile" && profile.learned === true;
405}
406
407/**
408 * A learned route borrows the credential of the route it was learned over, so
409 * it cannot outlive that route: removing T3 Connect also removes routes learned
410 * through it, and removing a paired address removes routes that borrow its
411 * token.
412 */
413export function routesAfterRemoving(
414 routes: ReadonlyArray<ConnectionRoute>,
415 removedId: string,
416): ReadonlyArray<ConnectionRoute> {
417 const removed = routes.find((route) => connectionRouteId(route.target) === removedId);
418 if (removed === undefined) return routes;
419 return routes.filter((route) => {
420 if (route === removed) return false;
421 if (!isLearned(route)) return true;
422 const profile = Option.getOrNull(route.profile);
423 if (profile?._tag === "BearerConnectionProfile" && profile.authorization === "t3-connect") {
424 return removed.target._tag !== "RelayConnectionTarget";
425 }
426 return credentialConnectionId(connectionRouteId(route.target)) !== removedId;
427 });
428}
429
430/**
431 * A dragged route order shows until the saved routes catch up with it. It is
432 * stale, and returns null, once the saved order matches it or the saved routes
433 * are no longer the same set: kept any longer, it would hide a route added
434 * later whenever the count happened to match again.
435 */
436export function pendingRouteOrder(
437 pending: ReadonlyArray<string> | null,
438 savedIds: ReadonlyArray<string>,
439): ReadonlyArray<string> | null {
440 if (pending === null || pending.length !== savedIds.length) return null;
441 const saved = new Set(savedIds);
442 if (!pending.every((id) => saved.has(id))) return null;
443 return pending.some((id, index) => id !== savedIds[index]) ? pending : null;
444}
445
446export function removedWithRelay(entry: ConnectionCatalogEntry): boolean {
447 return routesAfterRemoving(connectionRoutes(entry), RELAY_ROUTE_ID).length === 0;
448}
449
450export function sshTargetKey(target: DesktopSshEnvironmentTarget): string {
451 return JSON.stringify([target.alias, target.hostname, target.username, target.port]);
452}