Files
hyperframes/packages/cli/src/utils/studioSelectionClient.ts
T
Miguel Ángel 846cce4891 fix(cli): the CLI trusts a preview only once it proves this user started it (#7899)
* fix(cli): the CLI trusts a preview only once it proves this user started it

* test(cli): a listener that cannot prove it is the user's preview is never trusted

* test(cli): stand-in previews answer the challenge as the user's own do

* style(cli): format the preview proof changes

* fix(cli): a preview's proof names its own endpoint and config, and the token file must be private

* style(cli): format the proof changes

* test(studio): the fake request in the host check has a socket, as every real one does

* fix(studio): a Studio started by hand proves it is the user's, so the CLI still finds it

* fix(cli): the challenge travels in a header, so Studio's routes keep their exact paths

* style(studio): keep the config producer compact
2026-11-16 03:15:26 +00:00

209 lines
7.3 KiB
TypeScript

import {
newPreviewNonce,
PREVIEW_NONCE_HEADER,
provesPreviewOwner,
} from "@hyperframes/core/preview-proof";
import { existsSync, realpathSync } from "node:fs";
import { connect } from "node:net";
import { resolve } from "node:path";
import { scanActiveServers, type ActiveServer } from "../server/portUtils.js";
import type {
LintResult,
ResolvedProject,
StudioSelectionResponse,
} from "@hyperframes/studio-server";
export type StudioLintResponse = LintResult;
const VITE_STUDIO_DISCOVERY_PORTS = [5190] as const;
interface StudioProjectsResponse {
projects?: ResolvedProject[];
}
interface FindPreviewServerOptions {
preferredPort?: number;
}
export class AmbiguousPreviewServerError extends Error {
readonly ports: number[];
constructor(servers: ActiveServer[]) {
const ports = servers.map((server) => server.port).sort((a, b) => a - b);
super(
`Multiple Studio preview servers match this project (${ports.join(", ")}). Pass --port <port> to choose one.`,
);
this.name = "AmbiguousPreviewServerError";
this.ports = ports;
}
}
export class PreviewServerPortMismatchError extends Error {
readonly requestedPort: number;
readonly ports: number[];
constructor(requestedPort: number, servers: ActiveServer[], hint = "") {
const ports = servers.map((server) => server.port).sort((a, b) => a - b);
super(
`No Studio preview server for this project is running on port ${requestedPort}. Matching server port${ports.length === 1 ? "" : "s"}: ${ports.join(", ")}. Rerun with --port ${ports[0]}${ports.length > 1 ? " or omit --port to see all candidates" : ""}.${hint}`,
);
this.name = "PreviewServerPortMismatchError";
this.requestedPort = requestedPort;
this.ports = ports;
}
}
function normalizePath(path: string): string {
const resolved = resolve(path);
try {
if (existsSync(resolved)) {
return realpathSync(resolved).replace(/\\/g, "/").toLowerCase();
}
} catch {
// Fall through to resolved-path normalization.
}
return resolved.replace(/\\/g, "/").toLowerCase();
}
// A Studio on loopback accepts a connection in milliseconds.
const LOOPBACK_CONNECT_TIMEOUT_MS = 1000;
/**
* Fetches from a loopback Studio only once a bounded connect succeeds. Some
* hosts drop a connection to a closed port instead of refusing it (WSL
* mirrored networking, a firewall in stealth mode): fetch then waits for its
* 10 s connect timeout, and aborting it does not close the socket, so the
* command's process stays alive that long anyway. A destroyed socket does not.
*/
export async function fetchLoopback(url: string, init?: RequestInit): Promise<Response> {
const { hostname, port } = new URL(url);
const host = hostname.replace(/^\[|\]$/g, "");
await new Promise<void>((accept, refuse) => {
const socket = connect({ host, port: Number(port) });
const close = (error?: Error) => {
socket.destroy();
if (error) refuse(error);
else accept();
};
socket.setTimeout(LOOPBACK_CONNECT_TIMEOUT_MS, () =>
close(new Error(`connect to ${host}:${port} timed out`)),
);
socket.once("connect", () => close());
socket.once("error", close);
});
return fetch(url, init);
}
export async function findPreviewServerForProject(
projectDir: string,
startPort = 3002,
scan: (startPort?: number) => Promise<ActiveServer[]> = scanActiveServers,
fetchImpl: (url: string, init?: RequestInit) => Promise<Response> = fetchLoopback,
options: FindPreviewServerOptions = {},
): Promise<ActiveServer | null> {
const normalizedProjectDir = normalizePath(projectDir);
const servers = await scan(startPort);
const embeddedServers = servers.filter(
(server) => server.proven && normalizePath(server.projectDir) === normalizedProjectDir,
);
if (options.preferredPort !== undefined) {
const preferred = embeddedServers.find((server) => server.port === options.preferredPort);
if (preferred) return preferred;
const viteServer = await findViteStudioServerForProject(normalizedProjectDir, fetchImpl, [
options.preferredPort,
]);
if (viteServer) return viteServer;
if (embeddedServers.length > 0) {
throw new PreviewServerPortMismatchError(options.preferredPort, embeddedServers);
}
return null;
}
if (embeddedServers.length === 1) return embeddedServers[0]!;
if (embeddedServers.length > 1) throw new AmbiguousPreviewServerError(embeddedServers);
return findViteStudioServerForProject(normalizedProjectDir, fetchImpl);
}
export function studioSelectionUrl(server: ActiveServer): string {
return studioApiUrl(server, "selection");
}
export function studioApiUrl(server: ActiveServer, route: string): string {
const host = server.host ?? "127.0.0.1";
return `http://${host}:${server.port}/api/projects/${encodeURIComponent(server.projectName)}/${route}`;
}
// Vite dev servers bind IPv6 loopback (`::1`) by default while embedded servers
// bind IPv4 (`127.0.0.1`), so probe both — a single family misses the other and
// is exactly why `--selection`/`--context` failed against a local-studio preview.
const LOOPBACK_HOSTS = ["127.0.0.1", "[::1]"] as const;
async function provesOwnerAt(
host: string,
port: number,
fetchImpl: (url: string, init?: RequestInit) => Promise<Response>,
): Promise<boolean> {
const nonce = newPreviewNonce();
const response = await fetchImpl(`http://${host}:${port}/__hyperframes_config`, {
headers: { [PREVIEW_NONCE_HEADER]: nonce },
});
if (!response.ok) return false;
const config = (await response.json()) as Record<string, unknown>;
return provesPreviewOwner(nonce, { address: host, port }, config);
}
async function findViteStudioServerForProject(
normalizedProjectDir: string,
fetchImpl: (url: string, init?: RequestInit) => Promise<Response>,
ports: readonly number[] = VITE_STUDIO_DISCOVERY_PORTS,
): Promise<ActiveServer | null> {
for (const port of ports) {
for (const host of LOOPBACK_HOSTS) {
try {
const response = await fetchImpl(`http://${host}:${port}/api/projects`);
if (!response.ok) continue;
const payload = (await response.json()) as StudioProjectsResponse;
const project = payload.projects?.find(
(candidate) => normalizePath(candidate.dir) === normalizedProjectDir,
);
if (!project || !(await provesOwnerAt(host, port, fetchImpl))) continue;
return {
port,
host,
projectName: project.id,
projectDir: project.dir,
version: "studio-dev",
pid: null,
proven: true,
};
} catch {
// Not a Vite-served Studio on this host/port, or unreachable. Try next.
}
}
}
return null;
}
export async function fetchStudioSelection(
server: ActiveServer,
fetchImpl: typeof fetch = fetch,
): Promise<StudioSelectionResponse> {
const url = studioSelectionUrl(server);
const response = await fetchImpl(url);
if (!response.ok) {
throw new Error(`selection endpoint returned ${response.status}`);
}
return (await response.json()) as StudioSelectionResponse;
}
export async function fetchStudioLint(
server: ActiveServer,
fetchImpl: typeof fetch = fetch,
): Promise<StudioLintResponse> {
const url = studioApiUrl(server, "lint");
const response = await fetchImpl(url);
if (!response.ok) {
throw new Error(`lint endpoint returned ${response.status}`);
}
return (await response.json()) as StudioLintResponse;
}