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 * as ManagedLimits from "../policy/managedLimits.ts";
34import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
35import { resolveBaseDir } from "../os-jank.ts";
36import {
37 type PersistedServerRuntimeState,
38 isProcessAlive,
39 readPersistedServerRuntimeState,
40} from "../serverRuntimeState.ts";
41import {
42 buildPairingUrl,
43 formatHostForUrl,
44 isLoopbackHost,
45 isWildcardHost,
46 renderTerminalQrCode,
47 resolveHeadlessConnectionString,
48} from "../startupAccess.ts";
49import { authScopesFlag } from "./authScopes.ts";
50import { baseDirFlag, DurationFromString } from "./config.ts";
51import { resolveHostCliCommand } from "./invocation.ts";
52
53const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
54const PAIR_PROBE_TIMEOUT = Duration.millis(2_500);
55// Tailscale's first HTTPS request may take seconds to provision a certificate.
56const TAILSCALE_PROBE_ATTEMPTS = 5;
57const TAILSCALE_PROBE_RETRY_DELAY = Duration.seconds(1);
58
59export type PairStateVariant = "userdata" | "dev";
60
61// Only devUrl's presence selects dev state; its value is unused.
62const DEV_VARIANT_PLACEHOLDER_URL = new URL("http://localhost");
63
64export class NoRunningServerError extends Schema.TaggedError<NoRunningServerError>()(
65 "NoRunningServerError",
66 {
67 checkedStatePaths: Schema.Array(Schema.String),
68 inLinkedWorktree: Schema.Boolean,
69 serveCommand: Schema.String,
70 connectCommand: Schema.String,
71 },
72) {
73 override get message(): string {
74 return [
75 "No running T3 Code server found.",
76 ...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
77 ...(this.inLinkedWorktree
78 ? ["In a linked worktree, pass --base-dir to pair with a server outside it."]
79 : []),
80 `Start one with \`${this.serveCommand}\`, or connect this machine with T3 Connect: \`${this.connectCommand}\`.`,
81 ].join("\n");
82 }
83}
84
85export class IncompatibleServerProtocolError extends Schema.TaggedError<IncompatibleServerProtocolError>()(
86 "IncompatibleServerProtocolError",
87 { serverVersion: Schema.String, serverProtocolVersion: Schema.Number },
88) {
89 override get message(): string {
90 return [
91 `The running T3 Code server (${this.serverVersion}) speaks orchestration protocol ${String(this.serverProtocolVersion)}, but this CLI speaks protocol ${String(ORCHESTRATION_PROTOCOL_VERSION)}.`,
92 `Pair with the matching CLI instead: \`npx t3@${this.serverVersion} pair\`.`,
93 ].join("\n");
94 }
95}
96
97export class TailscaleUnavailableError extends Schema.TaggedError<TailscaleUnavailableError>()(
98 "TailscaleUnavailableError",
99 { cause: Schema.Defect() },
100) {
101 override get message(): string {
102 return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";
103 }
104}
105
106export class MagicDnsNameMissingError extends Schema.TaggedError<MagicDnsNameMissingError>()(
107 "MagicDnsNameMissingError",
108 {},
109) {
110 override get message(): string {
111 return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";
112 }
113}
114
115export class TailscaleServeNotEnabledError extends Schema.TaggedError<TailscaleServeNotEnabledError>()(
116 "TailscaleServeNotEnabledError",
117 {},
118) {
119 override get message(): string {
120 return "Tailscale Serve is not enabled on your tailnet. Enable HTTPS certificates at https://login.tailscale.com/admin/dns, then run this command again.";
121 }
122}
123
124export class ServesOtherEnvironmentError extends Schema.TaggedError<ServesOtherEnvironmentError>()(
125 "ServesOtherEnvironmentError",
126 { servePort: Schema.Number },
127) {
128 override get message(): string {
129 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.`;
130 }
131}
132
133export class TailscaleServeFailedError extends Schema.TaggedError<TailscaleServeFailedError>()(
134 "TailscaleServeFailedError",
135 { servePort: Schema.Number, cause: Schema.Defect() },
136) {
137 override get message(): string {
138 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.`;
139 }
140}
141
142export class ServePortOccupiedError extends Schema.TaggedError<ServePortOccupiedError>()(
143 "ServePortOccupiedError",
144 { servePort: Schema.Number },
145) {
146 override get message(): string {
147 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.`;
148 }
149}
150
151const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
152 state.devUrl ??
153 resolveHeadlessConnectionString(state.host, state.port, {
154 privateNetworkOnly: state.privateNetworkOnly,
155 });
156
157export class DevServerNotProxiableError extends Schema.TaggedError<DevServerNotProxiableError>()(
158 "DevServerNotProxiableError",
159 { devUrl: Schema.String },
160) {
161 override get message(): string {
162 return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;
163 }
164}
165
166const isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);
167
168/** Publish the single-origin web dev port, which proxies the backend. Serve requires HTTP targets. */
169export const resolveTailscaleLocalTarget = (
170 state: PersistedServerRuntimeState,
171): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {
172 if (state.devUrl !== undefined) {
173 const devUrl = new URL(state.devUrl);
174 if (devUrl.protocol !== "http:") {
175 return new DevServerNotProxiableError({ devUrl: state.devUrl });
176 }
177 const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;
178 return isLoopbackHost(devUrl.hostname)
179 ? { localPort }
180 : { localPort, localHost: devUrl.hostname };
181 }
182 if (state.host !== undefined && !isWildcardHost(state.host)) {
183 return { localPort: state.port, localHost: formatHostForUrl(state.host) };
184 }
185 return { localPort: state.port };
186};
187
188const formatPairOutput = (input: {
189 readonly serverLabel: string;
190 readonly origin: string;
191 readonly pairingUrl: string;
192 readonly token: string;
193 readonly expiresAt: DateTime.Utc;
194 readonly notes: ReadonlyArray<string>;
195}): string =>
196 [
197 `Pairing with ${input.serverLabel} (${input.origin}).`,
198 "",
199 renderTerminalQrCode(input.pairingUrl),
200 "",
201 `Pairing URL: ${input.pairingUrl}`,
202 `App link: ${buildPairingAppLink(input.pairingUrl)}`,
203 `Token: ${input.token}`,
204 `Expires: ${DateTime.formatIso(input.expiresAt)}`,
205 ...input.notes.flatMap((note) => ["", `Note: ${note}`]),
206 "",
207 ].join("\n");
208
209type EnvironmentProbeResult =
210 | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
211 | { readonly _tag: "unreachable" }
212 | { readonly _tag: "not-a-t3-server" };
213
214const probeEnvironmentDescriptor: (
215 baseUrl: string,
216) => Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> = Effect.fn(
217 "pair.probeEnvironmentDescriptor",
218)(
219 function* (baseUrl: string) {
220 const client = yield* HttpClient.HttpClient;
221 const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
222 const response = yield* client.execute(request).pipe(
223 Effect.timeout(PAIR_PROBE_TIMEOUT),
224 Effect.mapError(() => ({ _tag: "unreachable" }) as const),
225 );
226 // Gateway errors identify stale proxy mappings that pairing may repair.
227 if (response.status === 502 || response.status === 503 || response.status === 504) {
228 return { _tag: "unreachable" } as const;
229 }
230 const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
231 Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
232 Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
233 );
234 return { _tag: "descriptor", descriptor } as const;
235 },
236 Effect.catch((outcome) => Effect.succeed(outcome)),
237);
238
239interface DiscoveredPairTarget {
240 readonly baseDir: string;
241 readonly variant: PairStateVariant;
242 readonly state: PersistedServerRuntimeState;
243 readonly descriptor: ExecutionEnvironmentDescriptor;
244}
245
246const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
247 explicitBaseDir: string | undefined,
248) {
249 const bases: Array<string> = [];
250 let inLinkedWorktree = false;
251 const hasExplicitBaseDir = explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0;
252 if (hasExplicitBaseDir) {
253 bases.push(yield* resolveBaseDir(explicitBaseDir));
254 } else {
255 // Same precedence as dev-runner: inside a linked worktree only its own
256 // `.t3` counts. Minting opens the target database with this checkout's
257 // migrations, so falling back to the shared home could migrate the live
258 // install with unreleased schema.
259 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
260 if (worktreeHome !== undefined) {
261 bases.push(worktreeHome);
262 inLinkedWorktree = true;
263 } else {
264 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
265 bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
266 }
267 }
268
269 const checkedStatePaths: Array<string> = [];
270 for (const baseDir of new Set(bases)) {
271 for (const variant of ["userdata", "dev"] as const) {
272 const derivedPaths = yield* ServerConfig.deriveServerPaths(
273 baseDir,
274 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
275 {},
276 );
277 const statePath = derivedPaths.serverRuntimeStatePath;
278 checkedStatePaths.push(statePath);
279 const state = yield* readPersistedServerRuntimeState(statePath);
280 if (Option.isNone(state)) {
281 continue;
282 }
283 // A dead server's port may be reused; do not mint tokens in its old database for another 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 const baseDirArgs = hasExplicitBaseDir ? ["--base-dir", explicitBaseDir] : [];
300 return yield* new NoRunningServerError({
301 checkedStatePaths,
302 inLinkedWorktree,
303 serveCommand: (yield* resolveHostCliCommand("serve", baseDirArgs)).command,
304 connectCommand: (yield* resolveHostCliCommand("connect", baseDirArgs)).command,
305 });
306});
307
308/** Use the discovered state directory, independent of ambient config variables. */
309const makePairServerConfig = Effect.fn(function* (input: {
310 readonly target: DiscoveredPairTarget;
311 readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
312}) {
313 const { baseDir, variant, state } = input.target;
314 // Worktree dev servers can use `userdata`; only the recorded devUrl 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 unreachable ports or this environment's mappings are safe to reconfigure.
391 const existing = yield* probeEnvironmentDescriptor(baseUrl);
392 if (existing._tag === "descriptor") {
393 if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
394 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
395 }
396 // A dev backend also answers /.well-known, but /pair needs the web origin.
397 if (input.target.state.devUrl === undefined) {
398 return { baseUrl, notes };
399 }
400 }
401 if (existing._tag === "not-a-t3-server") {
402 return yield* new ServePortOccupiedError({ servePort: input.servePort });
403 }
404
405 const localTarget = resolveTailscaleLocalTarget(input.target.state);
406 if (isDevServerNotProxiableError(localTarget)) {
407 return yield* localTarget;
408 }
409 yield* ensureTailscaleServe({
410 localPort: localTarget.localPort,
411 servePort: input.servePort,
412 ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
413 }).pipe(
414 Effect.mapError(
415 (cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
416 ),
417 );
418 notes.push(
419 `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} --set-path=/ off\`.`,
420 );
421
422 const probed = yield* awaitEnvironmentDescriptor(baseUrl);
423 if (probed._tag === "descriptor") {
424 if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {
425 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
426 }
427 } else {
428 notes.push(
429 "The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.",
430 );
431 }
432 return { baseUrl, notes };
433 },
434);
435
436const mintPairingLink = Effect.fn("pair.mintPairingLink")(function* (input: {
437 readonly config: ServerConfig.ServerConfig["Service"];
438 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
439 readonly ttl: Option.Option<Duration.Duration>;
440 readonly label: Option.Option<string>;
441}) {
442 return yield* Effect.gen(function* () {
443 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
444 return yield* environmentAuth.createPairingLink({
445 scopes: input.scopes,
446 subject: "one-time-token",
447 label: Option.getOrElse(input.label, () => "t3 pair"),
448 ...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
449 });
450 }).pipe(
451 Effect.provide(
452 EnvironmentAuth.layerRuntime.pipe(
453 Layer.provide(ServerConfig.layer(input.config)),
454 Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
455 ),
456 ),
457 );
458});
459
460const ttlFlag = Flag.String("ttl").pipe(
461 Flag.withSchema(DurationFromString),
462 Flag.withDescription(
463 "Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
464 ),
465 Flag.optional,
466);
467
468const labelFlag = Flag.String("label").pipe(
469 Flag.withDescription("Optional label shown in the server's connections list."),
470 Flag.optional,
471);
472
473const tailscaleFlag = Flag.Boolean("tailscale").pipe(
474 Flag.withDescription(
475 "Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
476 ),
477 Flag.withDefault(false),
478);
479
480const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
481 Flag.withSchema(PortSchema),
482 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
483 Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
484);
485
486export const pairCommand = Command.make("pair", {
487 baseDir: baseDirFlag,
488 scopes: authScopesFlag(AuthStandardClientScopes),
489 ttl: ttlFlag,
490 label: labelFlag,
491 tailscale: tailscaleFlag,
492 tailscaleServePort: tailscaleServePortFlag,
493}).pipe(
494 Command.withDescription(
495 "Mint a pairing token for a running T3 Code server and print it as a QR code.",
496 ),
497 Command.withHandler((flags) =>
498 Effect.gen(function* () {
499 const cliLogLevel = yield* GlobalFlag.LogLevel;
500 const logLevel = Option.getOrElse(cliLogLevel, () => "Warn" as const);
501
502 const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));
503 // Each protocol keeps auth in its own database, so a token minted here
504 // for another protocol's server would never be accepted by it. Refuse
505 // before any local layer opens (and migrates) that database.
506 const serverProtocolVersion = target.descriptor.orchestrationProtocolVersion ?? 1;
507 if (serverProtocolVersion !== ORCHESTRATION_PROTOCOL_VERSION) {
508 return yield* new IncompatibleServerProtocolError({
509 serverVersion: target.descriptor.serverVersion,
510 serverProtocolVersion,
511 });
512 }
513
514 const notes: Array<string> = [];
515 let pairingBaseUrl: string;
516 if (flags.tailscale) {
517 // Serve stays on after this command exits, so refuse before turning it on.
518 const policy = yield* ManagedPolicy.ManagedPolicy.pipe(Effect.provide(ManagedPolicy.layer));
519 if (!ManagedLimits.allowsRemoteClients(policy)) {
520 return yield* ManagedLimits.refuseRemoteClients(
521 policy,
522 "so Tailscale Serve cannot be turned on",
523 );
524 }
525 const resolved = yield* resolveTailscalePairingBase({
526 target,
527 servePort: flags.tailscaleServePort,
528 });
529 pairingBaseUrl = resolved.baseUrl;
530 notes.push(...resolved.notes);
531 } else {
532 pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
533 if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
534 notes.push(
535 "This URL is only reachable from this machine. To reach it from your other devices, run `t3 up`, or re-run with --tailscale.",
536 );
537 } else if (target.state.privateNetworkOnly) {
538 notes.push(
539 "This URL works only from this machine's local network. From elsewhere, re-run with --tailscale or use T3 Connect.",
540 );
541 }
542 if (target.variant === "dev" && target.state.devUrl === undefined) {
543 notes.push(
544 "This dev server did not record its web URL; restart it so pairing can go through the web origin.",
545 );
546 }
547 }
548
549 const config = yield* makePairServerConfig({ target, logLevel });
550 const issued = yield* mintPairingLink({
551 config,
552 scopes: flags.scopes,
553 ttl: flags.ttl,
554 label: flags.label,
555 });
556 const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
557
558 yield* Console.log(
559 formatPairOutput({
560 serverLabel: target.descriptor.label,
561 origin: target.state.origin,
562 pairingUrl,
563 token: issued.credential,
564 expiresAt: issued.expiresAt,
565 notes,
566 }),
567 );
568 }).pipe(Effect.provide(FetchHttpClient.layer)),
569 ),
570);