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