Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

routes.ts

447 lines15.3 KB

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