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