Open History to see the last commit
1import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { EnvironmentId } from "@t3tools/contracts";
4import { it as effectIt } from "@effect/vitest";
5import type * as NodeOS from "node:os";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Deferred from "effect/Deferred";
9import * as Fiber from "effect/Fiber";
10import * as Ref from "effect/Ref";
11import * as Layer from "effect/Layer";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import * as HttpClient from "effect/http/HttpClient";
15import type * as HttpClientRequest from "effect/http/HttpClientRequest";
16import * as HttpClientResponse from "effect/http/HttpClientResponse";
17import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18import { describe, expect, it } from "vite-plus/test";
19
20import * as ServerConfig from "../config.ts";
21import * as DirectEndpoints from "./DirectEndpoints.ts";
22import * as ServerEnvironment from "./ServerEnvironment.ts";
23import { readIsolatedLinuxBridges, resolveBoundEndpoints } from "./DirectEndpoints.ts";
24
25const INTERFACES: ReturnType<typeof NodeOS.networkInterfaces> = {
26 lo0: [
27 {
28 address: "127.0.0.1",
29 netmask: "255.0.0.0",
30 family: "IPv4",
31 mac: "00:00:00:00:00:00",
32 internal: true,
33 cidr: "127.0.0.1/8",
34 },
35 ],
36 en0: [
37 {
38 address: "192.168.1.10",
39 netmask: "255.255.255.0",
40 family: "IPv4",
41 mac: "aa:bb:cc:dd:ee:ff",
42 internal: false,
43 cidr: "192.168.1.10/24",
44 },
45 {
46 address: "fe80::1",
47 netmask: "ffff:ffff:ffff:ffff::",
48 family: "IPv6",
49 mac: "aa:bb:cc:dd:ee:ff",
50 internal: false,
51 cidr: "fe80::1/64",
52 scopeid: 4,
53 },
54 ],
55 en1: [
56 {
57 address: "203.0.113.20",
58 netmask: "255.255.255.0",
59 family: "IPv4",
60 mac: "aa:bb:cc:dd:ee:00",
61 internal: false,
62 cidr: "203.0.113.20/24",
63 },
64 ],
65 utun4: [
66 {
67 address: "100.101.102.103",
68 netmask: "255.255.255.255",
69 family: "IPv4",
70 mac: "00:00:00:00:00:00",
71 internal: false,
72 cidr: "100.101.102.103/32",
73 },
74 {
75 address: "fd7a:115c:a1e0::1",
76 netmask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
77 family: "IPv6",
78 mac: "00:00:00:00:00:00",
79 internal: false,
80 cidr: "fd7a:115c:a1e0::1/128",
81 scopeid: 0,
82 },
83 ],
84};
85
86const vpnInterface = (address: string) => [
87 {
88 address,
89 netmask: "255.255.255.255",
90 family: "IPv4" as const,
91 mac: "00:00:00:00:00:00",
92 internal: false,
93 cidr: `${address}/32`,
94 },
95];
96
97const virtualInterface = (address: string, mac = "02:42:ac:11:00:01") => [
98 {
99 address,
100 netmask: "255.255.0.0",
101 family: "IPv4" as const,
102 mac,
103 internal: false,
104 cidr: `${address}/16`,
105 },
106];
107
108describe("resolveBoundEndpoints", () => {
109 it("lists every external IPv4 address for a wildcard bind, tagging the tailnet one", () => {
110 expect(
111 resolveBoundEndpoints({
112 platform: "linux",
113 host: "0.0.0.0",
114 port: 3773,
115 interfaces: INTERFACES,
116 }),
117 ).toEqual([
118 { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },
119 { kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" },
120 ]);
121 });
122
123 it("skips container and VM networks, which only this machine reaches", () => {
124 const interfaces = {
125 ...INTERFACES,
126 docker0: virtualInterface("172.17.0.1"),
127 "br-3f2a1b": virtualInterface("172.18.0.1"),
128 virbr0: virtualInterface("192.168.122.1"),
129 "vEthernet (WSL)": virtualInterface("172.24.0.1"),
130 bridge100: virtualInterface("192.168.64.1"),
131 vmbr0: virtualInterface("192.168.1.20"),
132 fhciowner: virtualInterface("10.221.0.1"),
133 };
134 expect(
135 resolveBoundEndpoints({
136 platform: "linux",
137 host: "0.0.0.0",
138 port: 3773,
139 interfaces,
140 isolatedBridges: new Set(["fhciowner"]),
141 }),
142 ).toEqual([
143 { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },
144 { kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" },
145 { kind: "lan", httpBaseUrl: "http://192.168.1.20:3773/" },
146 ]);
147 });
148
149 it("skips NixOS container and systemd-nspawn veths, which only this machine reaches", () => {
150 const interfaces = {
151 ...INTERFACES,
152 "ve-jellyfin": virtualInterface("192.168.53.193"),
153 "ve-qbittorrent": virtualInterface("192.168.55.225"),
154 "vb-jellyfin": virtualInterface("192.168.100.1"),
155 "vz-machine": virtualInterface("192.168.101.1"),
156 };
157 expect(
158 resolveBoundEndpoints({ platform: "linux", host: "0.0.0.0", port: 3773, interfaces }),
159 ).toEqual([
160 { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },
161 { kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" },
162 ]);
163 });
164
165 it("keeps a Windows alias matching a Linux container prefix eligible", () => {
166 const interfaces = {
167 ...INTERFACES,
168 "ve-office": virtualInterface("192.168.1.30"),
169 };
170 expect(
171 resolveBoundEndpoints({ platform: "win32", host: "0.0.0.0", port: 3773, interfaces }),
172 ).toEqual([
173 { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },
174 { kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" },
175 { kind: "lan", httpBaseUrl: "http://192.168.1.30:3773/" },
176 ]);
177 });
178
179 it("omits Windows host-only adapters without excluding guest NICs or explicit binds", () => {
180 const interfaces = {
181 ...INTERFACES,
182 "VirtualBox-Host-Only-Netzwerk": virtualInterface("192.168.56.1", "0A:00:27:00:01:01"),
183 "Ethernet 2": virtualInterface("192.168.150.1", "00:50:56:c0:00:01"),
184 "Renamed network": virtualInterface("192.168.151.1", "00:50:56:c0:00:08"),
185 guest1: virtualInterface("192.168.1.30", "08:00:27:5e:1a:22"),
186 guest2: virtualInterface("192.168.1.31", "00:50:56:2b:8c:01"),
187 guest3: virtualInterface("192.168.1.32", "00:0c:29:4f:8e:35"),
188 guest4: virtualInterface("192.168.1.33", "00:50:56:80:8c:01"),
189 };
190 const input = { host: "0.0.0.0", port: 3773, interfaces };
191 const retained = [
192 { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },
193 { kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" },
194 ...[30, 31, 32, 33].map((last) => ({
195 kind: "lan",
196 httpBaseUrl: `http://192.168.1.${last}:3773/`,
197 })),
198 ];
199 expect(resolveBoundEndpoints({ ...input, platform: "win32" })).toEqual(retained);
200 for (const platform of ["linux", "darwin"] as const) {
201 expect(resolveBoundEndpoints({ ...input, platform })).toHaveLength(retained.length + 3);
202 }
203 for (const host of ["192.168.56.1", "192.168.150.1", "192.168.151.1"]) {
204 expect(resolveBoundEndpoints({ ...input, platform: "win32", host })).toEqual([
205 { kind: "lan", httpBaseUrl: `http://${host}:3773/` },
206 ]);
207 }
208 });
209
210 it("tags only addresses on Tailscale's interface as tailnet, not other VPNs in its range", () => {
211 const interfaces = {
212 en0: INTERFACES.en0,
213 tailscale0: vpnInterface("100.70.1.2"),
214 CloudflareWARP: vpnInterface("100.96.0.1"),
215 utun7: vpnInterface("100.85.0.1"),
216 };
217 expect(
218 resolveBoundEndpoints({ platform: "linux", host: "0.0.0.0", port: 3773, interfaces }),
219 ).toEqual([
220 { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },
221 { kind: "tailnet", httpBaseUrl: "http://100.70.1.2:3773/" },
222 { kind: "lan", httpBaseUrl: "http://100.96.0.1:3773/" },
223 { kind: "lan", httpBaseUrl: "http://100.85.0.1:3773/" },
224 ]);
225 });
226
227 it("never reports a host name, which can resolve to another machine per client", () => {
228 for (const host of ["server.local", "devbox", "devbox.home.arpa"]) {
229 expect(
230 resolveBoundEndpoints({ platform: "linux", host, port: 3773, interfaces: INTERFACES }),
231 ).toEqual([]);
232 }
233 });
234
235 it("never reports a public address, which would carry the credential over plain HTTP", () => {
236 expect(
237 resolveBoundEndpoints({
238 platform: "linux",
239 host: "203.0.113.20",
240 port: 3773,
241 interfaces: INTERFACES,
242 }),
243 ).toEqual([]);
244 });
245
246 it("reports only the tailnet address on a cloud VM, whose private network no client shares", () => {
247 expect(
248 resolveBoundEndpoints({
249 platform: "linux",
250 host: "0.0.0.0",
251 port: 3773,
252 interfaces: INTERFACES,
253 onCloudVm: true,
254 }),
255 ).toEqual([{ kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" }]);
256 });
257
258 it("reports an explicit bind to Tailscale's IPv6 address as the tailnet route", () => {
259 expect(
260 resolveBoundEndpoints({
261 platform: "linux",
262 host: "fd7a:115c:a1e0::1",
263 port: 3773,
264 interfaces: INTERFACES,
265 }),
266 ).toEqual([{ kind: "tailnet", httpBaseUrl: "http://[fd7a:115c:a1e0::1]:3773/" }]);
267 });
268
269 it("never reports an IPv4-mapped host, which can name the client's own loopback", () => {
270 expect(
271 resolveBoundEndpoints({
272 platform: "linux",
273 host: "::ffff:127.0.0.1",
274 port: 3773,
275 interfaces: INTERFACES,
276 }),
277 ).toEqual([]);
278 });
279});
280
281describe("readIsolatedLinuxBridges", () => {
282 effectIt.effect("finds bridges whose ports never reach a NIC, under any name", () =>
283 Effect.gen(function* () {
284 const fs = yield* FileSystem.FileSystem;
285 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sysfs-" });
286 const dirs = [
287 "eth0/device",
288 "eth1/device",
289 "bond0/lower_eth1",
290 "veth1",
291 "br0/bridge",
292 "br0/brif/eth0",
293 "vmbr0/bridge",
294 "vmbr0/brif/bond0",
295 "fhciowner/bridge",
296 "fhciowner/brif/veth1",
297 "virbr0/bridge",
298 ];
299 for (const dir of dirs) yield* fs.makeDirectory(`${root}/${dir}`, { recursive: true });
300 const names = ["eth0", "bond0", "veth1", "br0", "vmbr0", "fhciowner", "virbr0"];
301 expect([...(yield* readIsolatedLinuxBridges(names, root))].toSorted()).toEqual([
302 "fhciowner",
303 "virbr0",
304 ]);
305 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
306 );
307});
308
309const TAILSCALE_STATUS_JSON = JSON.stringify({
310 Self: { DNSName: "bb-1.tail1234.ts.net.", TailscaleIPs: ["100.64.1.2"] },
311});
312
313const layerTailscaleUp = Layer.succeed(
314 ChildProcessSpawner.ChildProcessSpawner,
315 ChildProcessSpawner.make(() =>
316 Effect.succeed(
317 ChildProcessSpawner.makeHandle({
318 pid: ChildProcessSpawner.ProcessId(1),
319 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
320 isRunning: Effect.succeed(false),
321 kill: () => Effect.void,
322 unref: Effect.succeed(Effect.void),
323 stdin: Sink.drain,
324 stdout: Stream.make(new TextEncoder().encode(TAILSCALE_STATUS_JSON)),
325 stderr: Stream.empty,
326 all: Stream.empty,
327 getInputFd: () => Sink.drain,
328 getOutputFd: () => Stream.empty,
329 }),
330 ),
331 ),
332);
333
334const T3_DESCRIPTOR_BODY = JSON.stringify({
335 environmentId: "serve-test",
336 label: "Serve test",
337 platform: { os: "darwin", arch: "arm64" },
338 serverVersion: "0.0.0-test",
339 capabilities: { repositoryIdentity: true },
340});
341
342const serveProbeResponse = (request: HttpClientRequest.HttpClientRequest, status: number) =>
343 HttpClientResponse.fromWeb(
344 request,
345 new Response(status === 200 ? T3_DESCRIPTOR_BODY : null, { status }),
346 );
347
348const layerServeProbe = (status: number) =>
349 Layer.succeed(
350 HttpClient.HttpClient,
351 HttpClient.make((request) => Effect.succeed(serveProbeResponse(request, status))),
352 );
353
354const layerServeConfig = (host = "127.0.0.1") =>
355 Layer.effect(
356 ServerConfig.ServerConfig,
357 Effect.map(ServerConfig.ServerConfig, (config) => ({
358 ...config,
359 host,
360 port: 3773,
361 tailscaleServeEnabled: true,
362 tailscaleServePort: 443,
363 })),
364 ).pipe(
365 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-direct-" })),
366 Layer.provide(NodeServices.layer),
367 Layer.merge(
368 Layer.succeed(ServerEnvironment.ServerEnvironment, {
369 getEnvironmentId: Effect.succeed(EnvironmentId.make("serve-test")),
370 getDescriptor: Effect.die("unused"),
371 }),
372 ),
373 );
374
375const resolveWithServe = (probeStatus: number) =>
376 Effect.flatMap(DirectEndpoints.DirectEndpoints, (service) => service.resolve()).pipe(
377 Effect.provide(
378 DirectEndpoints.layer.pipe(
379 Layer.provide(
380 Layer.mergeAll(
381 layerServeConfig(),
382 layerTailscaleUp,
383 layerServeProbe(probeStatus),
384 NodeFileSystem.layer,
385 ),
386 ),
387 ),
388 ),
389 );
390
391describe("DirectEndpoints Tailscale Serve", () => {
392 effectIt.effect("lists the tailnet name once Serve answers for this server", () =>
393 Effect.gen(function* () {
394 expect(yield* resolveWithServe(200)).toEqual([
395 { kind: "tailnet", httpBaseUrl: "https://bb-1.tail1234.ts.net/" },
396 ]);
397 }),
398 );
399
400 effectIt.effect(
401 "returns bound endpoints during validation and reuses only a completed Serve result",
402 () =>
403 Effect.gen(function* () {
404 const status = yield* Ref.make(200);
405 const finishProbe = yield* Deferred.make<void>();
406 const probeStarted = yield* Deferred.make<void>();
407 const revalidationStarted = yield* Deferred.make<void>();
408 const finishRevalidation = yield* Deferred.make<void>();
409 const service = yield* DirectEndpoints.make.pipe(
410 Effect.provide(
411 Layer.mergeAll(
412 layerServeConfig("192.168.1.10"),
413 NodeFileSystem.layer,
414 layerTailscaleUp,
415 Layer.succeed(
416 HttpClient.HttpClient,
417 HttpClient.make((request) =>
418 Deferred.succeed(probeStarted, undefined).pipe(
419 Effect.andThen(Deferred.await(finishProbe)),
420 Effect.andThen(Ref.get(status)),
421 Effect.tap((status) =>
422 status === 502
423 ? Deferred.succeed(revalidationStarted, undefined).pipe(
424 Effect.andThen(Deferred.await(finishRevalidation)),
425 )
426 : Effect.void,
427 ),
428 Effect.map((status) => serveProbeResponse(request, status)),
429 ),
430 ),
431 ),
432 ),
433 ),
434 );
435 const resolving = yield* Effect.forkScoped(service.resolve());
436 yield* Deferred.await(probeStarted);
437 const bound = { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" };
438 expect(yield* service.resolveAvailable()).toEqual([bound]);
439 yield* Deferred.succeed(finishProbe, undefined);
440 const validated = yield* Fiber.join(resolving);
441 expect(validated).toEqual([
442 bound,
443 { kind: "tailnet", httpBaseUrl: "https://bb-1.tail1234.ts.net/" },
444 ]);
445 expect(yield* service.resolveAvailable()).toEqual(validated);
446 yield* Ref.set(status, 502);
447 const revalidating = yield* Effect.forkScoped(service.resolve());
448 yield* Deferred.await(revalidationStarted);
449 expect(yield* service.resolveAvailable()).toEqual(validated);
450 yield* Deferred.succeed(finishRevalidation, undefined);
451 expect(yield* Fiber.join(revalidating)).toEqual([bound]);
452 expect(yield* service.resolveAvailable()).toEqual([bound]);
453 }),
454 );
455
456 effectIt.effect("leaves the tailnet name out when Serve is not forwarding", () =>
457 Effect.gen(function* () {
458 expect(yield* resolveWithServe(502)).toEqual([]);
459 }),
460 );
461});