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

pair.ts

514 lines19.1 KB

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 readTailscaleStatus,
14} from "@t3tools/tailscale";
15import * as Config from "effect/Config";
16import * as Console from "effect/Console";
17import * as DateTime from "effect/DateTime";
18import * as Duration from "effect/Duration";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as References from "effect/References";
23import * as Schema from "effect/Schema";
24import { Command, Flag, GlobalFlag } from "effect/cli";
25import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
26​
27import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
28import * as ServerConfig from "../config.ts";
29import { resolveBaseDir } from "../os-jank.ts";
30import {
31 type PersistedServerRuntimeState,
32 isProcessAlive,
33 readPersistedServerRuntimeState,
34} from "../serverRuntimeState.ts";
35import {
36 buildPairingUrl,
37 formatHostForUrl,
38 isLoopbackHost,
39 isWildcardHost,
40 renderTerminalQrCode,
41 resolveHeadlessConnectionString,
42} from "../startupAccess.ts";
43import { authScopesFlag } from "./authScopes.ts";
44import { baseDirFlag, DurationFromString } from "./config.ts";
45​
46const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
47const PAIR_PROBE_TIMEOUT = Duration.millis(2_500);
48// Tailscale provisions an HTTPS certificate on the first request to a fresh
49// serve mapping, which can take a few seconds.
50const TAILSCALE_PROBE_ATTEMPTS = 5;
51const TAILSCALE_PROBE_RETRY_DELAY = Duration.seconds(1);
52​
53export type PairStateVariant = "userdata" | "dev";
54​
55// deriveServerPaths only checks devUrl for undefined-ness when picking the
56// dev-vs-userdata state directory; the value itself is not used.
57const DEV_VARIANT_PLACEHOLDER_URL = new URL("http://localhost");
58​
59export class NoRunningServerError extends Schema.TaggedError<NoRunningServerError>()(
60 "NoRunningServerError",
61 {
62 checkedStatePaths: Schema.Array(Schema.String),
63 },
64) {
65 override get message(): string {
66 return [
67 "No running T3 Code server found.",
68 ...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
69 "Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
70 ].join("\n");
71 }
73​
74export class TailscaleUnavailableError extends Schema.TaggedError<TailscaleUnavailableError>()(
75 "TailscaleUnavailableError",
76 { cause: Schema.Defect() },
77) {
78 override get message(): string {
79 return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";
80 }
82​
83export class MagicDnsNameMissingError extends Schema.TaggedError<MagicDnsNameMissingError>()(
84 "MagicDnsNameMissingError",
85 {},
86) {
87 override get message(): string {
88 return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";
89 }
91​
92export class ServesOtherEnvironmentError extends Schema.TaggedError<ServesOtherEnvironmentError>()(
93 "ServesOtherEnvironmentError",
94 { servePort: Schema.Number },
95) {
96 override get message(): string {
97 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.`;
98 }
100​
101export class TailscaleServeFailedError extends Schema.TaggedError<TailscaleServeFailedError>()(
102 "TailscaleServeFailedError",
103 { servePort: Schema.Number, cause: Schema.Defect() },
104) {
105 override get message(): string {
106 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.`;
107 }
109​
110export class ServePortOccupiedError extends Schema.TaggedError<ServePortOccupiedError>()(
111 "ServePortOccupiedError",
112 { servePort: Schema.Number },
113) {
114 override get message(): string {
115 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.`;
116 }
118​
119export const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
120 state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);
121​
122export class DevServerNotProxiableError extends Schema.TaggedError<DevServerNotProxiableError>()(
123 "DevServerNotProxiableError",
124 { devUrl: Schema.String },
125) {
126 override get message(): string {
127 return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;
128 }
130​
131const isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);
132​
133/**
134 * Dev servers are single-origin, so the web dev server's port is the one to publish; the
135 * backend rides along behind Vite's proxy. Serve targets are always plain HTTP, so an HTTPS dev
136 * URL cannot be proxied and is rejected.
137 */
138export const resolveTailscaleLocalTarget = (
139 state: PersistedServerRuntimeState,
140): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {
141 if (state.devUrl !== undefined) {
142 const devUrl = new URL(state.devUrl);
143 if (devUrl.protocol !== "http:") {
144 return new DevServerNotProxiableError({ devUrl: state.devUrl });
145 }
146 const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;
147 return isLoopbackHost(devUrl.hostname)
148 ? { localPort }
149 : { localPort, localHost: devUrl.hostname };
150 }
151 if (state.host !== undefined && !isWildcardHost(state.host) && !isLoopbackHost(state.host)) {
152 return { localPort: state.port, localHost: formatHostForUrl(state.host) };
153 }
154 return { localPort: state.port };
155};
156​
157const formatPairOutput = (input: {
158 readonly serverLabel: string;
159 readonly origin: string;
160 readonly pairingUrl: string;
161 readonly token: string;
162 readonly expiresAt: DateTime.Utc;
163 readonly notes: ReadonlyArray<string>;
164}): string =>
165 [
166 `Pairing with ${input.serverLabel} (${input.origin}).`,
167 "",
168 renderTerminalQrCode(input.pairingUrl),
169 "",
170 `Pairing URL: ${input.pairingUrl}`,
171 `Token: ${input.token}`,
172 `Expires: ${DateTime.formatIso(input.expiresAt)}`,
173 ...input.notes.flatMap((note) => ["", `Note: ${note}`]),
174 "",
175 ].join("\n");
176​
177type EnvironmentProbeResult =
178 | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
179 | { readonly _tag: "unreachable" }
180 | { readonly _tag: "not-a-t3-server" };
181​
182const probeEnvironmentDescriptor = (
183 baseUrl: string,
184): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>
185 Effect.gen(function* () {
186 const client = yield* HttpClient.HttpClient;
187 const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
188 const response = yield* client.execute(request).pipe(
189 Effect.timeout(PAIR_PROBE_TIMEOUT),
190 Effect.mapError(() => ({ _tag: "unreachable" }) as const),
191 );
192 // Bad-gateway family means a proxy (Tailscale Serve) answered for a
193 // backend that is gone — a stale mapping, not a live occupant. Treating
194 // it as unreachable lets `t3 pair --tailscale` repair its own mapping
195 // after the server's port changed.
196 if (response.status === 502 || response.status === 503 || response.status === 504) {
197 return { _tag: "unreachable" } as const;
198 }
199 const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
200 Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
201 Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
202 );
203 return { _tag: "descriptor", descriptor } as const;
204 }).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));
205​
206interface DiscoveredPairTarget {
207 readonly baseDir: string;
208 readonly variant: PairStateVariant;
209 readonly state: PersistedServerRuntimeState;
210 readonly descriptor: ExecutionEnvironmentDescriptor;
212​
213const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* (
214 explicitBaseDir: string | undefined,
215) {
216 const bases: Array<string> = [];
217 if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {
218 bases.push(yield* resolveBaseDir(explicitBaseDir));
219 } else {
220 // Same precedence as dev-runner: inside a linked worktree its own `.t3`
221 // outranks the shared home, so `t3 pair` in a worktree pairs with the dev
222 // server under test rather than the daily-driver install.
223 const worktreeHome = yield* resolveWorktreeT3Home(process.cwd());
224 if (worktreeHome !== undefined) {
225 bases.push(worktreeHome);
226 }
227 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
228 bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));
229 }
230​
231 const checkedStatePaths: Array<string> = [];
232 for (const baseDir of new Set(bases)) {
233 for (const variant of ["userdata", "dev"] as const) {
234 const derivedPaths = yield* ServerConfig.deriveServerPaths(
235 baseDir,
236 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
237 {},
238 );
239 const statePath = derivedPaths.serverRuntimeStatePath;
240 checkedStatePaths.push(statePath);
241 const state = yield* readPersistedServerRuntimeState(statePath);
242 if (Option.isNone(state)) {
243 continue;
244 }
245 // The pid check guards against a dead server's state file whose port
246 // was since reused by a different server: pairing would then mint a
247 // token in the old database while the QR code points at the new server.
248 if (!isProcessAlive(state.value.pid)) {
249 continue;
250 }
251 const probed = yield* probeEnvironmentDescriptor(state.value.origin);
252 if (probed._tag !== "descriptor") {
253 continue;
254 }
255 return {
256 baseDir,
257 variant,
258 state: state.value,
259 descriptor: probed.descriptor,
260 } satisfies DiscoveredPairTarget;
261 }
262 }
263 return yield* new NoRunningServerError({ checkedStatePaths });
264});
265​
266/**
267 * Built by hand rather than through `resolveServerConfig` to keep the dev-vs-userdata choice
268 * pinned to where the runtime state was actually found, independent of ambient environment
269 * variables.
270 */
271const makePairServerConfig = Effect.fn(function* (input: {
272 readonly target: DiscoveredPairTarget;
273 readonly logLevel: ServerConfig.ServerConfig["Service"]["logLevel"];
274}) {
275 const { baseDir, variant, state } = input.target;
276 // The state-dir variant does not imply dev-ness: a worktree dev server uses
277 // an explicit home and therefore lands in `userdata`. The recorded devUrl is
278 // what actually marks a dev server.
279 const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;
280 const derivedPaths = yield* ServerConfig.deriveServerPaths(
281 baseDir,
282 variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,
283 {},
284 );
285 return ServerConfig.make({
286 logLevel: input.logLevel,
287 traceMinLevel: "Info",
288 traceTimingEnabled: false,
289 traceBatchWindowMs: 1_000,
290 traceMaxBytes: 10 * 1024 * 1024,
291 traceMaxFiles: 10,
292 otlpTracesUrl: undefined,
293 otlpMetricsUrl: undefined,
294 otlpLogsUrl: undefined,
295 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
296 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
297 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
298 otelEnvironment: OtelEnvironment.none,
299 mode: "web",
300 port: state.port,
301 host: state.host,
302 cwd: process.cwd(),
303 baseDir,
304 ...derivedPaths,
305 staticDir: undefined,
306 devUrl,
307 devAllowedOrigins: [],
308 noBrowser: true,
309 startupPresentation: "headless",
310 desktopBootstrapToken: undefined,
311 desktopTelemetryFd: undefined,
312 desktopBrowserFd: undefined,
313 desktopBrowserControlFd: undefined,
314 desktopTelemetryControlFd: undefined,
315 resourceMonitorPath: undefined,
316 autoBootstrapProjectFromCwd: false,
317 logWebSocketEvents: false,
318 tailscaleServeEnabled: false,
319 tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
320 });
321});
322​
323const awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {
324 let last: EnvironmentProbeResult = { _tag: "unreachable" };
325 for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {
326 last = yield* probeEnvironmentDescriptor(baseUrl);
327 if (last._tag === "descriptor") {
328 return last;
329 }
330 yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);
331 }
332 return last;
333});
334​
335const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase")(
336 function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {
337 const notes: Array<string> = [];
338 const status = yield* readTailscaleStatus.pipe(
339 Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),
340 );
341 if (status.magicDnsName === null) {
342 return yield* new MagicDnsNameMissingError();
343 }
344 const baseUrl = buildTailscaleHttpsBaseUrl({
345 magicDnsName: status.magicDnsName,
346 servePort: input.servePort,
347 });
348​
349 // Only an unreachable port, or a mapping already fronting this exact
350 // environment, is safe to (re)configure. Any other responder — T3 or not
351 // — must not have its mapping silently replaced.
352 const existing = yield* probeEnvironmentDescriptor(baseUrl);
353 if (existing._tag === "descriptor") {
354 if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {
355 return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });
356 }
357 // Matching environment id proves the mapping reaches this server, but
358 // not through which port: for a dev server it may front the backend
359 // (whose /.well-known also answers) while /pair only renders through
360 // the web origin. Reuse as-is for regular servers; fall through and
361 // repoint our own mapping at the web port for dev servers.
362 if (input.target.state.devUrl === undefined) {
363 return { baseUrl, notes };
364 }
365 }
366 if (existing._tag === "not-a-t3-server") {
367 return yield* new ServePortOccupiedError({ servePort: input.servePort });
368 }
369​
370 const localTarget = resolveTailscaleLocalTarget(input.target.state);
371 if (isDevServerNotProxiableError(localTarget)) {
372 return yield* localTarget;
373 }
374 const { ensureTailscaleServe } = yield* Effect.promise(() => import("@t3tools/tailscale"));
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);