Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pair.ts

571 lines21.4 KB

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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
146​
147const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
148 state.devUrl ??
149 resolveHeadlessConnectionString(state.host, state.port, {
150 privateNetworkOnly: state.privateNetworkOnly,
151 });
152​
153export class DevServerNotProxiableError extends Schema.TaggedError<DevServerNotProxiableError>()(
154 "DevServerNotProxiableError",
155 { devUrl: Schema.String },
156) {
157 override get message(): string {
158 return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;
159 }
161​
162const isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);
163​
164/**
165 * Dev servers are single-origin, so the web dev server's port is the one to publish; the
166 * backend rides along behind Vite's proxy. Serve targets are always plain HTTP, so an HTTPS dev
167 * URL cannot be proxied and is rejected.
168 */
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 `Token: ${input.token}`,
203 `Expires: ${DateTime.formatIso(input.expiresAt)}`,
204 ...input.notes.flatMap((note) => ["", `Note: ${note}`]),
205 "",
206 ].join("\n");
207​
208type EnvironmentProbeResult =
209 | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
210 | { readonly _tag: "unreachable" }
211 | { readonly _tag: "not-a-t3-server" };
212​
213const probeEnvironmentDescriptor: (
214 baseUrl: string,
215) => Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> = Effect.fn(
216 "pair.probeEnvironmentDescriptor",
217)(
218 function* (baseUrl: string) {
219 const client = yield* HttpClient.HttpClient;
220 const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
221 const response = yield* client.execute(request).pipe(
222 Effect.timeout(PAIR_PROBE_TIMEOUT),
223 Effect.mapError(() => ({ _tag: "unreachable" }) as const),
224 );
225 // Bad-gateway family means a proxy (Tailscale Serve) answered for a
226 // backend that is gone — a stale mapping, not a live occupant. Treating
227 // it as unreachable lets `t3 pair --tailscale` repair its own mapping
228 // after the server's port changed.
229 if (response.status === 502 || response.status === 503 || response.status === 504) {
230 return { _tag: "unreachable" } as const;
231 }
232 const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
233 Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
234 Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
235 );
236 return { _tag: "descriptor", descriptor } as const;
237 },
238 Effect.catch((outcome) => Effect.succeed(outcome)),
239);
240​
241interface DiscoveredPairTarget {
242 readonly baseDir: string;
243 readonly variant: PairStateVariant;
244 readonly state: PersistedServerRuntimeState;
245 readonly descriptor: ExecutionEnvironmentDescriptor;
247​
248const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
249 explicitBaseDir: string | undefined,
250) {
251 const bases: Array<string> = [];
252 let inLinkedWorktree = false;
253 if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {
254 bases.push(yield* resolveBaseDir(explicitBaseDir));
255 } else {
256 // Same precedence as dev-runner: inside a linked worktree only its own
257 // `.t3` counts. Minting opens the target database with this checkout's
258 // migrations, so falling back to the shared home could migrate the live
259 // install with unreleased schema.
260 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
261 if (worktreeHome !== undefined) {
262 bases.push(worktreeHome);
263 inLinkedWorktree = true;
264 } else {
265 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
266 bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
267 }
268 }
269​
270 const checkedStatePaths: Array<string> = [];
271 for (const baseDir of new Set(bases)) {
272 for (const variant of ["userdata", "dev"] as const) {
273 const derivedPaths = yield* ServerConfig.deriveServerPaths(
274 baseDir,
275 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
276 {},
277 );
278 const statePath = derivedPaths.serverRuntimeStatePath;
279 checkedStatePaths.push(statePath);
280 const state = yield* readPersistedServerRuntimeState(statePath);
281 if (Option.isNone(state)) {
282 continue;
283 }
284 // The pid check guards against a dead server's state file whose port
285 // was since reused by a different server: pairing would then mint a
286 // token in the old database while the QR code points at the new server.
287 if (!isProcessAlive(state.value.pid)) {
288 continue;
289 }
290 const probed = yield* probeEnvironmentDescriptor(state.value.origin);
291 if (probed._tag !== "descriptor") {
292 continue;
293 }
294 return {
295 baseDir,
296 variant,
297 state: state.value,
298 descriptor: probed.descriptor,
299 } satisfies DiscoveredPairTarget;
300 }
301 }
302 return yield* new NoRunningServerError({ checkedStatePaths, inLinkedWorktree });
303});
304​
305/**
306 * Built by hand rather than through `resolveServerConfig` to keep the dev-vs-userdata choice
307 * pinned to where the runtime state was actually found, independent of ambient environment
308 * variables.
309 */
310const makePairServerConfig = Effect.fn(function* (input: {
311 readonly target: DiscoveredPairTarget;
312 readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
313}) {
314 const { baseDir, variant, state } = input.target;
315 // The state-dir variant does not imply dev-ness: a worktree dev server uses
316 // an explicit home and therefore lands in `userdata`. The recorded devUrl is
317 // what actually marks a dev server.
318 const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;
319 const derivedPaths = yield* ServerConfig.deriveServerPaths(
320 baseDir,
321 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
322 {},
323 );
324 return ServerConfig.make({
325 logLevel: input.logLevel,
326 traceMinLevel: "Info",
327 traceTimingEnabled: false,
328 traceBatchWindowMs: 1_000,
329 traceMaxBytes: 10 * 1024 * 1024,
330 traceMaxFiles: 10,
331 otlpTracesUrl: undefined,
332 otlpMetricsUrl: undefined,
333 otlpLogsUrl: undefined,
334 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
335 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
336 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
337 otelEnvironment: OtelEnvironment.none,
338 mode: "web",
339 port: state.port,
340 host: state.host,
341 cwd: process.cwd(),
342 baseDir,
343 ...derivedPaths,
344 staticDir: undefined,
345 devUrl,
346 devAllowedOrigins: [],
347 noBrowser: true,
348 startupPresentation: "headless",
349 desktopBootstrapToken: undefined,
350 desktopTelemetryFd: undefined,
351 desktopBrowserFd: undefined,
352 desktopBrowserControlFd: undefined,
353 desktopTelemetryControlFd: undefined,
354 resourceMonitorPath: undefined,
355 autoBootstrapProjectFromCwd: false,
356 logWebSocketEvents: false,
357 tailscaleServeEnabled: false,
358 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
359 });
360});
361​
362const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
363 let last: EnvironmentProbeResult = { _tag: "unreachable" };
364 for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
365 last = yield* probeEnvironmentDescriptor(baseUrl);
366 if (last._tag === "descriptor") {
367 return last;
368 }
369 yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
370 }
371 return last;
372});
373​
374const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
375 function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
376 const notes: Array<string> = [];
377 const status = yield* readTailscaleStatus.pipe(
378 Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
379 );
380 if (status.magicDnsName === null) {
381 return yield* new MagicDnsNameMissingError();
382 }
383 // Without the capability `tailscale serve` blocks on an enablement URL
384 // until it times out, which names neither the setting nor where to change it.
385 if (status.httpsServeEnabled === false) {
386 return yield* new TailscaleServeNotEnabledError();
387 }
388 const baseUrl = buildTailscaleHttpsBaseUrl({
389 magicDnsName: status.magicDnsName,
390 servePort: input.servePort,
391 });
392​
393 // Only an unreachable port, or a mapping already fronting this exact
394 // environment, is safe to (re)configure. Any other responder — T3 or not
395 // — must not have its mapping silently replaced.
396 const existing = yield* probeEnvironmentDescriptor(baseUrl);
397 if (existing._tag === "descriptor") {
398 if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
399 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
400 }
401 // Matching environment id proves the mapping reaches this server, but
402 // not through which port: for a dev server it may front the backend
403 // (whose /.well-known also answers) while /pair only renders through
404 // the web origin. Reuse as-is for regular servers; fall through and
405 // repoint our own mapping at the web port for dev servers.
406 if (input.target.state.devUrl === undefined) {
407 return { baseUrl, notes };
408 }
409 }
410 if (existing._tag === "not-a-t3-server") {
411 return yield* new ServePortOccupiedError({ servePort: input.servePort });
412 }
413​
414 const localTarget = resolveTailscaleLocalTarget(input.target.state);
415 if (isDevServerNotProxiableError(localTarget)) {
416 return yield* localTarget;
417 }
418 yield* ensureTailscaleServe({
419 localPort: localTarget.localPort,
420 servePort: input.servePort,
421 ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
422 }).pipe(
423 Effect.mapError(
424 (cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
425 ),
426 );
427 notes.push(
428 `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
429 );
430​
431 const probed = yield* awaitEnvironmentDescriptor(baseUrl);
432 if (probed._tag === "descriptor") {
433 if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {
434 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
435 }
436 } else {
437 notes.push(
438 "The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.",
439 );
440 }
441 return { baseUrl, notes };
442 },
443);
444​
445const mintPairingLink = Effect.fn("pair.mintPairingLink")(function* (input: {
446 readonly config: ServerConfig.ServerConfig["Service"];
447 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
448 readonly ttl: Option.Option<Duration.Duration>;
449 readonly label: Option.Option<string>;
450}) {
451 return yield* Effect.gen(function* () {
452 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
453 return yield* environmentAuth.createPairingLink({
454 scopes: input.scopes,
455 subject: "one-time-token",
456 label: Option.getOrElse(input.label, () => "t3 pair"),
457 ...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),
458 });
459 }).pipe(
460 Effect.provide(
461 EnvironmentAuth.layerRuntime.pipe(
462 Layer.provide(ServerConfig.layer(input.config)),
463 Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),
464 ),
465 ),
466 );
467});
468​
469const ttlFlag = Flag.String("ttl").pipe(
470 Flag.withSchema(DurationFromString),
471 Flag.withDescription(
472 "Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.",
473 ),
474 Flag.optional,
475);
476​
477const labelFlag = Flag.String("label").pipe(
478 Flag.withDescription("Optional label shown in the server's connections list."),
479 Flag.optional,
480);
481​
482const tailscaleFlag = Flag.Boolean("tailscale").pipe(
483 Flag.withDescription(
484 "Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.",
485 ),
486 Flag.withDefault(false),
487);
488​
489const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
490 Flag.withSchema(PortSchema),
491 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale is enabled."),
492 Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),
493);
494​
495export const pairCommand = Command.make("pair", {
496 baseDir: baseDirFlag,
497 scopes: authScopesFlag(AuthStandardClientScopes),
498 ttl: ttlFlag,
499 label: labelFlag,
500 tailscale: tailscaleFlag,
501 tailscaleServePort: tailscaleServePortFlag,
502}).pipe(
503 Command.withDescription(
504 "Mint a pairing token for a running T3 Code server and print it as a QR code.",
505 ),
506 Command.withHandler((flags) =>
507 Effect.gen(function* () {
508 const cliLogLevel = yield* GlobalFlag.LogLevel;
509 const logLevel = Option.getOrElse(cliLogLevel, () => "Warn" as const);
510​
511 const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));
512 // Each protocol keeps auth in its own database, so a token minted here
513 // for another protocol's server would never be accepted by it. Refuse
514 // before any local layer opens (and migrates) that database.
515 const serverProtocolVersion = target.descriptor.orchestrationProtocolVersion ?? 1;
516 if (serverProtocolVersion !== ORCHESTRATION_PROTOCOL_VERSION) {
517 return yield* new IncompatibleServerProtocolError({
518 serverVersion: target.descriptor.serverVersion,
519 serverProtocolVersion,
520 });
521 }
522​
523 const notes: Array<string> = [];
524 let pairingBaseUrl: string;
525 if (flags.tailscale) {
526 const resolved = yield* resolveTailscalePairingBase({
527 target,
528 servePort: flags.tailscaleServePort,
529 });
530 pairingBaseUrl = resolved.baseUrl;
531 notes.push(...resolved.notes);
532 } else {
533 pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
534 if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
535 notes.push(
536 "This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
537 );
538 } else if (target.state.privateNetworkOnly) {
539 notes.push(
540 "This URL works only from this machine's local network. From elsewhere, re-run with --tailscale or use T3 Connect.",
541 );
542 }
543 if (target.variant === "dev" && target.state.devUrl === undefined) {
544 notes.push(
545 "This dev server did not record its web URL; restart it so pairing can go through the web origin.",
546 );
547 }
548 }
549​
550 const config = yield* makePairServerConfig({ target, logLevel });
551 const issued = yield* mintPairingLink({
552 config,
553 scopes: flags.scopes,
554 ttl: flags.ttl,
555 label: flags.label,
556 });
557 const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);
558​
559 yield* Console.log(
560 formatPairOutput({
561 serverLabel: target.descriptor.label,
562 origin: target.state.origin,
563 pairingUrl,
564 token: issued.credential,
565 expiresAt: issued.expiresAt,
566 notes,
567 }),
568 );
569 }).pipe(Effect.provide(FetchHttpClient.layer)),
570 ),
571);