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

pair.ts

536 lines20.3 KB

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