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

pair.ts

538 lines20.4 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 * 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 }
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 }
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 }
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 }
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 }
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 }
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 }
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;
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 otlpServiceName: "t3-server",
330 otelEnvironment: OtelEnvironment.none,
331 mode: "web",
332 port: state.port,
333 host: state.host,
334 cwd: process.cwd(),
335 baseDir,
336 ...derivedPaths,
337 staticDir: undefined,
338 devUrl,
339 devAllowedOrigins: [],
340 noBrowser: true,
341 startupPresentation: "headless",
342 desktopBootstrapToken: undefined,
343 desktopTelemetryFd: undefined,
344 desktopTelemetryControlFd: undefined,
345 resourceMonitorPath: undefined,
346 autoBootstrapProjectFromCwd: false,
347 logWebSocketEvents: false,
348 tailscaleServeEnabled: false,
349 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
350 });
351});
352​
353const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
354 let last: EnvironmentProbeResult = { _tag: "unreachable" };
355 for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
356 last = yield* probeEnvironmentDescriptor(baseUrl);
357 if (last._tag === "descriptor") {
358 return last;
359 }
360 yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
361 }
362 return last;
363});
364​
365const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
366 function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
367 const notes: Array<string> = [];
368 const status = yield* readTailscaleStatus.pipe(
369 Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
370 );
371 if (status.magicDnsName === null) {
372 return yield* new MagicDnsNameMissingError();
373 }
374 const baseUrl = buildTailscaleHttpsBaseUrl({
375 magicDnsName: status.magicDnsName,
376 servePort: input.servePort,
377 });
378​
379 // Only an unreachable port, or a mapping already fronting this exact
380 // environment, is safe to (re)configure. Any other responder — T3 or not
381 // — must not have its mapping silently replaced.
382 const existing = yield* probeEnvironmentDescriptor(baseUrl);
383 if (existing._tag === "descriptor") {
384 if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
385 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
386 }
387 // Matching environment id proves the mapping reaches this server, but
388 // not through which port: for a dev server it may front the backend
389 // (whose /.well-known also answers) while /pair only renders through
390 // the web origin. Reuse as-is for regular servers; fall through and
391 // repoint our own mapping at the web port for dev servers.
392 if (input.target.state.devUrl === undefined) {
393 return { baseUrl, notes };
394 }
395 }
396 if (existing._tag === "not-a-t3-server") {
397 return yield* new ServePortOccupiedError({ servePort: input.servePort });
398 }
399​
400 const localTarget = resolveTailscaleLocalTarget(input.target.state);
401 if (isDevServerNotProxiableError(localTarget)) {
402 return yield* localTarget;
403 }
404 yield* ensureTailscaleServe({
405 localPort: localTarget.localPort,
406 servePort: input.servePort,
407 ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
408 }).pipe(
409 Effect.mapError(
410 (cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
411 ),
412 );
413 notes.push(
414 `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
415 );
416​
417 const probed = yield* awaitEnvironmentDescriptor(baseUrl);
418 if (probed._tag === "descriptor") {
419 if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {
420 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
421 }
422 } else {
423 notes.push(
424 "The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.",
425 );
426 }
427 return { baseUrl, notes };
428 },
429);
430​
431const mintPairingLink = Effect.fn("pair.mintPairingLink")(function* (input: {
432 readonly config: ServerConfig.ServerConfig["Service"];
433 readonly ttl: Option.Option<Duration.Duration>;
434 readonly label: Option.Option<string>;
435}) {
436 return yield* Effect.gen(function* () {
437 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
438 return yield* environmentAuth.createPairingLink({
439 scopes: AuthStandardClientScopes,
440 subject: "one-time-token",
441 label: Option.getOrElse(input.label, () => "t3 pair"),
442 ...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
443 });
444 }).pipe(
445 Effect.provide(
446 EnvironmentAuth.runtimeLayer.pipe(
447 Layer.provide(ServerConfig.layer(input.config)),
448 Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
449 ),
450 ),
451 );
452});
453​
454const ttlFlag = Flag.String("ttl").pipe(
455 Flag.withSchema(DurationFromString),
456 Flag.withDescription(
457 "Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
458 ),
459 Flag.optional,
460);
461​
462const labelFlag = Flag.String("label").pipe(
463 Flag.withDescription("Optional label shown in the server's connections list."),
464 Flag.optional,
465);
466​
467const tailscaleFlag = Flag.Boolean("tailscale").pipe(
468 Flag.withDescription(
469 "Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
470 ),
471 Flag.withDefault(false),
472);
473​
474const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
475 Flag.withSchema(PortSchema),
476 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
477 Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
478);
479​
480export const pairCommand = Command.make("pair", {
481 baseDir: baseDirFlag,
482 ttl: ttlFlag,
483 label: labelFlag,
484 tailscale: tailscaleFlag,
485 tailscaleServePort: tailscaleServePortFlag,
486}).pipe(
487 Command.withDescription(
488 "Mint a pairing token for a running T3 Code server and print it as a QR code.",
489 ),
490 Command.withHandler((flags) =>
491 Effect.gen(function* () {
492 const cliLogLevel = yield* GlobalFlag.LogLevel;
493 // Default to Warn so storage/migration chatter cannot bury the QR code;
494 // an explicit --log-level still wins.
495 const logLevel = Option.getOrElse(cliLogLevel, () => "Warn" as const);
496​
497 const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));
498​
499 const notes: Array<string> = [];
500 let pairingBaseUrl: string;
501 if (flags.tailscale) {
502 const resolved = yield* resolveTailscalePairingBase({
503 target,
504 servePort: flags.tailscaleServePort,
505 });
506 pairingBaseUrl = resolved.baseUrl;
507 notes.push(...resolved.notes);
508 } else {
509 pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
510 if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
511 notes.push(
512 "This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
513 );
514 }
515 if (target.variant === "dev" && target.state.devUrl === undefined) {
516 notes.push(
517 "This dev server did not record its web URL; restart it so pairing can go through the web origin.",
518 );
519 }
520 }
521​
522 const config = yield* makePairServerConfig({ target, logLevel });
523 const issued = yield* mintPairingLink({ config, ttl: flags.ttl, label: flags.label });
524 const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
525​
526 yield* Console.log(
527 formatPairOutput({
528 serverLabel: target.descriptor.label,
529 origin: target.state.origin,
530 pairingUrl,
531 token: issued.credential,
532 expiresAt: issued.expiresAt,
533 notes,
534 }),
535 );
536 }).pipe(Effect.provide(FetchHttpClient.layer)),
537 ),
538);