Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

refine Studio mutation origin and process cleanup

Qunlin Jinccbc7a1f0c12
diff --git a/packages/provider-hyperframes-local/src/process-tree.ts b/packages/provider-hyperframes-local/src/process-tree.ts
index 5397e05a..a72e43b4 100644
--- a/packages/provider-hyperframes-local/src/process-tree.ts
+++ b/packages/provider-hyperframes-local/src/process-tree.ts
@@ -35,7 +35,7 @@ export async function killRenderTree(pid: number): Promise<void> {
try { process.kill(target, "SIGKILL"); }
catch (error) {
const code = (error as NodeJS.ErrnoException).code;
- if (code !== "ESRCH" && code !== "EPERM") throw error;
+ if (code !== "ESRCH" && !(target < 0 && code === "EPERM")) throw error;
}
}
}
@@ -81,7 +81,7 @@ export function killRenderDescendantsSync(pid: number): void {
try { process.kill(target, "SIGKILL"); }
catch (error) {
const code = (error as NodeJS.ErrnoException).code;
- if (code !== "ESRCH" && code !== "EPERM") throw error;
+ if (code !== "ESRCH" && !(target < 0 && code === "EPERM")) throw error;
}
}
}
diff --git a/packages/runtime-local/src/process-control.ts b/packages/runtime-local/src/process-control.ts
index 5fa5c7c9..cff1eee6 100644
--- a/packages/runtime-local/src/process-control.ts
+++ b/packages/runtime-local/src/process-control.ts
@@ -18,17 +18,19 @@ export function processAlive(pid: number): boolean {
function signal(pid: number, force: boolean): ProcessStopResult {
if (!processAlive(pid)) return "gone";
const name = force ? "SIGKILL" : "SIGTERM";
- let sent = false;
for (const target of [-pid, pid]) {
try {
process.kill(target, name);
- sent = true;
+ return "sent";
} catch (error) {
- if (errorCode(error) === "EPERM" && target === pid) return "denied";
- if (errorCode(error) !== "ESRCH" && errorCode(error) !== "EPERM") throw error;
+ if (errorCode(error) === "EPERM") {
+ if (target < 0) continue;
+ return "denied";
+ }
+ if (errorCode(error) !== "ESRCH") throw error;
}
}
- return sent ? "sent" : "gone";
+ return "gone";
}
/**
diff --git a/packages/runtime-local/test/process-control.test.ts b/packages/runtime-local/test/process-control.test.ts
new file mode 100644
index 00000000..465ea107
--- /dev/null
+++ b/packages/runtime-local/test/process-control.test.ts
@@ -0,0 +1,15 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { stopProcessTree } from "../src/process-control.js";
+
+test("a process-group permission error still tries the owned process", { skip: process.platform === "win32" }, async (t) => {
+ const targets: number[] = [];
+ t.mock.method(process, "kill", (target: number, signal?: NodeJS.Signals | number) => {
+ if (signal === 0) return true;
+ targets.push(target);
+ if (target < 0) throw Object.assign(new Error("group signal denied"), { code: "EPERM" });
+ return true;
+ });
+ assert.equal(await stopProcessTree(4242), "sent");
+ assert.deepEqual(targets, [-4242, 4242]);
+});
diff --git a/packages/studio/src/feedback-server.ts b/packages/studio/src/feedback-server.ts
index 25233645..775417e5 100644
--- a/packages/studio/src/feedback-server.ts
+++ b/packages/studio/src/feedback-server.ts
@@ -3,6 +3,7 @@ import { relative } from "node:path";
import type { Plugin } from "vite";
import { createFeedbackStore, FeedbackConflict } from "./feedback-store.js";
import { readFeedbackMutation } from "./feedback.js";
+import { allowsStudioMutation } from "./mutation-origin.js";
import type { FeedbackDocument, FeedbackView } from "./feedback.js";
/** Review storage is separate from compilation, Results and Agent delivery. */
@@ -23,28 +24,10 @@ export function studioFeedbackPlugin(workspaceRoot: string, runPath: string): Pl
server.httpServer?.once("close", () => watcher.close());
server.middlewares.use((request, response, next) => {
if (new URL(request.url ?? "/", "http://studio.hypit.local").pathname !== "/__studio/feedback") return next();
- const origin = request.headers.origin;
- if (origin !== undefined) {
- try {
- const { hostname } = new URL(origin);
- const isLoopback = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
- if (!isLoopback) {
- response.statusCode = 403;
- response.setHeader("content-type", "application/json; charset=utf-8");
- response.end(JSON.stringify({ error: "Cross-origin feedback mutations are prohibited." }));
- return;
- }
- } catch {
- response.statusCode = 403;
- response.setHeader("content-type", "application/json; charset=utf-8");
- response.end(JSON.stringify({ error: "Invalid request origin." }));
- return;
- }
- }
- if (request.headers["sec-fetch-site"] === "cross-site") {
+ if (request.method === "POST" && !allowsStudioMutation(request.headers)) {
response.statusCode = 403;
response.setHeader("content-type", "application/json; charset=utf-8");
- response.end(JSON.stringify({ error: "Cross-site feedback mutations are prohibited." }));
+ response.end(JSON.stringify({ error: "Studio mutation must come from this local Studio session." }));
return;
}
response.setHeader("content-type", "application/json; charset=utf-8");
diff --git a/packages/studio/src/mutation-origin.ts b/packages/studio/src/mutation-origin.ts
new file mode 100644
index 00000000..e7ae4836
--- /dev/null
+++ b/packages/studio/src/mutation-origin.ts
@@ -0,0 +1,20 @@
+import type { IncomingHttpHeaders } from "node:http";
+
+/** Studio writes belong to the local page serving this Studio session. */
+export function allowsStudioMutation(headers: IncomingHttpHeaders): boolean {
+ const host = headers.host;
+ if (host === undefined) return false;
+ let target: URL;
+ try { target = new URL(`http://${host}`); } catch { return false; }
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(target.hostname) || target.host !== host.toLowerCase()) return false;
+
+ const origin = headers.origin;
+ if (origin !== undefined) {
+ let source: URL;
+ try { source = new URL(origin); } catch { return false; }
+ if (source.origin !== origin || source.origin !== target.origin) return false;
+ }
+
+ const site = headers["sec-fetch-site"];
+ return site === undefined || site === "same-origin" || site === "none";
+}
diff --git a/packages/studio/src/server.ts b/packages/studio/src/server.ts
index 5fb80d1e..a0fc7448 100644
--- a/packages/studio/src/server.ts
+++ b/packages/studio/src/server.ts
@@ -15,6 +15,7 @@ import type { ServedFile } from "./compile.js";
import type { StudioDomain } from "./domain.js";
import type { StudioCompanionRegistry } from "./studio-registry.js";
import { loadStudioRun } from "./run.js";
+import { allowsStudioMutation } from "./mutation-origin.js";
import { parameterAuthorValue, parameterOption, serializeParameterValue, serializeAttributeGroup, validateParameterValue } from "./parameter-values.js";
import { readStudioSession } from "./session.js";
import type { Range, StudioFailure, StudioLibraryRequest, StudioLibraryView, StudioMutation, StudioSnapshot } from "./shared.js";
@@ -76,22 +77,6 @@ function conflict(error: unknown): boolean {
return error instanceof Error && /changed outside Studio|Source changed outside Studio|mutation is already in progress/u.test(error.message);
}
-function isSafeStudioOrigin(request: import("node:http").IncomingMessage): boolean {
- const origin = request.headers.origin;
- if (origin !== undefined) {
- try {
- const { hostname } = new URL(origin);
- const isLoopback = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
- if (!isLoopback) return false;
- } catch {
- return false;
- }
- }
- const secFetchSite = request.headers["sec-fetch-site"];
- if (secFetchSite === "cross-site") return false;
- return true;
-}
-
class StudioMutationRejected extends Error {}
export function studioPlugin(options: StudioPluginOptions): Plugin {
@@ -489,7 +474,7 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
value.middlewares.use((request, response, next) => {
const url = new URL(request.url ?? "/", "http://studio.hypit.local");
if (request.method === "PUT" && url.pathname === "/__studio/source") {
- if (!isSafeStudioOrigin(request)) {
+ if (!allowsStudioMutation(request.headers)) {
json(response, 403, { error: "Cross-origin Studio mutations are prohibited." });
return;
}
@@ -544,7 +529,7 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
return;
}
if (request.method === "PUT" && url.pathname === "/__studio/artifact-name") {
- if (!isSafeStudioOrigin(request)) {
+ if (!allowsStudioMutation(request.headers)) {
json(response, 403, { error: "Cross-origin Studio mutations are prohibited." });
return;
}
@@ -570,7 +555,7 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
return;
}
if (request.method === "POST" && url.pathname === "/__studio/mutation") {
- if (!isSafeStudioOrigin(request)) {
+ if (!allowsStudioMutation(request.headers)) {
json(response, 403, { error: "Cross-origin Studio mutations are prohibited." });
return;
}
diff --git a/packages/studio/test/mutation-origin.test.ts b/packages/studio/test/mutation-origin.test.ts
new file mode 100644
index 00000000..db792b96
--- /dev/null
+++ b/packages/studio/test/mutation-origin.test.ts
@@ -0,0 +1,57 @@
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import type { FSWatcher } from "node:fs";
+import { mkdtemp, rm } from "node:fs/promises";
+import { createServer } from "node:http";
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { syncBuiltinESMExports } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import type { ViteDevServer } from "vite";
+import { studioFeedbackPlugin } from "../src/feedback-server.js";
+import { allowsStudioMutation } from "../src/mutation-origin.js";
+
+test("Studio mutations accept the actual local page and local non-browser clients", () => {
+ assert.equal(allowsStudioMutation({ host: "localhost:5173", origin: "http://localhost:5173", "sec-fetch-site": "same-origin" }), true);
+ assert.equal(allowsStudioMutation({ host: "127.0.0.1:5173" }), true);
+});
+
+test("Studio mutations reject other pages even when they use a loopback hostname", () => {
+ assert.equal(allowsStudioMutation({ host: "localhost:5173", origin: "https://example.com", "sec-fetch-site": "cross-site" }), false);
+ assert.equal(allowsStudioMutation({ host: "localhost:5173", origin: "http://localhost:4000", "sec-fetch-site": "same-site" }), false);
+ assert.equal(allowsStudioMutation({ host: "localhost:5173", "sec-fetch-site": "cross-site" }), false);
+ assert.equal(allowsStudioMutation({ host: "example.com:5173", origin: "http://example.com:5173" }), false);
+});
+
+test("the feedback write endpoint rejects a foreign page before reading its mutation", async (t) => {
+ t.mock.method(fs, "watch", () => ({ close() {} }) as FSWatcher);
+ syncBuiltinESMExports();
+ t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports(); });
+ const root = await mkdtemp(join(tmpdir(), "hypit-studio-origin-"));
+ let middleware: ((request: IncomingMessage, response: ServerResponse, next: () => void) => void) | undefined;
+ const server = createServer((request, response) => {
+ assert.ok(middleware);
+ middleware(request, response, () => { response.statusCode = 404; response.end(); });
+ });
+ const plugin = studioFeedbackPlugin(root, join(root, "runs", "main.svrun"));
+ (plugin.configureServer as (server: ViteDevServer) => void)({
+ httpServer: server,
+ ws: { send() {} },
+ middlewares: { use(handler: typeof middleware) { middleware = handler; } },
+ } as unknown as ViteDevServer);
+ try {
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ assert.ok(address && typeof address === "object");
+ const url = `http://127.0.0.1:${address.port}/__studio/feedback`;
+ const foreign = await fetch(url, { method: "POST", headers: { origin: "https://example.com" }, body: "{}" });
+ assert.equal(foreign.status, 403);
+ const local = await fetch(url, { method: "POST", headers: { origin: new URL(url).origin }, body: "{}" });
+ assert.equal(local.status, 400, "the local request reaches ordinary mutation validation");
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/packages/video-cli/src/process.ts b/packages/video-cli/src/process.ts
index d731eb02..b92defa5 100644
--- a/packages/video-cli/src/process.ts
+++ b/packages/video-cli/src/process.ts
@@ -9,12 +9,10 @@ function run(
args: readonly string[],
input: ProcessInput | undefined,
timeoutMs: number,
- maxStdoutBytes = 100 * 1024 * 1024,
): Promise<ProcessOutput> {
return new Promise((resolveRun, reject) => {
const child = spawn(executable, [...args], { stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], windowsHide: true });
const out: Buffer[] = [];
- let stdoutBytes = 0;
let err = "";
let settled = false;
const finish = (error?: Error): void => {
@@ -25,15 +23,7 @@ function run(
else reject(error);
};
const timer = setTimeout(() => { child.kill("SIGKILL"); finish(new Error(`${executable} timed out after ${timeoutMs} ms`)); }, timeoutMs);
- child.stdout?.on("data", (chunk: Buffer) => {
- stdoutBytes += chunk.byteLength;
- if (stdoutBytes > maxStdoutBytes) {
- child.kill("SIGKILL");
- finish(new Error(`${executable} stdout exceeded the limit of ${maxStdoutBytes} bytes`));
- return;
- }
- out.push(chunk);
- });
+ child.stdout?.on("data", (chunk: Buffer) => out.push(chunk));
child.stderr?.on("data", (chunk: Buffer) => { err = `${err}${chunk.toString("utf8")}`.slice(-100_000); });
child.on("error", (error) => finish(new Error(`${executable} could not start: ${error.message}`)));
child.on("close", (code) => {