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

pair.ts

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