Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

tailscale.ts

458 lines15.6 KB

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);
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 }
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 }
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 }
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 }
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 }
124​
125const TailscaleStatusSelf = Schema.Struct({
126 DNSName: Schema.optional(Schema.Unknown),
127 TailscaleIPs: Schema.optional(Schema.Unknown),
128 CapMap: Schema.optional(Schema.Unknown),
129});
130​
131const TailscaleStatusJson = Schema.Struct({
132 Self: Schema.optional(TailscaleStatusSelf),
133});
134​
135export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
136​
137export interface TailscaleStatus {
138 readonly magicDnsName: string | null;
139 readonly tailnetIpv4Addresses: readonly string[];
140 /**
141 * `tailscale serve --https` needs the `https` capability, which the control
142 * plane grants once the tailnet enables HTTPS certificates. `null` when the
143 * CLI reports no capability map (older CLI), so callers still attempt serve.
144 */
145 readonly httpsServeEnabled: boolean | null;
147​
148const collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
149 stream.pipe(
150 Stream.decodeText(),
151 Stream.runFold(
152 () => "",
153 (acc, chunk) => acc + chunk,
154 ),
155 );
156​
157const collectStderr = collectStdout;
158​
159const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
160​
161function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
162 const dnsName = status.Self?.DNSName;
163 if (typeof dnsName !== "string") {
164 return null;
165 }
166​
167 const normalized = dnsName.trim().replace(/\.$/u, "");
168 return normalized.length > 0 ? normalized : null;
170​
171export function isTailscaleIpv4Address(address: string): boolean {
172 const parts = address.split(".");
173 if (parts.length !== 4) {
174 return false;
175 }
176 const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
177 if (
178 first === undefined ||
179 second === undefined ||
180 third === undefined ||
181 fourth === undefined ||
182 [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
183 ) {
184 return false;
185 }
186 return first === 100 && second >= 64 && second <= 127;
188​
189export const parseTailscaleStatus = (
190 rawStatusJson: string,
191): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
192 decodeTailscaleStatusJson(rawStatusJson).pipe(
193 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
194 Effect.map((parsed) => {
195 const rawIps = parsed.Self?.TailscaleIPs;
196 const tailnetIpv4Addresses: Array<string> = [];
197 if (Array.isArray(rawIps)) {
198 for (const address of rawIps) {
199 if (typeof address === "string" && isTailscaleIpv4Address(address)) {
200 tailnetIpv4Addresses.push(address);
201 }
202 }
203 }
204​
205 const capMap = parsed.Self?.CapMap;
206 return {
207 magicDnsName: normalizeMagicDnsName(parsed),
208 tailnetIpv4Addresses,
209 httpsServeEnabled:
210 typeof capMap === "object" && capMap !== null && !Array.isArray(capMap)
211 ? Object.hasOwn(capMap, "https")
212 : null,
213 };
214 }),
215 );
216​
217const readTailscaleOutput = Effect.fn("tailscale.readTailscaleOutput")(function* (
218 subcommand: "status" | "debug",
219 args: readonly string[],
220) {
221 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
222 const hostPlatform = yield* HostProcess.Platform;
223 const executable = tailscaleCommandForPlatform(hostPlatform);
224 const commandContext = {
225 executable,
226 subcommand,
227 argumentCount: args.length,
228 };
229 return yield* Effect.gen(function* () {
230 const child = yield* spawner.spawn(ChildProcess.make(executable, [...args])).pipe(
231 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
232 // Spawning can also fail as a defect rather than a typed error - a
233 // non-directory entry on PATH makes node throw ENOTDIR synchronously.
234 // `mapError` never sees that, so it would escape as an uncaught error.
235 Effect.catchDefect((cause) =>
236 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
237 ),
238 );
239 const [stdout, stderr, exitCode] = yield* Effect.all(
240 [
241 collectStdout(child.stdout),
242 collectStderr(child.stderr),
243 child.exitCode.pipe(Effect.map(Number)),
244 ],
245 { concurrency: "unbounded" },
246 ).pipe(
247 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
248 );
249 if (exitCode !== 0) {
250 return yield* new TailscaleCommandExitError({
251 ...commandContext,
252 exitCode,
253 stdoutLength: stdout.length,
254 stderrLength: stderr.length,
255 ...(stderrDiagnosticOf(stderr) !== undefined
256 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
257 : {}),
258 });
259 }
260 return stdout;
261 }).pipe(
262 Effect.scoped,
263 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
264 Effect.catchTags({
265 TimeoutError: (cause) =>
266 Effect.fail(
267 new TailscaleCommandTimeoutError({
268 ...commandContext,
269 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
270 cause,
271 }),
272 ),
273 }),
274 );
275});
276​
277export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--json"]).pipe(
278 Effect.flatMap(parseTailscaleStatus),
279);
280​
281const TailscaleExitNodeJson = Schema.Struct({
282 ExitNodeStatus: Schema.optional(Schema.Struct({ Online: Schema.optional(Schema.Unknown) })),
283 Peer: Schema.optional(
284 Schema.Record(
285 Schema.String,
286 Schema.Struct({
287 ExitNode: Schema.optional(Schema.Unknown),
288 HostName: Schema.optional(Schema.Unknown),
289 DNSName: Schema.optional(Schema.Unknown),
290 }),
291 ),
292 ),
293});
294​
295const decodeTailscaleExitNodeJson = Schema.decodeEffect(
296 Schema.fromJsonString(TailscaleExitNodeJson),
297);
298​
299export interface TailscaleExitNode {
300 readonly name: string | null;
301 readonly online: boolean;
303​
304/**
305 * `ExitNodeStatus` is present only while an exit node is in use, but it has no
306 * name. The name comes from the peer marked `ExitNode: true`.
307 */
308export const parseTailscaleExitNode = (
309 rawStatusJson: string,
310): Effect.Effect<TailscaleExitNode | null, TailscaleStatusParseError> =>
311 decodeTailscaleExitNodeJson(rawStatusJson).pipe(
312 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
313 Effect.map((parsed) => {
314 if (parsed.ExitNodeStatus === undefined) return null;
315 const peer = Object.values(parsed.Peer ?? {}).find(
316 (candidate) => candidate.ExitNode === true,
317 );
318 // The DNS label is the tailnet machine name; HostName is the OS name and ignores renames.
319 const dnsLabel = typeof peer?.DNSName === "string" ? (peer.DNSName.split(".")[0] ?? "") : "";
320 const hostName = typeof peer?.HostName === "string" ? peer.HostName.trim() : "";
321 return {
322 name: dnsLabel || hostName || null,
323 online: parsed.ExitNodeStatus.Online === true,
324 };
325 }),
326 );
327​
328export const readTailscaleExitNode = readTailscaleOutput("status", ["status", "--json"]).pipe(
329 Effect.flatMap(parseTailscaleExitNode),
330);
331​
332const TailscalePrefsJson = Schema.Struct({
333 RunSSH: Schema.optional(Schema.Unknown),
334 WantRunning: Schema.optional(Schema.Unknown),
335});
336​
337const decodeTailscalePrefsJson = Schema.decodeEffect(Schema.fromJsonString(TailscalePrefsJson));
338​
339/**
340 * `tailscale status --json` does not report this for the local node. `tailscale
341 * down` clears WantRunning but keeps RunSSH, so check both.
342 */
343export const parseTailscaleSshEnabled = (
344 rawPrefsJson: string,
345): Effect.Effect<boolean, TailscaleStatusParseError> =>
346 decodeTailscalePrefsJson(rawPrefsJson).pipe(
347 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
348 Effect.map((prefs) => prefs.RunSSH === true && prefs.WantRunning !== false),
349 );
350​
351export const readTailscaleSshEnabled = readTailscaleOutput("debug", ["debug", "prefs"]).pipe(
352 Effect.flatMap(parseTailscaleSshEnabled),
353);
354​
355export function buildTailscaleHttpsBaseUrl(input: {
356 readonly magicDnsName: string;
357 readonly servePort?: number;
358}): string {
359 const url = new URL(`https://${input.magicDnsName}`);
360 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
361 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
362 url.port = String(servePort);
363 }
364 url.pathname = "/";
365 return url.toString();
367​
368const runTailscaleCommand = Effect.fn("tailscale.runTailscaleCommand")(function* (
369 args: readonly string[],
370 timeoutInput: Duration.Input,
371): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
372 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
373 const hostPlatform = yield* HostProcess.Platform;
374 const executable = tailscaleCommandForPlatform(hostPlatform);
375 const commandContext = {
376 executable,
377 subcommand: "serve" as const,
378 argumentCount: args.length,
379 };
380 const timeout = Duration.fromInputUnsafe(timeoutInput);
381 return yield* Effect.gen(function* () {
382 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
383 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
384 Effect.catchDefect((cause) =>
385 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
386 ),
387 );
388 const [stderr, exitCode] = yield* Effect.all(
389 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
390 { concurrency: "unbounded" },
391 ).pipe(
392 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
393 );
394 if (exitCode !== 0) {
395 return yield* new TailscaleCommandExitError({
396 ...commandContext,
397 exitCode,
398 stderrLength: stderr.length,
399 ...(stderrDiagnosticOf(stderr) !== undefined
400 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
401 : {}),
402 });
403 }
404 }).pipe(
405 Effect.scoped,
406 Effect.timeout(timeout),
407 Effect.catchTags({
408 TimeoutError: (cause) =>
409 Effect.fail(
410 new TailscaleCommandTimeoutError({
411 ...commandContext,
412 timeoutMs: Duration.toMillis(timeout),
413 cause,
414 }),
415 ),
416 }),
417 );
418});
419​
420export const ensureTailscaleServe = (input: {
421 readonly localPort: number;
422 readonly servePort?: number;
423 readonly localHost?: string;
424}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
425 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
426 const localHost = input.localHost ?? "127.0.0.1";
427 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
428 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
429};
430​
431export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (
432 input: {
433 readonly servePort?: number;
434 } = {},
435): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
436 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
437 return yield* runTailscaleCommand(
438 ["serve", `--https=${servePort}`, "off"],
439 TAILSCALE_SERVE_TIMEOUT,
440 );
441});
442​
443export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(
444 function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {
445 const client = yield* HttpClient.HttpClient;
446 const response = yield* Effect.gen(function* () {
447 const url = new URL("/.well-known/t3/environment", input.baseUrl);
448 const request = HttpClientRequest.get(url.toString());
449 return yield* client.execute(request);
450 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
451​
452 return Option.match(response, {
453 onNone: () => false,
454 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
455 });
456 },
457 Effect.orElseSucceed(() => false),
458);