Skip to content

Commit 7778c09

Browse files
authored
fix(preview): serve external symlink assets (#2764)
## What Allow Studio Preview to serve an asset reached through a project-local symlink whose target is in a shared directory outside the project, including browser-hostile video assets that need an authoring proxy. ## Why Preview rejected these assets with a 404 while the renderer accepted the same path. The initial static-route fix still failed for HEVC, ProRes, AV1, and VP9 assets because the proxy transcoder rejected the external target. ## How Use lexical project-root containment for the read-only static asset route and proxy source request. The transcoder canonicalizes the target for ffmpeg and includes that identity in its cache key, while keeping the proxy cache inside the project. Composition source paths retain canonical containment because preview can persist their data-hf-id values. ## Test plan - [x] Unit tests added/updated - [x] `bun run --cwd packages/studio-server test` (397 tests) - [x] Studio Server typecheck, oxlint, and oxfmt - [x] External-symlinked hostile-video proxy route regression - [x] Static-route traversal regression - [ ] Documentation updated (not applicable)
1 parent 9e7ddb0 commit 7778c09

5 files changed

Lines changed: 146 additions & 23 deletions

File tree

‎packages/lint/src/project.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
22
import { ChildProcess, execFile } from "node:child_process";
3-
import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs";
3+
import { mkdirSync, mkdtempSync, writeFileSync, rmSync, symlinkSync } from "node:fs";
44
import { join } from "node:path";
55
import { tmpdir } from "node:os";
66
import type { HyperframeLintFinding } from "./types.js";
@@ -47,6 +47,28 @@ afterEach(() => {
4747
dirs = [];
4848
});
4949

50+
describe("external symlink assets", () => {
51+
it("does not report a shared asset addressed through an in-project symlink", async () => {
52+
const project = makeProject(
53+
validHtml().replace("</div>", '<img src="assets/shared/sample.svg" /></div>'),
54+
);
55+
const externalDir = tmpProject("shared-assets");
56+
dirs.push(externalDir);
57+
mkdirSync(join(project, "assets"));
58+
writeFileSync(join(externalDir, "sample.svg"), "<svg>shared</svg>");
59+
try {
60+
symlinkSync(externalDir, join(project, "assets", "shared"), "dir");
61+
} catch {
62+
return;
63+
}
64+
65+
const { results } = await lintProject(project);
66+
const findings = results.flatMap((result) => result.result.findings);
67+
68+
expect(findings.some((finding) => finding.code === "missing_local_asset")).toBe(false);
69+
});
70+
});
71+
5072
describe("missing_or_empty_sub_composition", () => {
5173
function htmlWithSubComp(srcPath: string): string {
5274
return `<html><body>

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

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
existsSync,
44
mkdtempSync,
55
readdirSync,
6+
realpathSync,
67
rmSync,
78
symlinkSync,
89
utimesSync,
@@ -497,20 +498,25 @@ describe("resolveProxy", () => {
497498
expect(calls).toHaveLength(0);
498499
});
499500

500-
it("rejects an in-project symlink whose target escapes the project", async () => {
501+
it("proxies an external target reached through an in-project symlink", async () => {
501502
const { spawn, calls } = createSpawnSpy();
502-
const { resolveProxy, ProxySourceOutsideProjectError } = await loadModule(spawn, FFMPEG_PATH);
503+
const { resolveProxy, getProxyCachePath } = await loadModule(spawn, FFMPEG_PATH);
503504
const projectDir = tmpProject();
504505
const outsideDir = tmpProject();
505506
const outsidePath = join(outsideDir, "outside.mov");
506507
const sourcePath = join(projectDir, "linked.mov");
507508
writeFileSync(outsidePath, "source-bytes");
508509
symlinkSync(outsidePath, sourcePath);
509510

510-
await expect(resolveProxy(projectDir, sourcePath)).rejects.toBeInstanceOf(
511-
ProxySourceOutsideProjectError,
512-
);
513-
expect(calls).toHaveLength(0);
511+
const cachePath = getProxyCachePath(projectDir, sourcePath);
512+
const result = resolveProxy(projectDir, sourcePath);
513+
await flush();
514+
515+
expect(calls).toHaveLength(1);
516+
expect(calls[0]?.args).toContain(realpathSync(outsidePath));
517+
succeed(calls[0]!);
518+
await expect(result).resolves.toBe(cachePath);
519+
expect(cachePath.startsWith(join(realpathSync(projectDir), ".transcode-cache"))).toBe(true);
514520
});
515521

516522
it("retries after the source file changes (mtime in the cache key invalidates the remembered failure)", async () => {

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

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
unlinkSync,
1010
utimesSync,
1111
} from "node:fs";
12-
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
12+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
1313
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
1414
import { probeMediaMetadata } from "./mediaMetadata.js";
1515
import { cleanupProxyCache } from "./proxyCache.js";
@@ -96,7 +96,7 @@ export class ProxyCapacityError extends ProxyTranscodeError {
9696

9797
export class ProxySourceOutsideProjectError extends ProxyTranscodeError {
9898
constructor() {
99-
super("media proxy source must be inside the project", null, "");
99+
super("media proxy source must be addressed through the project", null, "");
100100
this.name = "ProxySourceOutsideProjectError";
101101
}
102102
}
@@ -129,41 +129,60 @@ export async function waitForProxy<T>(
129129
}
130130

131131
/**
132-
* Cache key inputs per the plan: source path relative to the project (so the
133-
* cache is portable across checkouts at different absolute locations), mtime
134-
* and file size (mtime alone can collide on same-second re-exports on
135-
* coarse-timestamp filesystems; size catches nearly all such cases at zero
136-
* cost), and a params version token so changing the ffmpeg recipe below
137-
* invalidates every cached proxy cleanly.
132+
* Cache key inputs per the plan: project-relative source path (portable across
133+
* checkouts), canonical source identity (so retargeted external symlinks do
134+
* not reuse a proxy), mtime and file size (mtime alone can collide on
135+
* same-second re-exports on coarse-timestamp filesystems; size catches nearly
136+
* all such cases at zero cost), and a params version token so changing the
137+
* ffmpeg recipe below invalidates every cached proxy cleanly.
138138
*/
139139
type CanonicalProxySource = {
140140
projectDir: string;
141141
sourcePath: string;
142142
relativePath: string;
143+
cacheIdentity: string;
143144
};
144145

145146
function canonicalizeProxySource(
146147
projectDir: string,
147148
absoluteSourcePath: string,
148149
): CanonicalProxySource {
149-
const canonicalProjectDir = realpathSync(projectDir);
150-
const canonicalSourcePath = realpathSync(absoluteSourcePath);
151-
const relPath = relative(canonicalProjectDir, canonicalSourcePath);
152-
if (relPath === ".." || relPath.startsWith(`..${sep}`) || isAbsolute(relPath)) {
150+
const requestedProjectDir = resolve(projectDir);
151+
const requestedSourcePath = resolve(absoluteSourcePath);
152+
const requestedRelativePath = relative(requestedProjectDir, requestedSourcePath);
153+
if (
154+
requestedRelativePath === ".." ||
155+
requestedRelativePath.startsWith(`..${sep}`) ||
156+
isAbsolute(requestedRelativePath)
157+
) {
153158
throw new ProxySourceOutsideProjectError();
154159
}
160+
161+
const canonicalProjectDir = realpathSync(projectDir);
162+
const canonicalSourcePath = realpathSync(absoluteSourcePath);
163+
const canonicalRelativePath = relative(canonicalProjectDir, canonicalSourcePath);
164+
const sourceIsInsideCanonicalProject =
165+
canonicalRelativePath !== ".." &&
166+
!canonicalRelativePath.startsWith(`..${sep}`) &&
167+
!isAbsolute(canonicalRelativePath);
155168
return {
156169
projectDir: canonicalProjectDir,
157170
sourcePath: canonicalSourcePath,
158-
relativePath: relPath.normalize("NFC"),
171+
relativePath: requestedRelativePath.normalize("NFC"),
172+
// An external target needs a stable identity in addition to its project-local
173+
// symlink path, otherwise retargeting the link can reuse an unrelated proxy.
174+
cacheIdentity: (sourceIsInsideCanonicalProject
175+
? canonicalRelativePath
176+
: canonicalSourcePath
177+
).normalize("NFC"),
159178
};
160179
}
161180

162181
function buildProxyCacheKey(source: CanonicalProxySource, variant: ProxyVariant): string {
163182
const stat = statSync(source.sourcePath);
164183
return createHash("sha256")
165184
.update(
166-
`${source.relativePath}\0${stat.mtimeMs}\0${stat.size}\0${PROXY_PARAMS_VERSION}\0${variant}`,
185+
`${source.relativePath}\0${source.cacheIdentity}\0${stat.mtimeMs}\0${stat.size}\0${PROXY_PARAMS_VERSION}\0${variant}`,
167186
)
168187
.digest("hex");
169188
}

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

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,31 @@ describe("hf-id surfacing in preview route", () => {
516516
expect(readFileSync(svgPath, "utf-8")).toBe(svgBytes);
517517
});
518518

519+
it("serves an asset reached through an in-project symlink to a shared external directory", async () => {
520+
const projectDir = createProjectDir();
521+
const externalDir = mkdtempSync(join(tmpdir(), "hf-preview-shared-assets-"));
522+
tempDirs.push(externalDir);
523+
mkdirSync(join(projectDir, "assets"));
524+
writeFileSync(join(externalDir, "sample.svg"), "<svg>shared</svg>");
525+
if (!tryCreateSymlink(externalDir, join(projectDir, "assets", "shared"), "dir")) return;
526+
527+
const app = new Hono();
528+
registerPreviewRoutes(app, createAdapter(projectDir));
529+
530+
const response = await app.request(
531+
"http://localhost/projects/demo/preview/assets/shared/sample.svg",
532+
);
533+
534+
expect(response.status).toBe(200);
535+
expect(response.headers.get("content-type")).toContain("image/svg+xml");
536+
expect(await response.text()).toBe("<svg>shared</svg>");
537+
538+
const traversal = await app.request(
539+
"http://localhost/projects/demo/preview/..%2f..%2f..%2fetc%2fpasswd",
540+
);
541+
expect(traversal.status).toBe(404);
542+
});
543+
519544
it("sub-comp route does NOT persist ids inside a plain <template> (runtime clone-source)", async () => {
520545
const { readFileSync } = await import("node:fs");
521546
const projectDir = createProjectDir();
@@ -1077,6 +1102,51 @@ describe("hf-proxy negotiation and media codec map injection (U3)", () => {
10771102
);
10781103
});
10791104

1105+
it("injects and serves a proxy for a hostile video through an external asset symlink", async () => {
1106+
const projectDir = createProjectDir();
1107+
const externalDir = mkdtempSync(join(tmpdir(), "hf-preview-shared-video-"));
1108+
tempDirs.push(externalDir);
1109+
mkdirSync(join(projectDir, "assets"));
1110+
writeFileSync(join(externalDir, "clip.mov"), "shared-hevc-bytes");
1111+
if (!tryCreateSymlink(externalDir, join(projectDir, "assets", "shared"), "dir")) return;
1112+
1113+
const proxyPath = join(projectDir, ".transcode-cache", "shared.mp4");
1114+
const resolveProxyMock = vi.fn(async () => {
1115+
mkdirSync(join(projectDir, ".transcode-cache"), { recursive: true });
1116+
writeFileSync(proxyPath, "proxy-bytes");
1117+
return proxyPath;
1118+
});
1119+
const scanMapMock = vi.fn(async () => ({
1120+
"/assets/shared/clip.mov": {
1121+
codecName: "hevc",
1122+
browserHostile: true,
1123+
representativeMime: 'video/mp4; codecs="hvc1.1.6.L120.B0"',
1124+
},
1125+
}));
1126+
const { registerPreviewRoutes: register } = await loadPreviewModule({
1127+
resolveProxyImpl: resolveProxyMock,
1128+
scanMapImpl: scanMapMock,
1129+
});
1130+
const app = new Hono();
1131+
register(app, createAdapter(projectDir));
1132+
1133+
const preview = await app.request("http://localhost/projects/demo/preview");
1134+
expect(await preview.text()).toContain("/assets/shared/clip.mov");
1135+
expect(scanMapMock).toHaveBeenCalled();
1136+
1137+
const proxied = await app.request(
1138+
"http://localhost/projects/demo/preview/assets/shared/clip.mov?hf-proxy=h264",
1139+
);
1140+
expect(proxied.status).toBe(200);
1141+
expect(proxied.headers.get("Content-Type")).toBe("video/mp4");
1142+
expect(await proxied.text()).toBe("proxy-bytes");
1143+
expect(resolveProxyMock).toHaveBeenCalledWith(
1144+
projectDir,
1145+
join(projectDir, "assets", "shared", "clip.mov"),
1146+
"h264",
1147+
);
1148+
});
1149+
10801150
it("escapes script terminators and JavaScript line separators in codec-map keys", async () => {
10811151
const projectDir = createProjectDir();
10821152
const { registerPreviewRoutes: register } = await loadPreviewModule({

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import type { Hono } from "hono";
22
import { existsSync, readFileSync, statSync } from "node:fs";
3-
import { join } from "node:path";
3+
import { join, resolve } from "node:path";
44
import { createHash } from "node:crypto";
55
import { injectScriptsIntoHtml, stripEmbeddedRuntimeScripts } from "@hyperframes/core/compiler";
6+
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
67
import type { StudioApiAdapter } from "../types.js";
78
import { resolveWithinProject } from "../helpers/safePath.js";
89
import { getMimeType } from "../helpers/mime.js";
@@ -528,7 +529,12 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vo
528529
const subPath = decodeURIComponent(
529530
c.req.path.replace(`/projects/${project.id}/preview/`, "").split("?")[0] ?? "",
530531
);
531-
const file = resolveWithinProject(project.dir, subPath);
532+
// Assets are read-only and should mirror the renderer: permit a path that
533+
// is lexically inside the project even if an explicit project symlink
534+
// targets a shared directory outside it. Composition source files still
535+
// use resolveWithinProject because preview mutates their data-hf-id values.
536+
const candidate = resolve(project.dir, subPath);
537+
const file = isWithinProjectRoot(project.dir, candidate) ? candidate : null;
532538
if (!file) {
533539
return c.text("not found", 404);
534540
}

0 commit comments

Comments
 (0)