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