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

pair.ts

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