mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(studio-server): file routes and the received-files follower read one path (#8652)
requestSubPath now matches its route on decoded segments, as Hono does, and returns null when the route is not in the URL. Every caller refuses that request. The received-files follower refuses it too, so it and the file route always act on the same path. The /api forwarder strips the first segment however it is spelled.
This commit is contained in:
@@ -239,6 +239,7 @@ export async function registerCompositionRoute(
|
||||
// fallow-ignore-next-line complexity
|
||||
app.get("/composition/*", async (ctx) => {
|
||||
const reqPath = requestSubPath(ctx.req.url, "composition");
|
||||
if (reqPath === null) return ctx.text("Not found", 404);
|
||||
const filePath = resolve(project.dir, reqPath);
|
||||
|
||||
// Security: don't allow path traversal outside project dir. isSafePath
|
||||
|
||||
@@ -327,6 +327,7 @@ export async function registerPresentCompositionRoute(
|
||||
sandboxForAnotherSite(app, "/composition/*");
|
||||
app.get("/composition/*", (ctx) => {
|
||||
const reqPath = requestSubPath(ctx.req.url, "composition");
|
||||
if (reqPath === null) return ctx.text("Not found", 404);
|
||||
const filePath = resolve(project.dir, reqPath);
|
||||
// Security: canonicalizes symlinks + guards the trailing separator so neither
|
||||
// an in-project symlink nor a sibling dir sharing the prefix can escape.
|
||||
|
||||
@@ -35,6 +35,8 @@ const busy = (c: Context) =>
|
||||
409,
|
||||
);
|
||||
|
||||
const notFound = (c: Context) => c.json({ error: "not found" }, 404);
|
||||
|
||||
const jsonBody = (c: Context): Promise<unknown> =>
|
||||
c.req.raw
|
||||
.clone()
|
||||
@@ -53,7 +55,8 @@ async function requestedChange(
|
||||
c: Context,
|
||||
projectDir: string,
|
||||
): Promise<{ from: string; to?: string } | null> {
|
||||
const from = writablePath(projectDir, requestSubPath(c.req.url, "projects/:id/files"));
|
||||
const named = requestSubPath(c.req.url, "projects/:id/files");
|
||||
const from = named === null ? null : writablePath(projectDir, named);
|
||||
if (from === null) return null;
|
||||
if (c.req.method !== "PATCH") return { from };
|
||||
const newPath = textAt(await jsonBody(c), "newPath")[0];
|
||||
@@ -79,6 +82,7 @@ async function startedChange(
|
||||
*/
|
||||
function followMovesAndDeletes(app: Hono, projectDir: string): void {
|
||||
app.on(["PATCH", "DELETE"], "/api/projects/:id/files/*", async (c, next) => {
|
||||
if (requestSubPath(c.req.url, "projects/:id/files") === null) return notFound(c);
|
||||
const requested = await requestedChange(c, projectDir);
|
||||
if (requested === null) return next();
|
||||
const change = await startedChange(projectDir, requested);
|
||||
@@ -114,11 +118,12 @@ const SAVES_NAMING_THE_FILE = [
|
||||
"gsap-mutation-rollback",
|
||||
];
|
||||
|
||||
async function savedPaths(c: Context): Promise<string[]> {
|
||||
async function savedPaths(c: Context): Promise<string[] | null> {
|
||||
const route = SAVES_NAMING_THE_FILE.find((prefix) =>
|
||||
c.req.routePath.startsWith(`/api/projects/:id/${prefix}/`),
|
||||
);
|
||||
const named = route === undefined ? "" : requestSubPath(c.req.url, `projects/:id/${route}`);
|
||||
if (named === null) return null;
|
||||
if (named) return [named];
|
||||
const body = await jsonBody(c);
|
||||
return [
|
||||
@@ -134,7 +139,9 @@ async function savedPaths(c: Context): Promise<string[]> {
|
||||
*/
|
||||
function followSaves(app: Hono, projectDir: string): void {
|
||||
const relistBeforeSave = async (c: Context, next: () => Promise<void>) => {
|
||||
const paths = (await savedPaths(c)).flatMap((path) => writablePath(projectDir, path) ?? []);
|
||||
const saved = await savedPaths(c);
|
||||
if (saved === null) return notFound(c);
|
||||
const paths = saved.flatMap((path) => writablePath(projectDir, path) ?? []);
|
||||
try {
|
||||
await relistReceivedContent(projectDir, paths.filter(isFile));
|
||||
} catch {
|
||||
|
||||
@@ -198,6 +198,78 @@ describe("a received folder with its own record, in a project with none", () =>
|
||||
});
|
||||
});
|
||||
|
||||
describe("a file request whose route segments are percent-encoded", () => {
|
||||
const ENCODED = "/api/pr%6Fjects/film/files/";
|
||||
const TAILS = [
|
||||
["the folder named plainly", "sub"],
|
||||
["the folder reached through encoded dot segments", "..%2F..%2Fsub"],
|
||||
] as const;
|
||||
|
||||
function withReceivedFolder(projectDir: string): void {
|
||||
write(join(projectDir, "index.html"), `<div data-composition-src="sub/scene.html"></div>`);
|
||||
write(join(projectDir, "sub", "scene.html"), `<img src="../../outside/pic.png">`);
|
||||
write(
|
||||
join(projectDir, "sub", ".hyperframes", "received-files.json"),
|
||||
JSON.stringify({ files: ["scene.html"] }),
|
||||
);
|
||||
}
|
||||
/** The folder is either still there, or gone with its received page listed in the project's own record. */
|
||||
function expectStillReceived(projectDir: string, at: string): void {
|
||||
if (existsSync(join(projectDir, "sub", "scene.html"))) return;
|
||||
expect(receivedFiles(projectDir)(at)).toBe(true);
|
||||
expect(allowed(projectDir)).toBe(false);
|
||||
}
|
||||
|
||||
it.each(TAILS)("keeps a folder delete received for %s", async (_, tail) => {
|
||||
const { projectDir, app } = studio();
|
||||
withReceivedFolder(projectDir);
|
||||
const deleted = await app.request(`${ENCODED}${tail}`, { method: "DELETE" });
|
||||
expect([200, 403, 404]).toContain(deleted.status);
|
||||
expectStillReceived(projectDir, "sub/scene.html");
|
||||
});
|
||||
|
||||
it.each(TAILS)("keeps a folder move received for %s", async (_, tail) => {
|
||||
const { projectDir, app } = studio();
|
||||
withReceivedFolder(projectDir);
|
||||
const moved = await app.request(`${ENCODED}${tail}`, {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ newPath: "dist" }),
|
||||
});
|
||||
expect([200, 403, 404]).toContain(moved.status);
|
||||
expectStillReceived(projectDir, "dist/scene.html");
|
||||
});
|
||||
|
||||
it("deletes the folder named plainly, listing its received page first", async () => {
|
||||
const { projectDir, app } = studio();
|
||||
withReceivedFolder(projectDir);
|
||||
expect((await app.request(`${ENCODED}sub`, { method: "DELETE" })).status).toBe(200);
|
||||
expect(existsSync(join(projectDir, "sub"))).toBe(false);
|
||||
expect(receivedFiles(projectDir)("sub/scene.html")).toBe(true);
|
||||
});
|
||||
|
||||
it("lists a page holding received content again before an encoded save changes it", async () => {
|
||||
const { projectDir, app } = studio();
|
||||
withReceivedFolder(projectDir);
|
||||
const scene = join(projectDir, "sub", "scene.html");
|
||||
const before = readFileSync(scene);
|
||||
expect((await app.request(`${ENCODED}sub%2Fscene.html`, { method: "DELETE" })).status).toBe(
|
||||
200,
|
||||
);
|
||||
rmSync(join(projectDir, "sub", ".hyperframes"), { recursive: true });
|
||||
write(join(projectDir, ".hyperframes", "received-files.json"), JSON.stringify({ files: [] }));
|
||||
writeFileSync(scene, before);
|
||||
const saved = await app.request(`${ENCODED}sub%2Fscene.html`, {
|
||||
method: "PUT",
|
||||
headers: { "If-Match": fileContentVersion(before) },
|
||||
body: `<img src="../../outside/pic.png"><p>2</p>`,
|
||||
});
|
||||
expect(saved.status).toBe(200);
|
||||
const record = join(projectDir, ".hyperframes", "received-files.json");
|
||||
expect(JSON.parse(readFileSync(record, "utf-8")).files).toContain("sub/scene.html");
|
||||
});
|
||||
});
|
||||
|
||||
describe("a Studio rename, move or delete in a project with a received-files record", () => {
|
||||
const record = (folder: string) => join(folder, ".hyperframes", "received-files.json");
|
||||
const listed = (folder: string) => JSON.parse(readFileSync(record(folder), "utf-8")).files;
|
||||
|
||||
@@ -1212,7 +1212,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
|
||||
const api = createStudioApi(adapter, { allowedHosts, sandboxThumbnailCaptures: true });
|
||||
app.all("/api/*", async (c) => {
|
||||
const url = new URL(c.req.url);
|
||||
url.pathname = url.pathname.slice(4); // Strip "/api" prefix
|
||||
url.pathname = url.pathname.replace(/^\/[^/]*/, ""); // Strip the "/api" segment however it is spelled
|
||||
const forwardReq = new Request(url.toString(), {
|
||||
method: c.req.method,
|
||||
headers: c.req.raw.headers,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { requestSubPath } from "./requestSubPath";
|
||||
|
||||
const ROUTE = "projects/:id/files";
|
||||
|
||||
describe("requestSubPath", () => {
|
||||
it.each([
|
||||
["/api/projects/film/files/scenes/intro.html", "/projects/film/files/scenes/intro.html"],
|
||||
["/api/pr%6Fjects/film/files/sub", "/pr%6Fjects/film/files/sub"],
|
||||
["/api/projects/film/fil%65s/a%20b.html", "/projects/film/fil%65s/a%20b.html"],
|
||||
["/api/pr%6Fjects/film/files/..%2F..%2Fsub", "/pr%6Fjects/film/files/..%2F..%2Fsub"],
|
||||
])("reads the same path from %s before and after /api is stripped", (outer, inner) => {
|
||||
const before = requestSubPath(`http://localhost${outer}`, ROUTE);
|
||||
expect(before).not.toBeNull();
|
||||
expect(requestSubPath(`http://localhost${inner}`, ROUTE)).toBe(before);
|
||||
});
|
||||
|
||||
it("decodes the path after the route", () => {
|
||||
expect(requestSubPath("http://localhost/pr%6Fjects/film/files/..%2F..%2Fsub", ROUTE)).toBe(
|
||||
"../../sub",
|
||||
);
|
||||
expect(requestSubPath("http://localhost/projects/film/files/100%.png", ROUTE)).toBe("100%.png");
|
||||
});
|
||||
|
||||
it("finds the route where it first appears", () => {
|
||||
expect(
|
||||
requestSubPath("http://localhost/projects/film/files/projects/x/files/a.html", ROUTE),
|
||||
).toBe("projects/x/files/a.html");
|
||||
});
|
||||
|
||||
it("gives no path when the route is not in the URL", () => {
|
||||
expect(requestSubPath("http://localhost/api/project/film/files/a.html", ROUTE)).toBeNull();
|
||||
expect(requestSubPath("http://localhost/projects/film", ROUTE)).toBeNull();
|
||||
expect(requestSubPath("http://localhost/elsewhere/a.html", "composition")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -5,10 +5,18 @@ export { decodeWellFormedEscapes } from "@hyperframes/parsers/asset-paths";
|
||||
|
||||
// The decoded path after `route` ("projects/:id/preview", "composition"), cut by segment from the raw URL:
|
||||
// Hono's c.req.path leaves %40 %25 %23 %26 %3F encoded, so cutting a decoded prefix out of it misses.
|
||||
export function requestSubPath(url: string, route: string): string {
|
||||
// The route's segments match decoded, as Hono matched them; null when the route is not in the URL.
|
||||
export function requestSubPath(url: string, route: string): string | null {
|
||||
const routeSegments = route.split("/");
|
||||
const segments = new URL(url).pathname.split("/");
|
||||
const start = segments.indexOf(routeSegments[0] ?? "");
|
||||
const matchesAt = (start: number) =>
|
||||
routeSegments.every(
|
||||
(part, at) =>
|
||||
start + at < segments.length &&
|
||||
(part.startsWith(":") || decodeWellFormedEscapes(segments[start + at]!) === part),
|
||||
);
|
||||
const start = segments.findIndex((_, at) => matchesAt(at));
|
||||
if (start < 0) return null;
|
||||
return decodeWellFormedEscapes(segments.slice(start + routeSegments.length).join("/"));
|
||||
}
|
||||
|
||||
|
||||
@@ -224,6 +224,7 @@ async function resolveProjectPath(
|
||||
}
|
||||
|
||||
const filePath = requestSubPath(c.req.url, `projects/:id/${route}`);
|
||||
if (filePath === null) return { error: c.json({ error: "not found" }, 404) } as const;
|
||||
if (filePath.includes("\0")) {
|
||||
return { error: c.json({ error: "forbidden", why: "nul" }, 403) } as const;
|
||||
}
|
||||
|
||||
@@ -63,6 +63,7 @@ async function resolveSource(adapter: StudioApiAdapter, id: string, url: string)
|
||||
const project = await adapter.resolveProject(id);
|
||||
if (!project) throw new HTTPException(404);
|
||||
const relative = requestSubPath(url, "projects/:id/image-thumbnail");
|
||||
if (relative === null) throw new HTTPException(404);
|
||||
if (!/\.jpe?g$/i.test(relative)) throw new HTTPException(415);
|
||||
const path = pinWithinProject(project.dir, relative);
|
||||
if (!path) throw new HTTPException(404);
|
||||
|
||||
@@ -18,6 +18,7 @@ export function registerPeakRoutes(
|
||||
const project = await adapter.resolveProject(c.req.param("id"));
|
||||
if (!project) return c.json({ error: "not found" }, 404);
|
||||
const assetPath = requestSubPath(c.req.url, "projects/:id/peaks");
|
||||
if (assetPath === null) return c.json({ error: "file not found" }, 404);
|
||||
const mediaPath = resolve(project.dir, assetPath);
|
||||
if (!isWithinProjectRoot(project.dir, mediaPath))
|
||||
return c.json({ error: "file not found" }, 404);
|
||||
|
||||
@@ -872,10 +872,8 @@ export function registerPreviewRoutes(
|
||||
const vars = previewVariablesFromRequest(c.req.query("variables"));
|
||||
if (vars.error !== undefined) return c.json({ error: vars.error }, 400);
|
||||
const previewVariables = vars.values;
|
||||
const compFile = resolveWithinProject(
|
||||
project.dir,
|
||||
requestSubPath(c.req.url, "projects/:id/preview/comp"),
|
||||
);
|
||||
const requested = requestSubPath(c.req.url, "projects/:id/preview/comp");
|
||||
const compFile = requested === null ? null : resolveWithinProject(project.dir, requested);
|
||||
// The sub-composition document takes its head from the root.
|
||||
await recordPreviewReadsOff(project.dir, compFile ? [compFile, "index.html"] : ["index.html"]);
|
||||
if (!compFile || !existsSync(compFile) || !statSync(compFile).isFile()) {
|
||||
@@ -953,6 +951,7 @@ export function registerPreviewRoutes(
|
||||
const project = await adapter.resolveProject(c.req.param("id"));
|
||||
if (!project) return c.json({ error: "not found" }, 404);
|
||||
const subPath = requestSubPath(c.req.url, "projects/:id/preview");
|
||||
if (subPath === null) return c.text("not found", 404);
|
||||
// Assets are read-only and should mirror the renderer: permit a path that
|
||||
// is lexically inside the project even if an explicit project symlink
|
||||
// targets a shared directory outside it. Composition source files still
|
||||
|
||||
@@ -141,6 +141,7 @@ export function registerThumbnailRoutes(
|
||||
const { project, signature: projectSignature } = resolved;
|
||||
|
||||
let compPath = requestSubPath(c.req.url, "projects/:id/thumbnail");
|
||||
if (compPath === null) return c.json({ error: "not found" }, 404);
|
||||
if (compPath && !compPath.includes(".")) compPath += ".html";
|
||||
const htmlFile = resolveWithinProject(project.dir, compPath);
|
||||
const source = htmlFile ? readFileOnce(htmlFile) : "not-a-file";
|
||||
|
||||
@@ -18,6 +18,7 @@ export function registerWaveformRoutes(api: Hono, adapter: StudioApiAdapter): vo
|
||||
if (!project) return c.json({ error: "not found" }, 404);
|
||||
|
||||
const assetPath = requestSubPath(c.req.url, "projects/:id/waveform");
|
||||
if (assetPath === null) return c.json({ error: "file not found" }, 404);
|
||||
const audioPath = resolve(project.dir, assetPath);
|
||||
if (!isWithinProjectRoot(project.dir, audioPath)) {
|
||||
return c.json({ error: "file not found" }, 404);
|
||||
|
||||
Reference in New Issue
Block a user