Add site-scoped file manager navigation and original file downloads
DC CMS qualification / qualify (push) Successful in 1m53s
DC CMS qualification / qualify (push) Successful in 1m53s
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, open } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
// Downloads belong to one site and contain only its public assets. In particular,
|
||||
// never follow a symlink into another site's files, CMS settings or credentials.
|
||||
export async function openMediaDownload(siteRoot, path) {
|
||||
const segments = String(path || "").split("/");
|
||||
if (segments.length < 2 || segments[0] !== "assets" || segments.some(segment =>
|
||||
!segment || segment.startsWith(".") || segment === "node_modules" || /[\\\x00-\x1f\x7f]/.test(segment)
|
||||
)) {
|
||||
throw Object.assign(new Error("Скачивание доступно только для файлов медиатеки текущего сайта"), { status: 403 });
|
||||
}
|
||||
|
||||
let absolutePath = siteRoot;
|
||||
for (const segment of segments) {
|
||||
absolutePath = join(absolutePath, segment);
|
||||
const info = await lstat(absolutePath);
|
||||
if (info.isSymbolicLink()) {
|
||||
throw Object.assign(new Error("Скачивание по символической ссылке запрещено"), { status: 403 });
|
||||
}
|
||||
if (!info.isDirectory() && !info.isFile()) throw Object.assign(new Error("Выберите файл для скачивания"), { status: 400 });
|
||||
}
|
||||
const handle = await open(absolutePath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
const info = await handle.stat();
|
||||
if (!info.isFile()) throw Object.assign(new Error("Выберите файл для скачивания"), { status: 400 });
|
||||
const name = segments.at(-1);
|
||||
const fallback = name.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
const encoded = encodeURIComponent(name).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
||||
return {
|
||||
handle,
|
||||
headers: {
|
||||
"content-type": "application/octet-stream",
|
||||
"content-disposition": `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`,
|
||||
"content-length": info.size,
|
||||
"cache-control": "no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await handle.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user