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

tailscale.ts

383 lines13.2 KB

1import { HostProcessPlatform } 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/unstable/http";
8import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
9​
10export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
11export const TAILSCALE_STATUS_TIMEOUT = Duration.millis(1_500);
12const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);
13const TAILSCALE_PROBE_TIMEOUT = Duration.millis(2_500);
14​
15// tailscale is a real executable everywhere (`tailscale.exe` on Windows), so
16// it is always spawned directly rather than through cmd.exe shell mode.
17const tailscaleCommandForPlatform = (platform: NodeJS.Platform): "tailscale" | "tailscale.exe" =>
18 platform === "win32" ? "tailscale.exe" : "tailscale";
19​
20const TailscaleCommandContext = {
21 executable: Schema.Literals(["tailscale", "tailscale.exe"]),
22 subcommand: Schema.Literals(["status", "serve"]),
23 argumentCount: Schema.Number,
24};
25​
26/**
27 * Failure kinds we can name without quoting the CLI. Anything unrecognized
28 * becomes "unknown" rather than falling back to raw text — stderr can contain
29 * auth keys (`tskey-…`) and node names, and these labels are logged.
30 */
31export const TailscaleStderrDiagnostic = Schema.Literals([
32 "no-existing-handler",
33 "not-logged-in",
34 "permission-denied",
35 "unknown",
36]);
37export type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;
38​
39// Matched against stderr, most specific first. Patterns are deliberately short
40// and anchored on tailscale's own wording.
41const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
42 readonly [RegExp, Exclude<TailscaleStderrDiagnostic, "unknown">]
43> = [
44 [/handler does not exist/i, "no-existing-handler"],
45 [/not logged in|logged out|needs? login/i, "not-logged-in"],
46 [/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
47];
48​
49/** Classifies stderr into a safe label, dropping the text itself. */
50const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {
51 if (stderr.trim().length === 0) {
52 return undefined;
53 }
54 return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? "unknown";
55};
56​
57export class TailscaleCommandSpawnError extends Schema.TaggedError<TailscaleCommandSpawnError>()(
58 "TailscaleCommandSpawnError",
59 {
60 ...TailscaleCommandContext,
61 cause: Schema.Defect(),
62 },
63) {
64 override get message(): string {
65 return `Failed to spawn tailscale ${this.subcommand}.`;
66 }
68​
69class TailscaleCommandOutputError extends Schema.TaggedError<TailscaleCommandOutputError>()(
70 "TailscaleCommandOutputError",
71 {
72 ...TailscaleCommandContext,
73 cause: Schema.Defect(),
74 },
75) {
76 override get message(): string {
77 return `Failed to read output from tailscale ${this.subcommand}.`;
78 }
80​
81export class TailscaleCommandExitError extends Schema.TaggedError<TailscaleCommandExitError>()(
82 "TailscaleCommandExitError",
83 {
84 ...TailscaleCommandContext,
85 exitCode: Schema.Number,
86 stdoutLength: Schema.optional(Schema.Number),
87 stderrLength: Schema.Number,
88 // A classified diagnostic, never raw CLI output. `tailscale` prints auth
89 // keys and node identifiers into stderr, and this field is surfaced in
90 // dev-runner logs — so it carries only a known-safe label from the closed
91 // set below. Callers that need to recognize a specific failure (e.g.
92 // `serve off` on a port with no mapping) match on the label.
93 stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
94 },
95) {
96 override get message(): string {
97 return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;
98 }
100​
101export class TailscaleCommandTimeoutError extends Schema.TaggedError<TailscaleCommandTimeoutError>()(
102 "TailscaleCommandTimeoutError",
103 {
104 ...TailscaleCommandContext,
105 timeoutMs: Schema.Number,
106 cause: Schema.Defect(),
107 },
108) {
109 override get message(): string {
110 return `tailscale ${this.subcommand} timed out after ${this.timeoutMs}ms.`;
111 }
113​
114export const TailscaleCommandError = Schema.Union([
115 TailscaleCommandSpawnError,
116 TailscaleCommandOutputError,
117 TailscaleCommandExitError,
118 TailscaleCommandTimeoutError,
119]);
120export type TailscaleCommandError = typeof TailscaleCommandError.Type;
121​
122export class TailscaleStatusParseError extends Schema.TaggedError<TailscaleStatusParseError>()(
123 "TailscaleStatusParseError",
124 { cause: Schema.Defect() },
125) {
126 override get message(): string {
127 return "Failed to decode tailscale status JSON.";
128 }
130​
131const TailscaleStatusSelf = Schema.Struct({
132 DNSName: Schema.optional(Schema.Unknown),
133 TailscaleIPs: Schema.optional(Schema.Unknown),
134});
135​
136const TailscaleStatusJson = Schema.Struct({
137 Self: Schema.optional(TailscaleStatusSelf),
138});
139​
140export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
141​
142export interface TailscaleStatus {
143 readonly magicDnsName: string | null;
144 readonly tailnetIpv4Addresses: readonly string[];
146​
147const collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
148 stream.pipe(
149 Stream.decodeText(),
150 Stream.runFold(
151 () => "",
152 (acc, chunk) => acc + chunk,
153 ),
154 );
155​
156const collectStderr = collectStdout;
157​
158const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
159​
160function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
161 const dnsName = status.Self?.DNSName;
162 if (typeof dnsName !== "string") {
163 return null;
164 }
165​
166 const normalized = dnsName.trim().replace(/\.$/u, "");
167 return normalized.length > 0 ? normalized : null;
169​
170export const parseTailscaleMagicDnsName = (
171 rawStatusJson: string,
172): Effect.Effect<string | null, TailscaleStatusParseError> =>
173 decodeTailscaleStatusJson(rawStatusJson).pipe(
174 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
175 Effect.map(normalizeMagicDnsName),
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;
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 return {
213 magicDnsName: normalizeMagicDnsName(parsed),
214 tailnetIpv4Addresses,
215 };
216 }),
217 );
218​
219export const readTailscaleStatus = Effect.gen(function* () {
220 const args = ["status", "--json"];
221 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
222 const hostPlatform = yield* HostProcessPlatform;
223 const executable = tailscaleCommandForPlatform(hostPlatform);
224 const commandContext = {
225 executable,
226 subcommand: "status" as const,
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 yield* parseTailscaleStatus(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 function buildTailscaleHttpsBaseUrl(input: {
278 readonly magicDnsName: string;
279 readonly servePort?: number;
280}): string {
281 const url = new URL(`https://${input.magicDnsName}`);
282 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
283 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
284 url.port = String(servePort);
285 }
286 url.pathname = "/";
287 return url.toString();
289​
290const runTailscaleCommand = (
291 args: readonly string[],
292 timeoutInput: Duration.Input,
293): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
294 Effect.gen(function* () {
295 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
296 const hostPlatform = yield* HostProcessPlatform;
297 const executable = tailscaleCommandForPlatform(hostPlatform);
298 const commandContext = {
299 executable,
300 subcommand: "serve" as const,
301 argumentCount: args.length,
302 };
303 const timeout = Duration.fromInputUnsafe(timeoutInput);
304 return yield* Effect.gen(function* () {
305 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
306 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
307 Effect.catchDefect((cause) =>
308 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
309 ),
310 );
311 const [stderr, exitCode] = yield* Effect.all(
312 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
313 { concurrency: "unbounded" },
314 ).pipe(
315 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
316 );
317 if (exitCode !== 0) {
318 return yield* new TailscaleCommandExitError({
319 ...commandContext,
320 exitCode,
321 stderrLength: stderr.length,
322 ...(stderrDiagnosticOf(stderr) !== undefined
323 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
324 : {}),
325 });
326 }
327 }).pipe(
328 Effect.scoped,
329 Effect.timeout(timeout),
330 Effect.catchTags({
331 TimeoutError: (cause) =>
332 Effect.fail(
333 new TailscaleCommandTimeoutError({
334 ...commandContext,
335 timeoutMs: Duration.toMillis(timeout),
336 cause,
337 }),
338 ),
339 }),
340 );
341 });
342​
343export const ensureTailscaleServe = (input: {
344 readonly localPort: number;
345 readonly servePort?: number;
346 readonly localHost?: string;
347}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
348 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
349 const localHost = input.localHost ?? "127.0.0.1";
350 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
351 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
352};
353​
354export const disableTailscaleServe = (
355 input: {
356 readonly servePort?: number;
357 } = {},
358): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
359 Effect.gen(function* () {
360 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
361 return yield* runTailscaleCommand(
362 ["serve", `--https=${servePort}`, "off"],
363 TAILSCALE_SERVE_TIMEOUT,
364 );
365 });
366​
367export const probeTailscaleHttpsEndpoint = (input: {
368 readonly baseUrl: string;
369 readonly timeout?: Duration.Input;
370}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
371 Effect.gen(function* () {
372 const client = yield* HttpClient.HttpClient;
373 const response = yield* Effect.gen(function* () {
374 const url = new URL("/.well-known/t3/environment", input.baseUrl);
375 const request = HttpClientRequest.get(url.toString());
376 return yield* client.execute(request);
377 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
378​
379 return Option.match(response, {
380 onNone: () => false,
381 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
382 });
383 }).pipe(Effect.orElseSucceed(() => false));