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

tailscale.ts

404 lines13.7 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});
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[];
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;
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;
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 = (subcommand: "status" | "debug", args: readonly string[]) =>
214 Effect.gen(function* () {
215 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
216 const hostPlatform = yield* HostProcess.Platform;
217 const executable = tailscaleCommandForPlatform(hostPlatform);
218 const commandContext = {
219 executable,
220 subcommand,
221 argumentCount: args.length,
222 };
223 return yield* Effect.gen(function* () {
224 const child = yield* spawner.spawn(ChildProcess.make(executable, [...args])).pipe(
225 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
226 // Spawning can also fail as a defect rather than a typed error - a
227 // non-directory entry on PATH makes node throw ENOTDIR synchronously.
228 // `mapError` never sees that, so it would escape as an uncaught error.
229 Effect.catchDefect((cause) =>
230 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
231 ),
232 );
233 const [stdout, stderr, exitCode] = yield* Effect.all(
234 [
235 collectStdout(child.stdout),
236 collectStderr(child.stderr),
237 child.exitCode.pipe(Effect.map(Number)),
238 ],
239 { concurrency: "unbounded" },
240 ).pipe(
241 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
242 );
243 if (exitCode !== 0) {
244 return yield* new TailscaleCommandExitError({
245 ...commandContext,
246 exitCode,
247 stdoutLength: stdout.length,
248 stderrLength: stderr.length,
249 ...(stderrDiagnosticOf(stderr) !== undefined
250 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
251 : {}),
252 });
253 }
254 return stdout;
255 }).pipe(
256 Effect.scoped,
257 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
258 Effect.catchTags({
259 TimeoutError: (cause) =>
260 Effect.fail(
261 new TailscaleCommandTimeoutError({
262 ...commandContext,
263 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
264 cause,
265 }),
266 ),
267 }),
268 );
269 });
270​
271export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--json"]).pipe(
272 Effect.flatMap(parseTailscaleStatus),
273);
274​
275const TailscalePrefsJson = Schema.Struct({
276 RunSSH: Schema.optional(Schema.Unknown),
277 WantRunning: Schema.optional(Schema.Unknown),
278});
279​
280const decodeTailscalePrefsJson = Schema.decodeEffect(Schema.fromJsonString(TailscalePrefsJson));
281​
282/**
283 * `tailscale status --json` does not report this for the local node. `tailscale
284 * down` clears WantRunning but keeps RunSSH, so check both.
285 */
286export const parseTailscaleSshEnabled = (
287 rawPrefsJson: string,
288): Effect.Effect<boolean, TailscaleStatusParseError> =>
289 decodeTailscalePrefsJson(rawPrefsJson).pipe(
290 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
291 Effect.map((prefs) => prefs.RunSSH === true && prefs.WantRunning !== false),
292 );
293​
294export const readTailscaleSshEnabled = readTailscaleOutput("debug", ["debug", "prefs"]).pipe(
295 Effect.flatMap(parseTailscaleSshEnabled),
296);
297​
298export function buildTailscaleHttpsBaseUrl(input: {
299 readonly magicDnsName: string;
300 readonly servePort?: number;
301}): string {
302 const url = new URL(`https://${input.magicDnsName}`);
303 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
304 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
305 url.port = String(servePort);
306 }
307 url.pathname = "/";
308 return url.toString();
310​
311const runTailscaleCommand = (
312 args: readonly string[],
313 timeoutInput: Duration.Input,
314): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
315 Effect.gen(function* () {
316 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
317 const hostPlatform = yield* HostProcess.Platform;
318 const executable = tailscaleCommandForPlatform(hostPlatform);
319 const commandContext = {
320 executable,
321 subcommand: "serve" as const,
322 argumentCount: args.length,
323 };
324 const timeout = Duration.fromInputUnsafe(timeoutInput);
325 return yield* Effect.gen(function* () {
326 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
327 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
328 Effect.catchDefect((cause) =>
329 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
330 ),
331 );
332 const [stderr, exitCode] = yield* Effect.all(
333 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
334 { concurrency: "unbounded" },
335 ).pipe(
336 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
337 );
338 if (exitCode !== 0) {
339 return yield* new TailscaleCommandExitError({
340 ...commandContext,
341 exitCode,
342 stderrLength: stderr.length,
343 ...(stderrDiagnosticOf(stderr) !== undefined
344 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
345 : {}),
346 });
347 }
348 }).pipe(
349 Effect.scoped,
350 Effect.timeout(timeout),
351 Effect.catchTags({
352 TimeoutError: (cause) =>
353 Effect.fail(
354 new TailscaleCommandTimeoutError({
355 ...commandContext,
356 timeoutMs: Duration.toMillis(timeout),
357 cause,
358 }),
359 ),
360 }),
361 );
362 });
363​
364export const ensureTailscaleServe = (input: {
365 readonly localPort: number;
366 readonly servePort?: number;
367 readonly localHost?: string;
368}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
369 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
370 const localHost = input.localHost ?? "127.0.0.1";
371 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
372 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
373};
374​
375export const disableTailscaleServe = (
376 input: {
377 readonly servePort?: number;
378 } = {},
379): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
380 Effect.gen(function* () {
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 = (input: {
389 readonly baseUrl: string;
390 readonly timeout?: Duration.Input;
391}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
392 Effect.gen(function* () {
393 const client = yield* HttpClient.HttpClient;
394 const response = yield* Effect.gen(function* () {
395 const url = new URL("/.well-known/t3/environment", input.baseUrl);
396 const request = HttpClientRequest.get(url.toString());
397 return yield* client.execute(request);
398 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
399​
400 return Option.match(response, {
401 onNone: () => false,
402 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
403 });
404 }).pipe(Effect.orElseSucceed(() => false));