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 */
17const TAILSCALE_STATUS_TIMEOUT = Duration.millis(3_500);
18/**
19 * How long a probe killed on timeout gets to exit after SIGTERM before its
20 * process group is SIGKILLed. Without it the spawner never escalates, so a group
21 * member that ignores SIGTERM outlives the call. Short because the timeout error
22 * only surfaces once cleanup finishes, and a healthy `tailscale` exits at once.
23 */
24const TAILSCALE_KILL_GRACE = Duration.millis(500);
25const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);
26const TAILSCALE_PROBE_TIMEOUT = Duration.millis(2_500);
27
28const tailscaleCommandForPlatform = (platform: NodeJS.Platform): "tailscale" | "tailscale.exe" =>
29 platform === "win32" ? "tailscale.exe" : "tailscale";
30
31const TailscaleCommandContext = {
32 executable: Schema.Literals(["tailscale", "tailscale.exe"]),
33 subcommand: Schema.Literals(["status", "serve", "debug"]),
34 argumentCount: Schema.Number,
35};
36
37/**
38 * Failure kinds we can name without quoting the CLI. Anything unrecognized
39 * becomes "unknown" rather than falling back to raw text — stderr can contain
40 * auth keys (`tskey-…`) and node names, and these labels are logged.
41 */
42export const TailscaleStderrDiagnostic = Schema.Literals([
43 "no-existing-handler",
44 "not-logged-in",
45 "permission-denied",
46 "unknown",
47]);
48export type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;
49
50const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
51 readonly [RegExp, Exclude<TailscaleStderrDiagnostic, "unknown">]
52> = [
53 [/handler does not exist/i, "no-existing-handler"],
54 [/not logged in|logged out|needs? login/i, "not-logged-in"],
55 [/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
56];
57
58const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {
59 if (stderr.trim().length === 0) {
60 return undefined;
61 }
62 return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? "unknown";
63};
64
65export class TailscaleCommandSpawnError extends Schema.TaggedError<TailscaleCommandSpawnError>()(
66 "TailscaleCommandSpawnError",
67 {
68 ...TailscaleCommandContext,
69 cause: Schema.Defect(),
70 },
71) {
72 override get message(): string {
73 return `Failed to spawn tailscale ${this.subcommand}.`;
74 }
75}
76
77class TailscaleCommandOutputError extends Schema.TaggedError<TailscaleCommandOutputError>()(
78 "TailscaleCommandOutputError",
79 {
80 ...TailscaleCommandContext,
81 cause: Schema.Defect(),
82 },
83) {
84 override get message(): string {
85 return `Failed to read output from tailscale ${this.subcommand}.`;
86 }
87}
88
89export class TailscaleCommandExitError extends Schema.TaggedError<TailscaleCommandExitError>()(
90 "TailscaleCommandExitError",
91 {
92 ...TailscaleCommandContext,
93 exitCode: Schema.Number,
94 stdoutLength: Schema.optional(Schema.Number),
95 stderrLength: Schema.Number,
96 stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
97 },
98) {
99 override get message(): string {
100 return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;
101 }
102}
103
104export class TailscaleCommandTimeoutError extends Schema.TaggedError<TailscaleCommandTimeoutError>()(
105 "TailscaleCommandTimeoutError",
106 {
107 ...TailscaleCommandContext,
108 timeoutMs: Schema.Number,
109 cause: Schema.Defect(),
110 },
111) {
112 override get message(): string {
113 return `tailscale ${this.subcommand} timed out after ${this.timeoutMs}ms.`;
114 }
115}
116
117export type TailscaleCommandError =
118 | TailscaleCommandSpawnError
119 | TailscaleCommandOutputError
120 | TailscaleCommandExitError
121 | TailscaleCommandTimeoutError;
122
123export class TailscaleStatusParseError extends Schema.TaggedError<TailscaleStatusParseError>()(
124 "TailscaleStatusParseError",
125 { cause: Schema.Defect() },
126) {
127 override get message(): string {
128 return "Failed to decode tailscale status JSON.";
129 }
130}
131
132const TailscaleStatusSelf = Schema.Struct({
133 DNSName: Schema.optional(Schema.Unknown),
134 TailscaleIPs: Schema.optional(Schema.Unknown),
135 CapMap: Schema.optional(Schema.Unknown),
136});
137
138const TailscaleStatusJson = Schema.Struct({
139 Self: Schema.optional(TailscaleStatusSelf),
140});
141
142export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
143
144export interface TailscaleStatus {
145 readonly magicDnsName: string | null;
146 readonly tailnetIpv4Addresses: readonly string[];
147 /**
148 * `tailscale serve --https` needs the `https` capability, which the control
149 * plane grants once the tailnet enables HTTPS certificates. `null` when the
150 * CLI reports no capability map (older CLI), so callers still attempt serve.
151 */
152 readonly httpsServeEnabled: boolean | null;
153}
154
155const collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
156 stream.pipe(
157 Stream.decodeText(),
158 Stream.runFold(
159 () => "",
160 (acc, chunk) => acc + chunk,
161 ),
162 );
163
164const collectStderr = collectStdout;
165
166const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
167
168function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
169 const dnsName = status.Self?.DNSName;
170 if (typeof dnsName !== "string") {
171 return null;
172 }
173
174 const normalized = dnsName.trim().replace(/\.$/u, "");
175 return normalized.length > 0 ? normalized : null;
176}
177
178export function isTailscaleIpv4Address(address: string): boolean {
179 const parts = address.split(".");
180 if (parts.length !== 4) {
181 return false;
182 }
183 const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
184 if (
185 first === undefined ||
186 second === undefined ||
187 third === undefined ||
188 fourth === undefined ||
189 [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
190 ) {
191 return false;
192 }
193 return first === 100 && second >= 64 && second <= 127;
194}
195
196export const parseTailscaleStatus = (
197 rawStatusJson: string,
198): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
199 decodeTailscaleStatusJson(rawStatusJson).pipe(
200 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
201 Effect.map((parsed) => {
202 const rawIps = parsed.Self?.TailscaleIPs;
203 const tailnetIpv4Addresses: Array<string> = [];
204 if (Array.isArray(rawIps)) {
205 for (const address of rawIps) {
206 if (typeof address === "string" && isTailscaleIpv4Address(address)) {
207 tailnetIpv4Addresses.push(address);
208 }
209 }
210 }
211
212 const capMap = parsed.Self?.CapMap;
213 return {
214 magicDnsName: normalizeMagicDnsName(parsed),
215 tailnetIpv4Addresses,
216 httpsServeEnabled:
217 typeof capMap === "object" && capMap !== null && !Array.isArray(capMap)
218 ? Object.hasOwn(capMap, "https")
219 : null,
220 };
221 }),
222 );
223
224const readTailscaleOutput = Effect.fn("tailscale.readTailscaleOutput")(function* (
225 subcommand: "status" | "debug",
226 args: readonly string[],
227) {
228 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
229 const hostPlatform = yield* HostProcess.Platform;
230 const executable = tailscaleCommandForPlatform(hostPlatform);
231 const commandContext = {
232 executable,
233 subcommand,
234 argumentCount: args.length,
235 };
236 const command = ChildProcess.make(executable, [...args], {
237 forceKillAfter: TAILSCALE_KILL_GRACE,
238 });
239 return yield* Effect.gen(function* () {
240 const child = yield* spawner.spawn(command).pipe(
241 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
242 // Spawning can also fail as a defect rather than a typed error - a
243 // non-directory entry on PATH makes node throw ENOTDIR synchronously.
244 // `mapError` never sees that, so it would escape as an uncaught error.
245 Effect.catchDefect((cause) =>
246 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
247 ),
248 );
249 const [stdout, stderr, exitCode] = yield* Effect.all(
250 [
251 collectStdout(child.stdout),
252 collectStderr(child.stderr),
253 child.exitCode.pipe(Effect.map(Number)),
254 ],
255 { concurrency: "unbounded" },
256 ).pipe(
257 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
258 );
259 if (exitCode !== 0) {
260 return yield* new TailscaleCommandExitError({
261 ...commandContext,
262 exitCode,
263 stdoutLength: stdout.length,
264 stderrLength: stderr.length,
265 ...(stderrDiagnosticOf(stderr) !== undefined
266 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
267 : {}),
268 });
269 }
270 return stdout;
271 }).pipe(
272 Effect.scoped,
273 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
274 Effect.catchTags({
275 TimeoutError: (cause) =>
276 Effect.fail(
277 new TailscaleCommandTimeoutError({
278 ...commandContext,
279 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
280 cause,
281 }),
282 ),
283 }),
284 );
285});
286
287export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--json"]).pipe(
288 Effect.flatMap(parseTailscaleStatus),
289);
290
291const TailscaleExitNodeJson = Schema.Struct({
292 ExitNodeStatus: Schema.optional(Schema.Struct({ Online: Schema.optional(Schema.Unknown) })),
293 Peer: Schema.optional(
294 Schema.Record(
295 Schema.String,
296 Schema.Struct({
297 ExitNode: Schema.optional(Schema.Unknown),
298 HostName: Schema.optional(Schema.Unknown),
299 DNSName: Schema.optional(Schema.Unknown),
300 }),
301 ),
302 ),
303});
304
305const decodeTailscaleExitNodeJson = Schema.decodeEffect(
306 Schema.fromJsonString(TailscaleExitNodeJson),
307);
308
309export interface TailscaleExitNode {
310 readonly name: string | null;
311 readonly online: boolean;
312}
313
314/**
315 * `ExitNodeStatus` is present only while an exit node is in use, but it has no
316 * name. The name comes from the peer marked `ExitNode: true`.
317 */
318export const parseTailscaleExitNode = (
319 rawStatusJson: string,
320): Effect.Effect<TailscaleExitNode | null, TailscaleStatusParseError> =>
321 decodeTailscaleExitNodeJson(rawStatusJson).pipe(
322 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
323 Effect.map((parsed) => {
324 if (parsed.ExitNodeStatus === undefined) return null;
325 const peer = Object.values(parsed.Peer ?? {}).find(
326 (candidate) => candidate.ExitNode === true,
327 );
328 // The DNS label is the tailnet machine name; HostName is the OS name and ignores renames.
329 const dnsLabel = typeof peer?.DNSName === "string" ? (peer.DNSName.split(".")[0] ?? "") : "";
330 const hostName = typeof peer?.HostName === "string" ? peer.HostName.trim() : "";
331 return {
332 name: dnsLabel || hostName || null,
333 online: parsed.ExitNodeStatus.Online === true,
334 };
335 }),
336 );
337
338export const readTailscaleExitNode = readTailscaleOutput("status", ["status", "--json"]).pipe(
339 Effect.flatMap(parseTailscaleExitNode),
340);
341
342const TailscalePrefsJson = Schema.Struct({
343 RunSSH: Schema.optional(Schema.Unknown),
344 WantRunning: Schema.optional(Schema.Unknown),
345});
346
347const decodeTailscalePrefsJson = Schema.decodeEffect(Schema.fromJsonString(TailscalePrefsJson));
348
349/**
350 * `tailscale status --json` does not report this for the local node. `tailscale
351 * down` clears WantRunning but keeps RunSSH, so check both.
352 */
353export const parseTailscaleSshEnabled = (
354 rawPrefsJson: string,
355): Effect.Effect<boolean, TailscaleStatusParseError> =>
356 decodeTailscalePrefsJson(rawPrefsJson).pipe(
357 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
358 Effect.map((prefs) => prefs.RunSSH === true && prefs.WantRunning !== false),
359 );
360
361export const readTailscaleSshEnabled = readTailscaleOutput("debug", ["debug", "prefs"]).pipe(
362 Effect.flatMap(parseTailscaleSshEnabled),
363);
364
365export function buildTailscaleHttpsBaseUrl(input: {
366 readonly magicDnsName: string;
367 readonly servePort?: number;
368}): string {
369 const url = new URL(`https://${input.magicDnsName}`);
370 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
371 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
372 url.port = String(servePort);
373 }
374 url.pathname = "/";
375 return url.toString();
376}
377
378const runTailscaleCommand = Effect.fn("tailscale.runTailscaleCommand")(function* (
379 args: readonly string[],
380 timeoutInput: Duration.Input,
381): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
382 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
383 const hostPlatform = yield* HostProcess.Platform;
384 const executable = tailscaleCommandForPlatform(hostPlatform);
385 const commandContext = {
386 executable,
387 subcommand: "serve" as const,
388 argumentCount: args.length,
389 };
390 const timeout = Duration.fromInputUnsafe(timeoutInput);
391 return yield* Effect.gen(function* () {
392 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
393 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
394 Effect.catchDefect((cause) =>
395 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
396 ),
397 );
398 const [stderr, exitCode] = yield* Effect.all(
399 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
400 { concurrency: "unbounded" },
401 ).pipe(
402 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
403 );
404 if (exitCode !== 0) {
405 return yield* new TailscaleCommandExitError({
406 ...commandContext,
407 exitCode,
408 stderrLength: stderr.length,
409 ...(stderrDiagnosticOf(stderr) !== undefined
410 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
411 : {}),
412 });
413 }
414 }).pipe(
415 Effect.scoped,
416 Effect.timeout(timeout),
417 Effect.catchTags({
418 TimeoutError: (cause) =>
419 Effect.fail(
420 new TailscaleCommandTimeoutError({
421 ...commandContext,
422 timeoutMs: Duration.toMillis(timeout),
423 cause,
424 }),
425 ),
426 }),
427 );
428});
429
430export const ensureTailscaleServe = (input: {
431 readonly localPort: number;
432 readonly servePort?: number;
433 readonly localHost?: string;
434}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
435 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
436 const localHost = input.localHost ?? "127.0.0.1";
437 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
438 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
439};
440
441export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (
442 input: {
443 readonly servePort?: number;
444 } = {},
445): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
446 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
447 return yield* runTailscaleCommand(
448 ["serve", `--https=${servePort}`, "off"],
449 TAILSCALE_SERVE_TIMEOUT,
450 );
451});
452
453export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(
454 function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {
455 const client = yield* HttpClient.HttpClient;
456 const response = yield* Effect.gen(function* () {
457 const url = new URL("/.well-known/t3/environment", input.baseUrl);
458 const request = HttpClientRequest.get(url.toString());
459 return yield* client.execute(request);
460 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
461
462 return Option.match(response, {
463 onNone: () => false,
464 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
465 });
466 },
467 Effect.orElseSucceed(() => false),
468);