Skip to content

Commit cdcfd93

Browse files
committed
fix(preview): proxy external symlink videos
1 parent 354a3ac commit cdcfd93

3 files changed

Lines changed: 95 additions & 20 deletions

File tree

‎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: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -534,6 +534,11 @@ describe("hf-id surfacing in preview route", () => {
534534
expect(response.status).toBe(200);
535535
expect(response.headers.get("content-type")).toContain("image/svg+xml");
536536
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);
537542
});
538543

539544
it("sub-comp route does NOT persist ids inside a plain <template> (runtime clone-source)", async () => {
@@ -1097,6 +1102,51 @@ describe("hf-proxy negotiation and media codec map injection (U3)", () => {
10971102
);
10981103
});
10991104

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+
11001150
it("escapes script terminators and JavaScript line separators in codec-map keys", async () => {
11011151
const projectDir = createProjectDir();
11021152
const { registerPreviewRoutes: register } = await loadPreviewModule({

0 commit comments

Comments
 (0)