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

tailscale.ts

668 lines24.6 KB

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 }
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 }
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 }
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 }
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 }
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;
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;
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;
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;
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();
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
401 .spawn(ChildProcess.make(executable, args, { forceKillAfter: TAILSCALE_KILL_GRACE }))
402 .pipe(
403 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
404 Effect.catchDefect((cause) =>
405 Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
406 ),
407 );
408 const [stderr, exitCode] = yield* Effect.all(
409 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
410 { concurrency: "unbounded" },
411 ).pipe(
412 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
413 );
414 if (exitCode !== 0) {
415 return yield* new TailscaleCommandExitError({
416 ...commandContext,
417 exitCode,
418 stderrLength: stderr.length,
419 ...(stderrDiagnosticOf(stderr) !== undefined
420 ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
421 : {}),
422 });
423 }
424 }).pipe(
425 Effect.scoped,
426 Effect.timeout(timeout),
427 Effect.catchTags({
428 TimeoutError: (cause) =>
429 Effect.fail(
430 new TailscaleCommandTimeoutError({
431 ...commandContext,
432 timeoutMs: Duration.toMillis(timeout),
433 cause,
434 }),
435 ),
436 }),
437 );
438});
439​
440export const ensureTailscaleServe = (input: {
441 readonly localPort: number;
442 readonly servePort?: number;
443 readonly localHost?: string;
444}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
445 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
446 const localHost = input.localHost ?? "127.0.0.1";
447 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
448 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
449};
450​
451/** A Serve route: a web handler at `mount` on `servePort`, or a TCP forward without one. */
452export interface TailscaleServeRoute {
453 readonly servePort: number;
454 readonly mount?: string;
455 /** The machine name a web route serves under. */
456 readonly host?: string;
457 /** A target, such as a name, that may dial this server or another service on the same port. */
458 readonly ambiguous?: string;
459 /** The Tailscale Service it belongs to, or `foreground` for a `tailscale serve` still running. */
460 readonly owner?: string;
462​
463/**
464 * The `tailscale` arguments that turn `route` off; a foreground route has none, since it ends with
465 * its command. A web route names its path: without one the CLI removes every handler on the port,
466 * and answers its own confirmation prompt with yes when nobody is there to answer.
467 */
468export const tailscaleServeOffArgs = (
469 route: TailscaleServeRoute,
470): ReadonlyArray<string> | undefined =>
471 route.owner === "foreground"
472 ? undefined
473 : [
474 "serve",
475 ...(route.owner === undefined ? [] : [`--service=${route.owner}`]),
476 ...(route.mount === undefined
477 ? [`--tcp=${route.servePort}`]
478 : [`--https=${route.servePort}`, `--set-path=${route.mount}`]),
479 "off",
480 ];
481​
482/** Removes the web handler at `mount` on `servePort`, the root one `ensureTailscaleServe` adds by default. */
483export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (
484 input: {
485 readonly servePort?: number;
486 readonly mount?: string;
487 } = {},
488): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
489 return yield* runTailscaleCommand(
490 tailscaleServeOffArgs({
491 servePort: input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT,
492 mount: input.mount ?? "/",
493 })!,
494 TAILSCALE_SERVE_TIMEOUT,
495 );
496});
497​
498/** Removes a TCP forward on `servePort`; one port holds one forward, so nothing else goes. */
499export const disableTailscaleServeTcp = (servePort: number) =>
500 runTailscaleCommand(tailscaleServeOffArgs({ servePort })!, TAILSCALE_SERVE_TIMEOUT);
501​
502const TailscaleServeConfigJson = Schema.Struct({
503 TCP: Schema.optional(
504 Schema.Record(Schema.String, Schema.Struct({ TCPForward: Schema.optional(Schema.String) })),
505 ),
506 Web: Schema.optional(
507 Schema.Record(
508 Schema.String,
509 Schema.Struct({
510 Handlers: Schema.optional(
511 Schema.Record(Schema.String, Schema.Struct({ Proxy: Schema.optional(Schema.String) })),
512 ),
513 }),
514 ),
515 ),
516});
517const TailscaleServeStatusJson = Schema.Struct({
518 ...TailscaleServeConfigJson.fields,
519 // A Tailscale Service's routes, and those of each `tailscale serve` still running in the foreground.
520 Services: Schema.optional(Schema.Record(Schema.String, TailscaleServeConfigJson)),
521 Foreground: Schema.optional(Schema.Record(Schema.String, TailscaleServeConfigJson)),
522});
523// A node without any Serve configuration prints `null`.
524const decodeTailscaleServeStatusJson = Schema.decodeUnknownOption(
525 Schema.fromJsonString(Schema.NullOr(TailscaleServeStatusJson)),
526);
527​
528/**
529 * Whether a proxy to `hostname` dials `bindHost`. `0.0.0.0` reaches 127.0.0.1. `[::]` may reach
530 * either loopback, since Go dials `::` and then 0.0.0.0 (golang/go#18806), and a name such as
531 * `localhost` may resolve to whatever the server binds.
532 */
533const reaches = (hostname: string, bindHost: string): "exact" | "either" | undefined => {
534 let address = normalizeHostname(hostname);
535 // Compare IPv6 by value: 0:0:0:0:0:ffff:7f00:1 is ::ffff:7f00:1.
536 if (address.includes(":") && URL.canParse(`http://[${address}]`)) {
537 address = normalizeHostname(new URL(`http://[${address}]`).hostname);
538 }
539 // An IPv4-mapped address can be written as hex, such as ::ffff:7f00:1 for 127.0.0.1.
540 const mapped = /^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u.exec(address);
541 if (mapped !== null) {
542 const high = Number.parseInt(mapped[1]!, 16);
543 const low = Number.parseInt(mapped[2]!, 16);
544 address = [high >>> 8, high & 0xff, low >>> 8, low & 0xff].join(".");
545 } else if (address.startsWith("::ffff:")) {
546 address = address.slice("::ffff:".length);
547 }
548 // Strict, as Go's ParseIP is; anything else, such as `127.1` or `box.1`, goes to the resolver.
549 const literal =
550 address.includes(":") ||
551 /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?!$)|$)){4}$/u.test(address);
552 if (!literal) return "either";
553 if (address === "::")
554 return bindHost === "127.0.0.1" || bindHost === "::1" ? "either" : undefined;
555 return (address === "0.0.0.0" ? "127.0.0.1" : address) === bindHost ? "exact" : undefined;
556};
557​
558/** The URL Tailscale's proxy dials for a handler's `Proxy`, expanded as its `expandProxyArg` does. */
559const expandProxy = (proxy: string) =>
560 /^\d+$/u.test(proxy)
561 ? `http://127.0.0.1:${proxy}`
562 : proxy.startsWith("https+insecure://")
563 ? `https://${proxy.slice("https+insecure://".length)}`
564 : /^(?:https?:\/\/|unix:)/u.test(proxy)
565 ? proxy
566 : `http://${proxy}`;
567​
568/**
569 * The host and port a proxy target dials, read as Go's url.Parse reads it rather than as a WHATWG
570 * URL, which rejects `box.1` and rewrites `127.1`; none for a Unix socket.
571 */
572const dialedHostPort = (url: string) => {
573 const match = /^(https?|tcp):\/\/(?:[^@/?#]*@)?(\[[^\]]*\]|[^/?#:]*)(?::(\d*))?/iu.exec(url);
574 if (match === null) return undefined;
575 const [, scheme = "", host = "", port] = match;
576 return { host, port: port || (scheme.toLowerCase() === "https" ? "443" : "80") };
577};
578​
579const reachesTarget = (url: string, target: { readonly host: string; readonly port: number }) => {
580 const dialed = dialedHostPort(url);
581 // Go reads the port as a decimal number, so 03773 is 3773.
582 if (dialed === undefined || Number(dialed.port) !== target.port) return undefined;
583 const reach = reaches(dialed.host, target.host);
584 return reach === undefined ? undefined : { reach, hostname: dialed.host };
585};
586​
587/**
588 * The Serve routes that forward to the server bound at `target`, or undefined when the status
589 * cannot be read.
590 */
591export const parseTailscaleServeRoutesTo = (
592 rawServeStatusJson: string,
593 target: { readonly host: string; readonly port: number },
594): ReadonlyArray<TailscaleServeRoute> | undefined => {
595 const status = decodeTailscaleServeStatusJson(rawServeStatusJson);
596 if (Option.isNone(status)) return undefined;
597 const routesIn = (
598 config: typeof TailscaleServeConfigJson.Type | undefined,
599 owner?: string,
600 ): ReadonlyArray<TailscaleServeRoute> => {
601 const scope = owner === undefined ? {} : { owner };
602 const reached = (url: string) => {
603 const found = reachesTarget(url, target);
604 if (found === undefined) return undefined;
605 return found.reach === "either" ? { ambiguous: found.hostname } : {};
606 };
607 const tcp = Object.entries(config?.TCP ?? {}).flatMap(([port, handler]) => {
608 const reach =
609 handler.TCPForward === undefined || handler.TCPForward.startsWith("unix:")
610 ? undefined
611 : reached(`tcp://${handler.TCPForward}`);
612 return reach !== undefined && Number.isInteger(Number(port))
613 ? [{ servePort: Number(port), ...reach, ...scope }]
614 : [];
615 });
616 const web = Object.entries(config?.Web ?? {}).flatMap(([hostPort, site]) => {
617 const separator = hostPort.lastIndexOf(":");
618 const servePort = Number(hostPort.slice(separator + 1));
619 if (!Number.isInteger(servePort)) return [];
620 const host = hostPort.slice(0, separator);
621 return Object.entries(site.Handlers ?? {}).flatMap(([mount, handler]) => {
622 const reach = handler.Proxy === undefined ? undefined : reached(expandProxy(handler.Proxy));
623 return reach === undefined ? [] : [{ servePort, mount, host, ...reach, ...scope }];
624 });
625 });
626 return [...tcp, ...web];
627 };
628 return [
629 ...routesIn(status.value ?? undefined),
630 ...Object.entries(status.value?.Services ?? {}).flatMap(([name, service]) =>
631 routesIn(service, name),
632 ),
633 ...Object.values(status.value?.Foreground ?? {}).flatMap((session) =>
634 routesIn(session, "foreground"),
635 ),
636 ];
637};
638​
639/** The Serve routes that forward to the server bound at `target` on this machine. */
640export const readTailscaleServeRoutesTo = (target: {
641 readonly host: string;
642 readonly port: number;
643}) =>
644 readTailscaleOutput("serve", ["serve", "status", "--json"]).pipe(
645 Effect.flatMap((status) => {
646 const routes = parseTailscaleServeRoutesTo(status, target);
647 return routes === undefined
648 ? Effect.fail(new TailscaleStatusParseError({ cause: "unreadable serve status" }))
649 : Effect.succeed(routes);
650 }),
651 );
652​
653export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(
654 function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {
655 const client = yield* HttpClient.HttpClient;
656 const response = yield* Effect.gen(function* () {
657 const url = new URL("/.well-known/t3/environment", input.baseUrl);
658 const request = HttpClientRequest.get(url.toString());
659 return yield* client.execute(request);
660 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
661​
662 return Option.match(response, {
663 onNone: () => false,
664 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
665 });
666 },
667 Effect.orElseSucceed(() => false),
668);