Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- replace the native OS lookup and sync its ESM bindings.
2import * as NodeModule from "node:module";
3import { it } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as NetService from "@t3tools/shared/Net";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import * as ChildProcess from "effect/process/ChildProcess";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13import type * as NodeDns from "node:dns";
14import type * as NodeOS from "node:os";
15import { afterEach, describe, expect, vi } from "vite-plus/test";
16
17import * as RemoteOpenTargets from "./RemoteOpenTargets.ts";
18
19afterEach(() => {
20 vi.restoreAllMocks();
21 NodeModule.syncBuiltinESMExports();
22});
23
24const encoder = new TextEncoder();
25const requireBuiltin = NodeModule.createRequire(import.meta.url);
26const nodeOs: typeof NodeOS = requireBuiltin("node:os");
27const nodeDns: typeof NodeDns = requireBuiltin("node:dns");
28
29const useMacTailnet = (input: { readonly ipv4?: boolean } = {}) => {
30 vi.spyOn(nodeOs, "networkInterfaces").mockReturnValue({
31 // Another VPN on the shared CGNAT range, listed before Tailscale.
32 utun3: [
33 {
34 address: "100.85.0.1",
35 netmask: "255.255.255.255",
36 family: "IPv4",
37 mac: "00:00:00:00:00:00",
38 internal: false,
39 cidr: "100.85.0.1/32",
40 },
41 ],
42 utun4: [
43 ...(input.ipv4 === false
44 ? []
45 : [
46 {
47 address: "100.64.1.2",
48 netmask: "255.255.255.255",
49 family: "IPv4" as const,
50 mac: "00:00:00:00:00:00",
51 internal: false,
52 cidr: "100.64.1.2/32",
53 },
54 ]),
55 {
56 address: "fd7a:115c:a1e0::1",
57 netmask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
58 family: "IPv6",
59 mac: "00:00:00:00:00:00",
60 internal: false,
61 cidr: "fd7a:115c:a1e0::1/128",
62 scopeid: 0,
63 },
64 ],
65 });
66 NodeModule.syncBuiltinESMExports();
67 return vi.spyOn(nodeDns.promises.Resolver.prototype, "reverse");
68};
69
70const TAILSCALE_STATUS_JSON = JSON.stringify({
71 Self: { DNSName: "bb-1.tail1234.ts.net.", TailscaleIPs: ["100.64.1.2"] },
72});
73
74interface CommandResult {
75 readonly exitCode: number;
76 readonly stdout: string;
77}
78
79const layerSpawner = (
80 input: { readonly status: CommandResult; readonly prefs: CommandResult },
81 spawned?: Array<unknown>,
82) =>
83 Layer.succeed(
84 ChildProcessSpawner.ChildProcessSpawner,
85 ChildProcessSpawner.make((command) => {
86 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
87 spawned?.push(args);
88 const result = args[0] === "debug" ? input.prefs : input.status;
89 return Effect.succeed(
90 ChildProcessSpawner.makeHandle({
91 pid: ChildProcessSpawner.ProcessId(1),
92 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
93 isRunning: Effect.succeed(false),
94 kill: () => Effect.void,
95 unref: Effect.succeed(Effect.void),
96 stdin: Sink.drain,
97 stdout: Stream.make(encoder.encode(result.stdout)),
98 stderr: Stream.empty,
99 all: Stream.empty,
100 getInputFd: () => Sink.drain,
101 getOutputFd: () => Stream.empty,
102 }),
103 );
104 }),
105 );
106
107const layerNet = (input: {
108 readonly ipv4: boolean;
109 readonly ipv6: boolean;
110 readonly tailnet?: boolean;
111}) =>
112 Layer.succeed(NetService.NetService, {
113 canListenOnHost: () => Effect.succeed(true),
114 isPortAvailableOnLoopback: () => Effect.succeed(true),
115 hasListenerOnHost: (_port, host) =>
116 Effect.succeed(
117 host === "127.0.0.1"
118 ? input.ipv4
119 : host === "::1"
120 ? input.ipv6
121 : (host === "100.64.1.2" || host === "bb-1.tail1234.ts.net") && input.tailnet === true,
122 ),
123 reserveLoopbackPort: () => Effect.succeed(40_000),
124 findAvailablePort: (preferred) => Effect.succeed(preferred),
125 });
126
127const resolveTargets = (input: {
128 readonly sshd: { readonly ipv4: boolean; readonly ipv6: boolean; readonly tailnet?: boolean };
129 readonly tailscale: { readonly status: CommandResult; readonly prefs: CommandResult };
130 readonly hostname: string;
131 readonly username?: string | null;
132 readonly platform?: NodeJS.Platform;
133 readonly spawned?: Array<unknown>;
134 readonly openSourceTailscaled?: boolean;
135}) => {
136 const resolve = Effect.flatMap(RemoteOpenTargets.RemoteOpenTargets, (service) =>
137 service.resolveTargets(),
138 ).pipe(
139 Effect.provideService(HostProcess.Hostname, input.hostname),
140 Effect.provide(
141 RemoteOpenTargets.layer.pipe(
142 Layer.provide(
143 Layer.mergeAll(
144 layerNet(input.sshd),
145 layerSpawner(input.tailscale, input.spawned),
146 FileSystem.layerNoop({
147 exists: (path) =>
148 Effect.succeed(
149 path === "/var/run/tailscaled.socket" && input.openSourceTailscaled === true,
150 ),
151 }),
152 ),
153 ),
154 ),
155 ),
156 Effect.provideService(HostProcess.Platform, input.platform ?? "linux"),
157 );
158
159 return input.username === undefined
160 ? resolve
161 : resolve.pipe(Effect.provideService(HostProcess.Username, input.username));
162};
163
164const prefsJson = (prefs: { readonly RunSSH: boolean; readonly WantRunning: boolean }) => ({
165 exitCode: 0,
166 stdout: JSON.stringify(
167 { ControlURL: "https://controlplane.tailscale.com", ...prefs },
168 null,
169 "\t",
170 ),
171});
172
173const STATUS_UP = { exitCode: 0, stdout: TAILSCALE_STATUS_JSON };
174const TAILSCALE_UP = { status: STATUS_UP, prefs: prefsJson({ RunSSH: false, WantRunning: true }) };
175const TAILSCALE_SSH = { status: STATUS_UP, prefs: prefsJson({ RunSSH: true, WantRunning: true }) };
176const TAILSCALE_DOWN = { status: { exitCode: 1, stdout: "" }, prefs: { exitCode: 1, stdout: "" } };
177
178describe("RemoteOpenTargets", () => {
179 it.effect("advertises nothing when no sshd accepts and Tailscale SSH is off", () =>
180 Effect.gen(function* () {
181 const targets = yield* resolveTargets({
182 sshd: { ipv4: false, ipv6: false },
183 tailscale: TAILSCALE_UP,
184 hostname: "bb-1",
185 username: "t3-user",
186 });
187 expect(targets).toEqual([]);
188 }),
189 );
190
191 it.effect("advertises only the tailnet name when Tailscale SSH serves without sshd", () =>
192 Effect.gen(function* () {
193 const targets = yield* resolveTargets({
194 sshd: { ipv4: false, ipv6: false },
195 tailscale: TAILSCALE_SSH,
196 hostname: "bb-1",
197 username: "t3-user",
198 });
199 expect(targets).toEqual([
200 { kind: "tailscale", host: "bb-1.tail1234.ts.net", username: "t3-user" },
201 ]);
202 }),
203 );
204
205 it.effect("advertises the tailnet name when sshd listens only on the tailnet address", () =>
206 Effect.gen(function* () {
207 const targets = yield* resolveTargets({
208 sshd: { ipv4: false, ipv6: false, tailnet: true },
209 tailscale: TAILSCALE_UP,
210 hostname: "bb-1",
211 username: "t3-user",
212 });
213 expect(targets).toEqual([
214 { kind: "tailscale", host: "bb-1.tail1234.ts.net", username: "t3-user" },
215 ]);
216 }),
217 );
218
219 it.effect("ignores a stored RunSSH after `tailscale down`", () =>
220 Effect.gen(function* () {
221 const targets = yield* resolveTargets({
222 sshd: { ipv4: false, ipv6: false },
223 tailscale: { status: STATUS_UP, prefs: prefsJson({ RunSSH: true, WantRunning: false }) },
224 hostname: "bb-1",
225 username: null,
226 });
227 expect(targets).toEqual([]);
228 }),
229 );
230
231 it.effect("with a macOS Tailscale app, resolves the tailnet host without the CLI", () =>
232 Effect.gen(function* () {
233 const reverseLookup = useMacTailnet();
234 // Tailscale's resolver also names peers; the other VPN's address may match one.
235 const reverseNames = (tailnetName: string | null) =>
236 reverseLookup.mockImplementation((address) =>
237 address === "100.64.1.2" && tailnetName !== null
238 ? Promise.resolve([tailnetName])
239 : address === "100.85.0.1"
240 ? Promise.resolve(["peer.tail1234.ts.net"])
241 : Promise.reject(Object.assign(new Error("ENOTFOUND"), { code: "ENOTFOUND" })),
242 );
243 reverseNames("renamed.tail1234.ts.net.");
244 const spawned: Array<unknown> = [];
245 const resolve = (sshd: {
246 readonly ipv4: boolean;
247 readonly ipv6: boolean;
248 readonly tailnet?: boolean;
249 }) =>
250 resolveTargets({
251 sshd,
252 tailscale: TAILSCALE_SSH,
253 hostname: "bb-1",
254 username: "t3-user",
255 platform: "darwin",
256 spawned,
257 });
258
259 expect(yield* resolve({ ipv4: true, ipv6: false })).toEqual([
260 { kind: "tailscale", host: "renamed.tail1234.ts.net", username: "t3-user" },
261 { kind: "mdns", host: "bb-1.local", username: "t3-user" },
262 ]);
263 // No MagicDNS answer for this host's own address: no tailnet target.
264 reverseNames(null);
265 expect(yield* resolve({ ipv4: true, ipv6: false })).toEqual([
266 { kind: "mdns", host: "bb-1.local", username: "t3-user" },
267 ]);
268 // sshd bound only to the tailnet address (ListenAddress).
269 reverseNames("bb-1.tail1234.ts.net.");
270 expect(yield* resolve({ ipv4: false, ipv6: false, tailnet: true })).toEqual([
271 { kind: "tailscale", host: "bb-1.tail1234.ts.net", username: "t3-user" },
272 ]);
273 expect(reverseLookup).toHaveBeenCalledWith("100.64.1.2");
274 expect(spawned).toEqual([]);
275 }),
276 );
277
278 it.effect("with a macOS Tailscale app on an IPv6-only tailnet, resolves from IPv6", () =>
279 Effect.gen(function* () {
280 const reverseLookup = useMacTailnet({ ipv4: false }).mockResolvedValue([
281 "bb-1.tail1234.ts.net.",
282 ]);
283 const targets = yield* resolveTargets({
284 sshd: { ipv4: true, ipv6: false },
285 tailscale: TAILSCALE_SSH,
286 hostname: "bb-1",
287 username: "t3-user",
288 platform: "darwin",
289 });
290 expect(targets).toEqual([
291 { kind: "tailscale", host: "bb-1.tail1234.ts.net", username: "t3-user" },
292 { kind: "mdns", host: "bb-1.local", username: "t3-user" },
293 ]);
294 expect(reverseLookup).toHaveBeenCalledWith("fd7a:115c:a1e0::1");
295 }),
296 );
297
298 it.effect("with open-source tailscaled on macOS, keeps the Tailscale SSH target", () =>
299 Effect.gen(function* () {
300 const reverseLookup = useMacTailnet();
301 const targets = yield* resolveTargets({
302 sshd: { ipv4: false, ipv6: false },
303 tailscale: TAILSCALE_SSH,
304 hostname: "bb-1",
305 username: "t3-user",
306 platform: "darwin",
307 openSourceTailscaled: true,
308 });
309 expect(targets).toEqual([
310 { kind: "tailscale", host: "bb-1.tail1234.ts.net", username: "t3-user" },
311 ]);
312 expect(reverseLookup).not.toHaveBeenCalled();
313 }),
314 );
315
316 it.effect("drops the tailnet name after `tailscale down` while sshd listens", () =>
317 Effect.gen(function* () {
318 const targets = yield* resolveTargets({
319 sshd: { ipv4: true, ipv6: false },
320 tailscale: {
321 // After `tailscale down`, status still exits 0 and keeps Self from the last netmap.
322 status: {
323 exitCode: 0,
324 stdout: JSON.stringify({
325 BackendState: "Stopped",
326 Self: {
327 DNSName: "bb-1.tail1234.ts.net.",
328 TailscaleIPs: ["100.64.1.2"],
329 Online: false,
330 },
331 }),
332 },
333 prefs: prefsJson({ RunSSH: false, WantRunning: false }),
334 },
335 hostname: "bb-1",
336 username: "t3-user",
337 });
338 expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local", username: "t3-user" }]);
339 }),
340 );
341
342 it.effect("accepts an sshd bound to IPv6 loopback only", () =>
343 Effect.gen(function* () {
344 const targets = yield* resolveTargets({
345 sshd: { ipv4: false, ipv6: true },
346 tailscale: TAILSCALE_DOWN,
347 hostname: "bb-1",
348 username: "t3-user",
349 });
350 expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local", username: "t3-user" }]);
351 }),
352 );
353});