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