Open History to see the last commit
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);
12export const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);
13export const 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. */
50export const 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 }
67}
68
69export class 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 }
79}
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 }
99}
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 }
112}
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 }
129}
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 TailscaleStatusSelf = typeof TailscaleStatusSelf.Type;
141export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
142
143export interface TailscaleStatus {
144 readonly magicDnsName: string | null;
145 readonly tailnetIpv4Addresses: readonly string[];
146}
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;
169}
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;
195}
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 return {
214 magicDnsName: normalizeMagicDnsName(parsed),
215 tailnetIpv4Addresses,
216 };
217 }),
218 );
219
220export const readTailscaleStatus = Effect.gen(function* () {
221 const args = ["status", "--json"];
222 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
223 const hostPlatform = yield* HostProcessPlatform;
224 const executable = tailscaleCommandForPlatform(hostPlatform);
225 const commandContext = {
226 executable,
227 subcommand: "status" as const,
228 argumentCount: args.length,
229 };
230 return yield* Effect.gen(function* () {
231 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
232 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
233 // Spawning can also fail as a defect rather than a typed error - a
234 // non-directory entry on PATH makes node throw ENOTDIR synchronously.
235 // `mapError` never sees that, so it would escape as an uncaught error.
236 Effect.catchDefect((cause) =>
237 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
238 ),
239 );
240 const [stdout, stderr, exitCode] = yield* Effect.all(
241 [
242 collectStdout(child.stdout),
243 collectStderr(child.stderr),
244 child.exitCode.pipe(Effect.map(Number)),
245 ],
246 { concurrency: "unbounded" },
247 ).pipe(
248 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
249 );
250 if (exitCode !== 0) {
251 return yield* new TailscaleCommandExitError({
252 ...commandContext,
253 exitCode,
254 stdoutLength: stdout.length,
255 stderrLength: stderr.length,
256 ...(stderrDiagnosticOf(stderr) !== undefined
257 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
258 : {}),
259 });
260 }
261 return yield* parseTailscaleStatus(stdout);
262 }).pipe(
263 Effect.scoped,
264 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
265 Effect.catchTags({
266 TimeoutError: (cause) =>
267 Effect.fail(
268 new TailscaleCommandTimeoutError({
269 ...commandContext,
270 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
271 cause,
272 }),
273 ),
274 }),
275 );
276});
277
278export function buildTailscaleHttpsBaseUrl(input: {
279 readonly magicDnsName: string;
280 readonly servePort?: number;
281}): string {
282 const url = new URL(`https://${input.magicDnsName}`);
283 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
284 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
285 url.port = String(servePort);
286 }
287 url.pathname = "/";
288 return url.toString();
289}
290
291const runTailscaleCommand = (
292 args: readonly string[],
293 timeoutInput: Duration.Input,
294): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
295 Effect.gen(function* () {
296 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
297 const hostPlatform = yield* HostProcessPlatform;
298 const executable = tailscaleCommandForPlatform(hostPlatform);
299 const commandContext = {
300 executable,
301 subcommand: "serve" as const,
302 argumentCount: args.length,
303 };
304 const timeout = Duration.fromInputUnsafe(timeoutInput);
305 return yield* Effect.gen(function* () {
306 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
307 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
308 Effect.catchDefect((cause) =>
309 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
310 ),
311 );
312 const [stderr, exitCode] = yield* Effect.all(
313 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
314 { concurrency: "unbounded" },
315 ).pipe(
316 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
317 );
318 if (exitCode !== 0) {
319 return yield* new TailscaleCommandExitError({
320 ...commandContext,
321 exitCode,
322 stderrLength: stderr.length,
323 ...(stderrDiagnosticOf(stderr) !== undefined
324 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
325 : {}),
326 });
327 }
328 }).pipe(
329 Effect.scoped,
330 Effect.timeout(timeout),
331 Effect.catchTags({
332 TimeoutError: (cause) =>
333 Effect.fail(
334 new TailscaleCommandTimeoutError({
335 ...commandContext,
336 timeoutMs: Duration.toMillis(timeout),
337 cause,
338 }),
339 ),
340 }),
341 );
342 });
343
344export const ensureTailscaleServe = (input: {
345 readonly localPort: number;
346 readonly servePort?: number;
347 readonly localHost?: string;
348}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
349 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
350 const localHost = input.localHost ?? "127.0.0.1";
351 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
352 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
353};
354
355export const disableTailscaleServe = (
356 input: {
357 readonly servePort?: number;
358 } = {},
359): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
360 Effect.gen(function* () {
361 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
362 return yield* runTailscaleCommand(
363 ["serve", `--https=${servePort}`, "off"],
364 TAILSCALE_SERVE_TIMEOUT,
365 );
366 });
367
368export const probeTailscaleHttpsEndpoint = (input: {
369 readonly baseUrl: string;
370 readonly timeout?: Duration.Input;
371}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
372 Effect.gen(function* () {
373 const client = yield* HttpClient.HttpClient;
374 const response = yield* Effect.gen(function* () {
375 const url = new URL("/.well-known/t3/environment", input.baseUrl);
376 const request = HttpClientRequest.get(url.toString());
377 return yield* client.execute(request);
378 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
379
380 return Option.match(response, {
381 onNone: () => false,
382 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
383 });
384 }).pipe(Effect.orElseSucceed(() => false));