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
26export class TailscaleCommandSpawnError extends Schema.TaggedErrorClass<TailscaleCommandSpawnError>()(
27 "TailscaleCommandSpawnError",
28 {
29 ...TailscaleCommandContext,
30 cause: Schema.Defect(),
31 },
32) {
33 override get message(): string {
34 return `Failed to spawn tailscale ${this.subcommand}.`;
35 }
36}
37
38export class TailscaleCommandOutputError extends Schema.TaggedErrorClass<TailscaleCommandOutputError>()(
39 "TailscaleCommandOutputError",
40 {
41 ...TailscaleCommandContext,
42 cause: Schema.Defect(),
43 },
44) {
45 override get message(): string {
46 return `Failed to read output from tailscale ${this.subcommand}.`;
47 }
48}
49
50export class TailscaleCommandExitError extends Schema.TaggedErrorClass<TailscaleCommandExitError>()(
51 "TailscaleCommandExitError",
52 {
53 ...TailscaleCommandContext,
54 exitCode: Schema.Number,
55 stdoutLength: Schema.optional(Schema.Number),
56 stderrLength: Schema.Number,
57 },
58) {
59 override get message(): string {
60 return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;
61 }
62}
63
64export class TailscaleCommandTimeoutError extends Schema.TaggedErrorClass<TailscaleCommandTimeoutError>()(
65 "TailscaleCommandTimeoutError",
66 {
67 ...TailscaleCommandContext,
68 timeoutMs: Schema.Number,
69 cause: Schema.Defect(),
70 },
71) {
72 override get message(): string {
73 return `tailscale ${this.subcommand} timed out after ${this.timeoutMs}ms.`;
74 }
75}
76
77export const TailscaleCommandError = Schema.Union([
78 TailscaleCommandSpawnError,
79 TailscaleCommandOutputError,
80 TailscaleCommandExitError,
81 TailscaleCommandTimeoutError,
82]);
83export type TailscaleCommandError = typeof TailscaleCommandError.Type;
84
85export class TailscaleStatusParseError extends Schema.TaggedErrorClass<TailscaleStatusParseError>()(
86 "TailscaleStatusParseError",
87 { cause: Schema.Defect() },
88) {
89 override get message(): string {
90 return "Failed to decode tailscale status JSON.";
91 }
92}
93
94const TailscaleStatusSelf = Schema.Struct({
95 DNSName: Schema.optional(Schema.Unknown),
96 TailscaleIPs: Schema.optional(Schema.Unknown),
97});
98
99const TailscaleStatusJson = Schema.Struct({
100 Self: Schema.optional(TailscaleStatusSelf),
101});
102
103export type TailscaleStatusSelf = typeof TailscaleStatusSelf.Type;
104export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
105
106export interface TailscaleStatus {
107 readonly magicDnsName: string | null;
108 readonly tailnetIpv4Addresses: readonly string[];
109}
110
111const collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
112 stream.pipe(
113 Stream.decodeText(),
114 Stream.runFold(
115 () => "",
116 (acc, chunk) => acc + chunk,
117 ),
118 );
119
120const collectStderr = collectStdout;
121
122const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
123
124function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
125 const dnsName = status.Self?.DNSName;
126 if (typeof dnsName !== "string") {
127 return null;
128 }
129
130 const normalized = dnsName.trim().replace(/\.$/u, "");
131 return normalized.length > 0 ? normalized : null;
132}
133
134export const parseTailscaleMagicDnsName = (
135 rawStatusJson: string,
136): Effect.Effect<string | null, TailscaleStatusParseError> =>
137 decodeTailscaleStatusJson(rawStatusJson).pipe(
138 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
139 Effect.map(normalizeMagicDnsName),
140 );
141
142export function isTailscaleIpv4Address(address: string): boolean {
143 const parts = address.split(".");
144 if (parts.length !== 4) {
145 return false;
146 }
147 const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
148 if (
149 first === undefined ||
150 second === undefined ||
151 third === undefined ||
152 fourth === undefined ||
153 [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
154 ) {
155 return false;
156 }
157 return first === 100 && second >= 64 && second <= 127;
158}
159
160export const parseTailscaleStatus = (
161 rawStatusJson: string,
162): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
163 decodeTailscaleStatusJson(rawStatusJson).pipe(
164 Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
165 Effect.map((parsed) => {
166 const rawIps = parsed.Self?.TailscaleIPs;
167 const tailnetIpv4Addresses: Array<string> = [];
168 if (Array.isArray(rawIps)) {
169 for (const address of rawIps) {
170 if (typeof address === "string" && isTailscaleIpv4Address(address)) {
171 tailnetIpv4Addresses.push(address);
172 }
173 }
174 }
175
176 return {
177 magicDnsName: normalizeMagicDnsName(parsed),
178 tailnetIpv4Addresses,
179 };
180 }),
181 );
182
183export const readTailscaleStatus = Effect.gen(function* () {
184 const args = ["status", "--json"];
185 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
186 const hostPlatform = yield* HostProcessPlatform;
187 const executable = tailscaleCommandForPlatform(hostPlatform);
188 const commandContext = {
189 executable,
190 subcommand: "status" as const,
191 argumentCount: args.length,
192 };
193 return yield* Effect.gen(function* () {
194 const child = yield* spawner
195 .spawn(ChildProcess.make(executable, args))
196 .pipe(
197 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
198 );
199 const [stdout, stderr, exitCode] = yield* Effect.all(
200 [
201 collectStdout(child.stdout),
202 collectStderr(child.stderr),
203 child.exitCode.pipe(Effect.map(Number)),
204 ],
205 { concurrency: "unbounded" },
206 ).pipe(
207 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
208 );
209 if (exitCode !== 0) {
210 return yield* new TailscaleCommandExitError({
211 ...commandContext,
212 exitCode,
213 stdoutLength: stdout.length,
214 stderrLength: stderr.length,
215 });
216 }
217 return yield* parseTailscaleStatus(stdout);
218 }).pipe(
219 Effect.scoped,
220 Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
221 Effect.catchTags({
222 TimeoutError: (cause) =>
223 Effect.fail(
224 new TailscaleCommandTimeoutError({
225 ...commandContext,
226 timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
227 cause,
228 }),
229 ),
230 }),
231 );
232});
233
234export function buildTailscaleHttpsBaseUrl(input: {
235 readonly magicDnsName: string;
236 readonly servePort?: number;
237}): string {
238 const url = new URL(`https://${input.magicDnsName}`);
239 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
240 if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
241 url.port = String(servePort);
242 }
243 url.pathname = "/";
244 return url.toString();
245}
246
247const runTailscaleCommand = (
248 args: readonly string[],
249 timeoutInput: Duration.Input,
250): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
251 Effect.gen(function* () {
252 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
253 const hostPlatform = yield* HostProcessPlatform;
254 const executable = tailscaleCommandForPlatform(hostPlatform);
255 const commandContext = {
256 executable,
257 subcommand: "serve" as const,
258 argumentCount: args.length,
259 };
260 const timeout = Duration.fromInputUnsafe(timeoutInput);
261 return yield* Effect.gen(function* () {
262 const child = yield* spawner
263 .spawn(ChildProcess.make(executable, args))
264 .pipe(
265 Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
266 );
267 const [stderr, exitCode] = yield* Effect.all(
268 [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
269 { concurrency: "unbounded" },
270 ).pipe(
271 Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
272 );
273 if (exitCode !== 0) {
274 return yield* new TailscaleCommandExitError({
275 ...commandContext,
276 exitCode,
277 stderrLength: stderr.length,
278 });
279 }
280 }).pipe(
281 Effect.scoped,
282 Effect.timeout(timeout),
283 Effect.catchTags({
284 TimeoutError: (cause) =>
285 Effect.fail(
286 new TailscaleCommandTimeoutError({
287 ...commandContext,
288 timeoutMs: Duration.toMillis(timeout),
289 cause,
290 }),
291 ),
292 }),
293 );
294 });
295
296export const ensureTailscaleServe = (input: {
297 readonly localPort: number;
298 readonly servePort?: number;
299 readonly localHost?: string;
300}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
301 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
302 const localHost = input.localHost ?? "127.0.0.1";
303 const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
304 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
305};
306
307export const disableTailscaleServe = (
308 input: {
309 readonly servePort?: number;
310 } = {},
311): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
312 Effect.gen(function* () {
313 const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
314 return yield* runTailscaleCommand(
315 ["serve", `--https=${servePort}`, "off"],
316 TAILSCALE_SERVE_TIMEOUT,
317 );
318 });
319
320export const probeTailscaleHttpsEndpoint = (input: {
321 readonly baseUrl: string;
322 readonly timeout?: Duration.Input;
323}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
324 Effect.gen(function* () {
325 const client = yield* HttpClient.HttpClient;
326 const response = yield* Effect.gen(function* () {
327 const url = new URL("/.well-known/t3/environment", input.baseUrl);
328 const request = HttpClientRequest.get(url.toString());
329 return yield* client.execute(request);
330 }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
331
332 return Option.match(response, {
333 onNone: () => false,
334 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
335 });
336 }).pipe(Effect.orElseSucceed(() => false));
337
338export const resolveTailscaleHttpsBaseUrl = (
339 input: {
340 readonly servePort?: number;
341 } = {},
342): Effect.Effect<
343 string | null,
344 TailscaleCommandError | TailscaleStatusParseError,
345 ChildProcessSpawner.ChildProcessSpawner
346> =>
347 readTailscaleStatus.pipe(
348 Effect.map((status) =>
349 status.magicDnsName
350 ? buildTailscaleHttpsBaseUrl({
351 magicDnsName: status.magicDnsName,
352 ...(input.servePort === undefined ? {} : { servePort: input.servePort }),
353 })
354 : null,
355 ),
356 );