Skip to content

Commit 32516b5

Browse files
fix(studio-server): keep the desktop app's hand-off and chat history out of the file routes (#5113)
* fix(studio-server): keep the desktop app's hand-off and chat history out of the file routes The file and preview routes reach any path inside the project. The desktop app keeps two files there that hold the person's agent session and their chat: .hyperframes/agent-handoff.json and .hyperframes/app-history.jsonl. No route now reads, writes, renames onto, duplicates or uploads over them, by any spelling or through a link. The rest of .hyperframes/ (Studio's motion file, prepared GIF assets) is served as before. * fix(studio-server): keep the desktop app's run log out of the file routes too The app records every chat run, the person's words included, in .hyperframes/agent-runs.jsonl. Only the app's main process reads it. * fix(studio-server): refuse everything under .hyperframes/ but Studio's own files Review (Jerrai, Rames): a list of three names missed the read marks the desktop app and the CLI also keep there, and renaming the folder reached them under a new name. The check is now an allow-list: no route reaches .hyperframes/ or anything in it, by any spelling or through a link, except Studio's studio-motion.json, studio-manual-edits.json and prepared-assets/. Studio's own internal files (backups, preview documents, history id) are read by path inside the server, not through a request path. The project's file tree leaves out the same paths. The upload test now sends a file uploads accept elsewhere, so the folder is the only reason it is refused. * fix(studio-server): serve the app's request pictures, close the renders and rename paths Review (Rames, Jerrai): - Desktop loads each request's picture from .hyperframes/requests/ through the preview route, so that folder joins the allow-list. An allowed folder's own path is allowed too. - The render-file route resolves against renders/, so a renders/ linked into .hyperframes/ reached the records. It now also checks the file against the project. - A rename's reference update walked every JSON/MD file, records included, and could rewrite them. It now skips private paths. - The allow-list reuses STUDIO_MOTION_PATH and STUDIO_MANUAL_EDITS_PATH. * chore(studio-server): keep render.ts's comment share at the base * fix(studio-server): list, view and download only renders the render-file route would serve Review (Jerrai, Rames): the render list found files in renders/ with join and statSync, which follow links, and registered them for /render/:id/view and /download, which read them with no check. A project shipping renders/leak.mp4 -> ../.hyperframes/app-history.jsonl had its chat served. The list now keeps an entry only when resolveWithinProject accepts it and it isn't private, and registers the resolved path. View and download serve only a plain file, so a link swapped in after the list is refused. This predates the PR; it's the same shipped-link case.
1 parent f80614c commit 32516b5

10 files changed

Lines changed: 313 additions & 26 deletions

File tree

‎packages/studio-server/src/helpers/safePath.test.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import { afterEach, describe, expect, it, vi } from "vitest";
6-
import { walkDir } from "./safePath";
6+
import { isPrivateProjectFile, walkDir } from "./safePath";
77

88
const hooks = vi.hoisted(() => ({ unreadable: new Map<string, string>() }));
99
vi.mock("node:fs", async (importOriginal) => {
@@ -82,3 +82,24 @@ describe("walkDir", () => {
8282
expect(() => walkDir(projectDir)).toThrow("EACCES");
8383
});
8484
});
85+
86+
describe("isPrivateProjectFile", () => {
87+
it("names everything under .hyperframes/ but Studio's own files and request pictures, in any case", () => {
88+
for (const name of [
89+
"agent-handoff.json",
90+
"agent-handoff-read.json",
91+
"app-history-seen.json",
92+
"share.json",
93+
])
94+
expect(isPrivateProjectFile("/p", `/p/.hyperframes/${name}`)).toBe(true);
95+
expect(isPrivateProjectFile("/p", "/p/.HyperFrames/App-History.JSONL")).toBe(true);
96+
expect(isPrivateProjectFile("/p", "/p/.hyperframes")).toBe(true);
97+
expect(isPrivateProjectFile("/p", "/p/.hyperframes/studio-motion.json")).toBe(false);
98+
expect(isPrivateProjectFile("/p", "/p/.hyperframes/studio-manual-edits.json")).toBe(false);
99+
expect(isPrivateProjectFile("/p", "/p/.hyperframes/prepared-assets/gif/a.mp4")).toBe(false);
100+
expect(isPrivateProjectFile("/p", "/p/.hyperframes/prepared-assets")).toBe(false);
101+
expect(isPrivateProjectFile("/p", "/p/.hyperframes/requests/1/before.png")).toBe(false);
102+
expect(isPrivateProjectFile("/p", "/p/.hyperframes/requests-old/x")).toBe(true);
103+
expect(isPrivateProjectFile("/p", "/p/agent-handoff.json")).toBe(false);
104+
});
105+
});

‎packages/studio-server/src/helpers/safePath.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
22
import { readdirSync, type Dirent } from "node:fs";
3-
import { realpath, resolveWithinProject } from "@hyperframes/core/safe-path";
3+
import { realpath, resolveWithinProject as resolveInProject } from "@hyperframes/core/safe-path";
4+
import { STUDIO_MANUAL_EDITS_PATH } from "./manualEditsRenderScript.js";
5+
import { STUDIO_MOTION_PATH } from "./studioMotionRenderScript.js";
46

57
// `isSafePath` lives at the package root so non-studio-api layers (compiler,
68
// CLI, engine) can share it without a backwards dependency on studio-api.
@@ -12,9 +14,14 @@ export {
1214
mkdirWithinProject,
1315
realpath,
1416
realProjectRoot,
15-
resolveWithinProject,
1617
} from "@hyperframes/core/safe-path";
1718

19+
/** Core's `resolveWithinProject`, closed to the desktop app's private files for every route a request path reaches. */
20+
export function resolveWithinProject(base: string, relativePath: string): string | null {
21+
const resolved = resolveInProject(base, relativePath);
22+
return resolved && !isPrivateProjectFile(base, resolved) ? resolved : null;
23+
}
24+
1825
/** The real path; for a path not there (yet, or any more), the nearest existing folder's real path plus the rest. */
1926
export function realFilePath(filePath: string): string {
2027
try {
@@ -25,6 +32,28 @@ export function realFilePath(filePath: string): string {
2532
}
2633
}
2734

35+
// `.hyperframes/` holds the desktop app's and the CLI's own records (a hand-off, chat history, read marks): no route
36+
// reaches any of it, the folder itself included, but Studio's own files and the app's request pictures.
37+
const STUDIO_FILES = new Set([STUDIO_MOTION_PATH, STUDIO_MANUAL_EDITS_PATH]);
38+
const STUDIO_FOLDERS = [".hyperframes/prepared-assets", ".hyperframes/requests"];
39+
40+
/** For a project-relative path with `/` separators. */
41+
export function isPrivateProjectPath(relPath: string): boolean {
42+
const path = relPath.toLowerCase();
43+
return (
44+
(path === ".hyperframes" || path.startsWith(".hyperframes/")) &&
45+
!STUDIO_FILES.has(path) &&
46+
!STUDIO_FOLDERS.some((folder) => path === folder || path.startsWith(`${folder}/`))
47+
);
48+
}
49+
50+
export function isPrivateProjectFile(projectDir: string, filePath: string): boolean {
51+
const rel = (from: string, to: string) => relative(from, to).split(sep).join("/");
52+
return [rel(projectDir, filePath), rel(realFilePath(projectDir), realFilePath(filePath))].some(
53+
isPrivateProjectPath,
54+
);
55+
}
56+
2857
/**
2958
* `resolveWithinProject` with every link inside the project resolved now, so a write to the result lands on the
3059
* file checked here even if a link on the way is retargeted before the write.

‎packages/studio-server/src/routes/files.pathSafety.test.ts‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,3 +695,124 @@ describe("rename reference updates", () => {
695695
},
696696
);
697697
});
698+
699+
describe("the desktop app's private files", () => {
700+
it("are never read, written or deleted through the file routes, however the path is spelled", async (context) => {
701+
const { app, project } = fixture();
702+
mkdirSync(join(project, ".hyperframes"));
703+
writeFileSync(
704+
join(project, ".hyperframes", "agent-handoff.json"),
705+
'{"engine":"claude","sessionId":"secret"}',
706+
);
707+
writeFileSync(join(project, ".hyperframes", "app-history.jsonl"), '{"said":"secret"}');
708+
writeFileSync(
709+
join(project, ".hyperframes", "agent-handoff-read.json"),
710+
'{"sessionId":"secret"}',
711+
);
712+
for (const path of [
713+
".hyperframes/agent-handoff.json",
714+
".hyperframes/app-history.jsonl",
715+
".HyperFrames/Agent-Handoff.JSON",
716+
".hyperframes/agent-handoff-read.json",
717+
]) {
718+
const res = await app.request(`/projects/p/files/${path}`);
719+
expect([403, 404]).toContain(res.status);
720+
expect(await res.text()).not.toContain("secret");
721+
}
722+
const put = await app.request("/projects/p/files/.hyperframes/agent-handoff.json", {
723+
method: "PUT",
724+
body: "{}",
725+
});
726+
expect(put.status).toBe(403);
727+
const del = await app.request("/projects/p/files/.hyperframes/app-history.jsonl", {
728+
method: "DELETE",
729+
});
730+
expect(del.status).toBe(403);
731+
linkOrSkip(
732+
context,
733+
join(project, ".hyperframes", "agent-handoff.json"),
734+
join(project, "link.json"),
735+
"file",
736+
);
737+
const viaLink = await app.request("/projects/p/files/link.json");
738+
expect(await viaLink.text()).not.toContain("secret");
739+
});
740+
741+
it("can't be reached by renaming their folder", async () => {
742+
const { app, project } = fixture();
743+
mkdirSync(join(project, ".hyperframes"));
744+
writeFileSync(join(project, ".hyperframes", "app-history.jsonl"), '{"said":"secret"}');
745+
const rename = await app.request("/projects/p/files/.hyperframes", {
746+
method: "PATCH",
747+
headers: { "content-type": "application/json" },
748+
body: JSON.stringify({ newPath: "x" }),
749+
});
750+
expect(rename.status).toBeGreaterThanOrEqual(400);
751+
expect(existsSync(join(project, "x"))).toBe(false);
752+
});
753+
754+
it("are neither read nor rewritten when a rename updates references", async () => {
755+
const { app, project } = fixture();
756+
mkdirSync(join(project, ".hyperframes"));
757+
const share = join(project, ".hyperframes", "share.json");
758+
writeFileSync(share, '{"ref":"inside.txt"}');
759+
const response = await app.request("/projects/p/files/inside.txt", {
760+
method: "PATCH",
761+
headers: { "content-type": "application/json" },
762+
body: JSON.stringify({ newPath: "moved.txt" }),
763+
});
764+
expect(response.status).toBe(200);
765+
expect(readFileSync(share, "utf8")).toBe('{"ref":"inside.txt"}');
766+
expect((await response.json()).updatedReferences).toBe(0);
767+
});
768+
769+
it("leave Studio's own files under .hyperframes/ reachable", async () => {
770+
const { app, project } = fixture();
771+
mkdirSync(join(project, ".hyperframes", "prepared-assets", "gif"), { recursive: true });
772+
writeFileSync(
773+
join(project, ".hyperframes", "studio-motion.json"),
774+
'{"version":1,"motions":[]}',
775+
);
776+
writeFileSync(join(project, ".hyperframes", "prepared-assets", "gif", "a.mp4"), "mp4");
777+
for (const path of ["studio-motion.json", "prepared-assets/gif/a.mp4"])
778+
expect((await app.request(`/projects/p/files/.hyperframes/${path}`)).status).toBe(200);
779+
});
780+
});
781+
782+
describe("routes that write a path from the request", () => {
783+
it("never plant or copy a file into .hyperframes/", async () => {
784+
const { app, project } = fixture();
785+
mkdirSync(join(project, ".hyperframes"));
786+
writeFileSync(
787+
join(project, ".hyperframes", "agent-handoff.json"),
788+
'{"engine":"claude","sessionId":"secret"}',
789+
);
790+
const rename = await app.request("/projects/p/files/inside.txt", {
791+
method: "PATCH",
792+
headers: { "content-type": "application/json" },
793+
body: JSON.stringify({ newPath: ".hyperframes/app-history.jsonl" }),
794+
});
795+
expect(rename.status).toBeGreaterThanOrEqual(400);
796+
expect(existsSync(join(project, ".hyperframes", "app-history.jsonl"))).toBe(false);
797+
const duplicate = await app.request("/projects/p/duplicate-file", {
798+
method: "POST",
799+
headers: { "content-type": "application/json" },
800+
body: JSON.stringify({ path: ".hyperframes/agent-handoff.json" }),
801+
});
802+
expect(duplicate.status).toBeGreaterThanOrEqual(400);
803+
expect(readdirSync(join(project, ".hyperframes"))).toEqual(["agent-handoff.json"]);
804+
const form = new FormData();
805+
// A file uploads accept anywhere else, so the folder is the only reason it is refused.
806+
form.append("file", new File(["plain words"], "notes.txt"));
807+
const upload = await app.request("/projects/p/upload?dir=.hyperframes", {
808+
method: "POST",
809+
body: form,
810+
});
811+
expect(upload.status).toBe(403);
812+
expect(existsSync(join(project, ".hyperframes", "notes.txt"))).toBe(false);
813+
const elsewhere = new FormData();
814+
elsewhere.append("file", new File(["plain words"], "notes.txt"));
815+
const fine = await app.request("/projects/p/upload", { method: "POST", body: elsewhere });
816+
expect((await fine.json()).files).toEqual(["notes.txt"]);
817+
});
818+
});

‎packages/studio-server/src/routes/files.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { validateUploadedMediaBuffer } from "../helpers/mediaValidation.js";
3030
import {
3131
folderGone,
3232
isInHiddenOrVendorDir,
33+
isPrivateProjectFile,
3334
isSafePath,
3435
mkdirWithinProject,
3536
pinWithinProject,
@@ -802,7 +803,7 @@ function updateReferences(
802803
const rewrite = referenceRewriter(oldPath, newPath, isDirectory, projectPaths(projectDir));
803804
let updatedCount = 0;
804805
for (const file of textFiles) {
805-
if (!isSafePath(projectDir, file)) continue;
806+
if (!isSafePath(projectDir, file) || isPrivateProjectFile(projectDir, file)) continue;
806807
const content = readableText(file);
807808
if (content === null) continue;
808809

@@ -2481,7 +2482,7 @@ async function processUploadedFiles(
24812482

24822483
// The collision suffix chooses a different path; validate that destination
24832484
// too, including dangling symlinks that existsSync treats as absent.
2484-
if (!isSafePath(projectDir, finalPath)) continue;
2485+
if (!isSafePath(projectDir, finalPath) || isPrivateProjectFile(projectDir, finalPath)) continue;
24852486

24862487
const buffer = Buffer.from(await value.arrayBuffer());
24872488
const validation = validateUploadedMediaBuffer(finalName, buffer);

‎packages/studio-server/src/routes/preview.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2281,3 +2281,34 @@ describe("preview asset byte ranges", () => {
22812281
expect(res.headers.get("Content-Range")).toBe("bytes */3");
22822282
});
22832283
});
2284+
2285+
describe("the desktop app's private folder", () => {
2286+
it("is served by neither the asset route nor the sub-composition route", async () => {
2287+
const projectDir = createProjectDir();
2288+
mkdirSync(join(projectDir, ".hyperframes"), { recursive: true });
2289+
writeFileSync(
2290+
join(projectDir, ".hyperframes", "agent-handoff.json"),
2291+
'{"engine":"claude","sessionId":"secret"}',
2292+
);
2293+
const app = new Hono();
2294+
registerPreviewRoutes(app, createAdapter(projectDir));
2295+
for (const route of ["preview", "preview/comp"]) {
2296+
const res = await app.request(
2297+
`http://localhost/projects/demo/${route}/.hyperframes/agent-handoff.json`,
2298+
);
2299+
expect(res.status).toBe(404);
2300+
expect(await res.text()).not.toContain("secret");
2301+
}
2302+
});
2303+
it("still serves the app's request pictures", async () => {
2304+
const projectDir = createProjectDir();
2305+
mkdirSync(join(projectDir, ".hyperframes", "requests", "1"), { recursive: true });
2306+
writeFileSync(join(projectDir, ".hyperframes", "requests", "1", "before.png"), "png");
2307+
const app = new Hono();
2308+
registerPreviewRoutes(app, createAdapter(projectDir));
2309+
const res = await app.request(
2310+
"http://localhost/projects/demo/preview/.hyperframes/requests/1/before.png",
2311+
);
2312+
expect(res.status).toBe(200);
2313+
});
2314+
});

