Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it as effectIt } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as NetService from "@t3tools/shared/Net";
5import type * as NodeOS from "node:os";
6import * as Context from "effect/Context";
7import * as Effect from "effect/Effect";
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 * as HttpClientResponse from "effect/http/HttpClientResponse";
16import * as ChildProcess from "effect/process/ChildProcess";
17import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18import * as TestClock from "effect/testing/TestClock";
19import { describe, expect, it } from "vite-plus/test";
20
21import * as ServerConfig from "../config.ts";
22import * as DirectEndpoints from "./DirectEndpoints.ts";
23import { resolveBoundEndpoints } from "./DirectEndpoints.ts";
24import * as RemoteOpenTargets from "./RemoteOpenTargets.ts";
25import * as TailscaleStatusReader from "./TailscaleStatusReader.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("omits Windows host-only adapters without excluding guest NICs or explicit binds", () => {
145 const interfaces = {
146 ...INTERFACES,
147 "VirtualBox-Host-Only-Netzwerk": virtualInterface("192.168.56.1", "0A:00:27:00:01:01"),
148 "Ethernet 2": virtualInterface("192.168.150.1", "00:50:56:c0:00:01"),
149 "Renamed network": virtualInterface("192.168.151.1", "00:50:56:c0:00:08"),
150 guest1: virtualInterface("192.168.1.30", "08:00:27:5e:1a:22"),
151 guest2: virtualInterface("192.168.1.31", "00:50:56:2b:8c:01"),
152 guest3: virtualInterface("192.168.1.32", "00:0c:29:4f:8e:35"),
153 guest4: virtualInterface("192.168.1.33", "00:50:56:80:8c:01"),
154 };
155 const input = { host: "0.0.0.0", port: 3773, interfaces };
156 const retained = [
157 { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },
158 { kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" },
159 ...[30, 31, 32, 33].map((last) => ({
160 kind: "lan",
161 httpBaseUrl: `http://192.168.1.${last}:3773/`,
162 })),
163 ];
164 expect(resolveBoundEndpoints({ ...input, platform: "win32" })).toEqual(retained);
165 for (const platform of ["linux", "darwin"] as const) {
166 expect(resolveBoundEndpoints({ ...input, platform })).toHaveLength(retained.length + 3);
167 }
168 for (const host of ["192.168.56.1", "192.168.150.1", "192.168.151.1"]) {
169 expect(resolveBoundEndpoints({ ...input, platform: "win32", host })).toEqual([
170 { kind: "lan", httpBaseUrl: `http://${host}:3773/` },
171 ]);
172 }
173 });
174
175 it("tags only addresses on Tailscale's interface as tailnet, not other VPNs in its range", () => {
176 const interfaces = {
177 en0: INTERFACES.en0,
178 tailscale0: vpnInterface("100.70.1.2"),
179 CloudflareWARP: vpnInterface("100.96.0.1"),
180 utun7: vpnInterface("100.85.0.1"),
181 };
182 expect(
183 resolveBoundEndpoints({ platform: "linux", host: "0.0.0.0", port: 3773, interfaces }),
184 ).toEqual([
185 { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" },
186 { kind: "tailnet", httpBaseUrl: "http://100.70.1.2:3773/" },
187 { kind: "lan", httpBaseUrl: "http://100.96.0.1:3773/" },
188 { kind: "lan", httpBaseUrl: "http://100.85.0.1:3773/" },
189 ]);
190 });
191
192 it("never reports a host name, which can resolve to another machine per client", () => {
193 for (const host of ["server.local", "devbox", "devbox.home.arpa"]) {
194 expect(
195 resolveBoundEndpoints({ platform: "linux", host, port: 3773, interfaces: INTERFACES }),
196 ).toEqual([]);
197 }
198 });
199
200 it("never reports a public address, which would carry the credential over plain HTTP", () => {
201 expect(
202 resolveBoundEndpoints({
203 platform: "linux",
204 host: "203.0.113.20",
205 port: 3773,
206 interfaces: INTERFACES,
207 }),
208 ).toEqual([]);
209 });
210
211 it("reports only the tailnet address on a cloud VM, whose private network no client shares", () => {
212 expect(
213 resolveBoundEndpoints({
214 platform: "linux",
215 host: "0.0.0.0",
216 port: 3773,
217 interfaces: INTERFACES,
218 onCloudVm: true,
219 }),
220 ).toEqual([{ kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" }]);
221 });
222
223 it("never reports an IPv4-mapped host, which can name the client's own loopback", () => {
224 expect(
225 resolveBoundEndpoints({
226 platform: "linux",
227 host: "::ffff:127.0.0.1",
228 port: 3773,
229 interfaces: INTERFACES,
230 }),
231 ).toEqual([]);
232 });
233});
234
235const TAILSCALE_STATUS_JSON = JSON.stringify({
236 Self: { DNSName: "bb-1.tail1234.ts.net.", TailscaleIPs: ["100.64.1.2"] },
237});
238
239const layerTailscaleUp = Layer.succeed(
240 ChildProcessSpawner.ChildProcessSpawner,
241 ChildProcessSpawner.make(() =>
242 Effect.succeed(
243 ChildProcessSpawner.makeHandle({
244 pid: ChildProcessSpawner.ProcessId(1),
245 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
246 isRunning: Effect.succeed(false),
247 kill: () => Effect.void,
248 unref: Effect.succeed(Effect.void),
249 stdin: Sink.drain,
250 stdout: Stream.make(new TextEncoder().encode(TAILSCALE_STATUS_JSON)),
251 stderr: Stream.empty,
252 all: Stream.empty,
253 getInputFd: () => Sink.drain,
254 getOutputFd: () => Stream.empty,
255 }),
256 ),
257 ),
258);
259
260const layerServeProbe = (status: number) =>
261 Layer.succeed(
262 HttpClient.HttpClient,
263 HttpClient.make((request) =>
264 Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status }))),
265 ),
266 );
267
268const layerServeConfig = (host = "127.0.0.1") =>
269 Layer.effect(
270 ServerConfig.ServerConfig,
271 Effect.map(ServerConfig.ServerConfig, (config) => ({
272 ...config,
273 host,
274 port: 3773,
275 tailscaleServeEnabled: true,
276 tailscaleServePort: 443,
277 })),
278 ).pipe(
279 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-direct-" })),
280 Layer.provide(NodeServices.layer),
281 );
282
283const resolveWithServe = (probeStatus: number) =>
284 Effect.flatMap(DirectEndpoints.DirectEndpoints, (service) => service.resolve()).pipe(
285 Effect.provide(
286 DirectEndpoints.layer.pipe(
287 Layer.provide(TailscaleStatusReader.layer),
288 Layer.provide(
289 Layer.mergeAll(layerServeConfig(), layerTailscaleUp, layerServeProbe(probeStatus)),
290 ),
291 ),
292 ),
293 );
294
295describe("DirectEndpoints Tailscale Serve", () => {
296 effectIt.effect("lists the tailnet name once Serve answers for this server", () =>
297 Effect.gen(function* () {
298 expect(yield* resolveWithServe(200)).toEqual([
299 { kind: "tailnet", httpBaseUrl: "https://bb-1.tail1234.ts.net/" },
300 ]);
301 }),
302 );
303
304 effectIt.effect(
305 "returns bound endpoints during validation and reuses only a completed Serve result",
306 () =>
307 Effect.gen(function* () {
308 const status = yield* Ref.make(200);
309 const finishProbe = yield* Deferred.make<void>();
310 const probeStarted = yield* Deferred.make<void>();
311 const revalidationStarted = yield* Deferred.make<void>();
312 const finishRevalidation = yield* Deferred.make<void>();
313 // Built in the test's scope: the reader's shared read outlives `make`, as the server's does.
314 const reader = yield* Layer.build(
315 TailscaleStatusReader.layer.pipe(Layer.provide(layerTailscaleUp)),
316 );
317 const service = yield* DirectEndpoints.make.pipe(
318 Effect.provide(reader),
319 Effect.provide(
320 Layer.mergeAll(
321 layerServeConfig("192.168.1.10"),
322 Layer.succeed(
323 HttpClient.HttpClient,
324 HttpClient.make((request) =>
325 Deferred.succeed(probeStarted, undefined).pipe(
326 Effect.andThen(Deferred.await(finishProbe)),
327 Effect.andThen(Ref.get(status)),
328 Effect.tap((status) =>
329 status === 502
330 ? Deferred.succeed(revalidationStarted, undefined).pipe(
331 Effect.andThen(Deferred.await(finishRevalidation)),
332 )
333 : Effect.void,
334 ),
335 Effect.map((status) =>
336 HttpClientResponse.fromWeb(request, new Response(null, { status })),
337 ),
338 ),
339 ),
340 ),
341 ),
342 ),
343 );
344 const resolving = yield* Effect.forkScoped(service.resolve());
345 yield* Deferred.await(probeStarted);
346 const bound = { kind: "lan", httpBaseUrl: "http://192.168.1.10:3773/" };
347 expect(yield* service.resolveAvailable()).toEqual([bound]);
348 yield* Deferred.succeed(finishProbe, undefined);
349 const validated = yield* Fiber.join(resolving);
350 expect(validated).toEqual([
351 bound,
352 { kind: "tailnet", httpBaseUrl: "https://bb-1.tail1234.ts.net/" },
353 ]);
354 expect(yield* service.resolveAvailable()).toEqual(validated);
355 yield* Ref.set(status, 502);
356 const revalidating = yield* Effect.forkScoped(service.resolve());
357 yield* Deferred.await(revalidationStarted);
358 expect(yield* service.resolveAvailable()).toEqual(validated);
359 yield* Deferred.succeed(finishRevalidation, undefined);
360 expect(yield* Fiber.join(revalidating)).toEqual([bound]);
361 expect(yield* service.resolveAvailable()).toEqual([bound]);
362 }).pipe(Effect.scoped),
363 );
364
365 effectIt.effect("leaves the tailnet name out when Serve is not forwarding", () =>
366 Effect.gen(function* () {
367 expect(yield* resolveWithServe(502)).toEqual([]);
368 }),
369 );
370});
371
372// A CLI that cannot reach tailscaled: `tailscale status` never answers, so each read waits out its timeout.
373const layerTailscaleHung = (onStatusSpawn: () => void) =>
374 Layer.succeed(
375 ChildProcessSpawner.ChildProcessSpawner,
376 ChildProcessSpawner.make((command) => {
377 if (ChildProcess.isStandardCommand(command) && command.args[0] === "status") onStatusSpawn();
378 return Effect.succeed(
379 ChildProcessSpawner.makeHandle({
380 pid: ChildProcessSpawner.ProcessId(1),
381 exitCode: Effect.never,
382 isRunning: Effect.succeed(true),
383 kill: () => Effect.void,
384 unref: Effect.succeed(Effect.void),
385 stdin: Sink.drain,
386 stdout: Stream.empty,
387 stderr: Stream.empty,
388 all: Stream.empty,
389 getInputFd: () => Sink.drain,
390 getOutputFd: () => Stream.empty,
391 }),
392 );
393 }),
394 );
395
396const layerSshdListening = Layer.succeed(NetService.NetService, {
397 canListenOnHost: () => Effect.succeed(true),
398 isPortAvailableOnLoopback: () => Effect.succeed(true),
399 hasListenerOnHost: () => Effect.succeed(true),
400 reserveLoopbackPort: () => Effect.succeed(40_000),
401 findAvailablePort: (preferred) => Effect.succeed(preferred),
402});
403
404describe("Tailscale status shared by DirectEndpoints and RemoteOpenTargets", () => {
405 effectIt.effect("reads `tailscale status` once per connect, not once per service", () =>
406 Effect.gen(function* () {
407 let statusReads = 0;
408 const context = yield* Layer.build(
409 Layer.mergeAll(DirectEndpoints.layer, RemoteOpenTargets.layer).pipe(
410 Layer.provide(TailscaleStatusReader.layer),
411 Layer.provide(
412 Layer.mergeAll(
413 layerServeConfig(),
414 layerTailscaleHung(() => statusReads++),
415 layerServeProbe(200),
416 layerSshdListening,
417 ),
418 ),
419 ),
420 );
421 const connect = yield* Effect.all(
422 [
423 Context.get(context, RemoteOpenTargets.RemoteOpenTargets).resolveTargets(),
424 Context.get(context, DirectEndpoints.DirectEndpoints).resolve(),
425 ],
426 { concurrency: "unbounded" },
427 ).pipe(
428 Effect.provideService(HostProcess.Hostname, "bb-1"),
429 Effect.provideService(HostProcess.Username, "t3-user"),
430 Effect.forkChild,
431 );
432 yield* TestClock.adjust("4 seconds");
433 expect(yield* Fiber.join(connect)).toEqual([
434 [{ kind: "mdns", host: "bb-1.local", username: "t3-user" }],
435 [],
436 ]);
437 expect(statusReads, "tailscale status spawns for one connect").toBe(1);
438 }),
439 );
440});