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

pair.ts

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