Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions packages/core/src/studio-api/helpers/safePath.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
import { resolve, sep, join } from "node:path";
import { readdirSync } from "node:fs";
import { resolve, sep, join, dirname, basename } from "node:path";
import { readdirSync, realpathSync } from "node:fs";

/** Reject paths that escape the project directory. */
export function isSafePath(base: string, resolved: string): boolean {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This closes a real escape, but I would still want one focused regression test here. isSafePath() is the guard for both the Studio file routes and preview asset serving, so the PR should prove a symlink inside the project cannot read or write outside the project root, while a normal in-project create still works. Otherwise this is easy to reopen later.

const norm = resolve(base) + sep;
return resolved.startsWith(norm) || resolved === resolve(base);
try {
const baseReal = realpathSync(resolve(base));
const target = resolve(resolved);
let probe = target;
const segments: string[] = [];
let targetReal: string;

while (true) {
try {
const real = realpathSync(probe);
targetReal = segments.length ? join(real, ...segments.reverse()) : real;
break;
} catch {
const parent = dirname(probe);
if (parent === probe) return false;
segments.push(basename(probe));
probe = parent;
}
}

const norm = baseReal + sep;
return targetReal.startsWith(norm) || targetReal === baseReal;
} catch {
return false;
}
}

const IGNORE_DIRS = new Set([".thumbnails", "node_modules", ".git"]);
Expand Down