forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtailscale.ts
More file actions
399 lines (366 loc) · 13.3 KB
/
Copy pathtailscale.ts
File metadata and controls
399 lines (366 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
export const TAILSCALE_STATUS_TIMEOUT = Duration.millis(1_500);
export const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);
export const TAILSCALE_PROBE_TIMEOUT = Duration.millis(2_500);
// tailscale is a real executable everywhere (`tailscale.exe` on Windows), so
// it is always spawned directly rather than through cmd.exe shell mode.
const tailscaleCommandForPlatform = (platform: NodeJS.Platform): "tailscale" | "tailscale.exe" =>
platform === "win32" ? "tailscale.exe" : "tailscale";
const TailscaleCommandContext = {
executable: Schema.Literals(["tailscale", "tailscale.exe"]),
subcommand: Schema.Literals(["status", "serve"]),
argumentCount: Schema.Number,
};
/**
* Failure kinds we can name without quoting the CLI. Anything unrecognized
* becomes "unknown" rather than falling back to raw text — stderr can contain
* auth keys (`tskey-…`) and node names, and these labels are logged.
*/
export const TailscaleStderrDiagnostic = Schema.Literals([
"no-existing-handler",
"not-logged-in",
"permission-denied",
"unknown",
]);
export type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;
// Matched against stderr, most specific first. Patterns are deliberately short
// and anchored on tailscale's own wording.
const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
readonly [RegExp, Exclude<TailscaleStderrDiagnostic, "unknown">]
> = [
[/handler does not exist/i, "no-existing-handler"],
[/not logged in|logged out|needs? login/i, "not-logged-in"],
[/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
];
/** Classifies stderr into a safe label, dropping the text itself. */
export const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {
if (stderr.trim().length === 0) {
return undefined;
}
return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? "unknown";
};
export class TailscaleCommandSpawnError extends Schema.TaggedErrorClass<TailscaleCommandSpawnError>()(
"TailscaleCommandSpawnError",
{
...TailscaleCommandContext,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to spawn tailscale ${this.subcommand}.`;
}
}
export class TailscaleCommandOutputError extends Schema.TaggedErrorClass<TailscaleCommandOutputError>()(
"TailscaleCommandOutputError",
{
...TailscaleCommandContext,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read output from tailscale ${this.subcommand}.`;
}
}
export class TailscaleCommandExitError extends Schema.TaggedErrorClass<TailscaleCommandExitError>()(
"TailscaleCommandExitError",
{
...TailscaleCommandContext,
exitCode: Schema.Number,
stdoutLength: Schema.optional(Schema.Number),
stderrLength: Schema.Number,
// A classified diagnostic, never raw CLI output. `tailscale` prints auth
// keys and node identifiers into stderr, and this field is surfaced in
// dev-runner logs — so it carries only a known-safe label from the closed
// set below. Callers that need to recognize a specific failure (e.g.
// `serve off` on a port with no mapping) match on the label.
stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
},
) {
override get message(): string {
return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;
}
}
export class TailscaleCommandTimeoutError extends Schema.TaggedErrorClass<TailscaleCommandTimeoutError>()(
"TailscaleCommandTimeoutError",
{
...TailscaleCommandContext,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `tailscale ${this.subcommand} timed out after ${this.timeoutMs}ms.`;
}
}
export const TailscaleCommandError = Schema.Union([
TailscaleCommandSpawnError,
TailscaleCommandOutputError,
TailscaleCommandExitError,
TailscaleCommandTimeoutError,
]);
export type TailscaleCommandError = typeof TailscaleCommandError.Type;
export class TailscaleStatusParseError extends Schema.TaggedErrorClass<TailscaleStatusParseError>()(
"TailscaleStatusParseError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to decode tailscale status JSON.";
}
}
const TailscaleStatusSelf = Schema.Struct({
DNSName: Schema.optional(Schema.Unknown),
TailscaleIPs: Schema.optional(Schema.Unknown),
});
const TailscaleStatusJson = Schema.Struct({
Self: Schema.optional(TailscaleStatusSelf),
});
export type TailscaleStatusSelf = typeof TailscaleStatusSelf.Type;
export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
export interface TailscaleStatus {
readonly magicDnsName: string | null;
readonly tailnetIpv4Addresses: readonly string[];
}
const collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
);
const collectStderr = collectStdout;
const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
const dnsName = status.Self?.DNSName;
if (typeof dnsName !== "string") {
return null;
}
const normalized = dnsName.trim().replace(/\.$/u, "");
return normalized.length > 0 ? normalized : null;
}
export const parseTailscaleMagicDnsName = (
rawStatusJson: string,
): Effect.Effect<string | null, TailscaleStatusParseError> =>
decodeTailscaleStatusJson(rawStatusJson).pipe(
Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
Effect.map(normalizeMagicDnsName),
);
export function isTailscaleIpv4Address(address: string): boolean {
const parts = address.split(".");
if (parts.length !== 4) {
return false;
}
const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
if (
first === undefined ||
second === undefined ||
third === undefined ||
fourth === undefined ||
[first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
) {
return false;
}
return first === 100 && second >= 64 && second <= 127;
}
export const parseTailscaleStatus = (
rawStatusJson: string,
): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
decodeTailscaleStatusJson(rawStatusJson).pipe(
Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
Effect.map((parsed) => {
const rawIps = parsed.Self?.TailscaleIPs;
const tailnetIpv4Addresses: Array<string> = [];
if (Array.isArray(rawIps)) {
for (const address of rawIps) {
if (typeof address === "string" && isTailscaleIpv4Address(address)) {
tailnetIpv4Addresses.push(address);
}
}
}
return {
magicDnsName: normalizeMagicDnsName(parsed),
tailnetIpv4Addresses,
};
}),
);
export const readTailscaleStatus = Effect.gen(function* () {
const args = ["status", "--json"];
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const hostPlatform = yield* HostProcessPlatform;
const executable = tailscaleCommandForPlatform(hostPlatform);
const commandContext = {
executable,
subcommand: "status" as const,
argumentCount: args.length,
};
return yield* Effect.gen(function* () {
const child = yield* spawner
.spawn(ChildProcess.make(executable, args))
.pipe(
Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStdout(child.stdout),
collectStderr(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
).pipe(
Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
);
if (exitCode !== 0) {
return yield* new TailscaleCommandExitError({
...commandContext,
exitCode,
stdoutLength: stdout.length,
stderrLength: stderr.length,
...(stderrDiagnosticOf(stderr) !== undefined
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
: {}),
});
}
return yield* parseTailscaleStatus(stdout);
}).pipe(
Effect.scoped,
Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
Effect.catchTags({
TimeoutError: (cause) =>
Effect.fail(
new TailscaleCommandTimeoutError({
...commandContext,
timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
cause,
}),
),
}),
);
});
export function buildTailscaleHttpsBaseUrl(input: {
readonly magicDnsName: string;
readonly servePort?: number;
}): string {
const url = new URL(`https://${input.magicDnsName}`);
const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
url.port = String(servePort);
}
url.pathname = "/";
return url.toString();
}
const runTailscaleCommand = (
args: readonly string[],
timeoutInput: Duration.Input,
): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const hostPlatform = yield* HostProcessPlatform;
const executable = tailscaleCommandForPlatform(hostPlatform);
const commandContext = {
executable,
subcommand: "serve" as const,
argumentCount: args.length,
};
const timeout = Duration.fromInputUnsafe(timeoutInput);
return yield* Effect.gen(function* () {
const child = yield* spawner
.spawn(ChildProcess.make(executable, args))
.pipe(
Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
);
const [stderr, exitCode] = yield* Effect.all(
[collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
{ concurrency: "unbounded" },
).pipe(
Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
);
if (exitCode !== 0) {
return yield* new TailscaleCommandExitError({
...commandContext,
exitCode,
stderrLength: stderr.length,
...(stderrDiagnosticOf(stderr) !== undefined
? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
: {}),
});
}
}).pipe(
Effect.scoped,
Effect.timeout(timeout),
Effect.catchTags({
TimeoutError: (cause) =>
Effect.fail(
new TailscaleCommandTimeoutError({
...commandContext,
timeoutMs: Duration.toMillis(timeout),
cause,
}),
),
}),
);
});
export const ensureTailscaleServe = (input: {
readonly localPort: number;
readonly servePort?: number;
readonly localHost?: string;
}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
const localHost = input.localHost ?? "127.0.0.1";
const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
};
export const disableTailscaleServe = (
input: {
readonly servePort?: number;
} = {},
): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.gen(function* () {
const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
return yield* runTailscaleCommand(
["serve", `--https=${servePort}`, "off"],
TAILSCALE_SERVE_TIMEOUT,
);
});
export const probeTailscaleHttpsEndpoint = (input: {
readonly baseUrl: string;
readonly timeout?: Duration.Input;
}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const response = yield* Effect.gen(function* () {
const url = new URL("/.well-known/t3/environment", input.baseUrl);
const request = HttpClientRequest.get(url.toString());
return yield* client.execute(request);
}).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));
return Option.match(response, {
onNone: () => false,
onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
});
}).pipe(Effect.orElseSucceed(() => false));
export const resolveTailscaleHttpsBaseUrl = (
input: {
readonly servePort?: number;
} = {},
): Effect.Effect<
string | null,
TailscaleCommandError | TailscaleStatusParseError,
ChildProcessSpawner.ChildProcessSpawner
> =>
readTailscaleStatus.pipe(
Effect.map((status) =>
status.magicDnsName
? buildTailscaleHttpsBaseUrl({
magicDnsName: status.magicDnsName,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
})
: null,
),
);