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

tailscale.ts

381 lines13.1 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/http";
8import { ChildProcess, ChildProcessSpawner } from "effect/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 type TailscaleCommandError =
115 | TailscaleCommandSpawnError
116 | TailscaleCommandOutputError
117 | TailscaleCommandExitError
118 | TailscaleCommandTimeoutError;
119​
120export class TailscaleStatusParseError extends Schema.TaggedError<TailscaleStatusParseError>()(
121 "TailscaleStatusParseError",
122 { cause: Schema.Defect() },
123) {
124 override get message(): string {
125 return "Failed to decode tailscale status JSON.";
126 }
128​
129const TailscaleStatusSelf = Schema.Struct({
130 DNSName: Schema.optional(Schema.Unknown),
131 TailscaleIPs: Schema.optional(Schema.Unknown),
132});
133​
134const TailscaleStatusJson = Schema.Struct({
135 Self: Schema.optional(TailscaleStatusSelf),
136});
137​
138export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
139​
140export interface TailscaleStatus {
141 readonly magicDnsName: string | null;
142 readonly tailnetIpv4Addresses: readonly string[];
144​
145const collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
146 stream.pipe(
147 Stream.decodeText(),
148 Stream.runFold(
149 () => "",
150 (acc, chunk) => acc + chunk,
151 ),
152 );
153​
154const collectStderr = collectStdout;
155​
156const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
157​
158function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
159 const dnsName = status.Self?.DNSName;
160 if (typeof dnsName !== "string") {
161 return null;
162 }
163​
164 const normalized = dnsName.trim().replace(/\.$/u, "");
165 return normalized.length > 0 ? normalized : null;
167​
168export const parseTailscaleMagicDnsName = (
169 rawStatusJson: string,
170): Effect.Effect<string | null, TailscaleStatusParseError> =>
171 decodeTailscaleStatusJson(rawStatusJson).pipe(
172 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
173 Effect.map(normalizeMagicDnsName),
174 );
175​
176export function isTailscaleIpv4Address(address: string): boolean {
177 const parts = address.split(".");
178 if (parts.length !== 4) {
179 return false;
180 }
181 const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
182 if (
183 first === undefined ||
184 second === undefined ||
185 third === undefined ||
186 fourth === undefined ||
187 [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
188 ) {
189 return false;
190 }
191 return first === 100 && second >= 64 && second <= 127;
193​
194export const parseTailscaleStatus = (
195 rawStatusJson: string,
196): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
197 decodeTailscaleStatusJson(rawStatusJson).pipe(
198 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
199 Effect.map((parsed) => {
200 const rawIps = parsed.Self?.TailscaleIPs;
201 const tailnetIpv4Addresses: Array<string> = [];
202 if (Array.isArray(rawIps)) {
203 for (const address of rawIps) {
204 if (typeof address === "string" && isTailscaleIpv4Address(address)) {
205 tailnetIpv4Addresses.push(address);
206 }
207 }
208 }
209​
210 return {
211 magicDnsName: normalizeMagicDnsName(parsed),
212 tailnetIpv4Addresses,
213 };
214 }),
215 );
216​
217export const readTailscaleStatus = Effect.gen(function* () {
218 const args = ["status", "--json"];
219 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
220 const hostPlatform = yield* HostProcessPlatform;
221 const executable = tailscaleCommandForPlatform(hostPlatform);
222 const commandContext = {
223 executable,
224 subcommand: "status" as const,
225 argumentCount: args.length,
226 };
227 return yield* Effect.gen(function* () {
228 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
229 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
230 // Spawning can also fail as a defect rather than a typed error - a
231 // non-directory entry on PATH makes node throw ENOTDIR synchronously.
232 // `mapError` never sees that, so it would escape as an uncaught error.
233 Effect.catchDefect((cause) =>
234 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
235 ),
236 );
237 const [stdout, stderr, exitCode] = yield* Effect.all(
238 [
239 collectStdout(child.stdout),
240 collectStderr(child.stderr),
241 child.exitCode.pipe(Effect.map(Number)),
242 ],
243 { concurrency: "unbounded" },
244 ).pipe(
245 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
246 );
247 if (exitCode !== 0) {
248 return yield* new TailscaleCommandExitError({
249 ...commandContext,
250 exitCode,
251 stdoutLength: stdout.length,
252 stderrLength: stderr.length,
253 ...(stderrDiagnosticOf(stderr) !== undefined
254 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
255 : {}),
256 });
257 }
258 return yield* parseTailscaleStatus(stdout);
259 }).pipe(
260 Effect.scoped,
261 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
262 Effect.catchTags({
263 TimeoutError: (cause) =>
264 Effect.fail(
265 new TailscaleCommandTimeoutError({
266 ...commandContext,
267 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
268 cause,
269 }),
270 ),
271 }),
272 );
273});
274​
275export function buildTailscaleHttpsBaseUrl(input: {
276 readonly magicDnsName: string;
277 readonly servePort?: number;
278}): string {
279 const url = new URL(`https://${input.magicDnsName}`);
280 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
281 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
282 url.port = String(servePort);
283 }
284 url.pathname = "/";
285 return url.toString();
287​
288const runTailscaleCommand = (
289 args: readonly string[],
290 timeoutInput: Duration.Input,
291): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
292 Effect.gen(function* () {
293 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
294 const hostPlatform = yield* HostProcessPlatform;
295 const executable = tailscaleCommandForPlatform(hostPlatform);
296 const commandContext = {
297 executable,
298 subcommand: "serve" as const,
299 argumentCount: args.length,
300 };
301 const timeout = Duration.fromInputUnsafe(timeoutInput);
302 return yield* Effect.gen(function* () {
303 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
304 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
305 Effect.catchDefect((cause) =>
306 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
307 ),
308 );
309 const [stderr, exitCode] = yield* Effect.all(
310 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
311 { concurrency: "unbounded" },
312 ).pipe(
313 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
314 );
315 if (exitCode !== 0) {
316 return yield* new TailscaleCommandExitError({
317 ...commandContext,
318 exitCode,
319 stderrLength: stderr.length,
320 ...(stderrDiagnosticOf(stderr) !== undefined
321 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
322 : {}),
323 });
324 }
325 }).pipe(
326 Effect.scoped,
327 Effect.timeout(timeout),
328 Effect.catchTags({
329 TimeoutError: (cause) =>
330 Effect.fail(
331 new TailscaleCommandTimeoutError({
332 ...commandContext,
333 timeoutMs: Duration.toMillis(timeout),
334 cause,
335 }),
336 ),
337 }),
338 );
339 });
340​
341export const ensureTailscaleServe = (input: {
342 readonly localPort: number;
343 readonly servePort?: number;
344 readonly localHost?: string;
345}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
346 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
347 const localHost = input.localHost ?? "127.0.0.1";
348 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
349 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
350};
351​
352export const disableTailscaleServe = (
353 input: {
354 readonly servePort?: number;
355 } = {},
356): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
357 Effect.gen(function* () {
358 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
359 return yield* runTailscaleCommand(
360 ["serve", `--https=${servePort}`, "off"],
361 TAILSCALE_SERVE_TIMEOUT,
362 );
363 });
364​
365export const probeTailscaleHttpsEndpoint = (input: {
366 readonly baseUrl: string;
367 readonly timeout?: Duration.Input;
368}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
369 Effect.gen(function* () {
370 const client = yield* HttpClient.HttpClient;
371 const response = yield* Effect.gen(function* () {
372 const url = new URL("/.well-known/t3/environment", input.baseUrl);
373 const request = HttpClientRequest.get(url.toString());
374 return yield* client.execute(request);
375 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
376​
377 return Option.match(response, {
378 onNone: () => false,
379 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
380 });
381 }).pipe(Effect.orElseSucceed(() => false));