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
232 .spawn(ChildProcess.make(executable, args))
233 .pipe(
234 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
235 );
236 const [stdout, stderr, exitCode] = yield* Effect.all(
237 [
238 collectStdout(child.stdout),
239 collectStderr(child.stderr),
240 child.exitCode.pipe(Effect.map(Number)),
241 ],
242 { concurrency: "unbounded" },
243 ).pipe(
244 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
245 );
246 if (exitCode !== 0) {
247 return yield* new TailscaleCommandExitError({
248 ...commandContext,
249 exitCode,
250 stdoutLength: stdout.length,
251 stderrLength: stderr.length,
252 ...(stderrDiagnosticOf(stderr) !== undefined
253 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
254 : {}),
255 });
256 }
257 return yield* parseTailscaleStatus(stdout);
258 }).pipe(
259 Effect.scoped,
260 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
261 Effect.catchTags({
262 TimeoutError: (cause) =>
263 Effect.fail(
264 new TailscaleCommandTimeoutError({
265 ...commandContext,
266 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
267 cause,
268 }),
269 ),
270 }),
271 );
272});
273
274export function buildTailscaleHttpsBaseUrl(input: {
275 readonly magicDnsName: string;
276 readonly servePort?: number;
277}): string {
278 const url = new URL(`https://${input.magicDnsName}`);
279 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
280 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
281 url.port = String(servePort);
282 }
283 url.pathname = "/";
284 return url.toString();
285}
286
287const runTailscaleCommand = (
288 args: readonly string[],
289 timeoutInput: Duration.Input,
290): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
291 Effect.gen(function* () {
292 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
293 const hostPlatform = yield* HostProcessPlatform;
294 const executable = tailscaleCommandForPlatform(hostPlatform);
295 const commandContext = {
296 executable,
297 subcommand: "serve" as const,
298 argumentCount: args.length,
299 };
300 const timeout = Duration.fromInputUnsafe(timeoutInput);
301 return yield* Effect.gen(function* () {
302 const child = yield* spawner
303 .spawn(ChildProcess.make(executable, args))
304 .pipe(
305 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
306 );
307 const [stderr, exitCode] = yield* Effect.all(
308 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
309 { concurrency: "unbounded" },
310 ).pipe(
311 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
312 );
313 if (exitCode !== 0) {
314 return yield* new TailscaleCommandExitError({
315 ...commandContext,
316 exitCode,
317 stderrLength: stderr.length,
318 ...(stderrDiagnosticOf(stderr) !== undefined
319 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
320 : {}),
321 });
322 }
323 }).pipe(
324 Effect.scoped,
325 Effect.timeout(timeout),
326 Effect.catchTags({
327 TimeoutError: (cause) =>
328 Effect.fail(
329 new TailscaleCommandTimeoutError({
330 ...commandContext,
331 timeoutMs: Duration.toMillis(timeout),
332 cause,
333 }),
334 ),
335 }),
336 );
337 });
338
339export const ensureTailscaleServe = (input: {
340 readonly localPort: number;
341 readonly servePort?: number;
342 readonly localHost?: string;
343}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
344 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
345 const localHost = input.localHost ?? "127.0.0.1";
346 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
347 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
348};
349
350export const disableTailscaleServe = (
351 input: {
352 readonly servePort?: number;
353 } = {},
354): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
355 Effect.gen(function* () {
356 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
357 return yield* runTailscaleCommand(
358 ["serve", `--https=${servePort}`, "off"],
359 TAILSCALE_SERVE_TIMEOUT,
360 );
361 });
362
363export const probeTailscaleHttpsEndpoint = (input: {
364 readonly baseUrl: string;
365 readonly timeout?: Duration.Input;
366}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
367 Effect.gen(function* () {
368 const client = yield* HttpClient.HttpClient;
369 const response = yield* Effect.gen(function* () {
370 const url = new URL("/.well-known/t3/environment", input.baseUrl);
371 const request = HttpClientRequest.get(url.toString());
372 return yield* client.execute(request);
373 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
374
375 return Option.match(response, {
376 onNone: () => false,
377 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
378 });
379 }).pipe(Effect.orElseSucceed(() => false));
380
381export const resolveTailscaleHttpsBaseUrl = (
382 input: {
383 readonly servePort?: number;
384 } = {},
385): Effect.Effect<
386 string | null,
387 TailscaleCommandError | TailscaleStatusParseError,
388 ChildProcessSpawner.ChildProcessSpawner
389> =>
390 readTailscaleStatus.pipe(
391 Effect.map((status) =>
392 status.magicDnsName
393 ? buildTailscaleHttpsBaseUrl({
394 magicDnsName: status.magicDnsName,
395 ...(input.servePort === undefined ? {} : { servePort: input.servePort }),
396 })
397 : null,
398 ),
399 );