Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import * as Stream from "effect/Stream";
7import { HttpClient, HttpClientRequest } from "effect/http";
8import { ChildProcess, ChildProcessSpawner } from "effect/process";
9
10export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
11/**
12 * Bounds `tailscale status` and `tailscale debug prefs`. Allows the 1.8-2.6 s
13 * `tailscale status` has been measured at when T3 Code spawns it on Windows.
14 * A CLI that never answers takes longer than this to fail, because the kill
15 * that follows the timeout also takes time (`taskkill` on Windows).
16 */
17export const TAILSCALE_STATUS_TIMEOUT = Duration.millis(3_500);
18const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);
19const TAILSCALE_PROBE_TIMEOUT = Duration.millis(2_500);
20
21const tailscaleCommandForPlatform = (platform: NodeJS.Platform): "tailscale" | "tailscale.exe" =>
22 platform === "win32" ? "tailscale.exe" : "tailscale";
23
24const TailscaleCommandContext = {
25 executable: Schema.Literals(["tailscale", "tailscale.exe"]),
26 subcommand: Schema.Literals(["status", "serve", "debug"]),
27 argumentCount: Schema.Number,
28};
29
30/**
31 * Failure kinds we can name without quoting the CLI. Anything unrecognized
32 * becomes "unknown" rather than falling back to raw text — stderr can contain
33 * auth keys (`tskey-…`) and node names, and these labels are logged.
34 */
35export const TailscaleStderrDiagnostic = Schema.Literals([
36 "no-existing-handler",
37 "not-logged-in",
38 "permission-denied",
39 "unknown",
40]);
41export type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;
42
43const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
44 readonly [RegExp, Exclude<TailscaleStderrDiagnostic, "unknown">]
45> = [
46 [/handler does not exist/i, "no-existing-handler"],
47 [/not logged in|logged out|needs? login/i, "not-logged-in"],
48 [/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
49];
50
51const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {
52 if (stderr.trim().length === 0) {
53 return undefined;
54 }
55 return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? "unknown";
56};
57
58export class TailscaleCommandSpawnError extends Schema.TaggedError<TailscaleCommandSpawnError>()(
59 "TailscaleCommandSpawnError",
60 {
61 ...TailscaleCommandContext,
62 cause: Schema.Defect(),
63 },
64) {
65 override get message(): string {
66 return `Failed to spawn tailscale ${this.subcommand}.`;
67 }
68}
69
70class TailscaleCommandOutputError extends Schema.TaggedError<TailscaleCommandOutputError>()(
71 "TailscaleCommandOutputError",
72 {
73 ...TailscaleCommandContext,
74 cause: Schema.Defect(),
75 },
76) {
77 override get message(): string {
78 return `Failed to read output from tailscale ${this.subcommand}.`;
79 }
80}
81
82export class TailscaleCommandExitError extends Schema.TaggedError<TailscaleCommandExitError>()(
83 "TailscaleCommandExitError",
84 {
85 ...TailscaleCommandContext,
86 exitCode: Schema.Number,
87 stdoutLength: Schema.optional(Schema.Number),
88 stderrLength: Schema.Number,
89 stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
90 },
91) {
92 override get message(): string {
93 return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;
94 }
95}
96
97export class TailscaleCommandTimeoutError extends Schema.TaggedError<TailscaleCommandTimeoutError>()(
98 "TailscaleCommandTimeoutError",
99 {
100 ...TailscaleCommandContext,
101 timeoutMs: Schema.Number,
102 cause: Schema.Defect(),
103 },
104) {
105 override get message(): string {
106 return `tailscale ${this.subcommand} timed out after ${this.timeoutMs}ms.`;
107 }
108}
109
110export type TailscaleCommandError =
111 | TailscaleCommandSpawnError
112 | TailscaleCommandOutputError
113 | TailscaleCommandExitError
114 | TailscaleCommandTimeoutError;
115
116export class TailscaleStatusParseError extends Schema.TaggedError<TailscaleStatusParseError>()(
117 "TailscaleStatusParseError",
118 { cause: Schema.Defect() },
119) {
120 override get message(): string {
121 return "Failed to decode tailscale status JSON.";
122 }
123}
124
125const TailscaleStatusSelf = Schema.Struct({
126 DNSName: Schema.optional(Schema.Unknown),
127 TailscaleIPs: Schema.optional(Schema.Unknown),
128});
129
130const TailscaleStatusJson = Schema.Struct({
131 Self: Schema.optional(TailscaleStatusSelf),
132});
133
134export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
135
136export interface TailscaleStatus {
137 readonly magicDnsName: string | null;
138 readonly tailnetIpv4Addresses: readonly string[];
139}
140
141const collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
142 stream.pipe(
143 Stream.decodeText(),
144 Stream.runFold(
145 () => "",
146 (acc, chunk) => acc + chunk,
147 ),
148 );
149
150const collectStderr = collectStdout;
151
152const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
153
154function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
155 const dnsName = status.Self?.DNSName;
156 if (typeof dnsName !== "string") {
157 return null;
158 }
159
160 const normalized = dnsName.trim().replace(/\.$/u, "");
161 return normalized.length > 0 ? normalized : null;
162}
163
164export const parseTailscaleMagicDnsName = (
165 rawStatusJson: string,
166): Effect.Effect<string | null, TailscaleStatusParseError> =>
167 decodeTailscaleStatusJson(rawStatusJson).pipe(
168 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
169 Effect.map(normalizeMagicDnsName),
170 );
171
172export function isTailscaleIpv4Address(address: string): boolean {
173 const parts = address.split(".");
174 if (parts.length !== 4) {
175 return false;
176 }
177 const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
178 if (
179 first === undefined ||
180 second === undefined ||
181 third === undefined ||
182 fourth === undefined ||
183 [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
184 ) {
185 return false;
186 }
187 return first === 100 && second >= 64 && second <= 127;
188}
189
190export const parseTailscaleStatus = (
191 rawStatusJson: string,
192): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
193 decodeTailscaleStatusJson(rawStatusJson).pipe(
194 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
195 Effect.map((parsed) => {
196 const rawIps = parsed.Self?.TailscaleIPs;
197 const tailnetIpv4Addresses: Array<string> = [];
198 if (Array.isArray(rawIps)) {
199 for (const address of rawIps) {
200 if (typeof address === "string" && isTailscaleIpv4Address(address)) {
201 tailnetIpv4Addresses.push(address);
202 }
203 }
204 }
205
206 return {
207 magicDnsName: normalizeMagicDnsName(parsed),
208 tailnetIpv4Addresses,
209 };
210 }),
211 );
212
213const readTailscaleOutput = Effect.fn("tailscale.readTailscaleOutput")(function* (
214 subcommand: "status" | "debug",
215 args: readonly string[],
216) {
217 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
218 const hostPlatform = yield* HostProcess.Platform;
219 const executable = tailscaleCommandForPlatform(hostPlatform);
220 const commandContext = {
221 executable,
222 subcommand,
223 argumentCount: args.length,
224 };
225 return yield* Effect.gen(function* () {
226 const child = yield* spawner.spawn(ChildProcess.make(executable, [...args])).pipe(
227 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
228 // Spawning can also fail as a defect rather than a typed error - a
229 // non-directory entry on PATH makes node throw ENOTDIR synchronously.
230 // `mapError` never sees that, so it would escape as an uncaught error.
231 Effect.catchDefect((cause) =>
232 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
233 ),
234 );
235 const [stdout, stderr, exitCode] = yield* Effect.all(
236 [
237 collectStdout(child.stdout),
238 collectStderr(child.stderr),
239 child.exitCode.pipe(Effect.map(Number)),
240 ],
241 { concurrency: "unbounded" },
242 ).pipe(
243 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
244 );
245 if (exitCode !== 0) {
246 return yield* new TailscaleCommandExitError({
247 ...commandContext,
248 exitCode,
249 stdoutLength: stdout.length,
250 stderrLength: stderr.length,
251 ...(stderrDiagnosticOf(stderr) !== undefined
252 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
253 : {}),
254 });
255 }
256 return stdout;
257 }).pipe(
258 Effect.scoped,
259 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
260 Effect.catchTags({
261 TimeoutError: (cause) =>
262 Effect.fail(
263 new TailscaleCommandTimeoutError({
264 ...commandContext,
265 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
266 cause,
267 }),
268 ),
269 }),
270 );
271});
272
273export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--json"]).pipe(
274 Effect.flatMap(parseTailscaleStatus),
275);
276
277const TailscalePrefsJson = Schema.Struct({
278 RunSSH: Schema.optional(Schema.Unknown),
279 WantRunning: Schema.optional(Schema.Unknown),
280});
281
282const decodeTailscalePrefsJson = Schema.decodeEffect(Schema.fromJsonString(TailscalePrefsJson));
283
284/**
285 * `tailscale status --json` does not report this for the local node. `tailscale
286 * down` clears WantRunning but keeps RunSSH, so check both.
287 */
288export const parseTailscaleSshEnabled = (
289 rawPrefsJson: string,
290): Effect.Effect<boolean, TailscaleStatusParseError> =>
291 decodeTailscalePrefsJson(rawPrefsJson).pipe(
292 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
293 Effect.map((prefs) => prefs.RunSSH === true && prefs.WantRunning !== false),
294 );
295
296export const readTailscaleSshEnabled = readTailscaleOutput("debug", ["debug", "prefs"]).pipe(
297 Effect.flatMap(parseTailscaleSshEnabled),
298);
299
300export function buildTailscaleHttpsBaseUrl(input: {
301 readonly magicDnsName: string;
302 readonly servePort?: number;
303}): string {
304 const url = new URL(`https://${input.magicDnsName}`);
305 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
306 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
307 url.port = String(servePort);
308 }
309 url.pathname = "/";
310 return url.toString();
311}
312
313const runTailscaleCommand = Effect.fn("tailscale.runTailscaleCommand")(function* (
314 args: readonly string[],
315 timeoutInput: Duration.Input,
316): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
317 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
318 const hostPlatform = yield* HostProcess.Platform;
319 const executable = tailscaleCommandForPlatform(hostPlatform);
320 const commandContext = {
321 executable,
322 subcommand: "serve" as const,
323 argumentCount: args.length,
324 };
325 const timeout = Duration.fromInputUnsafe(timeoutInput);
326 return yield* Effect.gen(function* () {
327 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
328 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
329 Effect.catchDefect((cause) =>
330 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
331 ),
332 );
333 const [stderr, exitCode] = yield* Effect.all(
334 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
335 { concurrency: "unbounded" },
336 ).pipe(
337 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
338 );
339 if (exitCode !== 0) {
340 return yield* new TailscaleCommandExitError({
341 ...commandContext,
342 exitCode,
343 stderrLength: stderr.length,
344 ...(stderrDiagnosticOf(stderr) !== undefined
345 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
346 : {}),
347 });
348 }
349 }).pipe(
350 Effect.scoped,
351 Effect.timeout(timeout),
352 Effect.catchTags({
353 TimeoutError: (cause) =>
354 Effect.fail(
355 new TailscaleCommandTimeoutError({
356 ...commandContext,
357 timeoutMs: Duration.toMillis(timeout),
358 cause,
359 }),
360 ),
361 }),
362 );
363});
364
365export const ensureTailscaleServe = (input: {
366 readonly localPort: number;
367 readonly servePort?: number;
368 readonly localHost?: string;
369}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
370 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
371 const localHost = input.localHost ?? "127.0.0.1";
372 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
373 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
374};
375
376export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (
377 input: {
378 readonly servePort?: number;
379 } = {},
380): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
381 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
382 return yield* runTailscaleCommand(
383 ["serve", `--https=${servePort}`, "off"],
384 TAILSCALE_SERVE_TIMEOUT,
385 );
386});
387
388export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(
389 function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {
390 const client = yield* HttpClient.HttpClient;
391 const response = yield* Effect.gen(function* () {
392 const url = new URL("/.well-known/t3/environment", input.baseUrl);
393 const request = HttpClientRequest.get(url.toString());
394 return yield* client.execute(request);
395 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
396
397 return Option.match(response, {
398 onNone: () => false,
399 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
400 });
401 },
402 Effect.orElseSucceed(() => false),
403);