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