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

pair.ts

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