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.

fix(security,runtime): prevent CSRF in studio, make video download async and sanitize process signals

alexqem55141ed8fafd
diff --git a/packages/provider-hyperframes-local/src/process-tree.ts b/packages/provider-hyperframes-local/src/process-tree.ts
index 086f59bf..5397e05a 100644
--- a/packages/provider-hyperframes-local/src/process-tree.ts
+++ b/packages/provider-hyperframes-local/src/process-tree.ts
@@ -33,7 +33,10 @@ export async function killRenderTree(pid: number): Promise<void> {
for (const child of descendants.reverse()) {
for (const target of [-child, child]) {
try { process.kill(target, "SIGKILL"); }
- catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
+ catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== "ESRCH" && code !== "EPERM") throw error;
+ }
}
}
const deadline = Date.now() + cleanupMs;
@@ -76,7 +79,10 @@ export function killRenderDescendantsSync(pid: number): void {
for (const child of descendants.slice(1).reverse()) {
for (const target of [-child, child]) {
try { process.kill(target, "SIGKILL"); }
- catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
+ catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== "ESRCH" && code !== "EPERM") throw error;
+ }
}
}
}
diff --git a/packages/runtime-local/src/process-control.ts b/packages/runtime-local/src/process-control.ts
index 85b3a3cd..5fa5c7c9 100644
--- a/packages/runtime-local/src/process-control.ts
+++ b/packages/runtime-local/src/process-control.ts
@@ -18,16 +18,17 @@ 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);
- return "sent";
+ sent = true;
} catch (error) {
- if (errorCode(error) === "EPERM") return "denied";
- if (errorCode(error) !== "ESRCH") throw error;
+ if (errorCode(error) === "EPERM" && target === pid) return "denied";
+ if (errorCode(error) !== "ESRCH" && errorCode(error) !== "EPERM") throw error;
}
}
- return "gone";
+ return sent ? "sent" : "gone";
}
/**
diff --git a/packages/studio/src/feedback-server.ts b/packages/studio/src/feedback-server.ts
index 8b817d73..25233645 100644
--- a/packages/studio/src/feedback-server.ts
+++ b/packages/studio/src/feedback-server.ts
@@ -23,6 +23,30 @@ 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") {
+ response.statusCode = 403;
+ response.setHeader("content-type", "application/json; charset=utf-8");
+ response.end(JSON.stringify({ error: "Cross-site feedback mutations are prohibited." }));
+ return;
+ }
response.setHeader("content-type", "application/json; charset=utf-8");
response.setHeader("cache-control", "no-store");
void (async () => {
diff --git a/packages/studio/src/server.ts b/packages/studio/src/server.ts
index 70936748..5fb80d1e 100644
--- a/packages/studio/src/server.ts
+++ b/packages/studio/src/server.ts
@@ -76,6 +76,22 @@ 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 {
@@ -473,6 +489,10 @@ 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)) {
+ json(response, 403, { error: "Cross-origin Studio mutations are prohibited." });
+ return;
+ }
void (async () => {
let acquired = false;
try {
@@ -524,6 +544,10 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
return;
}
if (request.method === "PUT" && url.pathname === "/__studio/artifact-name") {
+ if (!isSafeStudioOrigin(request)) {
+ json(response, 403, { error: "Cross-origin Studio mutations are prohibited." });
+ return;
+ }
void (async () => {
try {
const chunks: Buffer[] = [];
@@ -546,6 +570,10 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {
return;
}
if (request.method === "POST" && url.pathname === "/__studio/mutation") {
+ if (!isSafeStudioOrigin(request)) {
+ json(response, 403, { error: "Cross-origin Studio mutations are prohibited." });
+ return;
+ }
void (async () => {
try {
const chunks: Buffer[] = [];
diff --git a/packages/video-cli/src/process.ts b/packages/video-cli/src/process.ts
index b92defa5..d731eb02 100644
--- a/packages/video-cli/src/process.ts
+++ b/packages/video-cli/src/process.ts
@@ -9,10 +9,12 @@ 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 => {
@@ -23,7 +25,15 @@ 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) => out.push(chunk));
+ 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.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) => {
diff --git a/packages/yt-dlp/src/download.ts b/packages/yt-dlp/src/download.ts
index 4af27079..52110428 100644
--- a/packages/yt-dlp/src/download.ts
+++ b/packages/yt-dlp/src/download.ts
@@ -10,13 +10,22 @@
* keep changing, so an unpinned copy makes the same link fetch differently on two machines. This is
* the same shape WhisperX and OpenCV already use for their Python programs.
*/
-import { spawnSync } from "node:child_process";
+import { execFile } from "node:child_process";
import { copyFile, mkdtemp, readdir, rename, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { extname, join } from "node:path";
import { requireVideoDownload } from "./environment.js";
+function runExec(file: string, args: readonly string[], options: { readonly timeout?: number; readonly maxBuffer?: number; readonly signal?: AbortSignal | undefined } = {}): Promise<{ readonly stdout: string; readonly stderr: string }> {
+ return new Promise((resolve, reject) => {
+ execFile(file, [...args], { encoding: "utf8", windowsHide: true, ...options }, (error, stdout, stderr) => {
+ if (error !== null) reject(Object.assign(error, { stdout, stderr }));
+ else resolve({ stdout: String(stdout), stderr: String(stderr) });
+ });
+ });
+}
+
/**
* Whether this is a link to fetch rather than a path to open.
*
@@ -42,30 +51,35 @@ export function isVideoUrl(value: string): boolean {
* nothing under the bound. `--no-playlist` keeps a link inside a playlist from fetching the playlist.
* The container follows the target's extension.
*/
-export async function downloadVideo(url: string, target: string): Promise<void> {
+export async function downloadVideo(url: string, target: string, options: { readonly signal?: AbortSignal } = {}): Promise<void> {
const container = extname(target).slice(1).toLowerCase();
if (!["mp4", "mkv", "webm", "mov"].includes(container)) {
throw new Error(`${target} must end in .mp4, .mkv, .webm or .mov`);
}
const executable = requireVideoDownload();
- const media = spawnSync("ffmpeg", ["-version"], { encoding: "utf8", windowsHide: true, timeout: 15_000 });
- if (media.status !== 0) throw new Error("FFmpeg is unavailable on PATH; install your selected media toolchain before fetching video");
+ try {
+ await runExec("ffmpeg", ["-version"], { timeout: 15_000, signal: options.signal });
+ } catch (error) {
+ if (options.signal?.aborted) throw error;
+ throw new Error("FFmpeg is unavailable on PATH; install your selected media toolchain before fetching video");
+ }
const work = await mkdtemp(join(tmpdir(), "hypit-fetch-"));
try {
- const result = spawnSync(executable, [
- "--ignore-config", "--no-update", "--no-remote-components", "--no-plugin-dirs",
- "--no-js-runtimes", "--js-runtimes", `node:${process.execPath}`,
- "--no-playlist", "--no-progress", "--quiet",
- "--format", "bv*+ba/b",
- "--merge-output-format", container,
- "--format-sort", "res:1080,vcodec:h264",
- "--output", join(work, "video.%(ext)s"),
- url,
- ], { encoding: "utf8", windowsHide: true, timeout: 900_000 });
-
- if (result.error !== undefined) throw result.error;
- if (result.status !== 0) {
- throw new Error(`yt-dlp could not fetch ${url}: ${(result.stderr ?? "").trim().slice(-2000)}`);
+ try {
+ await runExec(executable, [
+ "--ignore-config", "--no-update", "--no-remote-components", "--no-plugin-dirs",
+ "--no-js-runtimes", "--js-runtimes", `node:${process.execPath}`,
+ "--no-playlist", "--no-progress", "--quiet",
+ "--format", "bv*+ba/b",
+ "--merge-output-format", container,
+ "--format-sort", "res:1080,vcodec:h264",
+ "--output", join(work, "video.%(ext)s"),
+ url,
+ ], { timeout: 900_000, maxBuffer: 10 * 1024 * 1024, signal: options.signal });
+ } catch (cause) {
+ if (options.signal?.aborted) throw cause;
+ const error = cause as { stderr?: string; message?: string };
+ throw new Error(`yt-dlp could not fetch ${url}: ${(error.stderr ?? error.message ?? "").trim().slice(-2000)}`);
}
const finished = (await readdir(work)).filter((name) => !name.endsWith(".part"));
const [file] = finished.sort();
diff --git a/packages/yt-dlp/test/download.test.ts b/packages/yt-dlp/test/download.test.ts
index ea5da859..b276c869 100644
--- a/packages/yt-dlp/test/download.test.ts
+++ b/packages/yt-dlp/test/download.test.ts
@@ -62,14 +62,23 @@ test("download resolves its declared service from an installed package outside t
calls++;
assert.notEqual(command, "uv", "fetch must not run the environment installer");
if (args.includes("--version")) return { status: 0, stderr: "", stdout: "2026.08.19\n" };
- if (command === "ffmpeg") return { status: 0, stderr: "", stdout: "ffmpeg" };
+ return { status: 0, stderr: "", stdout: "" };
+ });
+ t.mock.method(childProcess, "execFile", (command: string, ...rest: unknown[]) => {
+ calls++;
+ const callback = (typeof rest.at(-1) === "function" ? rest.at(-1) : undefined) as ((err: Error | null, stdout: string, stderr: string) => void) | undefined;
+ const args = (Array.isArray(rest[0]) ? rest[0] : []) as string[];
+ if (command === "ffmpeg") {
+ callback?.(null, "ffmpeg", "");
+ return;
+ }
assert.match(command, /yt-dlp/u);
assert.ok(args.includes("--no-remote-components"));
assert.ok(args.includes("--ignore-config"));
assert.equal(args.at(-1), "https://example.test/video");
const output = args[args.indexOf("--output") + 1]!.replace("%(ext)s", "mp4");
writeFileSync(output, "downloaded bytes");
- return { status: 0, stderr: "", stdout: "" };
+ callback?.(null, "", "");
});
syncBuiltinESMExports();
t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports(); });