fix(cli): check and snapshot run where a sandbox refuses to listen on localhost (#5618)

This commit is contained in:
Miguel Ángel
2026-10-14 19:19:37 +00:00
committed by GitHub
parent b14a456471
commit 71595dd820
4 changed files with 266 additions and 7 deletions
+105 -1
View File
@@ -1,4 +1,5 @@
import { createServer, type ServerResponse } from "node:http";
import { createServer, request as httpRequest, type Server, type ServerResponse } from "node:http";
import { Duplex } from "node:stream";
import { createReadStream, existsSync, statSync } from "node:fs";
import { isAbsolute, relative, resolve } from "node:path";
import { getMimeType } from "@hyperframes/core/studio-api";
@@ -22,8 +23,92 @@ import {
export interface StaticProjectServer {
url: string;
/** 0 when nothing listens: the server answers in this process only (see `answer`). */
port: number;
close: () => Promise<void>;
/** Set when a sandbox refused listen(): the browser's requests to `url` come here instead of a socket. */
answer?: (request: InProcessRequest) => Promise<InProcessResponse>;
}
export interface InProcessRequest {
method: string;
/** Path and query, e.g. `/assets/a.mp4?hf-proxy=alpha`. */
path: string;
headers: Record<string, string>;
}
export interface InProcessResponse {
status: number;
headers: Record<string, string>;
body: Buffer;
}
/** A sandbox refuses a loopback listen() with one of these; any other bind error stays fatal. */
const REFUSED_LISTEN = new Set(["EPERM", "EACCES"]);
/** Two connected in-memory sockets: what one side writes, the other reads. */
function socketPair(): [Duplex, Duplex] {
const sides: Duplex[] = [];
const side = (other: () => Duplex) =>
new Duplex({
read() {},
write(chunk, _encoding, done) {
other().push(chunk);
done();
},
final(done) {
other().push(null);
done();
},
});
sides.push(
side(() => sides[1]!),
side(() => sides[0]!),
);
return [sides[0]!, sides[1]!];
}
/** Hands one request to `server` over an in-memory socket, so its handler (Range, proxies) answers unchanged. */
function answerInProcess(server: Server, request: InProcessRequest): Promise<InProcessResponse> {
const [client, served] = socketPair();
server.emit("connection", served);
return new Promise((resolveAnswer, rejectAnswer) => {
const req = httpRequest(
{
method: request.method,
path: request.path,
headers: { ...request.headers, connection: "close" },
// No `agent`: Node uses createConnection only when no agent is given.
createConnection: () => client as never,
},
(res) => {
const chunks: Buffer[] = [];
res.on("data", (chunk: Buffer) => chunks.push(chunk));
res.on("error", rejectAnswer);
res.on("end", () => {
const headers: Record<string, string> = {};
for (const [name, value] of Object.entries(res.headers)) {
if (value !== undefined && name !== "connection" && name !== "transfer-encoding")
headers[name] = Array.isArray(value) ? value.join(", ") : value;
}
resolveAnswer({ status: res.statusCode ?? 500, headers, body: Buffer.concat(chunks) });
});
},
);
req.on("error", rejectAnswer);
req.end();
});
}
let inProcessServers = 0;
const inProcessAnswers = new Map<
string,
(request: InProcessRequest) => Promise<InProcessResponse>
>();
/** The in-process answer for a URL served by `serveStaticProjectHtml` when listen() was refused, else undefined. */
export function inProcessAnswer(url: string) {
return inProcessAnswers.get(new URL(url).origin);
}
/**
@@ -229,8 +314,27 @@ export async function serveStaticProjectHtml(
if (!resolvedPort) rejectPort(new Error(bindErrorMessage));
else resolvePort(resolvedPort);
});
}).catch((error: unknown) => {
if (REFUSED_LISTEN.has((error as NodeJS.ErrnoException).code ?? "")) return 0;
throw error;
});
if (port === 0) {
server.removeAllListeners("error");
// A sandbox (e.g. an agent's) may refuse listen(); the browser asks this origin and the process answers.
const url = `http://hyperframes-${++inProcessServers}.localhost/`;
const answer = (request: InProcessRequest) => answerInProcess(server, request);
inProcessAnswers.set(new URL(url).origin, answer);
return {
url,
port: 0,
close: async () => {
inProcessAnswers.delete(new URL(url).origin);
},
answer,
};
}
return {
url: `http://127.0.0.1:${port}/`,
port,