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

pair.ts

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