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

tailscale.ts

415 lines14.1 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 */
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 }
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 const parseTailscaleMagicDnsName = (
172 rawStatusJson: string,
173): Effect.Effect<string | null, TailscaleStatusParseError> =>
174 decodeTailscaleStatusJson(rawStatusJson).pipe(
175 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
176 Effect.map(normalizeMagicDnsName),
177 );
178​
179export function isTailscaleIpv4Address(address: string): boolean {
180 const parts = address.split(".");
181 if (parts.length !== 4) {
182 return false;
183 }
184 const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
185 if (
186 first === undefined ||
187 second === undefined ||
188 third === undefined ||
189 fourth === undefined ||
190 [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
191 ) {
192 return false;
193 }
194 return first === 100 && second >= 64 && second <= 127;
196​
197export const parseTailscaleStatus = (
198 rawStatusJson: string,
199): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
200 decodeTailscaleStatusJson(rawStatusJson).pipe(
201 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
202 Effect.map((parsed) => {
203 const rawIps = parsed.Self?.TailscaleIPs;
204 const tailnetIpv4Addresses: Array<string> = [];
205 if (Array.isArray(rawIps)) {
206 for (const address of rawIps) {
207 if (typeof address === "string" && isTailscaleIpv4Address(address)) {
208 tailnetIpv4Addresses.push(address);
209 }
210 }
211 }
212​
213 const capMap = parsed.Self?.CapMap;
214 return {
215 magicDnsName: normalizeMagicDnsName(parsed),
216 tailnetIpv4Addresses,
217 httpsServeEnabled:
218 typeof capMap === "object" && capMap !== null && !Array.isArray(capMap)
219 ? Object.hasOwn(capMap, "https")
220 : null,
221 };
222 }),
223 );
224​
225const readTailscaleOutput = Effect.fn("tailscale.readTailscaleOutput")(function* (
226 subcommand: "status" | "debug",
227 args: readonly string[],
228) {
229 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
230 const hostPlatform = yield* HostProcess.Platform;
231 const executable = tailscaleCommandForPlatform(hostPlatform);
232 const commandContext = {
233 executable,
234 subcommand,
235 argumentCount: args.length,
236 };
237 return yield* Effect.gen(function* () {
238 const child = yield* spawner.spawn(ChildProcess.make(executable, [...args])).pipe(
239 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
240 // Spawning can also fail as a defect rather than a typed error - a
241 // non-directory entry on PATH makes node throw ENOTDIR synchronously.
242 // `mapError` never sees that, so it would escape as an uncaught error.
243 Effect.catchDefect((cause) =>
244 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
245 ),
246 );
247 const [stdout, stderr, exitCode] = yield* Effect.all(
248 [
249 collectStdout(child.stdout),
250 collectStderr(child.stderr),
251 child.exitCode.pipe(Effect.map(Number)),
252 ],
253 { concurrency: "unbounded" },
254 ).pipe(
255 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
256 );
257 if (exitCode !== 0) {
258 return yield* new TailscaleCommandExitError({
259 ...commandContext,
260 exitCode,
261 stdoutLength: stdout.length,
262 stderrLength: stderr.length,
263 ...(stderrDiagnosticOf(stderr) !== undefined
264 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
265 : {}),
266 });
267 }
268 return stdout;
269 }).pipe(
270 Effect.scoped,
271 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
272 Effect.catchTags({
273 TimeoutError: (cause) =>
274 Effect.fail(
275 new TailscaleCommandTimeoutError({
276 ...commandContext,
277 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
278 cause,
279 }),
280 ),
281 }),
282 );
283});
284​
285export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--json"]).pipe(
286 Effect.flatMap(parseTailscaleStatus),
287);
288​
289const TailscalePrefsJson = Schema.Struct({
290 RunSSH: Schema.optional(Schema.Unknown),
291 WantRunning: Schema.optional(Schema.Unknown),
292});
293​
294const decodeTailscalePrefsJson = Schema.decodeEffect(Schema.fromJsonString(TailscalePrefsJson));
295​
296/**
297 * `tailscale status --json` does not report this for the local node. `tailscale
298 * down` clears WantRunning but keeps RunSSH, so check both.
299 */
300export const parseTailscaleSshEnabled = (
301 rawPrefsJson: string,
302): Effect.Effect<boolean, TailscaleStatusParseError> =>
303 decodeTailscalePrefsJson(rawPrefsJson).pipe(
304 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
305 Effect.map((prefs) => prefs.RunSSH === true && prefs.WantRunning !== false),
306 );
307​
308export const readTailscaleSshEnabled = readTailscaleOutput("debug", ["debug", "prefs"]).pipe(
309 Effect.flatMap(parseTailscaleSshEnabled),
310);
311​
312export function buildTailscaleHttpsBaseUrl(input: {
313 readonly magicDnsName: string;
314 readonly servePort?: number;
315}): string {
316 const url = new URL(`https://${input.magicDnsName}`);
317 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
318 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
319 url.port = String(servePort);
320 }
321 url.pathname = "/";
322 return url.toString();
324​
325const runTailscaleCommand = Effect.fn("tailscale.runTailscaleCommand")(function* (
326 args: readonly string[],
327 timeoutInput: Duration.Input,
328): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
329 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
330 const hostPlatform = yield* HostProcess.Platform;
331 const executable = tailscaleCommandForPlatform(hostPlatform);
332 const commandContext = {
333 executable,
334 subcommand: "serve" as const,
335 argumentCount: args.length,
336 };
337 const timeout = Duration.fromInputUnsafe(timeoutInput);
338 return yield* Effect.gen(function* () {
339 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
340 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
341 Effect.catchDefect((cause) =>
342 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
343 ),
344 );
345 const [stderr, exitCode] = yield* Effect.all(
346 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
347 { concurrency: "unbounded" },
348 ).pipe(
349 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
350 );
351 if (exitCode !== 0) {
352 return yield* new TailscaleCommandExitError({
353 ...commandContext,
354 exitCode,
355 stderrLength: stderr.length,
356 ...(stderrDiagnosticOf(stderr) !== undefined
357 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
358 : {}),
359 });
360 }
361 }).pipe(
362 Effect.scoped,
363 Effect.timeout(timeout),
364 Effect.catchTags({
365 TimeoutError: (cause) =>
366 Effect.fail(
367 new TailscaleCommandTimeoutError({
368 ...commandContext,
369 timeoutMs: Duration.toMillis(timeout),
370 cause,
371 }),
372 ),
373 }),
374 );
375});
376​
377export const ensureTailscaleServe = (input: {
378 readonly localPort: number;
379 readonly servePort?: number;
380 readonly localHost?: string;
381}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
382 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
383 const localHost = input.localHost ?? "127.0.0.1";
384 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
385 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
386};
387​
388export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (
389 input: {
390 readonly servePort?: number;
391 } = {},
392): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
393 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
394 return yield* runTailscaleCommand(
395 ["serve", `--https=${servePort}`, "off"],
396 TAILSCALE_SERVE_TIMEOUT,
397 );
398});
399​
400export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(
401 function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {
402 const client = yield* HttpClient.HttpClient;
403 const response = yield* Effect.gen(function* () {
404 const url = new URL("/.well-known/t3/environment", input.baseUrl);
405 const request = HttpClientRequest.get(url.toString());
406 return yield* client.execute(request);
407 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
408​
409 return Option.match(response, {
410 onNone: () => false,
411 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
412 });
413 },
414 Effect.orElseSucceed(() => false),
415);