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