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