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

tailscale.ts

464 lines16.0 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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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​
160// `tailscale serve status --json` nests the mapping under
161// Web["<host>:<port>"].Handlers["/"].Proxy. Only that leaf is needed and the
162// surrounding shape moves between tailscale releases, so it is walked as
163// unknown rather than modelled.
164const TailscaleServeStatusJson = Schema.Struct({
165 Web: Schema.optional(Schema.Unknown),
166});
167​
168const decodeTailscaleServeStatusJson = Schema.decodeEffect(
169 Schema.fromJsonString(TailscaleServeStatusJson),
170);
171​
172function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
173 const dnsName = status.Self?.DNSName;
174 if (typeof dnsName !== "string") {
175 return null;
176 }
177​
178 const normalized = dnsName.trim().replace(/\.$/u, "");
179 return normalized.length > 0 ? normalized : null;
181​
182export const parseTailscaleMagicDnsName = (
183 rawStatusJson: string,
184): Effect.Effect<string | null, TailscaleStatusParseError> =>
185 decodeTailscaleStatusJson(rawStatusJson).pipe(
186 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
187 Effect.map(normalizeMagicDnsName),
188 );
189​
190export function isTailscaleIpv4Address(address: string): boolean {
191 const parts = address.split(".");
192 if (parts.length !== 4) {
193 return false;
194 }
195 const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
196 if (
197 first === undefined ||
198 second === undefined ||
199 third === undefined ||
200 fourth === undefined ||
201 [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
202 ) {
203 return false;
204 }
205 return first === 100 && second >= 64 && second <= 127;
207​
208export const parseTailscaleStatus = (
209 rawStatusJson: string,
210): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
211 decodeTailscaleStatusJson(rawStatusJson).pipe(
212 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
213 Effect.map((parsed) => {
214 const rawIps = parsed.Self?.TailscaleIPs;
215 const tailnetIpv4Addresses: Array<string> = [];
216 if (Array.isArray(rawIps)) {
217 for (const address of rawIps) {
218 if (typeof address === "string" && isTailscaleIpv4Address(address)) {
219 tailnetIpv4Addresses.push(address);
220 }
221 }
222 }
223​
224 return {
225 magicDnsName: normalizeMagicDnsName(parsed),
226 tailnetIpv4Addresses,
227 };
228 }),
229 );
230​
231/**
232 * Runs a tailscale subcommand and returns its stdout. Shared by every reader
233 * here so the scoped spawn, the timeout, and the redacted error shape stay
234 * identical across `status` and `serve status`.
235 */
236const captureTailscaleCommand = (
237 args: readonly string[],
238 subcommand: "status" | "serve",
239 timeoutInput: Duration.Input,
240): Effect.Effect<string, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
241 Effect.gen(function* () {
242 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
243 const hostPlatform = yield* HostProcessPlatform;
244 const executable = tailscaleCommandForPlatform(hostPlatform);
245 const commandContext = {
246 executable,
247 subcommand,
248 argumentCount: args.length,
249 };
250 const timeout = Duration.fromInputUnsafe(timeoutInput);
251 return yield* Effect.gen(function* () {
252 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
253 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
254 // Spawning can also fail as a defect rather than a typed error - a
255 // non-directory entry on PATH makes node throw ENOTDIR synchronously.
256 // `mapError` never sees that, so it would escape as an uncaught error.
257 Effect.catchDefect((cause) =>
258 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
259 ),
260 );
261 const [stdout, stderr, exitCode] = yield* Effect.all(
262 [
263 collectStdout(child.stdout),
264 collectStderr(child.stderr),
265 child.exitCode.pipe(Effect.map(Number)),
266 ],
267 { concurrency: "unbounded" },
268 ).pipe(
269 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
270 );
271 if (exitCode !== 0) {
272 return yield* new TailscaleCommandExitError({
273 ...commandContext,
274 exitCode,
275 stdoutLength: stdout.length,
276 stderrLength: stderr.length,
277 ...(stderrDiagnosticOf(stderr) !== undefined
278 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
279 : {}),
280 });
281 }
282 return stdout;
283 }).pipe(
284 Effect.scoped,
285 Effect.timeout(timeout),
286 Effect.catchTags({
287 TimeoutError: (cause) =>
288 Effect.fail(
289 new TailscaleCommandTimeoutError({
290 ...commandContext,
291 timeoutMs: Duration.toMillis(timeout),
292 cause,
293 }),
294 ),
295 }),
296 );
297 });
298​
299export const readTailscaleStatus = captureTailscaleCommand(
300 ["status", "--json"],
301 "status",
302 TAILSCALE_STATUS_TIMEOUT,
303).pipe(Effect.flatMap(parseTailscaleStatus));
304​
305export function buildTailscaleHttpsBaseUrl(input: {
306 readonly magicDnsName: string;
307 readonly servePort?: number;
308}): string {
309 const url = new URL(`https://${input.magicDnsName}`);
310 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
311 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
312 url.port = String(servePort);
313 }
314 url.pathname = "/";
315 return url.toString();
317​
318const runTailscaleCommand = (
319 args: readonly string[],
320 timeoutInput: Duration.Input,
321): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
322 captureTailscaleCommand(args, "serve", timeoutInput).pipe(Effect.asVoid);
323​
324export const ensureTailscaleServe = (input: {
325 readonly localPort: number;
326 readonly servePort?: number;
327 readonly localHost?: string;
328}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
329 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
330 const localHost = input.localHost ?? "127.0.0.1";
331 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
332 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
333};
334​
335export const disableTailscaleServe = (
336 input: {
337 readonly servePort?: number;
338 } = {},
339): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
340 Effect.gen(function* () {
341 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
342 return yield* runTailscaleCommand(
343 ["serve", `--https=${servePort}`, "off"],
344 TAILSCALE_SERVE_TIMEOUT,
345 );
346 });
347​
348export const probeTailscaleHttpsEndpoint = (input: {
349 readonly baseUrl: string;
350 readonly timeout?: Duration.Input;
351}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
352 Effect.gen(function* () {
353 const client = yield* HttpClient.HttpClient;
354 const response = yield* Effect.gen(function* () {
355 const url = new URL("/.well-known/t3/environment", input.baseUrl);
356 const request = HttpClientRequest.get(url.toString());
357 return yield* client.execute(request);
358 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
359​
360 return Option.match(response, {
361 onNone: () => false,
362 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
363 });
364 }).pipe(Effect.orElseSucceed(() => false));
365​
366/** Where a serve mapping points: the local origin Tailscale proxies to. */
367export interface TailscaleServeTarget {
368 readonly localHost: string;
369 readonly localPort: number;
371​
372/**
373 * The Web section is keyed by "<host>:<port>"; a key without a port is the
374 * implicit HTTPS default.
375 */
376const servePortOfWebKey = (hostPort: string): number => {
377 const separator = hostPort.lastIndexOf(":");
378 if (separator === -1) {
379 return DEFAULT_TAILSCALE_SERVE_PORT;
380 }
381 const port = Number.parseInt(hostPort.slice(separator + 1), 10);
382 return Number.isInteger(port) ? port : DEFAULT_TAILSCALE_SERVE_PORT;
383};
384​
385const rootProxyOfWebEntry = (entry: unknown): string | undefined => {
386 if (typeof entry !== "object" || entry === null) {
387 return undefined;
388 }
389 const handlers = (entry as { readonly Handlers?: unknown }).Handlers;
390 if (typeof handlers !== "object" || handlers === null) {
391 return undefined;
392 }
393 const root = (handlers as Record<string, unknown>)["/"];
394 if (typeof root !== "object" || root === null) {
395 return undefined;
396 }
397 const proxy = (root as { readonly Proxy?: unknown }).Proxy;
398 return typeof proxy === "string" && proxy.length > 0 ? proxy : undefined;
399};
400​
401const parseProxyTarget = (proxy: string): TailscaleServeTarget | null => {
402 // Tailscale writes a full URL, but a bare host:port is tolerated so a
403 // hand-written mapping classifies as occupied instead of as absent.
404 for (const candidate of [proxy, `http://${proxy}`]) {
405 let url: URL;
406 try {
407 url = new URL(candidate);
408 } catch {
409 continue;
410 }
411 const port =
412 url.port.length > 0 ? Number.parseInt(url.port, 10) : url.protocol === "https:" ? 443 : 80;
413 if (!Number.isInteger(port) || url.hostname.length === 0) {
414 continue;
415 }
416 return { localHost: url.hostname, localPort: port };
417 }
418 return null;
419};
420​
421/**
422 * The local target of the serve mapping on `servePort`, or null when that port
423 * carries no mapping this can read as a proxy.
424 */
425export const parseTailscaleServeTarget = (
426 rawServeStatusJson: string,
427 input: { readonly servePort?: number } = {},
428): Effect.Effect<TailscaleServeTarget | null, TailscaleStatusParseError> =>
429 decodeTailscaleServeStatusJson(rawServeStatusJson).pipe(
430 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
431 Effect.map((parsed) => {
432 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
433 const web = parsed.Web;
434 if (typeof web !== "object" || web === null) {
435 return null;
436 }
437 for (const [hostPort, entry] of Object.entries(web as Record<string, unknown>)) {
438 if (servePortOfWebKey(hostPort) !== servePort) {
439 continue;
440 }
441 const proxy = rootProxyOfWebEntry(entry);
442 if (proxy === undefined) {
443 continue;
444 }
445 return parseProxyTarget(proxy);
446 }
447 return null;
448 }),
449 );
450​
451/**
452 * Reads who currently owns the serve mapping. Callers use this to avoid
453 * repointing a mapping that already fronts a live server.
454 */
455export const readTailscaleServeTarget = (
456 input: { readonly servePort?: number } = {},
457): Effect.Effect<
458 TailscaleServeTarget | null,
459 TailscaleCommandError | TailscaleStatusParseError,
460 ChildProcessSpawner.ChildProcessSpawner
461> =>
462 captureTailscaleCommand(["serve", "status", "--json"], "serve", TAILSCALE_STATUS_TIMEOUT).pipe(
463 Effect.flatMap((stdout) => parseTailscaleServeTarget(stdout, input)),
464 );