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
This commit is contained in:
Miguel Ángel
2026-11-16 03:15:26 +00:00
committed by GitHub
parent 756b2fcae1
commit 846cce4891
18 changed files with 531 additions and 24 deletions
+1
View File
@@ -108,6 +108,7 @@ describe("endPreviewBeforeOpening", () => {
projectName: "hyperframes-open-project",
projectDir,
version: "test",
proven: true,
pid: String(background.pid),
pidSource: "os",
};
@@ -153,6 +153,7 @@ describe("preview --status reporting", () => {
projectDir: "/tmp/preview-unverified",
projectName: "scanned-project",
version: "test",
proven: true,
},
],
listManaged: async () => [{ pid: null, port: 32600, projectDir: "/tmp/preview-unverified" }],
@@ -0,0 +1,132 @@
import { mkdtempSync, rmSync } from "node:fs";
import { createServer, type IncomingMessage } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { PREVIEW_NONCE_HEADER, previewProof } from "@hyperframes/core/preview-proof";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import {
activeServerOnPort,
detectHyperframesServer,
type ActiveServer,
} from "../server/portUtils.js";
import { findPreviewServerForProject } from "../utils/studioSelectionClient.js";
import { readBackgroundPreviewStatus, stopBackgroundPreview } from "./previewLifecycle.js";
const projectDir = resolve("/tmp/hyperframes-impostor-project");
const config = {
isHyperframes: true,
pid: 1,
projectName: "impostor",
projectDir,
version: "test",
};
async function serve(answer: (request: IncomingMessage) => Promise<object>): Promise<number> {
const server = createServer((request, response) => {
void answer(request).then((body) => {
response.setHeader("content-type", "application/json");
response.end(JSON.stringify(body));
});
});
await new Promise<void>((listening) => server.listen(0, "127.0.0.1", () => listening()));
onTestFinished(() => new Promise<void>((done) => server.close(() => done())));
return (server.address() as AddressInfo).port;
}
// A listener that answers the config probe for this project. Without the user's token it cannot answer the challenge.
const listener = (answersChallenge: boolean) =>
serve(async ({ headers, socket }) => {
const endpoint = { address: socket.localAddress!, port: socket.localPort! };
const proof = answersChallenge
? previewProof(headers[PREVIEW_NONCE_HEADER], endpoint, config)
: null;
return { ...config, ...(proof && { proof }) };
});
// Forwards the CLI's challenge to a genuine preview and passes its answer back, with the project changed or not.
const relay = (genuinePort: number, projectDir?: string) =>
serve(async ({ headers }) => {
const nonce = String(headers[PREVIEW_NONCE_HEADER]);
const answer = await fetch(`http://127.0.0.1:${genuinePort}/__hyperframes_config`, {
headers: { [PREVIEW_NONCE_HEADER]: nonce },
});
return { ...((await answer.json()) as object), ...(projectDir && { projectDir }) };
});
const ownPid = async () => String(process.pid);
const claimed = (port: number): ActiveServer => ({
port,
projectName: "impostor",
projectDir,
version: "test",
pid: String(process.pid),
pidSource: "os",
proven: false,
});
function stateHome(): string {
const dir = mkdtempSync(join(tmpdir(), "hf-impostor-state-"));
onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
return dir;
}
describe("a listener that claims this user's project without proving it", () => {
it("is marked unproven by the probe, while one that answers the challenge is proven", async () => {
expect((await activeServerOnPort(await listener(false), ownPid))?.proven).toBe(false);
expect((await activeServerOnPort(await listener(true), ownPid))?.proven).toBe(true);
});
it("is not proven by relaying the challenge to a genuine preview", async () => {
const genuine = await listener(true);
expect((await activeServerOnPort(await relay(genuine, "/forged"), ownPid))?.proven).toBe(false);
expect((await activeServerOnPort(await relay(genuine), ownPid))?.proven).toBe(false);
expect((await activeServerOnPort(genuine, ownPid))?.proven).toBe(true);
});
it("is not reused by a foreground preview", async () => {
const normalized = projectDir.replace(/\\/g, "/").toLowerCase();
expect((await detectHyperframesServer(await listener(false), normalized)).type).toBe(
"unproven",
);
expect((await detectHyperframesServer(await listener(true), normalized)).type).toBe("match");
});
it("is not consulted for agent context", async () => {
const port = await listener(false);
const notStudio = vi.fn(async () => new Response("", { status: 404 }));
expect(
await findPreviewServerForProject(projectDir, port, async () => [claimed(port)], notStudio),
).toBeNull();
});
it("is not reported as the running preview, so no browser opens on it", async () => {
const port = await listener(false);
expect(
await readBackgroundPreviewStatus(projectDir, port, {
scan: async () => [claimed(port)],
stateHome: stateHome(),
}),
).toBeNull();
});
it("is not stopped", async () => {
const port = await listener(false);
const kill = vi.fn();
await expect(
stopBackgroundPreview(projectDir, port, {
scan: async () => [claimed(port)],
probe: async () => claimed(port),
kill,
sleep: async () => {},
stateHome: stateHome(),
}),
).rejects.toThrow(/ownership could not be proven/);
expect(kill).not.toHaveBeenCalled();
});
});
@@ -29,6 +29,7 @@ const server: ActiveServer = {
projectName: "preview-lifecycle-project",
projectDir,
version: "test",
proven: true,
pid: "4321",
pidSource: "os",
};
@@ -477,6 +478,7 @@ describe("background preview lifecycle", () => {
projectName: "managed-custom-port",
projectDir: otherProjectDir,
version: "test",
proven: true,
pid: "8765",
pidSource: "os",
},
@@ -331,7 +331,7 @@ function statusServer(
saved: PreviewSession | null,
preferredPort: number | undefined,
): ActiveServer | null {
const candidates = sameProjectServers(servers, projectDir);
const candidates = sameProjectServers(servers, projectDir).filter((server) => server.proven);
return (
candidates.find((server) => server.port === preferredPort) ??
candidates.find((server) => server.port === saved?.port) ??
@@ -518,11 +518,12 @@ function provenStopTargetPid(
liveServerPid: number,
dependencies: LifecycleDependencies,
): number {
if (server.pidSource === "os") return ownedStopTargetPid(saved, liveServerPid, dependencies);
if (server.pidSource === "os" && server.proven)
return ownedStopTargetPid(saved, liveServerPid, dependencies);
if (saved && isCurrentPreviewWrapper(saved, dependencies)) return saved.pid;
throw new Error(
`preview ownership could not be proven for ${resolve(projectDir)}: the system did not say which process listens on port ${server.port}. ` +
"Stop that preview from the terminal it runs in.",
`preview ownership could not be proven for ${resolve(projectDir)}: the server on port ${server.port} is not a preview this user started, ` +
"or the system did not say which process it is. Stop that preview from the terminal it runs in.",
);
}
@@ -595,7 +596,7 @@ function reuseExistingPreview(
candidates: ActiveServer[],
dependencies: LifecycleDependencies,
): Extract<BackgroundPreviewResult, { type: "reused" }> | null {
if (!reusableExisting || dependencies.forceNew) return null;
if (!reusableExisting?.proven || dependencies.forceNew) return null;
const unmet = unmetPreferredPort(reusableExisting.port, dependencies.preferredPort);
if (unmet !== undefined) {
throw new PreviewServerPortMismatchError(
+6 -2
View File
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createServer, type Server } from "node:net";
import { PREVIEW_NONCE_HEADER, previewProof } from "@hyperframes/core/preview-proof";
import { spawn } from "node:child_process";
import { resolve } from "node:path";
import { createServer as createHttpServer, get, type Server as HttpServer } from "node:http";
@@ -50,9 +51,12 @@ function boundAddress(server: ServerType): string {
}
async function startConfigProbeServer(payload: Record<string, unknown>): Promise<number> {
const server = createHttpServer((_req, res) => {
const server = createHttpServer((req, res) => {
const nonce = req.headers[PREVIEW_NONCE_HEADER];
const endpoint = { address: req.socket.localAddress!, port: req.socket.localPort! };
const proof = previewProof(nonce, endpoint, payload);
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(payload));
res.end(JSON.stringify({ ...payload, ...(proof && { proof }) }));
});
openHttpServers.push(server);
await new Promise<void>((resolve, reject) => {
+26 -2
View File
@@ -10,6 +10,11 @@
* - Smart port selection with instance reuse
*/
import {
newPreviewNonce,
PREVIEW_NONCE_HEADER,
provesPreviewOwner,
} from "@hyperframes/core/preview-proof";
import net from "node:net";
import http from "node:http";
import { execFile } from "node:child_process";
@@ -103,10 +108,13 @@ interface HyperframesConfigResponse {
serverBuildSignature?: string | null;
browserGpuMode?: BrowserGpuMode;
version: string;
proof?: string;
proven?: boolean;
}
export type DetectionResult =
| { type: "match" }
| { type: "unproven" }
| { type: "mismatch"; projectName: string }
| { type: "not-hyperframes" };
@@ -120,12 +128,14 @@ export function detectHyperframesServer(
expectedServerBuildSignature: string | null = null,
expectedBrowserGpuMode?: BrowserGpuMode,
): Promise<DetectionResult> {
const nonce = newPreviewNonce();
return new Promise<DetectionResult>((resolveResult) => {
const req = http.get(
{
hostname: "127.0.0.1",
port,
path: "/__hyperframes_config",
headers: { [PREVIEW_NONCE_HEADER]: nonce },
timeout: PROBE_TIMEOUT_MS,
},
(res) => {
@@ -169,6 +179,8 @@ export function detectHyperframesServer(
) {
return resolveResult({ type: "mismatch", projectName: json.projectName });
}
if (!provesPreviewOwner(nonce, { address: "127.0.0.1", port }, { ...json }))
return resolveResult({ type: "unproven" });
return resolveResult({ type: "match" });
}
@@ -258,6 +270,8 @@ export interface ActiveServer {
*/
pidSource?: "os" | "self-reported";
browserGpuMode?: BrowserGpuMode;
/** The server answered this user's preview-token challenge, so it is a preview this user started. */
proven?: boolean;
}
/**
@@ -265,9 +279,16 @@ export interface ActiveServer {
* Returns the full config or null if not a HyperFrames server.
*/
function probePort(port: number): Promise<HyperframesConfigResponse | null> {
const nonce = newPreviewNonce();
return new Promise<HyperframesConfigResponse | null>((resolveResult) => {
const req = http.get(
{ hostname: "127.0.0.1", port, path: "/__hyperframes_config", timeout: PROBE_TIMEOUT_MS },
{
hostname: "127.0.0.1",
port,
path: "/__hyperframes_config",
headers: { [PREVIEW_NONCE_HEADER]: nonce },
timeout: PROBE_TIMEOUT_MS,
},
(res) => {
if (res.statusCode !== 200) {
res.resume();
@@ -287,7 +308,9 @@ function probePort(port: number): Promise<HyperframesConfigResponse | null> {
res.on("end", () => {
try {
const json = JSON.parse(data) as HyperframesConfigResponse;
resolveResult(json.isHyperframes === true ? json : null);
if (json.isHyperframes !== true) return resolveResult(null);
const proven = provesPreviewOwner(nonce, { address: "127.0.0.1", port }, { ...json });
resolveResult({ ...json, proven });
} catch {
resolveResult(null);
}
@@ -369,6 +392,7 @@ function identityFrom(
projectDir: config.projectDir,
version: config.version,
browserGpuMode: config.browserGpuMode,
proven: config.proven === true,
};
}
+14 -2
View File
@@ -5,6 +5,8 @@
* providing a CLI-specific adapter for single-project, in-process rendering.
*/
import { PREVIEW_NONCE_HEADER, previewProof } from "@hyperframes/core/preview-proof";
import type { HttpBindings } from "@hono/node-server";
import { Hono, type Context } from "hono";
import { streamSSE } from "hono/streaming";
import { realpath } from "@hyperframes/core";
@@ -951,7 +953,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
app.get("/__hyperframes_config", (c) => {
const serve = async () => {
const serverBuildSignature = await loadPreviewServerBuildSignature();
return c.json({
const config = {
isHyperframes: true,
pid: process.pid,
projectName: projectId,
@@ -959,7 +961,17 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
serverBuildSignature,
browserGpuMode,
version,
});
};
const socket = (c.env as Partial<HttpBindings> | undefined)?.incoming?.socket;
const proof =
socket?.localAddress && socket.localPort
? previewProof(
c.req.header(PREVIEW_NONCE_HEADER),
{ address: socket.localAddress, port: socket.localPort },
config,
)
: null;
return c.json({ ...config, ...(proof && { proof }) });
};
return serve();
});
@@ -13,6 +13,7 @@ import {
studioSelectionUrl,
} from "./studioSelectionClient";
import type { ActiveServer } from "../server/portUtils";
import { previewConfigPayload } from "../../../studio/vite.preview-config";
const servers: ActiveServer[] = [
{
@@ -20,6 +21,7 @@ const servers: ActiveServer[] = [
projectName: "other",
projectDir: "/tmp/other",
version: "0.7.17",
proven: true,
pid: null,
},
{
@@ -27,12 +29,25 @@ const servers: ActiveServer[] = [
projectName: "demo project",
projectDir: "/tmp/demo",
version: "0.7.17",
proven: true,
pid: "123",
},
];
// The real Studio dev server's answer to the CLI's challenge, started by hand (no launch project).
function proofResponse(url: string, init?: RequestInit): Response | null {
const { hostname, port, pathname } = new URL(url);
if (pathname !== "/__hyperframes_config") return null;
const headers = init?.headers as Record<string, string> | undefined;
const socket = { localAddress: hostname.replace(/^\[|\]$/g, ""), localPort: Number(port) };
const answer = previewConfigPayload({}, 1, "dev", { headers, socket } as never);
return new Response(JSON.stringify(answer), { status: answer ? 200 : 404 });
}
function mockProjectsFetch(port = 5190): typeof fetch {
return vi.fn(async (url: string | URL | Request) => {
return vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
const proven = proofResponse(String(url), init);
if (proven) return proven;
expect(String(url)).toBe(`http://127.0.0.1:${port}/api/projects`);
return new Response(
JSON.stringify({
@@ -61,6 +76,7 @@ describe("studioSelectionClient", () => {
projectName: "third",
projectDir: "/tmp/third",
version: "0.7.17",
proven: true,
pid: null,
},
]);
@@ -119,6 +135,7 @@ describe("studioSelectionClient", () => {
projectName: "demo project",
projectDir: "/tmp/demo",
version: "studio-dev",
proven: true,
pid: null,
});
});
@@ -126,8 +143,10 @@ describe("studioSelectionClient", () => {
it("discovers a Vite Studio that only binds IPv6 loopback ([::1])", async () => {
const scan = vi.fn(async () => []);
// Vite binds ::1 only: the IPv4 probe is refused, the IPv6 probe succeeds.
const fetchImpl = vi.fn(async (url: string | URL | Request) => {
const fetchImpl = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
const u = String(url);
const proven = proofResponse(u, init);
if (proven) return proven;
if (u === "http://127.0.0.1:5190/api/projects") throw new Error("ECONNREFUSED");
expect(u).toBe("http://[::1]:5190/api/projects");
return new Response(
@@ -144,6 +163,7 @@ describe("studioSelectionClient", () => {
projectName: "demo project",
projectDir: "/tmp/demo",
version: "studio-dev",
proven: true,
pid: null,
});
// Follow-up API calls must target the IPv6 host the server was found on.
@@ -1,3 +1,8 @@
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";
@@ -70,7 +75,7 @@ const LOOPBACK_CONNECT_TIMEOUT_MS = 1000;
* 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): Promise<Response> {
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) => {
@@ -86,20 +91,20 @@ export async function fetchLoopback(url: string): Promise<Response> {
socket.once("connect", () => close());
socket.once("error", close);
});
return fetch(url);
return fetch(url, init);
}
export async function findPreviewServerForProject(
projectDir: string,
startPort = 3002,
scan: (startPort?: number) => Promise<ActiveServer[]> = scanActiveServers,
fetchImpl: (url: string) => Promise<Response> = fetchLoopback,
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) => normalizePath(server.projectDir) === normalizedProjectDir,
(server) => server.proven && normalizePath(server.projectDir) === normalizedProjectDir,
);
if (options.preferredPort !== undefined) {
const preferred = embeddedServers.find((server) => server.port === options.preferredPort);
@@ -132,9 +137,23 @@ export function studioApiUrl(server: ActiveServer, route: string): string {
// 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) => Promise<Response>,
fetchImpl: (url: string, init?: RequestInit) => Promise<Response>,
ports: readonly number[] = VITE_STUDIO_DISCOVERY_PORTS,
): Promise<ActiveServer | null> {
for (const port of ports) {
@@ -146,7 +165,7 @@ async function findViteStudioServerForProject(
const project = payload.projects?.find(
(candidate) => normalizePath(candidate.dir) === normalizedProjectDir,
);
if (!project) continue;
if (!project || !(await provesOwnerAt(host, port, fetchImpl))) continue;
return {
port,
host,
@@ -154,6 +173,7 @@ async function findViteStudioServerForProject(
projectDir: project.dir,
version: "studio-dev",
pid: null,
proven: true,
};
} catch {
// Not a Vite-served Studio on this host/port, or unreachable. Try next.
+6
View File
@@ -80,6 +80,12 @@
"types": "./dist/atomicFile.d.ts",
"environments": ["bun", "node"]
},
"./preview-proof": {
"source": "./src/previewProof.ts",
"runtime": "./dist/previewProof.js",
"types": "./dist/previewProof.d.ts",
"environments": ["bun", "node"]
},
"./cache-dir": {
"source": "./src/cacheDir.ts",
"runtime": "./dist/cacheDir.js",
+10
View File
@@ -92,6 +92,12 @@
"import": "./src/atomicFile.ts",
"types": "./src/atomicFile.ts"
},
"./preview-proof": {
"bun": "./src/previewProof.ts",
"node": "./dist/previewProof.js",
"import": "./src/previewProof.ts",
"types": "./src/previewProof.ts"
},
"./cache-dir": {
"bun": "./src/cacheDir.ts",
"node": "./dist/cacheDir.js",
@@ -712,6 +718,10 @@
"import": "./dist/atomicFile.js",
"types": "./dist/atomicFile.d.ts"
},
"./preview-proof": {
"import": "./dist/previewProof.js",
"types": "./dist/previewProof.d.ts"
},
"./cache-dir": {
"import": "./dist/cacheDir.js",
"types": "./dist/cacheDir.d.ts"
+101
View File
@@ -0,0 +1,101 @@
import {
chmodSync,
linkSync,
mkdtempSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import {
newPreviewNonce,
previewProof,
previewToken,
previewTokenDir,
previewTokenPath,
provesPreviewOwner,
} from "./previewProof";
const KNOWN = "a".repeat(64);
const posix = process.platform !== "win32";
function tempDir(): string {
const dir = mkdtempSync(join(tmpdir(), "hf-preview-proof-"));
onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
return dir;
}
const endpoint = { address: "127.0.0.1", port: 3002 };
const config = { isHyperframes: true, projectDir: "/tmp/video", pid: 7 };
describe("preview token", () => {
it("is made once in a file only this user can read, and kept", () => {
const dir = tempDir();
const token = previewToken(dir);
expect(token).toMatch(/^[0-9a-f]{64}$/);
expect(previewToken(dir)).toBe(token);
if (posix) expect(statSync(previewTokenPath(dir)).mode & 0o077).toBe(0);
});
it("lives in the user's home, not in a cache folder that may be shared", () => {
const cache = tempDir();
vi.stubEnv("HYPERFRAMES_CACHE_DIR", cache);
onTestFinished(() => vi.unstubAllEnvs());
expect(previewTokenDir().startsWith(cache)).toBe(false);
});
it.runIf(posix)(
"is refused, never adopted, when the file is a link or others can read it",
() => {
const known = join(tempDir(), "known");
writeFileSync(known, KNOWN, { mode: 0o644 });
chmodSync(known, 0o644);
const linked = tempDir();
symlinkSync(known, previewTokenPath(linked));
const readable = tempDir();
writeFileSync(previewTokenPath(readable), KNOWN, { mode: 0o644 });
chmodSync(previewTokenPath(readable), 0o644);
const hardLinked = tempDir();
const privateKnown = join(tempDir(), "private");
writeFileSync(privateKnown, KNOWN, { mode: 0o600 });
linkSync(privateKnown, previewTokenPath(hardLinked));
for (const dir of [linked, readable, hardLinked]) expect(previewToken(dir)).toBeNull();
},
);
});
describe("preview proof", () => {
it("checks out only for the same nonce, endpoint, config and token", () => {
const token = previewToken(tempDir())!;
const nonce = newPreviewNonce();
const answered = { ...config, proof: previewProof(nonce, endpoint, config, token) };
expect(provesPreviewOwner(nonce, endpoint, answered, token)).toBe(true);
expect(
provesPreviewOwner(nonce, { address: "::ffff:127.0.0.1", port: 3002 }, answered, token),
).toBe(true);
expect(provesPreviewOwner(newPreviewNonce(), endpoint, answered, token)).toBe(false);
expect(provesPreviewOwner(nonce, { ...endpoint, port: 3003 }, answered, token)).toBe(false);
expect(provesPreviewOwner(nonce, { ...endpoint, address: "::1" }, answered, token)).toBe(false);
expect(provesPreviewOwner(nonce, endpoint, { ...answered, projectDir: "/forged" }, token)).toBe(
false,
);
expect(provesPreviewOwner(nonce, endpoint, answered, previewToken(tempDir())!)).toBe(false);
for (const proof of [undefined, "", "0".repeat(64), `${answered.proof}0`]) {
expect(provesPreviewOwner(nonce, endpoint, { ...config, proof }, token)).toBe(false);
}
});
it("answers no malformed challenge", () => {
const token = previewToken(tempDir())!;
for (const nonce of [null, "", "short", "../x", "G".repeat(32)]) {
expect(previewProof(nonce, endpoint, config, token)).toBeNull();
}
});
});
+110
View File
@@ -0,0 +1,110 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { closeSync, constants, fstatSync, mkdirSync, openSync, readSync, writeSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
const TOKEN_SHAPE = /^[0-9a-f]{64}$/;
const NONCE_SHAPE = /^[0-9a-f]{32}$/;
/** The address and port a preview accepted a connection on, or that the CLI dialed. */
export interface PreviewEndpoint {
address: string;
port: number;
}
/** The token's folder: always in the user's own home, never a cache folder another user may share. */
export function previewTokenDir(): string {
if (process.platform === "win32")
return join(
process.env["LOCALAPPDATA"]?.trim() || join(homedir(), "AppData", "Local"),
"hyperframes",
);
return join(homedir(), ".local", "state", "hyperframes", "auth");
}
export const previewTokenPath = (dir = previewTokenDir()) => join(dir, "preview-token");
// ponytail: Windows relies on the user-only ACL of LOCALAPPDATA; check the ACL itself if that folder can be shared.
function isPrivateFile(fd: number): boolean {
const stat = fstatSync(fd);
if (!stat.isFile() || stat.nlink !== 1) return false;
if (process.platform === "win32") return true;
return stat.uid === process.getuid?.() && (stat.mode & 0o077) === 0;
}
function readToken(path: string): string | null {
let fd: number;
try {
fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
} catch {
return null;
}
try {
if (!isPrivateFile(fd)) return null;
const bytes = Buffer.alloc(65);
const token = bytes.subarray(0, readSync(fd, bytes, 0, bytes.length, 0)).toString("utf-8");
return TOKEN_SHAPE.test(token) ? token : null;
} finally {
closeSync(fd);
}
}
/** This user's preview token, made on first use; null when the file is missing, unsafe or unreadable. */
export function previewToken(dir = previewTokenDir()): string | null {
const path = previewTokenPath(dir);
const existing = readToken(path);
if (existing) return existing;
try {
mkdirSync(dir, { recursive: true, mode: 0o700 });
const flags =
constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0);
const fd = openSync(path, flags, 0o600);
const token = randomBytes(32).toString("hex");
try {
writeSync(fd, token);
} finally {
closeSync(fd);
}
return token;
} catch {
// expected: the file exists (made by another process, or unsafe); only a safe one is used
return readToken(path);
}
}
export const newPreviewNonce = () => randomBytes(16).toString("hex");
/** Carries the CLI's challenge; a custom header also makes a browser preflight any cross-site probe. */
export const PREVIEW_NONCE_HEADER = "x-hyperframes-nonce";
const endpointKey = ({ address, port }: PreviewEndpoint) =>
`${address.replace(/^\[(.*)\]$/, "$1").replace(/^::ffff:/i, "")}:${port}`;
/** The answer to `nonce` from the preview at `endpoint` serving `config`. It binds all three, so an answer
* relayed from another preview, or with its config altered, does not check out. */
export function previewProof(
nonce: unknown,
endpoint: PreviewEndpoint,
config: Record<string, unknown>,
token = previewToken(),
): string | null {
if (!token || typeof nonce !== "string" || !NONCE_SHAPE.test(nonce)) return null;
const { proof: _proof, ...signed } = config;
const fields = JSON.stringify(signed, Object.keys(signed).sort());
return createHmac("sha256", token)
.update(`${nonce}\n${endpointKey(endpoint)}\n${fields}`)
.digest("hex");
}
/** Whether `config`, read from `endpoint` in answer to `nonce`, carries this user's proof. */
export function provesPreviewOwner(
nonce: string,
endpoint: PreviewEndpoint,
config: Record<string, unknown>,
token = previewToken(),
): boolean {
const expected = previewProof(nonce, endpoint, config, token);
const proof = config["proof"];
if (!expected || typeof proof !== "string" || proof.length !== expected.length) return false;
return timingSafeEqual(Buffer.from(expected), Buffer.from(proof));
}
+2 -1
View File
@@ -81,7 +81,8 @@ function request(middlewares: Middleware[], url: string, host: string): Promise<
resolve(reply);
},
});
const req = { url, method: "GET", headers: { host } } as IncomingMessage;
const socket = { localAddress: "127.0.0.1", localPort: 5190 };
const req = { url, method: "GET", headers: { host }, socket } as unknown as IncomingMessage;
const run = (index: number): void => {
const middleware = middlewares[index];
if (!middleware) return resolve(reply);
+1 -1
View File
@@ -239,7 +239,7 @@ function devProjectApi(): Plugin {
server.middlewares.use((req, res, next) => {
if (req.url !== "/__hyperframes_config") return next();
const payload = previewConfigPayload(process.env, process.pid, studioPkg.version);
const payload = previewConfigPayload(process.env, process.pid, studioPkg.version, req);
if (!payload) return next();
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
res.end(JSON.stringify(payload));
+51 -1
View File
@@ -1,6 +1,22 @@
import { describe, expect, it } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
newPreviewNonce,
PREVIEW_NONCE_HEADER,
provesPreviewOwner,
type PreviewEndpoint,
} from "@hyperframes/core/preview-proof";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import { previewConfigPayload } from "./vite.preview-config";
// The request the CLI's challenge arrives as, on a socket accepted at `endpoint`.
const challenge = (nonce: string, { address, port }: PreviewEndpoint) =>
({
headers: { [PREVIEW_NONCE_HEADER]: nonce },
socket: { localAddress: address, localPort: port },
}) as never;
describe("previewConfigPayload", () => {
it("identifies a detached Vite preview to the CLI lifecycle scanner", () => {
expect(
@@ -24,6 +40,40 @@ describe("previewConfigPayload", () => {
});
});
it("answers the CLI's challenge with this user's preview token, for its own endpoint", () => {
const home = mkdtempSync(join(tmpdir(), "hf-vite-proof-"));
onTestFinished(() => rmSync(home, { recursive: true, force: true }));
vi.stubEnv("HOME", home);
vi.stubEnv("LOCALAPPDATA", home);
onTestFinished(() => vi.unstubAllEnvs());
const env = {
HYPERFRAMES_PREVIEW_PROJECT_DIR: "/tmp/video",
HYPERFRAMES_PREVIEW_PROJECT_NAME: "video",
};
const nonce = newPreviewNonce();
const endpoint = { address: "::1", port: 5190 };
const answer = previewConfigPayload(env, 1, "dev", challenge(nonce, endpoint))!;
expect(provesPreviewOwner(nonce, endpoint, answer)).toBe(true);
expect(provesPreviewOwner(nonce, { ...endpoint, address: "127.0.0.1" }, answer)).toBe(false);
expect(previewConfigPayload(env, 1, "dev")).not.toHaveProperty("proof");
});
it("proves a Studio started by hand is this user's, without claiming a project", () => {
const home = mkdtempSync(join(tmpdir(), "hf-vite-proof-"));
onTestFinished(() => rmSync(home, { recursive: true, force: true }));
vi.stubEnv("HOME", home);
vi.stubEnv("LOCALAPPDATA", home);
onTestFinished(() => vi.unstubAllEnvs());
const nonce = newPreviewNonce();
const endpoint = { address: "127.0.0.1", port: 5190 };
const answer = previewConfigPayload({}, 1, "dev", challenge(nonce, endpoint))!;
expect(answer).not.toHaveProperty("isHyperframes");
expect(answer).not.toHaveProperty("projectDir");
expect(provesPreviewOwner(nonce, endpoint, answer)).toBe(true);
});
it("does not claim unrelated direct Vite sessions", () => {
expect(previewConfigPayload({})).toBeNull();
});
+14 -2
View File
@@ -1,16 +1,27 @@
import { PREVIEW_NONCE_HEADER, previewProof } from "@hyperframes/core/preview-proof";
export type PreviewConfigEnv = Record<string, string | undefined>;
type ConfigRequest = Pick<import("node:http").IncomingMessage, "headers" | "socket">;
function signed(config: Record<string, unknown>, req?: ConfigRequest) {
const { localAddress: address, localPort: port } = req?.socket ?? {};
const nonce = req?.headers[PREVIEW_NONCE_HEADER];
const proof = address && port ? previewProof(nonce, { address, port }, config) : null;
return proof ? { ...config, proof } : null;
}
export function previewConfigPayload(
env: PreviewConfigEnv,
pid = process.pid,
version = "dev",
req?: ConfigRequest,
): Record<string, unknown> | null {
const projectDir = env.HYPERFRAMES_PREVIEW_PROJECT_DIR;
const projectName = env.HYPERFRAMES_PREVIEW_PROJECT_NAME;
if (!projectDir || !projectName) return null;
// A Studio started by hand serves many projects: it proves only that it is this user's, never a project.
if (!projectDir || !projectName) return signed({ isStudio: true }, req);
const browserGpuMode = env.HYPERFRAMES_PREVIEW_BROWSER_GPU_MODE;
return {
const config = {
isHyperframes: true,
pid,
projectName,
@@ -19,4 +30,5 @@ export function previewConfigPayload(
...(browserGpuMode ? { browserGpuMode } : {}),
version,
};
return signed(config, req) ?? config;
}