feat(cli): `npx t3 pair` - generate QR code from a running server #4955
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 3 commits into
main fromrefs/pull/4955/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/cli/pair.ts lines 86 to 111OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +91,21 @@91+ "magicdns-missing",92+ "serves-other-environment",93+ "serve-failed",94+ ]),95+ servePort: Schema.Number,96+ cause: Schema.optional(Schema.Defect()),97+ },98+) {99+ override get message(): string {100+ switch (this.reason) {101+ case "status-unavailable":102+ return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";103+ case "magicdns-missing":104+ return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";105+ case "serves-other-environment":106+ 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.`;107+ case "serve-failed":108+ 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.`;109+ }110+ }111+}
- apps/server/src/cli/pair.ts line 148Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +97,21 @@97+ },98+) {99+ override get message(): string {100+ switch (this.reason) {101+ case "status-unavailable":102+ return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";103+ case "magicdns-missing":104+ return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";105+ case "serves-other-environment":106+ 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.`;107+ case "serve-failed":108+ 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.`;109+ }110+ }111+}112+113+/** The URL a browser or phone should pair through, absent Tailscale. */114+export const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>115+ state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);116+117+/**apps/server/src/cli/pair.ts line 148Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +97,21 @@97+ },98+) {99+ override get message(): string {100+ switch (this.reason) {101+ case "status-unavailable":102+ return "Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.";103+ case "magicdns-missing":104+ return "This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.";105+ case "serves-other-environment":106+ 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.`;107+ case "serve-failed":108+ 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.`;109+ }110+ }111+}112+113+/** The URL a browser or phone should pair through, absent Tailscale. */114+export const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>115+ state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);116+117+/**apps/server/src/cli/pair.ts line 163OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +143,21 @@143+export const formatPairOutput = (input: {144+ readonly serverLabel: string;145+ readonly origin: string;146+ readonly pairingUrl: string;147+ readonly token: string;148+ readonly expiresAt: DateTime.Utc;149+ readonly notes: ReadonlyArray<string>;150+}): string =>151+ [152+ `Pairing with ${input.serverLabel} (${input.origin}).`,153+ "",154+ renderTerminalQrCode(input.pairingUrl),155+ "",156+ `Pairing URL: ${input.pairingUrl}`,157+ `Token: ${input.token}`,158+ `Expires: ${DateTime.formatIso(input.expiresAt)}`,159+ ...input.notes.flatMap((note) => ["", `Note: ${note}`]),160+ "",161+ ].join("\n");162+163+const probeEnvironmentDescriptor = (baseUrl: string) =>apps/server/src/cli/pair.ts line 212OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +192,21 @@192+ bases.push(worktreeHome);193+ }194+ const envHome = yield* Config.string("T3CODE_HOME").pipe(Config.option);195+ bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));196+ }197+198+ const checkedStatePaths: Array<string> = [];199+ for (const baseDir of new Set(bases)) {200+ for (const variant of ["userdata", "dev"] as const) {201+ const derivedPaths = yield* ServerConfig.deriveServerPaths(202+ baseDir,203+ variant === "dev" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,204+ {},205+ );206+ const statePath = derivedPaths.serverRuntimeStatePath;207+ checkedStatePaths.push(statePath);208+ const state = yield* readPersistedServerRuntimeState(statePath);209+ if (Option.isNone(state)) {210+ continue;211+ }212+ const descriptor = yield* probeEnvironmentDescriptor(state.value.origin);
- @@ -0,0 +302,21 @@302+ }),303+ ),304+ );305+ if (status.magicDnsName === null) {306+ return yield* new PairTailscaleError({307+ reason: "magicdns-missing",308+ servePort: input.servePort,309+ });310+ }311+ const baseUrl = buildTailscaleHttpsBaseUrl({312+ magicDnsName: status.magicDnsName,313+ servePort: input.servePort,314+ });315+316+ // If the HTTPS port already reaches this exact server, there is nothing to317+ // configure. If it reaches a different T3 Code server, refuse: silently318+ // replacing that mapping would break whatever is pairing through it.319+ const existing = yield* probeEnvironmentDescriptor(baseUrl);320+ if (Option.isSome(existing)) {321+ if (existing.value.environmentId === input.target.descriptor.environmentId) {322+ return { baseUrl, notes };
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -0,0 +145,21 @@145+146+const isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);147+148+/**149+ * The local endpoint Tailscale Serve should proxy to. Dev servers are150+ * single-origin, so the web dev server's port is the one to publish; the151+ * backend rides along behind Vite's proxy. Serve targets are always plain152+ * HTTP, so an HTTPS dev URL cannot be proxied and is rejected.153+ */154+export const resolveTailscaleLocalTarget = (155+ state: PersistedServerRuntimeState,156+): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {157+ if (state.devUrl !== undefined) {158+ const devUrl = new URL(state.devUrl);159+ if (devUrl.protocol !== "http:") {160+ return new DevServerNotProxiableError({ devUrl: state.devUrl });161+ }162+ const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;163+ return isLoopbackHost(devUrl.hostname)164+ ? { localPort }165+ : { localPort, localHost: devUrl.hostname };@@ -0,0 +200,21 @@200+type EnvironmentProbeResult =201+ | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }202+ | { readonly _tag: "unreachable" }203+ | { readonly _tag: "not-a-t3-server" };204+205+const probeEnvironmentDescriptor = (206+ baseUrl: string,207+): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>208+ Effect.gen(function* () {209+ const client = yield* HttpClient.HttpClient;210+ const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());211+ const response = yield* client.execute(request).pipe(212+ Effect.timeout(PAIR_PROBE_TIMEOUT),213+ // Transport failure or timeout: nothing (reachable) is listening there.214+ Effect.mapError(() => ({ _tag: "unreachable" }) as const),215+ );216+ // Anything that answered HTTP but not with a valid descriptor is some217+ // other service.218+ const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(219+ Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),220+ Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
- @@ -0,0 +201,21 @@201+ | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }202+ | { readonly _tag: "unreachable" }203+ | { readonly _tag: "not-a-t3-server" };204+205+const probeEnvironmentDescriptor = (206+ baseUrl: string,207+): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>208+ Effect.gen(function* () {209+ const client = yield* HttpClient.HttpClient;210+ const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());211+ const response = yield* client.execute(request).pipe(212+ Effect.timeout(PAIR_PROBE_TIMEOUT),213+ // Transport failure or timeout: nothing (reachable) is listening there.214+ Effect.mapError(() => ({ _tag: "unreachable" }) as const),215+ );216+ // Bad-gateway family means a proxy (Tailscale Serve) answered for a217+ // backend that is gone — a stale mapping, not a live occupant. Treating218+ // it as unreachable lets `t3 pair --tailscale` repair its own mapping219+ // after the server's port changed.220+ if (response.status === 502 || response.status === 503 || response.status === 504) {221+ return { _tag: "unreachable" } as const;
t3dotgg(GitHub profile, opens in a new tab) changed the title
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
a220ed00-9ef1-420c-873c-5a2317dd18e1You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share