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