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

routes.ts

427 lines14.4 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​
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 );
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 const reported = new Map<string, URL>();
222 const tailscaleOrigins = new Set<string>();
223 for (const endpoint of input.reported) {
224 let url: URL;
225 try {
226 url = new URL(endpoint.httpBaseUrl);
227 } catch {
228 continue;
229 }
230 if (url.protocol !== "http:" && url.protocol !== "https:") continue;
231 if (url.protocol === "http:" && !input.allowInsecure) continue;
232 // A loopback address names whichever device opens it, never the server.
233 if (isLocalLoopbackHost(url.hostname)) continue;
234 reported.set(url.origin, url);
235 if (endpoint.kind === "tailnet") tailscaleOrigins.add(url.origin);
236 }
237 const normalized = (url: string) => url.replace(/\/+$/, "");
238 const known = new Set(
239 saved.flatMap((route) => {
240 const url = routeHttpBaseUrl(route);
241 return url === null || isLearned(route) ? [] : [normalized(url)];
242 }),
243 );
244 const kept = saved.flatMap((route): ReadonlyArray<ConnectionRoute> => {
245 const url = routeHttpBaseUrl(route);
246 if (!isLearned(route)) {
247 return [
248 url === null || !reported.has(normalized(url))
249 ? route
250 : withNetwork(route, tailscaleOrigins.has(normalized(url))),
251 ];
252 }
253 if (url === null || !reported.has(normalized(url)) || known.has(normalized(url))) return [];
254 if (sendsTokenInClear(saved, route, tailscaleOrigins.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 if (
262 url.protocol === "http:" &&
263 sharedCredential !== undefined &&
264 !tailscaleOrigins.has(url.origin) &&
265 !tokenAllowsPlainHttp(saved, sharedCredential)
266 ) {
267 continue;
268 }
269 const httpBaseUrl = `${url.origin}/`;
270 const connectionId = learnedConnectionId(
271 entry.target.environmentId,
272 url.origin,
273 sharedCredential,
274 );
275 next = insertRoute(next, {
276 target: new BearerConnectionTarget({
277 environmentId: entry.target.environmentId,
278 label: entry.target.label,
279 connectionId,
280 }),
281 profile: Option.some(
282 new BearerConnectionProfile({
283 connectionId,
284 environmentId: entry.target.environmentId,
285 label: entry.target.label,
286 httpBaseUrl,
287 wsBaseUrl: `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}/`,
288 learned: true,
289 ...(authorization === undefined ? {} : { authorization }),
290 ...(tailscaleOrigins.has(url.origin) ? { network: "tailscale" as const } : {}),
291 }),
292 ),
293 });
294 }
295 const signature = (routes: ReadonlyArray<ConnectionRoute>) =>
296 routes
297 .map(
298 (route) =>
299 `${connectionRouteId(route.target)} ${routeHttpBaseUrl(route) ?? ""} ${connectionRouteKind(route)}`,
300 )
301 .join("\n");
302 return signature(saved) === signature(next) ? null : next;
304​
305// A paired token goes to a plain HTTP address outside the tailnet only when
306// it was paired that way, so a token paired over HTTPS, loopback, or the
307// tailnet keeps to the transports it was issued for.
308function tokenAllowsPlainHttp(
309 routes: ReadonlyArray<ConnectionRoute>,
310 credentialId: string,
311): boolean {
312 const credentialRoute = routes.find((route) => connectionRouteId(route.target) === credentialId);
313 return (
314 credentialRoute !== undefined &&
315 routeHttpBaseUrl(credentialRoute)?.startsWith("http:") === true &&
316 (connectionRouteKind(credentialRoute) === "lan" ||
317 connectionRouteKind(credentialRoute) === "public")
318 );
320​
321/**
322 * Whether connecting over `route` would send a paired token over plain HTTP
323 * that it wasn't paired over. Checked against the token the route borrows,
324 * so a route learned before this rule existed is refused too.
325 */
326export function sendsTokenInClear(
327 routes: ReadonlyArray<ConnectionRoute>,
328 route: ConnectionRoute,
329 tailscale?: boolean,
330): boolean {
331 const profile = Option.getOrNull(route.profile);
332 if (profile?._tag !== "BearerConnectionProfile" || profile.authorization === "t3-connect") {
333 return false;
334 }
335 if ((tailscale ?? profile.network === "tailscale") || !profile.httpBaseUrl.startsWith("http:")) {
336 return false;
337 }
338 const credentialId = credentialConnectionId(connectionRouteId(route.target));
339 return (
340 credentialId !== connectionRouteId(route.target) && !tokenAllowsPlainHttp(routes, credentialId)
341 );
343​
344/** Routes a connect may use: none sends a paired token over plain HTTP it wasn't paired over. */
345export function usableRoutes(entry: ConnectionCatalogEntry): ReadonlyArray<ConnectionRoute> {
346 const routes = connectionRoutes(entry);
347 return routes.filter((route) => !sendsTokenInClear(routes, route));
349​
350export interface ReportedEndpoint {
351 readonly httpBaseUrl: string;
352 readonly kind?: string;
354​
355function withNetwork(route: ConnectionRoute, tailscale: boolean): ConnectionRoute {
356 const profile = Option.getOrNull(route.profile);
357 if (profile?._tag !== "BearerConnectionProfile") return route;
358 if ((profile.network === "tailscale") === tailscale) return route;
359 return {
360 target: route.target,
361 profile: Option.some(
362 new BearerConnectionProfile({
363 connectionId: profile.connectionId,
364 environmentId: profile.environmentId,
365 label: profile.label,
366 httpBaseUrl: profile.httpBaseUrl,
367 wsBaseUrl: profile.wsBaseUrl,
368 ...(profile.learned === undefined ? {} : { learned: profile.learned }),
369 ...(profile.authorization === undefined ? {} : { authorization: profile.authorization }),
370 ...(tailscale ? { network: "tailscale" as const } : {}),
371 }),
372 ),
373 };
375​
376function learnedConnectionId(
377 environmentId: string,
378 origin: string,
379 sharedCredential: string | undefined,
380): string {
381 return sharedCredential === undefined
382 ? `learned:${environmentId}:${origin}`
383 : `learned:${environmentId}:${origin}@${sharedCredential}`;
385​
386export function credentialConnectionId(connectionId: string): string {
387 const at = connectionId.indexOf("@");
388 return connectionId.startsWith("learned:") && at !== -1
389 ? connectionId.slice(at + 1)
390 : connectionId;
392​
393export function isLearned(route: ConnectionRoute): boolean {
394 const profile = Option.getOrNull(route.profile);
395 return profile?._tag === "BearerConnectionProfile" && profile.learned === true;
397​
398/**
399 * A learned route borrows the credential of the route it was learned over, so
400 * it cannot outlive that route: removing T3 Connect also removes routes learned
401 * through it, and removing a paired address removes routes that borrow its
402 * 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 });
420​
421export function removedWithRelay(entry: ConnectionCatalogEntry): boolean {
422 return routesAfterRemoving(connectionRoutes(entry), RELAY_ROUTE_ID).length === 0;
424​
425export function sshTargetKey(target: DesktopSshEnvironmentTarget): string {
426 return JSON.stringify([target.alias, target.hostname, target.username, target.port]);