Open History to see the last commit
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 }
73}
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 }
82}
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 }
91}
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 }
100}
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 }
109}
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 }
118}
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 }
127}
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 }
139}
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)) {
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> = Effect.fn(
195 "pair.probeEnvironmentDescriptor",
196)(
197 function* (baseUrl: string) {
198 const client = yield* HttpClient.HttpClient;
199 const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
200 const response = yield* client.execute(request).pipe(
201 Effect.timeout(PAIR_PROBE_TIMEOUT),
202 Effect.mapError(() => ({ _tag: "unreachable" }) as const),
203 );
204 // Bad-gateway family means a proxy (Tailscale Serve) answered for a
205 // backend that is gone — a stale mapping, not a live occupant. Treating
206 // it as unreachable lets `t3 pair --tailscale` repair its own mapping
207 // after the server's port changed.
208 if (response.status === 502 || response.status === 503 || response.status === 504) {
209 return { _tag: "unreachable" } as const;
210 }
211 const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
212 Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
213 Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
214 );
215 return { _tag: "descriptor", descriptor } as const;
216 },
217 Effect.catch((outcome) => Effect.succeed(outcome)),
218);
219
220interface DiscoveredPairTarget {
221 readonly baseDir: string;
222 readonly variant: PairStateVariant;
223 readonly state: PersistedServerRuntimeState;
224 readonly descriptor: ExecutionEnvironmentDescriptor;
225}
226
227const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
228 explicitBaseDir: string | undefined,
229) {
230 const bases: Array<string> = [];
231 if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {
232 bases.push(yield* resolveBaseDir(explicitBaseDir));
233 } else {
234 // Same precedence as dev-runner: inside a linked worktree its own `.t3`
235 // outranks the shared home, so `t3 pair` in a worktree pairs with the dev
236 // server under test rather than the daily-driver install.
237 const worktreeHome = yield* resolveWorktreeT3Home(process.cwd());
238 if (worktreeHome !== undefined) {
239 bases.push(worktreeHome);
240 }
241 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
242 bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
243 }
244
245 const checkedStatePaths: Array<string> = [];
246 for (const baseDir of new Set(bases)) {
247 for (const variant of ["userdata", "dev"] as const) {
248 const derivedPaths = yield* ServerConfig.deriveServerPaths(
249 baseDir,
250 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
251 {},
252 );
253 const statePath = derivedPaths.serverRuntimeStatePath;
254 checkedStatePaths.push(statePath);
255 const state = yield* readPersistedServerRuntimeState(statePath);
256 if (Option.isNone(state)) {
257 continue;
258 }
259 // The pid check guards against a dead server's state file whose port
260 // was since reused by a different server: pairing would then mint a
261 // token in the old database while the QR code points at the new server.
262 if (!isProcessAlive(state.value.pid)) {
263 continue;
264 }
265 const probed = yield* probeEnvironmentDescriptor(state.value.origin);
266 if (probed._tag !== "descriptor") {
267 continue;
268 }
269 return {
270 baseDir,
271 variant,
272 state: state.value,
273 descriptor: probed.descriptor,
274 } satisfies DiscoveredPairTarget;
275 }
276 }
277 return yield* new NoRunningServerError({ checkedStatePaths });
278});
279
280/**
281 * Built by hand rather than through `resolveServerConfig` to keep the dev-vs-userdata choice
282 * pinned to where the runtime state was actually found, independent of ambient environment
283 * variables.
284 */
285const makePairServerConfig = Effect.fn(function* (input: {
286 readonly target: DiscoveredPairTarget;
287 readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
288}) {
289 const { baseDir, variant, state } = input.target;
290 // The state-dir variant does not imply dev-ness: a worktree dev server uses
291 // an explicit home and therefore lands in `userdata`. The recorded devUrl is
292 // what actually marks a dev server.
293 const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;
294 const derivedPaths = yield* ServerConfig.deriveServerPaths(
295 baseDir,
296 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
297 {},
298 );
299 return ServerConfig.make({
300 logLevel: input.logLevel,
301 traceMinLevel: "Info",
302 traceTimingEnabled: false,
303 traceBatchWindowMs: 1_000,
304 traceMaxBytes: 10 * 1024 * 1024,
305 traceMaxFiles: 10,
306 otlpTracesUrl: undefined,
307 otlpMetricsUrl: undefined,
308 otlpLogsUrl: undefined,
309 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
310 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
311 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
312 otelEnvironment: OtelEnvironment.none,
313 mode: "web",
314 port: state.port,
315 host: state.host,
316 cwd: process.cwd(),
317 baseDir,
318 ...derivedPaths,
319 staticDir: undefined,
320 devUrl,
321 devAllowedOrigins: [],
322 noBrowser: true,
323 startupPresentation: "headless",
324 desktopBootstrapToken: undefined,
325 desktopTelemetryFd: undefined,
326 desktopBrowserFd: undefined,
327 desktopBrowserControlFd: undefined,
328 desktopTelemetryControlFd: undefined,
329 resourceMonitorPath: undefined,
330 autoBootstrapProjectFromCwd: false,
331 logWebSocketEvents: false,
332 tailscaleServeEnabled: false,
333 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
334 });
335});
336
337const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
338 let last: EnvironmentProbeResult = { _tag: "unreachable" };
339 for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
340 last = yield* probeEnvironmentDescriptor(baseUrl);
341 if (last._tag === "descriptor") {
342 return last;
343 }
344 yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
345 }
346 return last;
347});
348
349const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
350 function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
351 const notes: Array<string> = [];
352 const status = yield* readTailscaleStatus.pipe(
353 Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
354 );
355 if (status.magicDnsName === null) {
356 return yield* new MagicDnsNameMissingError();
357 }
358 // Without the capability `tailscale serve` blocks on an enablement URL
359 // until it times out, which names neither the setting nor where to change it.
360 if (status.httpsServeEnabled === false) {
361 return yield* new TailscaleServeNotEnabledError();
362 }
363 const baseUrl = buildTailscaleHttpsBaseUrl({
364 magicDnsName: status.magicDnsName,
365 servePort: input.servePort,
366 });
367
368 // Only an unreachable port, or a mapping already fronting this exact
369 // environment, is safe to (re)configure. Any other responder — T3 or not
370 // — must not have its mapping silently replaced.
371 const existing = yield* probeEnvironmentDescriptor(baseUrl);
372 if (existing._tag === "descriptor") {
373 if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
374 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
375 }
376 // Matching environment id proves the mapping reaches this server, but
377 // not through which port: for a dev server it may front the backend
378 // (whose /.well-known also answers) while /pair only renders through
379 // the web origin. Reuse as-is for regular servers; fall through and
380 // repoint our own mapping at the web port for dev servers.
381 if (input.target.state.devUrl === undefined) {
382 return { baseUrl, notes };
383 }
384 }
385 if (existing._tag === "not-a-t3-server") {
386 return yield* new ServePortOccupiedError({ servePort: input.servePort });
387 }
388
389 const localTarget = resolveTailscaleLocalTarget(input.target.state);
390 if (isDevServerNotProxiableError(localTarget)) {
391 return yield* localTarget;
392 }
393 yield* ensureTailscaleServe({
394 localPort: localTarget.localPort,
395 servePort: input.servePort,
396 ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
397 }).pipe(
398 Effect.mapError(
399 (cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
400 ),
401 );
402 notes.push(
403 `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
404 );
405
406 const probed = yield* awaitEnvironmentDescriptor(baseUrl);
407 if (probed._tag === "descriptor") {
408 if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {
409 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
410 }
411 } else {
412 notes.push(
413 "The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.",
414 );
415 }
416 return { baseUrl, notes };
417 },
418);
419
420const mintPairingLink = Effect.fn("pair.mintPairingLink")(function* (input: {
421 readonly config: ServerConfig.ServerConfig["Service"];
422 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
423 readonly ttl: Option.Option<Duration.Duration>;
424 readonly label: Option.Option<string>;
425}) {
426 return yield* Effect.gen(function* () {
427 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
428 return yield* environmentAuth.createPairingLink({
429 scopes: input.scopes,
430 subject: "one-time-token",
431 label: Option.getOrElse(input.label, () => "t3 pair"),
432 ...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
433 });
434 }).pipe(
435 Effect.provide(
436 EnvironmentAuth.layerRuntime.pipe(
437 Layer.provide(ServerConfig.layer(input.config)),
438 Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
439 ),
440 ),
441 );
442});
443
444const ttlFlag = Flag.String("ttl").pipe(
445 Flag.withSchema(DurationFromString),
446 Flag.withDescription(
447 "Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
448 ),
449 Flag.optional,
450);
451
452const labelFlag = Flag.String("label").pipe(
453 Flag.withDescription("Optional label shown in the server's connections list."),
454 Flag.optional,
455);
456
457const tailscaleFlag = Flag.Boolean("tailscale").pipe(
458 Flag.withDescription(
459 "Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
460 ),
461 Flag.withDefault(false),
462);
463
464const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
465 Flag.withSchema(PortSchema),
466 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
467 Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
468);
469
470export const pairCommand = Command.make("pair", {
471 baseDir: baseDirFlag,
472 scopes: authScopesFlag(AuthStandardClientScopes),
473 ttl: ttlFlag,
474 label: labelFlag,
475 tailscale: tailscaleFlag,
476 tailscaleServePort: tailscaleServePortFlag,
477}).pipe(
478 Command.withDescription(
479 "Mint a pairing token for a running T3 Code server and print it as a QR code.",
480 ),
481 Command.withHandler((flags) =>
482 Effect.gen(function* () {
483 const cliLogLevel = yield* GlobalFlag.LogLevel;
484 const logLevel = Option.getOrElse(cliLogLevel, () => "Warn" as const);
485
486 const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));
487
488 const notes: Array<string> = [];
489 let pairingBaseUrl: string;
490 if (flags.tailscale) {
491 const resolved = yield* resolveTailscalePairingBase({
492 target,
493 servePort: flags.tailscaleServePort,
494 });
495 pairingBaseUrl = resolved.baseUrl;
496 notes.push(...resolved.notes);
497 } else {
498 pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
499 if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
500 notes.push(
501 "This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
502 );
503 }
504 if (target.variant === "dev" && target.state.devUrl === undefined) {
505 notes.push(
506 "This dev server did not record its web URL; restart it so pairing can go through the web origin.",
507 );
508 }
509 }
510
511 const config = yield* makePairServerConfig({ target, logLevel });
512 const issued = yield* mintPairingLink({
513 config,
514 scopes: flags.scopes,
515 ttl: flags.ttl,
516 label: flags.label,
517 });
518 const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
519
520 yield* Console.log(
521 formatPairOutput({
522 serverLabel: target.descriptor.label,
523 origin: target.state.origin,
524 pairingUrl,
525 token: issued.credential,
526 expiresAt: issued.expiresAt,
527 notes,
528 }),
529 );
530 }).pipe(Effect.provide(FetchHttpClient.layer)),
531 ),
532);