Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import { normalizeHostname } from "@t3tools/shared/hostClassification";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as Stream from "effect/Stream";
8import { HttpClient, HttpClientRequest } from "effect/http";
9import { ChildProcess, ChildProcessSpawner } from "effect/process";
10
11export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
12/**
13 * Bounds `tailscale status` and `tailscale debug prefs`. Allows the 1.8-2.6 s
14 * `tailscale status` has been measured at when T3 Code spawns it on Windows.
15 * A CLI that never answers takes longer than this to fail, because the kill
16 * that follows the timeout also takes time (`taskkill` on Windows).
17 */
18const TAILSCALE_STATUS_TIMEOUT = Duration.millis(3_500);
19/**
20 * How long a probe killed on timeout gets to exit after SIGTERM before its
21 * process group is SIGKILLed. Without it the spawner never escalates, so a group
22 * member that ignores SIGTERM outlives the call. Short because the timeout error
23 * only surfaces once cleanup finishes, and a healthy `tailscale` exits at once.
24 */
25const TAILSCALE_KILL_GRACE = Duration.millis(500);
26const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);
27const TAILSCALE_PROBE_TIMEOUT = Duration.millis(2_500);
28
29const tailscaleCommandForPlatform = (platform: NodeJS.Platform): "tailscale" | "tailscale.exe" =>
30 platform === "win32" ? "tailscale.exe" : "tailscale";
31
32const TailscaleCommandContext = {
33 executable: Schema.Literals(["tailscale", "tailscale.exe"]),
34 subcommand: Schema.Literals(["status", "serve", "debug"]),
35 argumentCount: Schema.Number,
36};
37
38/**
39 * Failure kinds we can name without quoting the CLI. Anything unrecognized
40 * becomes "unknown" rather than falling back to raw text — stderr can contain
41 * auth keys (`tskey-…`) and node names, and these labels are logged.
42 */
43export const TailscaleStderrDiagnostic = Schema.Literals([
44 "no-existing-handler",
45 "not-logged-in",
46 "not-running",
47 "permission-denied",
48 "unknown",
49]);
50export type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;
51
52const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
53 readonly [RegExp, Exclude<TailscaleStderrDiagnostic, "unknown">]
54> = [
55 [/handler does not exist/i, "no-existing-handler"],
56 [/not logged in|logged out|needs? login/i, "not-logged-in"],
57 // Only answers that confirm no daemon; a dial can also fail for want of permission. Windows
58 // reports a missing service as its pipe not being found, without the usual prefix.
59 [
60 /doesn't appear to be running|tailscaled\.service not running|tailscale is stopped|tailscaled: the system cannot find the file specified|failed to connect to local tailscale[\s\S]*(connection refused|no such file or directory|cannot find the file)/i,
61 "not-running",
62 ],
63 [/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
64];
65
66const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {
67 if (stderr.trim().length === 0) {
68 return undefined;
69 }
70 return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? "unknown";
71};
72
73export class TailscaleCommandSpawnError extends Schema.TaggedError<TailscaleCommandSpawnError>()(
74 "TailscaleCommandSpawnError",
75 {
76 ...TailscaleCommandContext,
77 cause: Schema.Defect(),
78 },
79) {
80 override get message(): string {
81 return `Failed to spawn tailscale ${this.subcommand}.`;
82 }
83}
84
85class TailscaleCommandOutputError extends Schema.TaggedError<TailscaleCommandOutputError>()(
86 "TailscaleCommandOutputError",
87 {
88 ...TailscaleCommandContext,
89 cause: Schema.Defect(),
90 },
91) {
92 override get message(): string {
93 return `Failed to read output from tailscale ${this.subcommand}.`;
94 }
95}
96
97export class TailscaleCommandExitError extends Schema.TaggedError<TailscaleCommandExitError>()(
98 "TailscaleCommandExitError",
99 {
100 ...TailscaleCommandContext,
101 exitCode: Schema.Number,
102 stdoutLength: Schema.optional(Schema.Number),
103 stderrLength: Schema.Number,
104 stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
105 },
106) {
107 override get message(): string {
108 return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;
109 }
110}
111
112export class TailscaleCommandTimeoutError extends Schema.TaggedError<TailscaleCommandTimeoutError>()(
113 "TailscaleCommandTimeoutError",
114 {
115 ...TailscaleCommandContext,
116 timeoutMs: Schema.Number,
117 cause: Schema.Defect(),
118 },
119) {
120 override get message(): string {
121 return `tailscale ${this.subcommand} timed out after ${this.timeoutMs}ms.`;
122 }
123}
124
125export type TailscaleCommandError =
126 | TailscaleCommandSpawnError
127 | TailscaleCommandOutputError
128 | TailscaleCommandExitError
129 | TailscaleCommandTimeoutError;
130
131export class TailscaleStatusParseError extends Schema.TaggedError<TailscaleStatusParseError>()(
132 "TailscaleStatusParseError",
133 { cause: Schema.Defect() },
134) {
135 override get message(): string {
136 return "Failed to decode tailscale status JSON.";
137 }
138}
139
140const TailscaleStatusSelf = Schema.Struct({
141 DNSName: Schema.optional(Schema.Unknown),
142 TailscaleIPs: Schema.optional(Schema.Unknown),
143 CapMap: Schema.optional(Schema.Unknown),
144});
145
146const TailscaleStatusJson = Schema.Struct({
147 Self: Schema.optional(TailscaleStatusSelf),
148});
149
150export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
151
152export interface TailscaleStatus {
153 readonly magicDnsName: string | null;
154 readonly tailnetIpv4Addresses: readonly string[];
155 /**
156 * `tailscale serve --https` needs the `https` capability, which the control
157 * plane grants once the tailnet enables HTTPS certificates. `null` when the
158 * CLI reports no capability map (older CLI), so callers still attempt serve.
159 */
160 readonly httpsServeEnabled: boolean | null;
161}
162
163const collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
164 stream.pipe(
165 Stream.decodeText(),
166 Stream.runFold(
167 () => "",
168 (acc, chunk) => acc + chunk,
169 ),
170 );
171
172const collectStderr = collectStdout;
173
174const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
175
176function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
177 const dnsName = status.Self?.DNSName;
178 if (typeof dnsName !== "string") {
179 return null;
180 }
181
182 const normalized = dnsName.trim().replace(/\.$/u, "");
183 return normalized.length > 0 ? normalized : null;
184}
185
186export function isTailscaleIpv4Address(address: string): boolean {
187 const parts = address.split(".");
188 if (parts.length !== 4) {
189 return false;
190 }
191 const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
192 if (
193 first === undefined ||
194 second === undefined ||
195 third === undefined ||
196 fourth === undefined ||
197 [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
198 ) {
199 return false;
200 }
201 return first === 100 && second >= 64 && second <= 127;
202}
203
204export const parseTailscaleStatus = (
205 rawStatusJson: string,
206): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
207 decodeTailscaleStatusJson(rawStatusJson).pipe(
208 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
209 Effect.map((parsed) => {
210 const rawIps = parsed.Self?.TailscaleIPs;
211 const tailnetIpv4Addresses: Array<string> = [];
212 if (Array.isArray(rawIps)) {
213 for (const address of rawIps) {
214 if (typeof address === "string" && isTailscaleIpv4Address(address)) {
215 tailnetIpv4Addresses.push(address);
216 }
217 }
218 }
219
220 const capMap = parsed.Self?.CapMap;
221 return {
222 magicDnsName: normalizeMagicDnsName(parsed),
223 tailnetIpv4Addresses,
224 httpsServeEnabled:
225 typeof capMap === "object" && capMap !== null && !Array.isArray(capMap)
226 ? Object.hasOwn(capMap, "https")
227 : null,
228 };
229 }),
230 );
231
232const readTailscaleOutput = Effect.fn("tailscale.readTailscaleOutput")(function* (
233 subcommand: "status" | "serve" | "debug",
234 args: readonly string[],
235) {
236 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
237 const hostPlatform = yield* HostProcess.Platform;
238 const executable = tailscaleCommandForPlatform(hostPlatform);
239 const commandContext = {
240 executable,
241 subcommand,
242 argumentCount: args.length,
243 };
244 const command = ChildProcess.make(executable, [...args], {
245 forceKillAfter: TAILSCALE_KILL_GRACE,
246 });
247 return yield* Effect.gen(function* () {
248 const child = yield* spawner.spawn(command).pipe(
249 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
250 // Spawning can also fail as a defect rather than a typed error - a
251 // non-directory entry on PATH makes node throw ENOTDIR synchronously.
252 // `mapError` never sees that, so it would escape as an uncaught error.
253 Effect.catchDefect((cause) =>
254 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
255 ),
256 );
257 const [stdout, stderr, exitCode] = yield* Effect.all(
258 [
259 collectStdout(child.stdout),
260 collectStderr(child.stderr),
261 child.exitCode.pipe(Effect.map(Number)),
262 ],
263 { concurrency: "unbounded" },
264 ).pipe(
265 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
266 );
267 if (exitCode !== 0) {
268 return yield* new TailscaleCommandExitError({
269 ...commandContext,
270 exitCode,
271 stdoutLength: stdout.length,
272 stderrLength: stderr.length,
273 ...(stderrDiagnosticOf(stderr) !== undefined
274 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
275 : {}),
276 });
277 }
278 return stdout;
279 }).pipe(
280 Effect.scoped,
281 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
282 Effect.catchTags({
283 TimeoutError: (cause) =>
284 Effect.fail(
285 new TailscaleCommandTimeoutError({
286 ...commandContext,
287 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
288 cause,
289 }),
290 ),
291 }),
292 );
293});
294
295export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--json"]).pipe(
296 Effect.flatMap(parseTailscaleStatus),
297);
298
299const TailscaleExitNodeJson = Schema.Struct({
300 ExitNodeStatus: Schema.optional(Schema.Struct({ Online: Schema.optional(Schema.Unknown) })),
301 Peer: Schema.optional(
302 Schema.Record(
303 Schema.String,
304 Schema.Struct({
305 ExitNode: Schema.optional(Schema.Unknown),
306 HostName: Schema.optional(Schema.Unknown),
307 DNSName: Schema.optional(Schema.Unknown),
308 }),
309 ),
310 ),
311});
312
313const decodeTailscaleExitNodeJson = Schema.decodeEffect(
314 Schema.fromJsonString(TailscaleExitNodeJson),
315);
316
317export interface TailscaleExitNode {
318 readonly name: string | null;
319 readonly online: boolean;
320}
321
322/**
323 * `ExitNodeStatus` is present only while an exit node is in use, but it has no
324 * name. The name comes from the peer marked `ExitNode: true`.
325 */
326export const parseTailscaleExitNode = (
327 rawStatusJson: string,
328): Effect.Effect<TailscaleExitNode | null, TailscaleStatusParseError> =>
329 decodeTailscaleExitNodeJson(rawStatusJson).pipe(
330 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
331 Effect.map((parsed) => {
332 if (parsed.ExitNodeStatus === undefined) return null;
333 const peer = Object.values(parsed.Peer ?? {}).find(
334 (candidate) => candidate.ExitNode === true,
335 );
336 // The DNS label is the tailnet machine name; HostName is the OS name and ignores renames.
337 const dnsLabel = typeof peer?.DNSName === "string" ? (peer.DNSName.split(".")[0] ?? "") : "";
338 const hostName = typeof peer?.HostName === "string" ? peer.HostName.trim() : "";
339 return {
340 name: dnsLabel || hostName || null,
341 online: parsed.ExitNodeStatus.Online === true,
342 };
343 }),
344 );
345
346export const readTailscaleExitNode = readTailscaleOutput("status", ["status", "--json"]).pipe(
347 Effect.flatMap(parseTailscaleExitNode),
348);
349
350const TailscalePrefsJson = Schema.Struct({
351 RunSSH: Schema.optional(Schema.Unknown),
352 WantRunning: Schema.optional(Schema.Unknown),
353});
354
355const decodeTailscalePrefsJson = Schema.decodeEffect(Schema.fromJsonString(TailscalePrefsJson));
356
357/**
358 * `tailscale status --json` does not report this for the local node. `tailscale
359 * down` clears WantRunning but keeps RunSSH, so check both.
360 */
361export const parseTailscaleSshEnabled = (
362 rawPrefsJson: string,
363): Effect.Effect<boolean, TailscaleStatusParseError> =>
364 decodeTailscalePrefsJson(rawPrefsJson).pipe(
365 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
366 Effect.map((prefs) => prefs.RunSSH === true && prefs.WantRunning !== false),
367 );
368
369export const readTailscaleSshEnabled = readTailscaleOutput("debug", ["debug", "prefs"]).pipe(
370 Effect.flatMap(parseTailscaleSshEnabled),
371);
372
373export function buildTailscaleHttpsBaseUrl(input: {
374 readonly magicDnsName: string;
375 readonly servePort?: number;
376}): string {
377 const url = new URL(`https://${input.magicDnsName}`);
378 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
379 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
380 url.port = String(servePort);
381 }
382 url.pathname = "/";
383 return url.toString();
384}
385
386const runTailscaleCommand = Effect.fn("tailscale.runTailscaleCommand")(function* (
387 args: readonly string[],
388 timeoutInput: Duration.Input,
389): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
390 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
391 const hostPlatform = yield* HostProcess.Platform;
392 const executable = tailscaleCommandForPlatform(hostPlatform);
393 const commandContext = {
394 executable,
395 subcommand: "serve" as const,
396 argumentCount: args.length,
397 };
398 const timeout = Duration.fromInputUnsafe(timeoutInput);
399 return yield* Effect.gen(function* () {
400 const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
401 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
402 Effect.catchDefect((cause) =>
403 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
404 ),
405 );
406 const [stderr, exitCode] = yield* Effect.all(
407 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
408 { concurrency: "unbounded" },
409 ).pipe(
410 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
411 );
412 if (exitCode !== 0) {
413 return yield* new TailscaleCommandExitError({
414 ...commandContext,
415 exitCode,
416 stderrLength: stderr.length,
417 ...(stderrDiagnosticOf(stderr) !== undefined
418 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
419 : {}),
420 });
421 }
422 }).pipe(
423 Effect.scoped,
424 Effect.timeout(timeout),
425 Effect.catchTags({
426 TimeoutError: (cause) =>
427 Effect.fail(
428 new TailscaleCommandTimeoutError({
429 ...commandContext,
430 timeoutMs: Duration.toMillis(timeout),
431 cause,
432 }),
433 ),
434 }),
435 );
436});
437
438export const ensureTailscaleServe = (input: {
439 readonly localPort: number;
440 readonly servePort?: number;
441 readonly localHost?: string;
442}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
443 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
444 const localHost = input.localHost ?? "127.0.0.1";
445 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
446 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
447};
448
449/** A Serve route: a web handler at `mount` on `servePort`, or a TCP forward without one. */
450export interface TailscaleServeRoute {
451 readonly servePort: number;
452 readonly mount?: string;
453 /** The machine name a web route serves under. */
454 readonly host?: string;
455 /** A target, such as a name, that may dial this server or another service on the same port. */
456 readonly ambiguous?: string;
457 /** The Tailscale Service it belongs to, or `foreground` for a `tailscale serve` still running. */
458 readonly owner?: string;
459}
460
461/**
462 * The `tailscale` arguments that turn `route` off; a foreground route has none, since it ends with
463 * its command. A web route names its path: without one the CLI removes every handler on the port,
464 * and answers its own confirmation prompt with yes when nobody is there to answer.
465 */
466export const tailscaleServeOffArgs = (
467 route: TailscaleServeRoute,
468): ReadonlyArray<string> | undefined =>
469 route.owner === "foreground"
470 ? undefined
471 : [
472 "serve",
473 ...(route.owner === undefined ? [] : [`--service=${route.owner}`]),
474 ...(route.mount === undefined
475 ? [`--tcp=${route.servePort}`]
476 : [`--https=${route.servePort}`, `--set-path=${route.mount}`]),
477 "off",
478 ];
479
480/** Removes the web handler at `mount` on `servePort`, the root one `ensureTailscaleServe` adds by default. */
481export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (
482 input: {
483 readonly servePort?: number;
484 readonly mount?: string;
485 } = {},
486): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
487 return yield* runTailscaleCommand(
488 tailscaleServeOffArgs({
489 servePort: input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT,
490 mount: input.mount ?? "/",
491 })!,
492 TAILSCALE_SERVE_TIMEOUT,
493 );
494});
495
496/** Removes a TCP forward on `servePort`; one port holds one forward, so nothing else goes. */
497export const disableTailscaleServeTcp = (servePort: number) =>
498 runTailscaleCommand(tailscaleServeOffArgs({ servePort })!, TAILSCALE_SERVE_TIMEOUT);
499
500const TailscaleServeConfigJson = Schema.Struct({
501 TCP: Schema.optional(
502 Schema.Record(Schema.String, Schema.Struct({ TCPForward: Schema.optional(Schema.String) })),
503 ),
504 Web: Schema.optional(
505 Schema.Record(
506 Schema.String,
507 Schema.Struct({
508 Handlers: Schema.optional(
509 Schema.Record(Schema.String, Schema.Struct({ Proxy: Schema.optional(Schema.String) })),
510 ),
511 }),
512 ),
513 ),
514});
515const TailscaleServeStatusJson = Schema.Struct({
516 ...TailscaleServeConfigJson.fields,
517 // A Tailscale Service's routes, and those of each `tailscale serve` still running in the foreground.
518 Services: Schema.optional(Schema.Record(Schema.String, TailscaleServeConfigJson)),
519 Foreground: Schema.optional(Schema.Record(Schema.String, TailscaleServeConfigJson)),
520});
521// A node without any Serve configuration prints `null`.
522const decodeTailscaleServeStatusJson = Schema.decodeUnknownOption(
523 Schema.fromJsonString(Schema.NullOr(TailscaleServeStatusJson)),
524);
525
526/**
527 * Whether a proxy to `hostname` dials `bindHost`. `0.0.0.0` reaches 127.0.0.1. `[::]` may reach
528 * either loopback, since Go dials `::` and then 0.0.0.0 (golang/go#18806), and a name such as
529 * `localhost` may resolve to whatever the server binds.
530 */
531const reaches = (hostname: string, bindHost: string): "exact" | "either" | undefined => {
532 let address = normalizeHostname(hostname);
533 // Compare IPv6 by value: 0:0:0:0:0:ffff:7f00:1 is ::ffff:7f00:1.
534 if (address.includes(":") && URL.canParse(`http://[${address}]`)) {
535 address = normalizeHostname(new URL(`http://[${address}]`).hostname);
536 }
537 // An IPv4-mapped address can be written as hex, such as ::ffff:7f00:1 for 127.0.0.1.
538 const mapped = /^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u.exec(address);
539 if (mapped !== null) {
540 const high = Number.parseInt(mapped[1]!, 16);
541 const low = Number.parseInt(mapped[2]!, 16);
542 address = [high >>> 8, high & 0xff, low >>> 8, low & 0xff].join(".");
543 } else if (address.startsWith("::ffff:")) {
544 address = address.slice("::ffff:".length);
545 }
546 // Strict, as Go's ParseIP is; anything else, such as `127.1` or `box.1`, goes to the resolver.
547 const literal =
548 address.includes(":") ||
549 /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?!$)|$)){4}$/u.test(address);
550 if (!literal) return "either";
551 if (address === "::")
552 return bindHost === "127.0.0.1" || bindHost === "::1" ? "either" : undefined;
553 return (address === "0.0.0.0" ? "127.0.0.1" : address) === bindHost ? "exact" : undefined;
554};
555
556/** The URL Tailscale's proxy dials for a handler's `Proxy`, expanded as its `expandProxyArg` does. */
557const expandProxy = (proxy: string) =>
558 /^\d+$/u.test(proxy)
559 ? `http://127.0.0.1:${proxy}`
560 : proxy.startsWith("https+insecure://")
561 ? `https://${proxy.slice("https+insecure://".length)}`
562 : /^(?:https?:\/\/|unix:)/u.test(proxy)
563 ? proxy
564 : `http://${proxy}`;
565
566/**
567 * The host and port a proxy target dials, read as Go's url.Parse reads it rather than as a WHATWG
568 * URL, which rejects `box.1` and rewrites `127.1`; none for a Unix socket.
569 */
570const dialedHostPort = (url: string) => {
571 const match = /^(https?|tcp):\/\/(?:[^@/?#]*@)?(\[[^\]]*\]|[^/?#:]*)(?::(\d*))?/iu.exec(url);
572 if (match === null) return undefined;
573 const [, scheme = "", host = "", port] = match;
574 return { host, port: port || (scheme.toLowerCase() === "https" ? "443" : "80") };
575};
576
577const reachesTarget = (url: string, target: { readonly host: string; readonly port: number }) => {
578 const dialed = dialedHostPort(url);
579 // Go reads the port as a decimal number, so 03773 is 3773.
580 if (dialed === undefined || Number(dialed.port) !== target.port) return undefined;
581 const reach = reaches(dialed.host, target.host);
582 return reach === undefined ? undefined : { reach, hostname: dialed.host };
583};
584
585/**
586 * The Serve routes that forward to the server bound at `target`, or undefined when the status
587 * cannot be read.
588 */
589export const parseTailscaleServeRoutesTo = (
590 rawServeStatusJson: string,
591 target: { readonly host: string; readonly port: number },
592): ReadonlyArray<TailscaleServeRoute> | undefined => {
593 const status = decodeTailscaleServeStatusJson(rawServeStatusJson);
594 if (Option.isNone(status)) return undefined;
595 const routesIn = (
596 config: typeof TailscaleServeConfigJson.Type | undefined,
597 owner?: string,
598 ): ReadonlyArray<TailscaleServeRoute> => {
599 const scope = owner === undefined ? {} : { owner };
600 const reached = (url: string) => {
601 const found = reachesTarget(url, target);
602 if (found === undefined) return undefined;
603 return found.reach === "either" ? { ambiguous: found.hostname } : {};
604 };
605 const tcp = Object.entries(config?.TCP ?? {}).flatMap(([port, handler]) => {
606 const reach =
607 handler.TCPForward === undefined || handler.TCPForward.startsWith("unix:")
608 ? undefined
609 : reached(`tcp://${handler.TCPForward}`);
610 return reach !== undefined && Number.isInteger(Number(port))
611 ? [{ servePort: Number(port), ...reach, ...scope }]
612 : [];
613 });
614 const web = Object.entries(config?.Web ?? {}).flatMap(([hostPort, site]) => {
615 const separator = hostPort.lastIndexOf(":");
616 const servePort = Number(hostPort.slice(separator + 1));
617 if (!Number.isInteger(servePort)) return [];
618 const host = hostPort.slice(0, separator);
619 return Object.entries(site.Handlers ?? {}).flatMap(([mount, handler]) => {
620 const reach = handler.Proxy === undefined ? undefined : reached(expandProxy(handler.Proxy));
621 return reach === undefined ? [] : [{ servePort, mount, host, ...reach, ...scope }];
622 });
623 });
624 return [...tcp, ...web];
625 };
626 return [
627 ...routesIn(status.value ?? undefined),
628 ...Object.entries(status.value?.Services ?? {}).flatMap(([name, service]) =>
629 routesIn(service, name),
630 ),
631 ...Object.values(status.value?.Foreground ?? {}).flatMap((session) =>
632 routesIn(session, "foreground"),
633 ),
634 ];
635};
636
637/** The Serve routes that forward to the server bound at `target` on this machine. */
638export const readTailscaleServeRoutesTo = (target: {
639 readonly host: string;
640 readonly port: number;
641}) =>
642 readTailscaleOutput("serve", ["serve", "status", "--json"]).pipe(
643 Effect.flatMap((status) => {
644 const routes = parseTailscaleServeRoutesTo(status, target);
645 return routes === undefined
646 ? Effect.fail(new TailscaleStatusParseError({ cause: "unreadable serve status" }))
647 : Effect.succeed(routes);
648 }),
649 );
650
651export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(
652 function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {
653 const client = yield* HttpClient.HttpClient;
654 const response = yield* Effect.gen(function* () {
655 const url = new URL("/.well-known/t3/environment", input.baseUrl);
656 const request = HttpClientRequest.get(url.toString());
657 return yield* client.execute(request);
658 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
659
660 return Option.match(response, {
661 onNone: () => false,
662 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
663 });
664 },
665 Effect.orElseSucceed(() => false),
666);