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

pair.ts

528 lines19.6 KB

1import {
2 type AuthEnvironmentScope,
3 AuthStandardClientScopes,
4 ExecutionEnvironmentDescriptor,
5 PortSchema,
6} from "@t3tools/contracts";
7import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
8import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
9import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
10import {
11 buildTailscaleHttpsBaseUrl,
12 DEFAULT_TAILSCALE_SERVE_PORT,
13 ensureTailscaleServe,
14 readTailscaleStatus,
15} from "@t3tools/tailscale";
16import * as Config from "effect/Config";
17import * as Console from "effect/Console";
18import * as DateTime from "effect/DateTime";
19import * as Duration from "effect/Duration";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as References from "effect/References";
24import * as Schema from "effect/Schema";
25import { Command, Flag, GlobalFlag } from "effect/cli";
26import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
27​
28import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
29import * as ServerConfig from "../config.ts";
30import { resolveBaseDir } from "../os-jank.ts";
31import {
32 type PersistedServerRuntimeState,
33 isProcessAlive,
34 readPersistedServerRuntimeState,
35} from "../serverRuntimeState.ts";
36import {
37 buildPairingUrl,
38 formatHostForUrl,
39 isLoopbackHost,
40 isWildcardHost,
41 renderTerminalQrCode,
42 resolveHeadlessConnectionString,
43} from "../startupAccess.ts";
44import { authScopesFlag } from "./authScopes.ts";
45import { baseDirFlag, DurationFromString } from "./config.ts";
46​
47const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
48const PAIR_PROBE_TIMEOUT = Duration.millis(2_500);
49// Tailscale provisions an HTTPS certificate on the first request to a fresh
50// serve mapping, which can take a few seconds.
51const TAILSCALE_PROBE_ATTEMPTS = 5;
52const TAILSCALE_PROBE_RETRY_DELAY = Duration.seconds(1);
53​
54export type PairStateVariant = "userdata" | "dev";
55​
56// deriveServerPaths only checks devUrl for undefined-ness when picking the
57// dev-vs-userdata state directory; the value itself is not used.
58const DEV_VARIANT_PLACEHOLDER_URL = new URL("http://localhost");
59​
60export class NoRunningServerError extends Schema.TaggedError<NoRunningServerError>()(
61 "NoRunningServerError",
62 {
63 checkedStatePaths: Schema.Array(Schema.String),
64 },
65) {
66 override get message(): string {
67 return [
68 "No running T3 Code server found.",
69 ...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
70 "Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
71 ].join("\n");
72 }
74​
75export class TailscaleUnavailableError extends Schema.TaggedError<TailscaleUnavailableError>()(
76 "TailscaleUnavailableError",
77 { cause: Schema.Defect() },
78) {
79 override get message(): string {
80 return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";
81 }
83​
84export class MagicDnsNameMissingError extends Schema.TaggedError<MagicDnsNameMissingError>()(
85 "MagicDnsNameMissingError",
86 {},
87) {
88 override get message(): string {
89 return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";
90 }
92​
93export class TailscaleServeNotEnabledError extends Schema.TaggedError<TailscaleServeNotEnabledError>()(
94 "TailscaleServeNotEnabledError",
95 {},
96) {
97 override get message(): string {
98 return "Tailscale Serve is not enabled on your tailnet. Enable HTTPS certificates at https://login.tailscale.com/admin/dns, then run this command again.";
99 }
101​
102export class ServesOtherEnvironmentError extends Schema.TaggedError<ServesOtherEnvironmentError>()(
103 "ServesOtherEnvironmentError",
104 { servePort: Schema.Number },
105) {
106 override get message(): string {
107 return `Tailscale Serve on HTTPS port ${String(this.servePort)} already fronts a different T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;
108 }
110​
111export class TailscaleServeFailedError extends Schema.TaggedError<TailscaleServeFailedError>()(
112 "TailscaleServeFailedError",
113 { servePort: Schema.Number, cause: Schema.Defect() },
114) {
115 override get message(): string {
116 return `tailscale serve failed for HTTPS port ${String(this.servePort)}. Run \`tailscale serve --https=${String(this.servePort)} --bg <local-url>\` by hand to see why.`;
117 }
119​
120export class ServePortOccupiedError extends Schema.TaggedError<ServePortOccupiedError>()(
121 "ServePortOccupiedError",
122 { servePort: Schema.Number },
123) {
124 override get message(): string {
125 return `HTTPS port ${String(this.servePort)} on the tailnet already serves something that is not a T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;
126 }
128​
129export const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
130 state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);
131​
132export class DevServerNotProxiableError extends Schema.TaggedError<DevServerNotProxiableError>()(
133 "DevServerNotProxiableError",
134 { devUrl: Schema.String },
135) {
136 override get message(): string {
137 return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;
138 }
140​
141const isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);
142​
143/**
144 * Dev servers are single-origin, so the web dev server's port is the one to publish; the
145 * backend rides along behind Vite's proxy. Serve targets are always plain HTTP, so an HTTPS dev
146 * URL cannot be proxied and is rejected.
147 */
148export const resolveTailscaleLocalTarget = (
149 state: PersistedServerRuntimeState,
150): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {
151 if (state.devUrl !== undefined) {
152 const devUrl = new URL(state.devUrl);
153 if (devUrl.protocol !== "http:") {
154 return new DevServerNotProxiableError({ devUrl: state.devUrl });
155 }
156 const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;
157 return isLoopbackHost(devUrl.hostname)
158 ? { localPort }
159 : { localPort, localHost: devUrl.hostname };
160 }
161 if (state.host !== undefined && !isWildcardHost(state.host) && !isLoopbackHost(state.host)) {
162 return { localPort: state.port, localHost: formatHostForUrl(state.host) };
163 }
164 return { localPort: state.port };
165};
166​
167const formatPairOutput = (input: {
168 readonly serverLabel: string;
169 readonly origin: string;
170 readonly pairingUrl: string;
171 readonly token: string;
172 readonly expiresAt: DateTime.Utc;
173 readonly notes: ReadonlyArray<string>;
174}): string =>
175 [
176 `Pairing with ${input.serverLabel} (${input.origin}).`,
177 "",
178 renderTerminalQrCode(input.pairingUrl),
179 "",
180 `Pairing URL: ${input.pairingUrl}`,
181 `Token: ${input.token}`,
182 `Expires: ${DateTime.formatIso(input.expiresAt)}`,
183 ...input.notes.flatMap((note) => ["", `Note: ${note}`]),
184 "",
185 ].join("\n");
186​
187type EnvironmentProbeResult =
188 | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
189 | { readonly _tag: "unreachable" }
190 | { readonly _tag: "not-a-t3-server" };
191​
192const probeEnvironmentDescriptor = (
193 baseUrl: string,
194): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>
195 Effect.gen(function* () {
196 const client = yield* HttpClient.HttpClient;
197 const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
198 const response = yield* client.execute(request).pipe(
199 Effect.timeout(PAIR_PROBE_TIMEOUT),
200 Effect.mapError(() => ({ _tag: "unreachable" }) as const),
201 );
202 // Bad-gateway family means a proxy (Tailscale Serve) answered for a
203 // backend that is gone — a stale mapping, not a live occupant. Treating
204 // it as unreachable lets `t3 pair --tailscale` repair its own mapping
205 // after the server's port changed.
206 if (response.status === 502 || response.status === 503 || response.status === 504) {
207 return { _tag: "unreachable" } as const;
208 }
209 const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
210 Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
211 Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
212 );
213 return { _tag: "descriptor", descriptor } as const;
214 }).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));
215​
216interface DiscoveredPairTarget {
217 readonly baseDir: string;
218 readonly variant: PairStateVariant;
219 readonly state: PersistedServerRuntimeState;
220 readonly descriptor: ExecutionEnvironmentDescriptor;
222​
223const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
224 explicitBaseDir: string | undefined,
225) {
226 const bases: Array<string> = [];
227 if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {
228 bases.push(yield* resolveBaseDir(explicitBaseDir));
229 } else {
230 // Same precedence as dev-runner: inside a linked worktree its own `.t3`
231 // outranks the shared home, so `t3 pair` in a worktree pairs with the dev
232 // server under test rather than the daily-driver install.
233 const worktreeHome = yield* resolveWorktreeT3Home(process.cwd());
234 if (worktreeHome !== undefined) {
235 bases.push(worktreeHome);
236 }
237 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
238 bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
239 }
240​
241 const checkedStatePaths: Array<string> = [];
242 for (const baseDir of new Set(bases)) {
243 for (const variant of ["userdata", "dev"] as const) {
244 const derivedPaths = yield* ServerConfig.deriveServerPaths(
245 baseDir,
246 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
247 {},
248 );
249 const statePath = derivedPaths.serverRuntimeStatePath;
250 checkedStatePaths.push(statePath);
251 const state = yield* readPersistedServerRuntimeState(statePath);
252 if (Option.isNone(state)) {
253 continue;
254 }
255 // The pid check guards against a dead server's state file whose port
256 // was since reused by a different server: pairing would then mint a
257 // token in the old database while the QR code points at the new server.
258 if (!isProcessAlive(state.value.pid)) {
259 continue;
260 }
261 const probed = yield* probeEnvironmentDescriptor(state.value.origin);
262 if (probed._tag !== "descriptor") {
263 continue;
264 }
265 return {
266 baseDir,
267 variant,
268 state: state.value,
269 descriptor: probed.descriptor,
270 } satisfies DiscoveredPairTarget;
271 }
272 }
273 return yield* new NoRunningServerError({ checkedStatePaths });
274});
275​
276/**
277 * Built by hand rather than through `resolveServerConfig` to keep the dev-vs-userdata choice
278 * pinned to where the runtime state was actually found, independent of ambient environment
279 * variables.
280 */
281const makePairServerConfig = Effect.fn(function* (input: {
282 readonly target: DiscoveredPairTarget;
283 readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
284}) {
285 const { baseDir, variant, state } = input.target;
286 // The state-dir variant does not imply dev-ness: a worktree dev server uses
287 // an explicit home and therefore lands in `userdata`. The recorded devUrl is
288 // what actually marks a dev server.
289 const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;
290 const derivedPaths = yield* ServerConfig.deriveServerPaths(
291 baseDir,
292 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
293 {},
294 );
295 return ServerConfig.make({
296 logLevel: input.logLevel,
297 traceMinLevel: "Info",
298 traceTimingEnabled: false,
299 traceBatchWindowMs: 1_000,
300 traceMaxBytes: 10 * 1024 * 1024,
301 traceMaxFiles: 10,
302 otlpTracesUrl: undefined,
303 otlpMetricsUrl: undefined,
304 otlpLogsUrl: undefined,
305 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
306 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
307 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
308 otelEnvironment: OtelEnvironment.none,
309 mode: "web",
310 port: state.port,
311 host: state.host,
312 cwd: process.cwd(),
313 baseDir,
314 ...derivedPaths,
315 staticDir: undefined,
316 devUrl,
317 devAllowedOrigins: [],
318 noBrowser: true,
319 startupPresentation: "headless",
320 desktopBootstrapToken: undefined,
321 desktopTelemetryFd: undefined,
322 desktopBrowserFd: undefined,
323 desktopBrowserControlFd: undefined,
324 desktopTelemetryControlFd: undefined,
325 resourceMonitorPath: undefined,
326 autoBootstrapProjectFromCwd: false,
327 logWebSocketEvents: false,
328 tailscaleServeEnabled: false,
329 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
330 });
331});
332​
333const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
334 let last: EnvironmentProbeResult = { _tag: "unreachable" };
335 for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
336 last = yield* probeEnvironmentDescriptor(baseUrl);
337 if (last._tag === "descriptor") {
338 return last;
339 }
340 yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
341 }
342 return last;
343});
344​
345const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
346 function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
347 const notes: Array<string> = [];
348 const status = yield* readTailscaleStatus.pipe(
349 Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
350 );
351 if (status.magicDnsName === null) {
352 return yield* new MagicDnsNameMissingError();
353 }
354 // Without the capability `tailscale serve` blocks on an enablement URL
355 // until it times out, which names neither the setting nor where to change it.
356 if (status.httpsServeEnabled === false) {
357 return yield* new TailscaleServeNotEnabledError();
358 }
359 const baseUrl = buildTailscaleHttpsBaseUrl({
360 magicDnsName: status.magicDnsName,
361 servePort: input.servePort,
362 });
363​
364 // Only an unreachable port, or a mapping already fronting this exact
365 // environment, is safe to (re)configure. Any other responder — T3 or not
366 // — must not have its mapping silently replaced.
367 const existing = yield* probeEnvironmentDescriptor(baseUrl);
368 if (existing._tag === "descriptor") {
369 if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
370 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
371 }
372 // Matching environment id proves the mapping reaches this server, but
373 // not through which port: for a dev server it may front the backend
374 // (whose /.well-known also answers) while /pair only renders through
375 // the web origin. Reuse as-is for regular servers; fall through and
376 // repoint our own mapping at the web port for dev servers.
377 if (input.target.state.devUrl === undefined) {
378 return { baseUrl, notes };
379 }
380 }
381 if (existing._tag === "not-a-t3-server") {
382 return yield* new ServePortOccupiedError({ servePort: input.servePort });
383 }
384​
385 const localTarget = resolveTailscaleLocalTarget(input.target.state);
386 if (isDevServerNotProxiableError(localTarget)) {
387 return yield* localTarget;
388 }
389 yield* ensureTailscaleServe({
390 localPort: localTarget.localPort,
391 servePort: input.servePort,
392 ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
393 }).pipe(
394 Effect.mapError(
395 (cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
396 ),
397 );
398 notes.push(
399 `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
400 );
401​
402 const probed = yield* awaitEnvironmentDescriptor(baseUrl);
403 if (probed._tag === "descriptor") {
404 if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {
405 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
406 }
407 } else {
408 notes.push(
409 "The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.",
410 );
411 }
412 return { baseUrl, notes };
413 },
414);
415​
416const mintPairingLink = Effect.fn("pair.mintPairingLink")(function* (input: {
417 readonly config: ServerConfig.ServerConfig["Service"];
418 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
419 readonly ttl: Option.Option<Duration.Duration>;
420 readonly label: Option.Option<string>;
421}) {
422 return yield* Effect.gen(function* () {
423 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
424 return yield* environmentAuth.createPairingLink({
425 scopes: input.scopes,
426 subject: "one-time-token",
427 label: Option.getOrElse(input.label, () => "t3 pair"),
428 ...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
429 });
430 }).pipe(
431 Effect.provide(
432 EnvironmentAuth.layerRuntime.pipe(
433 Layer.provide(ServerConfig.layer(input.config)),
434 Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
435 ),
436 ),
437 );
438});
439​
440const ttlFlag = Flag.String("ttl").pipe(
441 Flag.withSchema(DurationFromString),
442 Flag.withDescription(
443 "Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
444 ),
445 Flag.optional,
446);
447​
448const labelFlag = Flag.String("label").pipe(
449 Flag.withDescription("Optional label shown in the server's connections list."),
450 Flag.optional,
451);
452​
453const tailscaleFlag = Flag.Boolean("tailscale").pipe(
454 Flag.withDescription(
455 "Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
456 ),
457 Flag.withDefault(false),
458);
459​
460const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
461 Flag.withSchema(PortSchema),
462 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
463 Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
464);
465​
466export const pairCommand = Command.make("pair", {
467 baseDir: baseDirFlag,
468 scopes: authScopesFlag(AuthStandardClientScopes),
469 ttl: ttlFlag,
470 label: labelFlag,
471 tailscale: tailscaleFlag,
472 tailscaleServePort: tailscaleServePortFlag,
473}).pipe(
474 Command.withDescription(
475 "Mint a pairing token for a running T3 Code server and print it as a QR code.",
476 ),
477 Command.withHandler((flags) =>
478 Effect.gen(function* () {
479 const cliLogLevel = yield* GlobalFlag.LogLevel;
480 const logLevel = Option.getOrElse(cliLogLevel, () => "Warn" as const);
481​
482 const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));
483​
484 const notes: Array<string> = [];
485 let pairingBaseUrl: string;
486 if (flags.tailscale) {
487 const resolved = yield* resolveTailscalePairingBase({
488 target,
489 servePort: flags.tailscaleServePort,
490 });
491 pairingBaseUrl = resolved.baseUrl;
492 notes.push(...resolved.notes);
493 } else {
494 pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
495 if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
496 notes.push(
497 "This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
498 );
499 }
500 if (target.variant === "dev" && target.state.devUrl === undefined) {
501 notes.push(
502 "This dev server did not record its web URL; restart it so pairing can go through the web origin.",
503 );
504 }
505 }
506​
507 const config = yield* makePairServerConfig({ target, logLevel });
508 const issued = yield* mintPairingLink({
509 config,
510 scopes: flags.scopes,
511 ttl: flags.ttl,
512 label: flags.label,
513 });
514 const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
515​
516 yield* Console.log(
517 formatPairOutput({
518 serverLabel: target.descriptor.label,
519 origin: target.state.origin,
520 pairingUrl,
521 token: issued.credential,
522 expiresAt: issued.expiresAt,
523 notes,
524 }),
525 );
526 }).pipe(Effect.provide(FetchHttpClient.layer)),
527 ),
528);