diff --git a/packages/cli/src/commands/play.ts b/packages/cli/src/commands/play.ts index a865124b64..a92fea553a 100644 --- a/packages/cli/src/commands/play.ts +++ b/packages/cli/src/commands/play.ts @@ -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 diff --git a/packages/cli/src/commands/present.ts b/packages/cli/src/commands/present.ts index e32202a508..6fe5e20e91 100644 --- a/packages/cli/src/commands/present.ts +++ b/packages/cli/src/commands/present.ts @@ -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. diff --git a/packages/cli/src/server/followReceivedRecords.ts b/packages/cli/src/server/followReceivedRecords.ts index 33d6a9e385..a3dda9b75d 100644 --- a/packages/cli/src/server/followReceivedRecords.ts +++ b/packages/cli/src/server/followReceivedRecords.ts @@ -35,6 +35,8 @@ const busy = (c: Context) => 409, ); +const notFound = (c: Context) => c.json({ error: "not found" }, 404); + const jsonBody = (c: Context): Promise => 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 { +async function savedPaths(c: Context): Promise { 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 { */ function followSaves(app: Hono, projectDir: string): void { const relistBeforeSave = async (c: Context, next: () => Promise) => { - 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 { diff --git a/packages/cli/src/server/studioServer.receivedRecord.test.ts b/packages/cli/src/server/studioServer.receivedRecord.test.ts index 4ca5e47e9f..a624beebab 100644 --- a/packages/cli/src/server/studioServer.receivedRecord.test.ts +++ b/packages/cli/src/server/studioServer.receivedRecord.test.ts @@ -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"), `
`); + write(join(projectDir, "sub", "scene.html"), ``); + 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: `

2

`, + }); + 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; diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index dcb3f13589..a8edc1c9c2 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -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, diff --git a/packages/studio-server/src/helpers/requestSubPath.test.ts b/packages/studio-server/src/helpers/requestSubPath.test.ts new file mode 100644 index 0000000000..35362d2e7e --- /dev/null +++ b/packages/studio-server/src/helpers/requestSubPath.test.ts @@ -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(); + }); +}); diff --git a/packages/studio-server/src/helpers/requestSubPath.ts b/packages/studio-server/src/helpers/requestSubPath.ts index 5a3384392a..3f5d59a0ee 100644 --- a/packages/studio-server/src/helpers/requestSubPath.ts +++ b/packages/studio-server/src/helpers/requestSubPath.ts @@ -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("/")); } diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts index 7877ce4aea..87d5c487bc 100644 --- a/packages/studio-server/src/routes/files.ts +++ b/packages/studio-server/src/routes/files.ts @@ -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; } diff --git a/packages/studio-server/src/routes/imageThumbnail.ts b/packages/studio-server/src/routes/imageThumbnail.ts index 014478d9c1..ced247ddc1 100644 --- a/packages/studio-server/src/routes/imageThumbnail.ts +++ b/packages/studio-server/src/routes/imageThumbnail.ts @@ -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); diff --git a/packages/studio-server/src/routes/peaks.ts b/packages/studio-server/src/routes/peaks.ts index a842b5d793..168b34a686 100644 --- a/packages/studio-server/src/routes/peaks.ts +++ b/packages/studio-server/src/routes/peaks.ts @@ -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); diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index bad569ca6f..e0efabc443 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -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 diff --git a/packages/studio-server/src/routes/thumbnail.ts b/packages/studio-server/src/routes/thumbnail.ts index c0077f9884..84e1c4dec6 100644 --- a/packages/studio-server/src/routes/thumbnail.ts +++ b/packages/studio-server/src/routes/thumbnail.ts @@ -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"; diff --git a/packages/studio-server/src/routes/waveform.ts b/packages/studio-server/src/routes/waveform.ts index c32a7b78c3..b7c3d61eac 100644 --- a/packages/studio-server/src/routes/waveform.ts +++ b/packages/studio-server/src/routes/waveform.ts @@ -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);