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

pair.ts

569 lines21.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 type LocalServerPairCommandOutput,
16 PortSchema,
17} from "@t3tools/contracts";
18import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
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​
197export const formatPairJsonOutput = (input: {
198 readonly pairingUrl: string;
199 readonly token: string;
200 readonly expiresAt: DateTime.Utc;
201 readonly origin: string;
202 readonly environmentId: LocalServerPairCommandOutput["environmentId"];
203 readonly label: string;
204}): string =>
205 JSON.stringify({
206 pairingUrl: input.pairingUrl,
207 token: input.token,
208 expiresAt: DateTime.formatIso(input.expiresAt),
209 origin: input.origin,
210 environmentId: input.environmentId,
211 label: input.label,
212 } satisfies LocalServerPairCommandOutput);
213​
214/**
215 * Three outcomes, because they drive different decisions: a T3 descriptor
216 * (pair with it), nothing answering (safe to configure Tailscale Serve), or
217 * something answering that is not a T3 server (do NOT overwrite its mapping).
218 */
219type EnvironmentProbeResult =
220 | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
221 | { readonly _tag: "unreachable" }
222 | { readonly _tag: "not-a-t3-server" };
223​
224const probeEnvironmentDescriptor = (
225 baseUrl: string,
226): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>
227 Effect.gen(function* () {
228 const client = yield* HttpClient.HttpClient;
229 const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
230 const response = yield* client.execute(request).pipe(
231 Effect.timeout(PAIR_PROBE_TIMEOUT),
232 // Transport failure or timeout: nothing (reachable) is listening there.
233 Effect.mapError(() => ({ _tag: "unreachable" }) as const),
234 );
235 // Bad-gateway family means a proxy (Tailscale Serve) answered for a
236 // backend that is gone — a stale mapping, not a live occupant. Treating
237 // it as unreachable lets `t3 pair --tailscale` repair its own mapping
238 // after the server's port changed.
239 if (response.status === 502 || response.status === 503 || response.status === 504) {
240 return { _tag: "unreachable" } as const;
241 }
242 // Anything else that answered HTTP but not with a valid descriptor is
243 // some other service.
244 const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
245 Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
246 Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
247 );
248 return { _tag: "descriptor", descriptor } as const;
249 }).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));
250​
251interface DiscoveredPairTarget {
252 readonly baseDir: string;
253 readonly variant: PairStateVariant;
254 readonly state: PersistedServerRuntimeState;
255 readonly descriptor: ExecutionEnvironmentDescriptor;
257​
258const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
259 explicitBaseDir: string | undefined,
260) {
261 const bases: Array<string> = [];
262 if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {
263 bases.push(yield* resolveBaseDir(explicitBaseDir));
264 } else {
265 // Same precedence as dev-runner: inside a linked worktree its own `.t3`
266 // outranks the shared home, so `t3 pair` in a worktree pairs with the dev
267 // server under test rather than the daily-driver install.
268 const worktreeHome = yield* resolveWorktreeT3Home(process.cwd());
269 if (worktreeHome !== undefined) {
270 bases.push(worktreeHome);
271 }
272 const envHome = yield* Config.string("T3CODE_HOME").pipe(Config.option);
273 bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
274 }
275​
276 const checkedStatePaths: Array<string> = [];
277 for (const baseDir of new Set(bases)) {
278 for (const variant of ["userdata", "dev"] as const) {
279 const derivedPaths = yield* ServerConfig.deriveServerPaths(
280 baseDir,
281 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
282 {},
283 );
284 const statePath = derivedPaths.serverRuntimeStatePath;
285 checkedStatePaths.push(statePath);
286 const state = yield* readPersistedServerRuntimeState(statePath);
287 if (Option.isNone(state)) {
288 continue;
289 }
290 // The pid check guards against a dead server's state file whose port
291 // was since reused by a different server: pairing would then mint a
292 // token in the old database while the QR code points at the new server.
293 if (!isProcessAlive(state.value.pid)) {
294 continue;
295 }
296 const probed = yield* probeEnvironmentDescriptor(state.value.origin);
297 if (probed._tag !== "descriptor") {
298 continue;
299 }
300 return {
301 baseDir,
302 variant,
303 state: state.value,
304 descriptor: probed.descriptor,
305 } satisfies DiscoveredPairTarget;
306 }
307 }
308 return yield* new NoRunningServerError({ checkedStatePaths });
309});
310​
311/**
312 * Server config pointed at the discovered server's state directory, so the
313 * minted token lands in the database the running server reads from. Built by
314 * hand rather than through `resolveServerConfig` to keep the dev-vs-userdata
315 * choice pinned to where the runtime state was actually found, independent of
316 * ambient environment variables.
317 */
318const makePairServerConfig = Effect.fn(function* (input: {
319 readonly target: DiscoveredPairTarget;
320 readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
321}) {
322 const { baseDir, variant, state } = input.target;
323 // The state-dir variant does not imply dev-ness: a worktree dev server uses
324 // an explicit home and therefore lands in `userdata`. The recorded devUrl is
325 // what actually marks a dev server.
326 const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;
327 const derivedPaths = yield* ServerConfig.deriveServerPaths(
328 baseDir,
329 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
330 {},
331 );
332 return ServerConfig.make({
333 logLevel: input.logLevel,
334 traceMinLevel: "Info",
335 traceTimingEnabled: false,
336 traceBatchWindowMs: 1_000,
337 traceMaxBytes: 10 * 1024 * 1024,
338 traceMaxFiles: 10,
339 otlpTracesUrl: undefined,
340 otlpMetricsUrl: undefined,
341 otlpExportIntervalMs: 10_000,
342 otlpServiceName: "t3-server",
343 otlpHeaders: undefined,
344 otlpProtocol: "http/json",
345 mode: "web",
346 port: state.port,
347 host: state.host,
348 cwd: process.cwd(),
349 baseDir,
350 ...derivedPaths,
351 staticDir: undefined,
352 devUrl,
353 devAllowedOrigins: [],
354 noBrowser: true,
355 startupPresentation: "headless",
356 desktopBootstrapToken: undefined,
357 desktopTelemetryFd: undefined,
358 desktopTelemetryControlFd: undefined,
359 resourceMonitorPath: undefined,
360 autoBootstrapProjectFromCwd: false,
361 logWebSocketEvents: false,
362 tailscaleServeEnabled: false,
363 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
364 });
365});
366​
367const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
368 let last: EnvironmentProbeResult = { _tag: "unreachable" };
369 for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
370 last = yield* probeEnvironmentDescriptor(baseUrl);
371 if (last._tag === "descriptor") {
372 return last;
373 }
374 yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
375 }
376 return last;
377});
378​
379const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
380 function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
381 const notes: Array<string> = [];
382 const status = yield* readTailscaleStatus.pipe(
383 Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
384 );
385 if (status.magicDnsName === null) {
386 return yield* new MagicDnsNameMissingError();
387 }
388 const baseUrl = buildTailscaleHttpsBaseUrl({
389 magicDnsName: status.magicDnsName,
390 servePort: input.servePort,
391 });
392​
393 // Only an unreachable port, or a mapping already fronting this exact
394 // environment, is safe to (re)configure. Any other responder — T3 or not
395 // — must not have its mapping silently replaced.
396 const existing = yield* probeEnvironmentDescriptor(baseUrl);
397 if (existing._tag === "descriptor") {
398 if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
399 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
400 }
401 // Matching environment id proves the mapping reaches this server, but
402 // not through which port: for a dev server it may front the backend
403 // (whose /.well-known also answers) while /pair only renders through
404 // the web origin. Reuse as-is for regular servers; fall through and
405 // repoint our own mapping at the web port for dev servers.
406 if (input.target.state.devUrl === undefined) {
407 return { baseUrl, notes };
408 }
409 }
410 if (existing._tag === "not-a-t3-server") {
411 return yield* new ServePortOccupiedError({ servePort: input.servePort });
412 }
413​
414 const localTarget = resolveTailscaleLocalTarget(input.target.state);
415 if (isDevServerNotProxiableError(localTarget)) {
416 return yield* localTarget;
417 }
418 yield* ensureTailscaleServe({
419 localPort: localTarget.localPort,
420 servePort: input.servePort,
421 ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
422 }).pipe(
423 Effect.mapError(
424 (cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
425 ),
426 );
427 notes.push(
428 `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
429 );
430​
431 const probed = yield* awaitEnvironmentDescriptor(baseUrl);
432 if (probed._tag === "descriptor") {
433 if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {
434 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
435 }
436 } else {
437 notes.push(
438 "The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.",
439 );
440 }
441 return { baseUrl, notes };
442 },
443);
444​
445const mintPairingLink = Effect.fn("pair.mintPairingLink")(function* (input: {
446 readonly config: ServerConfig.ServerConfig["Service"];
447 readonly ttl: Option.Option<Duration.Duration>;
448 readonly label: Option.Option<string>;
449}) {
450 return yield* Effect.gen(function* () {
451 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
452 return yield* environmentAuth.createPairingLink({
453 scopes: AuthStandardClientScopes,
454 subject: "one-time-token",
455 label: Option.getOrElse(input.label, () => "t3 pair"),
456 ...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
457 });
458 }).pipe(
459 Effect.provide(
460 EnvironmentAuth.runtimeLayer.pipe(
461 Layer.provide(ServerConfig.layer(input.config)),
462 Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
463 ),
464 ),
465 );
466});
467​
468const ttlFlag = Flag.string("ttl").pipe(
469 Flag.withSchema(DurationFromString),
470 Flag.withDescription(
471 "Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
472 ),
473 Flag.optional,
474);
475​
476const labelFlag = Flag.string("label").pipe(
477 Flag.withDescription("Optional label shown in the server's connections list."),
478 Flag.optional,
479);
480​
481const jsonFlag = Flag.boolean("json").pipe(
482 Flag.withDescription("Emit JSON instead of human-readable output."),
483 Flag.withDefault(false),
484);
485​
486const tailscaleFlag = Flag.boolean("tailscale").pipe(
487 Flag.withDescription(
488 "Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
489 ),
490 Flag.withDefault(false),
491);
492​
493const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
494 Flag.withSchema(PortSchema),
495 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
496 Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
497);
498​
499export const pairCommand = Command.make("pair", {
500 baseDir: baseDirFlag,
501 ttl: ttlFlag,
502 label: labelFlag,
503 json: jsonFlag,
504 tailscale: tailscaleFlag,
505 tailscaleServePort: tailscaleServePortFlag,
506}).pipe(
507 Command.withDescription(
508 "Mint a pairing token for a running T3 Code server and print it as a QR code.",
509 ),
510 Command.withHandler((flags) =>
511 Effect.gen(function* () {
512 const cliLogLevel = yield* GlobalFlag.LogLevel;
513 // JSON is consumed by other processes, so keep storage/migration chatter
514 // off stdout. Human output defaults to Warn so it cannot bury the QR.
515 const logLevel = flags.json
516 ? ("Error" as const)
517 : Option.getOrElse(cliLogLevel, () => "Warn" as const);
518​
519 const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));
520​
521 const notes: Array<string> = [];
522 let pairingBaseUrl: string;
523 if (flags.tailscale) {
524 const resolved = yield* resolveTailscalePairingBase({
525 target,
526 servePort: flags.tailscaleServePort,
527 });
528 pairingBaseUrl = resolved.baseUrl;
529 notes.push(...resolved.notes);
530 } else {
531 pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
532 if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
533 notes.push(
534 "This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
535 );
536 }
537 if (target.variant === "dev" && target.state.devUrl === undefined) {
538 notes.push(
539 "This dev server did not record its web URL; restart it so pairing can go through the web origin.",
540 );
541 }
542 }
543​
544 const config = yield* makePairServerConfig({ target, logLevel });
545 const issued = yield* mintPairingLink({ config, ttl: flags.ttl, label: flags.label });
546 const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
547​
548 yield* Console.log(
549 flags.json
550 ? formatPairJsonOutput({
551 pairingUrl,
552 token: issued.credential,
553 expiresAt: issued.expiresAt,
554 origin: target.state.origin,
555 environmentId: target.descriptor.environmentId,
556 label: target.descriptor.label,
557 })
558 : formatPairOutput({
559 serverLabel: target.descriptor.label,
560 origin: target.state.origin,
561 pairingUrl,
562 token: issued.credential,
563 expiresAt: issued.expiresAt,
564 notes,
565 }),
566 );
567 }).pipe(Effect.provide(FetchHttpClient.layer)),
568 ),
569);