Skip to content

Write HTML. Render video. Built for agents.

fix(studio-server): a write through a link lands on the file the system resolves (#4589)

Miguel Ángel59e3850f6a54
diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts
index b4c1cad4b2..ad0549d692 100644
--- a/packages/cli/src/commands/add.ts
+++ b/packages/cli/src/commands/add.ts
@@ -14,7 +14,7 @@ export const examples: Example[] = [
import { existsSync, readFileSync } from "node:fs";
import { parseHTML } from "linkedom";
import { resolve, relative } from "node:path";
-import { ITEM_TYPE_DIRS, type RegistryItem } from "@hyperframes/core";
+import { ITEM_TYPE_DIRS, realpath, type RegistryItem } from "@hyperframes/core";
import { c } from "../ui/colors.js";
import {
DEFAULT_REGISTRY_URL,
@@ -510,14 +510,15 @@ export default defineCommand({
}
console.log("");
console.log(`${c.success("✓")} Added ${c.accent(result.name)} (${result.type})`);
+ const root = realpath(projectDir);
for (const file of result.preserved) {
console.log(
- ` ${c.warn("kept")} ${relative(projectDir, file) || file} — you have edited this; --force to overwrite`,
+ ` ${c.warn("kept")} ${relative(root, file) || file} — you have edited this; --force to overwrite`,
);
}
for (const file of result.written) {
- console.log(` ${c.dim(relative(projectDir, file))}`);
+ console.log(` ${c.dim(relative(root, file))}`);
}
if (result.variablesApplied.length > 0) {
// Say it out loud. A component's values are baked into the file rather
diff --git a/packages/cli/src/commands/catalog.ts b/packages/cli/src/commands/catalog.ts
index ce4f1b8686..4b7fd8a8c2 100644
--- a/packages/cli/src/commands/catalog.ts
+++ b/packages/cli/src/commands/catalog.ts
@@ -10,12 +10,12 @@ export const examples: Example[] = [
];
import * as clack from "@clack/prompts";
-import { type ItemType, type RegistryItem } from "@hyperframes/core";
+import { realpath, type ItemType, type RegistryItem } from "@hyperframes/core";
import { c } from "../ui/colors.js";
import { loadAllItems } from "../registry/resolver.js";
import { fetchRegistryManifest } from "../registry/remote.js";
import { loadProjectConfig, DEFAULT_PROJECT_CONFIG } from "../utils/projectConfig.js";
-import { resolve } from "node:path";
+import { relative, resolve } from "node:path";
import { finishCommand } from "../utils/commandResult.js";
import { isAttendedTerminal } from "../utils/attendedTerminal.js";
import { runAdd } from "./add.js";
@@ -472,9 +472,9 @@ export default defineCommand({
}
console.log("");
console.log(`${c.success("✓")} Installed ${c.accent(result.name)} (${result.type})`);
+ const root = realpath(dir);
for (const file of result.written) {
- const rel = file.replace(dir + "/", "");
- console.log(` ${c.dim(rel)}`);
+ console.log(` ${c.dim(relative(root, file))}`);
}
if (result.snippet) {
console.log("");
diff --git a/packages/cli/src/registry/publication.test.ts b/packages/cli/src/registry/publication.test.ts
index 46feabbec1..3150ae7299 100644
--- a/packages/cli/src/registry/publication.test.ts
+++ b/packages/cli/src/registry/publication.test.ts
@@ -84,6 +84,26 @@ it("publishes through an internal leaf alias to its physical target", () => {
}
});
+it.skipIf(process.platform === "win32")(
+ "publishes through a leaf alias whose target climbs out of a linked folder to the file it resolves",
+ () => {
+ const root = registryRoot(mkdtempSync(join(tmpdir(), "hf-publish-")));
+ try {
+ mkdirSync(join(root, "deep", "nested"), { recursive: true });
+ mkdirSync(join(root, "m"));
+ writeFileSync(join(root, "deep", "y.html"), "old");
+ writeFileSync(join(root, "y.html"), "decoy");
+ symlinkSync(join(root, "deep", "nested"), join(root, "sub"), "dir");
+ symlinkSync("../sub/../y.html", join(root, "m", "x.html"), "file");
+ publishRegistryFile(root, "m/x.html", "new");
+ expect(readFileSync(join(root, "deep", "y.html"), "utf8")).toBe("new");
+ expect(readFileSync(join(root, "y.html"), "utf8")).toBe("decoy");
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ },
+);
+
it.skipIf(process.platform === "win32")(
"preserves executable mode when replacing an installed file",
() => {
diff --git a/packages/cli/src/registry/publication.ts b/packages/cli/src/registry/publication.ts
index 41023f79b1..56a3f9b595 100644
--- a/packages/cli/src/registry/publication.ts
+++ b/packages/cli/src/registry/publication.ts
@@ -3,16 +3,16 @@ import {
chmodSync,
mkdirSync,
mkdtempSync,
- realpathSync,
renameSync,
rmSync,
writeFileSync,
} from "node:fs";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { realpath } from "@hyperframes/core";
export function registryRoot(directory: string): string {
mkdirSync(directory, { recursive: true });
- return realpathSync(directory);
+ return realpath(directory);
}
export function registryTargetPath(root: string, target: string): string {
@@ -21,7 +21,7 @@ export function registryTargetPath(root: string, target: string): string {
let path = root;
for (const part of parts) {
path = join(path, part);
- if (lstatSync(path, { throwIfNoEntry: false })) path = realpathSync(path);
+ if (lstatSync(path, { throwIfNoEntry: false })) path = realpath(path);
assertContained(root, path);
}
return path;
@@ -54,7 +54,7 @@ export function publishRegistryFile(
): string {
const path = registryTargetPath(root, target);
mkdirSync(dirname(path), { recursive: true });
- const parent = realpathSync(dirname(path));
+ const parent = realpath(dirname(path));
assertContained(root, parent);
const destination = resolve(parent, basename(path));
const stage = mkdtempSync(join(parent, ".hf-install-"));
diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts
index 3ae36dc6f3..409ec871d4 100644
--- a/packages/cli/src/server/studioServer.ts
+++ b/packages/cli/src/server/studioServer.ts
@@ -7,7 +7,8 @@
import { Hono, type Context } from "hono";
import { streamSSE } from "hono/streaming";
-import { existsSync, readFileSync, realpathSync, writeFileSync, unlinkSync } from "node:fs";
+import { realpath } from "@hyperframes/core";
+import { existsSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { resolve, join, basename, relative, sep } from "node:path";
@@ -784,7 +785,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
recordRewrittenInstall(opts.project.dir, written);
// The item's own file first, as add recorded it, since Studio mounts the first .html it gets.
- const root = realpathSync(opts.project.dir);
+ const root = realpath(opts.project.dir);
const primary = primaryInstalledTarget(item);
const primaryPath = registryTargetPath(root, primary);
const others = written
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 48d0993ad3..2d159f18e6 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -275,7 +275,7 @@ export {
type MediaVisualStyleProperty,
} from "./inline-scripts/parityContract";
export { redactKnownPaths, redactTelemetryString } from "./telemetryRedaction";
-export { isSafePath, resolveWithinProject } from "./safePath";
+export { isSafePath, realpath, resolveWithinProject } from "./safePath";
export type {
HyperframePickerApi,
HyperframePickerBoundingBox,
diff --git a/packages/core/src/safePath.ts b/packages/core/src/safePath.ts
index 7cff767b6b..750761919f 100644
--- a/packages/core/src/safePath.ts
+++ b/packages/core/src/safePath.ts
@@ -1,7 +1,7 @@
import { resolve, sep, join, dirname, basename } from "node:path";
import { lstatSync, realpathSync } from "node:fs";
-function realpath(path: string): string {
+export function realpath(path: string): string {
try {
return realpathSync.native(path);
} catch (error) {
diff --git a/packages/studio-server/src/helpers/compositionInsertion.ts b/packages/studio-server/src/helpers/compositionInsertion.ts
index 7aa4aca7bd..af103d7e45 100644
--- a/packages/studio-server/src/helpers/compositionInsertion.ts
+++ b/packages/studio-server/src/helpers/compositionInsertion.ts
@@ -1,8 +1,8 @@
-import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { dirname, relative, resolve, sep } from "node:path";
import { parseHTML } from "linkedom";
-import { isSafePath, resolveWithinProject } from "./safePath.js";
+import { isSafePath, realpath, resolveWithinProject } from "./safePath.js";
export class CompositionInsertionError extends Error {
constructor(
@@ -43,8 +43,8 @@ function canonicalProjectPath(projectDir: string, candidate: string | null): str
if (!existsSync(candidate)) {
throw new CompositionInsertionError("Composition source was not found", 404);
}
- const canonical = realpathSync(candidate);
- if (!isSafePath(realpathSync(projectDir), canonical)) {
+ const canonical = realpath(candidate);
+ if (!isSafePath(realpath(projectDir), canonical)) {
throw new CompositionInsertionError("Composition source escapes the project", 400);
}
return canonical;
diff --git a/packages/studio-server/src/helpers/mediaCodecMap.ts b/packages/studio-server/src/helpers/mediaCodecMap.ts
index 32ed8adad9..15649e2df9 100644
--- a/packages/studio-server/src/helpers/mediaCodecMap.ts
+++ b/packages/studio-server/src/helpers/mediaCodecMap.ts
@@ -1,4 +1,5 @@
-import { existsSync, realpathSync, statSync } from "node:fs";
+import { existsSync, statSync } from "node:fs";
+import { realpath } from "./safePath.js";
import { relative, resolve, sep } from "node:path";
import { rewriteAssetPath } from "@hyperframes/parsers/asset-paths";
import {
@@ -253,7 +254,7 @@ export async function probeAssetCodec(
let target: string;
try {
stat = statSync(filePath);
- target = realpathSync(filePath);
+ target = realpath(filePath);
} catch {
return null;
}
diff --git a/packages/studio-server/src/helpers/proxyTranscoder.ts b/packages/studio-server/src/helpers/proxyTranscoder.ts
index 40f33d5dd6..1ec6cf6d0a 100644
--- a/packages/studio-server/src/helpers/proxyTranscoder.ts
+++ b/packages/studio-server/src/helpers/proxyTranscoder.ts
@@ -1,19 +1,12 @@
import { spawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
-import {
- existsSync,
- mkdirSync,
- realpathSync,
- renameSync,
- statSync,
- unlinkSync,
- utimesSync,
-} from "node:fs";
+import { existsSync, mkdirSync, renameSync, statSync, unlinkSync, utimesSync } from "node:fs";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
import { probeMediaMetadata } from "./mediaMetadata.js";
import { cleanupProxyCache } from "./proxyCache.js";
import { PROXY_VARIANT_CONFIG, type ProxyVariant } from "./mediaCodecMap.js";
+import { realpath } from "./safePath.js";
/**
* Transcodes browser-hostile local video sources (HEVC, ProRes, ...) into a
@@ -158,8 +151,8 @@ function canonicalizeProxySource(
throw new ProxySourceOutsideProjectError();
}
- const canonicalProjectDir = realpathSync(projectDir);
- const canonicalSourcePath = realpathSync(absoluteSourcePath);
+ const canonicalProjectDir = realpath(projectDir);
+ const canonicalSourcePath = realpath(absoluteSourcePath);
const canonicalRelativePath = relative(canonicalProjectDir, canonicalSourcePath);
const sourceIsInsideCanonicalProject =
canonicalRelativePath !== ".." &&
diff --git a/packages/studio-server/src/helpers/safePath.ts b/packages/studio-server/src/helpers/safePath.ts
index 3d9ccc3a3e..df86009b6f 100644
--- a/packages/studio-server/src/helpers/safePath.ts
+++ b/packages/studio-server/src/helpers/safePath.ts
@@ -1,16 +1,16 @@
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
-import { readdirSync, realpathSync, type Dirent } from "node:fs";
-import { resolveWithinProject } from "@hyperframes/core";
+import { readdirSync, type Dirent } from "node:fs";
+import { realpath, resolveWithinProject } from "@hyperframes/core";
// `isSafePath` lives at the package root so non-studio-api layers (compiler,
// CLI, engine) can share it without a backwards dependency on studio-api.
// Re-exported here for back-compat with existing `../helpers/safePath.js` imports.
-export { isSafePath, resolveWithinProject } from "@hyperframes/core";
+export { isSafePath, realpath, resolveWithinProject } from "@hyperframes/core";
/** The real path; for a path not there (yet, or any more), the nearest existing folder's real path plus the rest. */
export function realFilePath(filePath: string): string {
try {
- return realpathSync(filePath);
+ return realpath(filePath);
} catch {
const dir = dirname(filePath);
return dir === filePath ? filePath : join(realFilePath(dir), basename(filePath));
diff --git a/packages/studio-server/src/routes/files.pathSafety.test.ts b/packages/studio-server/src/routes/files.pathSafety.test.ts
index c66cdbe769..fd4a348cad 100644
--- a/packages/studio-server/src/routes/files.pathSafety.test.ts
+++ b/packages/studio-server/src/routes/files.pathSafety.test.ts
@@ -73,6 +73,46 @@ function upload(app: Hono, dir = "", filename = "upload.txt") {
}
describe("file route containment", () => {
+ it("writes the file a link resolves to when its target climbs out of a linked folder", async (context) => {
+ const { app, project } = fixture();
+ mkdirSync(join(project, "deep", "nested"), { recursive: true });
+ mkdirSync(join(project, "m"));
+ writeFileSync(join(project, "deep", "y.txt"), "old");
+ writeFileSync(join(project, "y.txt"), "decoy");
+ linkOrSkip(context, join(project, "deep", "nested"), join(project, "sub"), "dir");
+ linkOrSkip(context, "../sub/../y.txt", join(project, "m", "x.txt"), "file");
+
+ const response = await app.request(fileUrl("m/x.txt"), {
+ method: "PUT",
+ headers: { "If-Match": fileContentVersion("old") },
+ body: "new",
+ });
+
+ expect(response.status).toBe(200);
+ expect(readFileSync(join(project, "deep", "y.txt"), "utf8")).toBe("new");
+ expect(readFileSync(join(project, "y.txt"), "utf8")).toBe("decoy");
+ });
+
+ it("refuses a write through a link whose target climbs out of a folder linked outside", async (context) => {
+ const { app, project, outside } = fixture();
+ mkdirSync(join(outside, "a", "b"), { recursive: true });
+ mkdirSync(join(project, "m"));
+ writeFileSync(join(outside, "a", "y.txt"), "outside secret");
+ writeFileSync(join(project, "y.txt"), "decoy");
+ linkOrSkip(context, join(outside, "a", "b"), join(project, "sub"), "dir");
+ linkOrSkip(context, "../sub/../y.txt", join(project, "m", "x.txt"), "file");
+
+ const response = await app.request(fileUrl("m/x.txt"), {
+ method: "PUT",
+ headers: { "If-Match": fileContentVersion("outside secret") },
+ body: "overwrite",
+ });
+
+ expect(response.status).toBe(403);
+ expect(readFileSync(join(outside, "a", "y.txt"), "utf8")).toBe("outside secret");
+ expect(readFileSync(join(project, "y.txt"), "utf8")).toBe("decoy");
+ });
+
it.each(["GET", "PUT", "POST", "DELETE"])(
"rejects encoded traversal through %s without changing outside bytes",
async (method) => {