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