‎packages/studio-server/src/routes/preview.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@ import { gsapCdnDist, motionPathPluginUrl } from "@hyperframes/core/gsap-cdn";
1818
import { findStartTags, injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document";
1919
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
2020
import type { ResolvedProject, StudioApiAdapter } from "../types.js";
21-
import { isProjectRootMissing, resolveWithinProject } from "../helpers/safePath.js";
21+
import {
22+
isPrivateProjectFile,
23+
isProjectRootMissing,
24+
resolveWithinProject,
25+
} from "../helpers/safePath.js";
2226
import { getMimeType } from "../helpers/mime.js";
2327
import { buildSubCompositionHtml, hasBaseElement } from "../helpers/subComposition.js";
2428
import {
@@ -615,7 +619,7 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vo
615619
// use resolveWithinProject because saves write their data-hf-id values.
616620
const candidate = resolve(project.dir, subPath);
617621
const file = isWithinProjectRoot(project.dir, candidate) ? candidate : null;
618-
if (!file) {
622+
if (!file || isPrivateProjectFile(project.dir, file)) {
619623
return c.text("not found", 404);
620624
}
621625
recordPreviewRead(project.dir, file);

‎packages/studio-server/src/routes/projects.test.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,9 @@ const COMPOSITION_HTML = '<html><body><div data-composition-id="main"></div></bo
2222
// - .cache/examples/ a vendored dot-dir. walkDir does NOT special-case
2323
// it, so it stays listed in the file tree, but it is
2424
// gated out of composition discovery (isInHiddenOrVendorDir).
25-
// - .hyperframes/examples/ vendored under Studio's dir — also listed in the
26-
// file tree, also gated out of discovery.
27-
// - .hyperframes/backup/ Studio's internal snapshots — the only thing hidden
28-
// from the file tree (walkDir's shouldIgnoreDir).
25+
// - .hyperframes/examples/ under the app's folder — gated out of discovery,
26+
// and hidden from the tree like every non-Studio record.
27+
// - .hyperframes/backup/ Studio's internal snapshots — hidden from the tree.
2928
function createProjectDir(): string {
3029
const projectDir = mkdtempSync(join(tmpdir(), "hf-projects-test-"));
3130
tempDirs.push(projectDir);
@@ -149,8 +148,10 @@ describe("registerProjectRoutes — composition discovery (#1384)", () => {
149148
expect(payload.compositions).not.toContain(".hyperframes/examples/preset.html");
150149
});
151150

152-
it("lists vendored dot-directory files in the file tree but hides Studio backups", async () => {
151+
it("lists vendored dot-directory files in the file tree, but nothing under .hyperframes/ that isn't Studio's", async () => {
153152
const projectDir = createProjectDir();
153+
writeFileSync(join(projectDir, ".hyperframes", "app-history.jsonl"), "{}");
154+
writeFileSync(join(projectDir, ".hyperframes", "studio-motion.json"), "{}");
154155
const app = new Hono();
155156
registerProjectRoutes(app, createAdapter(projectDir));
156157

@@ -159,9 +160,9 @@ describe("registerProjectRoutes — composition discovery (#1384)", () => {
159160

160161
// Vendored dot-dirs stay browsable — discovery is gated, the file tree is not.
161162
expect(payload.files).toContain(".cache/examples/preset.html");
162-
expect(payload.files).toContain(".hyperframes/examples/preset.html");
163-
// Only Studio's own backup snapshots are hidden from the tree (#1366).
164-
expect(payload.files).not.toContain(".hyperframes/backup/snapshot.html");
163+
expect(payload.files).toContain(".hyperframes/studio-motion.json");
164+
for (const hidden of ["examples/preset.html", "backup/snapshot.html", "app-history.jsonl"])
165+
expect(payload.files).not.toContain(`.hyperframes/${hidden}`);
165166
});
166167

167168
it("omits generated cache files from the project file tree", async () => {

‎packages/studio-server/src/routes/projects.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";
22
import { join } from "node:path";
33
import type { Hono } from "hono";
44
import type { StudioApiAdapter } from "../types.js";
5-
import { isInHiddenOrVendorDir, walkDir } from "../helpers/safePath.js";
5+
import { isInHiddenOrVendorDir, isPrivateProjectPath, walkDir } from "../helpers/safePath.js";
66
import { isCompositionSource } from "../helpers/hfIdPersist.js";
77
import { resolveProjectSignature } from "../helpers/projectSignature.js";
88

@@ -50,7 +50,7 @@ export function registerProjectRoutes(api: Hono, adapter: StudioApiAdapter): voi
5050
api.get("/projects/:id", async (c) => {
5151
const project = await adapter.resolveProject(c.req.param("id"));
5252
if (!project) return c.json({ error: "not found" }, 404);
53-
const files = walkDir(project.dir);
53+
const files = walkDir(project.dir).filter((file) => !isPrivateProjectPath(file));
5454
const compositions = await filterCompositionFiles(project.dir, files);
5555
return c.json({ id: project.id, dir: project.dir, title: project.title, files, compositions });
5656
});

0 commit comments

Comments
 (0)