The best way to control Claude Code, Codex and more from any computer or phone

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