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

tailscale.ts

674 lines25.0 KB

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