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

pair.ts

595 lines22.5 KB

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