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 * as HostProcess from "@t3tools/shared/HostProcess";
9import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
10import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
11import {
12 buildTailscaleHttpsBaseUrl,
13 DEFAULT_TAILSCALE_SERVE_PORT,
14 ensureTailscaleServe,
15 readTailscaleStatus,
16} from "@t3tools/tailscale";
17import * as Config from "effect/Config";
18import * as Console from "effect/Console";
19import * as DateTime from "effect/DateTime";
20import * as Duration from "effect/Duration";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as References from "effect/References";
25import * as Schema from "effect/Schema";
26import { Command, Flag, GlobalFlag } from "effect/cli";
27import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
28
29import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
30import * as ServerConfig from "../config.ts";
31import { resolveBaseDir } from "../os-jank.ts";
32import {
33 type PersistedServerRuntimeState,
34 isProcessAlive,
35 readPersistedServerRuntimeState,
36} from "../serverRuntimeState.ts";
37import {
38 buildPairingUrl,
39 formatHostForUrl,
40 isLoopbackHost,
41 isWildcardHost,
42 renderTerminalQrCode,
43 resolveHeadlessConnectionString,
44} from "../startupAccess.ts";
45import { authScopesFlag } from "./authScopes.ts";
46import { baseDirFlag, DurationFromString } from "./config.ts";
47
48const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
49const PAIR_PROBE_TIMEOUT = Duration.millis(2_500);
50// Tailscale provisions an HTTPS certificate on the first request to a fresh
51// serve mapping, which can take a few seconds.
52const TAILSCALE_PROBE_ATTEMPTS = 5;
53const TAILSCALE_PROBE_RETRY_DELAY = Duration.seconds(1);
54
55export type PairStateVariant = "userdata" | "dev";
56
57// deriveServerPaths only checks devUrl for undefined-ness when picking the
58// dev-vs-userdata state directory; the value itself is not used.
59const DEV_VARIANT_PLACEHOLDER_URL = new URL("http://localhost");
60
61export class NoRunningServerError extends Schema.TaggedError<NoRunningServerError>()(
62 "NoRunningServerError",
63 {
64 checkedStatePaths: Schema.Array(Schema.String),
65 inLinkedWorktree: Schema.Boolean,
66 },
67) {
68 override get message(): string {
69 return [
70 "No running T3 Code server found.",
71 ...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
72 ...(this.inLinkedWorktree
73 ? ["In a linked worktree, pass --base-dir to pair with a server outside it."]
74 : []),
75 "Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
76 ].join("\n");
77 }
78}
79
80export class TailscaleUnavailableError extends Schema.TaggedError<TailscaleUnavailableError>()(
81 "TailscaleUnavailableError",
82 { cause: Schema.Defect() },
83) {
84 override get message(): string {
85 return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";
86 }
87}
88
89export class MagicDnsNameMissingError extends Schema.TaggedError<MagicDnsNameMissingError>()(
90 "MagicDnsNameMissingError",
91 {},
92) {
93 override get message(): string {
94 return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";
95 }
96}
97
98export class TailscaleServeNotEnabledError extends Schema.TaggedError<TailscaleServeNotEnabledError>()(
99 "TailscaleServeNotEnabledError",
100 {},
101) {
102 override get message(): string {
103 return "Tailscale Serve is not enabled on your tailnet. Enable HTTPS certificates at https://login.tailscale.com/admin/dns, then run this command again.";
104 }
105}
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 }
114}
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 }
123}
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 }
132}
133
134const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
135 state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);
136
137export class DevServerNotProxiableError extends Schema.TaggedError<DevServerNotProxiableError>()(
138 "DevServerNotProxiableError",
139 { devUrl: Schema.String },
140) {
141 override get message(): string {
142 return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;
143 }
144}
145
146const isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);
147
148/**
149 * Dev servers are single-origin, so the web dev server's port is the one to publish; the
150 * backend rides along behind Vite's proxy. Serve targets are always plain HTTP, so an HTTPS dev
151 * URL cannot be proxied and is rejected.
152 */
153export const resolveTailscaleLocalTarget = (
154 state: PersistedServerRuntimeState,
155): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {
156 if (state.devUrl !== undefined) {
157 const devUrl = new URL(state.devUrl);
158 if (devUrl.protocol !== "http:") {
159 return new DevServerNotProxiableError({ devUrl: state.devUrl });
160 }
161 const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;
162 return isLoopbackHost(devUrl.hostname)
163 ? { localPort }
164 : { localPort, localHost: devUrl.hostname };
165 }
166 if (state.host !== undefined && !isWildcardHost(state.host)) {
167 return { localPort: state.port, localHost: formatHostForUrl(state.host) };
168 }
169 return { localPort: state.port };
170};
171
172const formatPairOutput = (input: {
173 readonly serverLabel: string;
174 readonly origin: string;
175 readonly pairingUrl: string;
176 readonly token: string;
177 readonly expiresAt: DateTime.Utc;
178 readonly notes: ReadonlyArray<string>;
179}): string =>
180 [
181 `Pairing with ${input.serverLabel} (${input.origin}).`,
182 "",
183 renderTerminalQrCode(input.pairingUrl),
184 "",
185 `Pairing URL: ${input.pairingUrl}`,
186 `Token: ${input.token}`,
187 `Expires: ${DateTime.formatIso(input.expiresAt)}`,
188 ...input.notes.flatMap((note) => ["", `Note: ${note}`]),
189 "",
190 ].join("\n");
191
192type EnvironmentProbeResult =
193 | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
194 | { readonly _tag: "unreachable" }
195 | { readonly _tag: "not-a-t3-server" };
196
197const probeEnvironmentDescriptor: (
198 baseUrl: string,
199) => Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> = Effect.fn(
200 "pair.probeEnvironmentDescriptor",
201)(
202 function* (baseUrl: string) {
203 const client = yield* HttpClient.HttpClient;
204 const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
205 const response = yield* client.execute(request).pipe(
206 Effect.timeout(PAIR_PROBE_TIMEOUT),
207 Effect.mapError(() => ({ _tag: "unreachable" }) as const),
208 );
209 // Bad-gateway family means a proxy (Tailscale Serve) answered for a
210 // backend that is gone — a stale mapping, not a live occupant. Treating
211 // it as unreachable lets `t3 pair --tailscale` repair its own mapping
212 // after the server's port changed.
213 if (response.status === 502 || response.status === 503 || response.status === 504) {
214 return { _tag: "unreachable" } as const;
215 }
216 const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
217 Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
218 Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
219 );
220 return { _tag: "descriptor", descriptor } as const;
221 },
222 Effect.catch((outcome) => Effect.succeed(outcome)),
223);
224
225interface DiscoveredPairTarget {
226 readonly baseDir: string;
227 readonly variant: PairStateVariant;
228 readonly state: PersistedServerRuntimeState;
229 readonly descriptor: ExecutionEnvironmentDescriptor;
230}
231
232const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
233 explicitBaseDir: string | undefined,
234) {
235 const bases: Array<string> = [];
236 let inLinkedWorktree = false;
237 if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {
238 bases.push(yield* resolveBaseDir(explicitBaseDir));
239 } else {
240 // Same precedence as dev-runner: inside a linked worktree only its own
241 // `.t3` counts. Minting opens the target database with this checkout's
242 // migrations, so falling back to the shared home could migrate the live
243 // install with unreleased schema.
244 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
245 if (worktreeHome !== undefined) {
246 bases.push(worktreeHome);
247 inLinkedWorktree = true;
248 } else {
249 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
250 bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
251 }
252 }
253
254 const checkedStatePaths: Array<string> = [];
255 for (const baseDir of new Set(bases)) {
256 for (const variant of ["userdata", "dev"] as const) {
257 const derivedPaths = yield* ServerConfig.deriveServerPaths(
258 baseDir,
259 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
260 {},
261 );
262 const statePath = derivedPaths.serverRuntimeStatePath;
263 checkedStatePaths.push(statePath);
264 const state = yield* readPersistedServerRuntimeState(statePath);
265 if (Option.isNone(state)) {
266 continue;
267 }
268 // The pid check guards against a dead server's state file whose port
269 // was since reused by a different server: pairing would then mint a
270 // token in the old database while the QR code points at the new server.
271 if (!isProcessAlive(state.value.pid)) {
272 continue;
273 }
274 const probed = yield* probeEnvironmentDescriptor(state.value.origin);
275 if (probed._tag !== "descriptor") {
276 continue;
277 }
278 return {
279 baseDir,
280 variant,
281 state: state.value,
282 descriptor: probed.descriptor,
283 } satisfies DiscoveredPairTarget;
284 }
285 }
286 return yield* new NoRunningServerError({ checkedStatePaths, inLinkedWorktree });
287});
288
289/**
290 * Built by hand rather than through `resolveServerConfig` to keep the dev-vs-userdata choice
291 * pinned to where the runtime state was actually found, independent of ambient environment
292 * variables.
293 */
294const makePairServerConfig = Effect.fn(function* (input: {
295 readonly target: DiscoveredPairTarget;
296 readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
297}) {
298 const { baseDir, variant, state } = input.target;
299 // The state-dir variant does not imply dev-ness: a worktree dev server uses
300 // an explicit home and therefore lands in `userdata`. The recorded devUrl is
301 // what actually marks a dev server.
302 const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;
303 const derivedPaths = yield* ServerConfig.deriveServerPaths(
304 baseDir,
305 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
306 {},
307 );
308 return ServerConfig.make({
309 logLevel: input.logLevel,
310 traceMinLevel: "Info",
311 traceTimingEnabled: false,
312 traceBatchWindowMs: 1_000,
313 traceMaxBytes: 10 * 1024 * 1024,
314 traceMaxFiles: 10,
315 otlpTracesUrl: undefined,
316 otlpMetricsUrl: undefined,
317 otlpLogsUrl: undefined,
318 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
319 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
320 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
321 otelEnvironment: OtelEnvironment.none,
322 mode: "web",
323 port: state.port,
324 host: state.host,
325 cwd: process.cwd(),
326 baseDir,
327 ...derivedPaths,
328 staticDir: undefined,
329 devUrl,
330 devAllowedOrigins: [],
331 noBrowser: true,
332 startupPresentation: "headless",
333 desktopBootstrapToken: undefined,
334 desktopTelemetryFd: undefined,
335 desktopBrowserFd: undefined,
336 desktopBrowserControlFd: undefined,
337 desktopTelemetryControlFd: undefined,
338 resourceMonitorPath: undefined,
339 autoBootstrapProjectFromCwd: false,
340 logWebSocketEvents: false,
341 tailscaleServeEnabled: false,
342 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
343 });
344});
345
346const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
347 let last: EnvironmentProbeResult = { _tag: "unreachable" };
348 for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
349 last = yield* probeEnvironmentDescriptor(baseUrl);
350 if (last._tag === "descriptor") {
351 return last;
352 }
353 yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
354 }
355 return last;
356});
357
358const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
359 function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
360 const notes: Array<string> = [];
361 const status = yield* readTailscaleStatus.pipe(
362 Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
363 );
364 if (status.magicDnsName === null) {
365 return yield* new MagicDnsNameMissingError();
366 }
367 // Without the capability `tailscale serve` blocks on an enablement URL
368 // until it times out, which names neither the setting nor where to change it.
369 if (status.httpsServeEnabled === false) {
370 return yield* new TailscaleServeNotEnabledError();
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 scopes: ReadonlyArray<AuthEnvironmentScope>;
432 readonly ttl: Option.Option<Duration.Duration>;
433 readonly label: Option.Option<string>;
434}) {
435 return yield* Effect.gen(function* () {
436 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
437 return yield* environmentAuth.createPairingLink({
438 scopes: input.scopes,
439 subject: "one-time-token",
440 label: Option.getOrElse(input.label, () => "t3 pair"),
441 ...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
442 });
443 }).pipe(
444 Effect.provide(
445 EnvironmentAuth.layerRuntime.pipe(
446 Layer.provide(ServerConfig.layer(input.config)),
447 Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
448 ),
449 ),
450 );
451});
452
453const ttlFlag = Flag.String("ttl").pipe(
454 Flag.withSchema(DurationFromString),
455 Flag.withDescription(
456 "Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
457 ),
458 Flag.optional,
459);
460
461const labelFlag = Flag.String("label").pipe(
462 Flag.withDescription("Optional label shown in the server's connections list."),
463 Flag.optional,
464);
465
466const tailscaleFlag = Flag.Boolean("tailscale").pipe(
467 Flag.withDescription(
468 "Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
469 ),
470 Flag.withDefault(false),
471);
472
473const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
474 Flag.withSchema(PortSchema),
475 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
476 Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
477);
478
479export const pairCommand = Command.make("pair", {
480 baseDir: baseDirFlag,
481 scopes: authScopesFlag(AuthStandardClientScopes),
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 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({
522 config,
523 scopes: flags.scopes,
524 ttl: flags.ttl,
525 label: flags.label,
526 });
527 const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
528
529 yield* Console.log(
530 formatPairOutput({
531 serverLabel: target.descriptor.label,
532 origin: target.state.origin,
533 pairingUrl,
534 token: issued.credential,
535 expiresAt: issued.expiresAt,
536 notes,
537 }),
538 );
539 }).pipe(Effect.provide(FetchHttpClient.layer)),
540 ),
541);