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:
+77
-77
File diff suppressed because one or more lines are too long
+2
-1
File diff suppressed because one or more lines are too long
@@ -41,6 +41,22 @@ runtime-зависимостей. Лимит — 2 ГБ и 60 000 файлов.
|
||||
ссылки и отмену; `test/multisite.test.mjs` скачивает оба сайта, проверяет
|
||||
изоляцию и авторизацию и импортирует полученный ZIP обратно в тестовый сайт.
|
||||
|
||||
## Файлы сайта
|
||||
|
||||
Кнопка «Файлы» в верхней навигации открывает существующий файловый менеджер
|
||||
для выбранного сайта. В заголовке указано имя сайта; список, загрузки, корзина,
|
||||
скачивание и запомненная папка изолированы по `/s/<site-id>/`. Просмотр и загрузка
|
||||
в этом режиме не подставляют файл в открытое поле и не меняют черновик страницы.
|
||||
Загрузки без привязки к полю сохраняются в `assets/uploads/media/library`.
|
||||
|
||||
После выбора файла кнопка «Скачать» передаёт его исходные байты и имя через
|
||||
авторизованный `GET /s/<site-id>/api/media/download?path=assets/...`.
|
||||
Видео передаются потоком без сборки ZIP и без загрузки целого файла в память
|
||||
браузера. Доступны публичные файлы `assets`; директории, скрытые/служебные
|
||||
пути и символические ссылки запрещены. Для удалённого файла сначала требуется
|
||||
восстановление из корзины. Кнопка скачивания доступна также в обычном выборе
|
||||
изображения, включая Open Graph. Публикация сайта остаётся отдельным действием.
|
||||
|
||||
## Git
|
||||
|
||||
Workflow `.gitea/workflows/ci.yml` квалифицирует точный commit в `master`, устанавливает зависимости по lockfile, проверяет синтаксис и изоляцию сайтов. Он сохраняет артефакт `dc-cms-release`. CI не получает учётные данные продакшена.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import SftpClient from "ssh2-sftp-client";
|
||||
import AdmZip from "adm-zip";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { createSiteBackup, siteBackupFilename } from "./site-backup.mjs";
|
||||
import { openMediaDownload } from "./media-download.mjs";
|
||||
|
||||
const cmsRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const port = Number(process.env.PORT || 8090);
|
||||
@@ -3034,6 +3035,21 @@ async function handle(req, res) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "GET" && url.pathname === "/api/media/download") {
|
||||
let download;
|
||||
try {
|
||||
download = await openMediaDownload(repoRoot, url.searchParams.get("path"));
|
||||
} catch (error) {
|
||||
const status = error.status || (["ENOENT", "ENOTDIR"].includes(error.code) ? 404 : 500);
|
||||
sendJson(res, status, { ok: false, error: status === 404 ? "Файл не найден" : status === 500 ? "Не удалось скачать файл" : error.message });
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, download.headers);
|
||||
// Stream large videos directly to the browser; do not hold a Blob in memory.
|
||||
pipeline(download.handle.createReadStream(), res).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "GET" && url.pathname === "/api/media/site-size") {
|
||||
sendJson(res, 200, await calculateProjectSize());
|
||||
return;
|
||||
|
||||
+30
-1
@@ -81,6 +81,35 @@ test('independent sites, rendering, secrets and publication ownership', async t
|
||||
assert.equal(await readFile(join(original,'index.html'),'utf8'),'<h1>Original</h1>');
|
||||
assert.equal(await (await fetch(base+'/s/mission-core/index.html')).text(),'<h1>Mission edited</h1>');
|
||||
});
|
||||
await t.test('media downloads keep original bytes, filename and selected-site ownership',async()=>{
|
||||
for (const [site,expected] of [['nodedc','original-asset'],['mission-core','mission-asset']]) {
|
||||
const response=await fetch(`${base}/s/${site}/api/media/download?path=assets%2Fproof.txt`);
|
||||
assert.equal(response.status,200);
|
||||
assert.match(response.headers.get('content-disposition'),/^attachment; filename="proof.txt"/);
|
||||
assert.equal(response.headers.get('cache-control'),'no-store');
|
||||
assert.equal(Number(response.headers.get('content-length')),Buffer.byteLength(expected));
|
||||
assert.equal(await response.text(),expected);
|
||||
}
|
||||
const name='Сессия 1 (оригинал).mp4',bytes=Buffer.from([0,1,2,255,128,0]);
|
||||
const missionRoot=join(projects,'sites/mission-core');
|
||||
await writeFile(join(missionRoot,'assets',name),bytes);
|
||||
const response=await fetch(`${base}/s/mission-core/api/media/download?path=${encodeURIComponent('assets/'+name)}`);
|
||||
assert.equal(response.status,200);
|
||||
assert.equal(decodeURIComponent(response.headers.get('content-disposition').split("filename*=UTF-8''")[1]),name);
|
||||
assert.deepEqual(Buffer.from(await response.arrayBuffer()),bytes);
|
||||
assert.equal((await fetch(`${base}/s/nodedc/api/media/download?path=${encodeURIComponent('assets/'+name)}`)).status,404);
|
||||
for (const path of ['../nodedc.json','assets/../../nodedc.json','content/pages/home.json','assets/.trash/private','assets/.env','/assets/proof.txt']) {
|
||||
assert.equal((await fetch(`${base}/s/mission-core/api/media/download?path=${encodeURIComponent(path)}`)).status,403,path);
|
||||
}
|
||||
await symlink(original,join(missionRoot,'assets/other-site'));
|
||||
await symlink(join(original,'assets/proof.txt'),join(missionRoot,'assets/linked.txt'));
|
||||
for (const path of ['assets/other-site/assets/proof.txt','assets/linked.txt']) {
|
||||
assert.equal((await fetch(`${base}/s/mission-core/api/media/download?path=${encodeURIComponent(path)}`)).status,403,path);
|
||||
}
|
||||
assert.equal((await fetch(`${base}/s/mission-core/api/media/download?path=assets/missing.jpg`)).status,404);
|
||||
assert.equal((await fetch(`${base}/s/mission-core/api/media/download?path=assets`)).status,403);
|
||||
for (const path of ['assets/other-site','assets/linked.txt','assets/'+name]) await rm(join(missionRoot,path));
|
||||
});
|
||||
await t.test('preview root links stay within their selected site',async()=>{
|
||||
const page=await (await fetch(base+'/s/mission-core/knowledge/')).text();
|
||||
assert.match(page,/href="\/s\/mission-core\/knowledge\/fleet\/"/);
|
||||
@@ -164,7 +193,7 @@ test('independent sites, rendering, secrets and publication ownership', async t
|
||||
});
|
||||
await stop();await start(true);
|
||||
await t.test('registry, scoped content and preview retain authentication',async()=>{
|
||||
for(const path of ['/api/sites','/s/mission-core/api/page/home','/s/mission-core/api/project/backup']){const response=await fetch(base+path,{redirect:'manual'});assert.equal(response.status,401,path);assert.match(response.headers.get('content-type'),/json/);}
|
||||
for(const path of ['/api/sites','/s/mission-core/api/page/home','/s/mission-core/api/project/backup','/s/mission-core/api/media/download?path=assets/proof.txt']){const response=await fetch(base+path,{redirect:'manual'});assert.equal(response.status,401,path);assert.match(response.headers.get('content-type'),/json/);}
|
||||
assert.equal((await fetch(base+'/s/mission-core/api/project/backup',{method:'POST',redirect:'manual'})).status,401);
|
||||
assert.equal((await fetch(base+'/s/mission-core/index.html',{redirect:'manual'})).status,302);
|
||||
assert.equal((await fetch(base+'/healthz')).status,200);
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ const header = h(AppHeader, {
|
||||
brand: h("img", { src: "./nodedc-logo.svg", alt: "NODE.DC" }),
|
||||
brandMonochrome: true,
|
||||
left: ib("toggle-navigation", "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0440\u0430\u0437\u0434\u0435\u043B\u044B", "panel"),
|
||||
center: h(HeaderNavigation, { label: "\u0420\u0430\u0437\u0434\u0435\u043B\u044B CMS", value: "content", onChange: noop, items: [["content", "\u041A\u043E\u043D\u0442\u0435\u043D\u0442"], ["seo", "SEO"], ["knowledge", "\u0411\u0430\u0437\u0430 \u0437\u043D\u0430\u043D\u0438\u0439"]].map(([value, label]) => ({ value, label: h("span", { "data-cms-mode": value }, label) })) }),
|
||||
center: h(HeaderNavigation, { label: "\u0420\u0430\u0437\u0434\u0435\u043B\u044B CMS", value: "content", onChange: noop, items: [["content", "\u041A\u043E\u043D\u0442\u0435\u043D\u0442"], ["seo", "SEO"], ["knowledge", "\u0411\u0430\u0437\u0430 \u0437\u043D\u0430\u043D\u0438\u0439"], ["files", "Файлы"]].map(([value, label]) => ({ value, label: h("span", { "data-cms-mode": value }, label) })) }),
|
||||
right: h("span", { id: "cms-profile", className: "cms-ui-island" })
|
||||
});
|
||||
const siteContext = h("div", { className: "cms-site-context" },
|
||||
|
||||
@@ -81,6 +81,7 @@
|
||||
</div>
|
||||
<div class="media-preview-actions">
|
||||
<button id="media-select" class="primary-btn" type="button" disabled>Выбрать</button>
|
||||
<button id="media-download" class="ghost-btn" type="button" disabled>Скачать</button>
|
||||
<button id="media-delete" class="danger-btn media-delete-btn" type="button" aria-label="Удалить файл" title="Удалить файл" disabled>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M3.75 6.75h16.5" />
|
||||
|
||||
+31
-7
@@ -215,6 +215,7 @@ const BLOCK_SEO_FIELDS = [
|
||||
|
||||
const el = {
|
||||
modeContent: document.querySelector("#admin-mode-content"),
|
||||
modeFiles: document.querySelector("#admin-mode-files"),
|
||||
modeSeo: document.querySelector("#admin-mode-seo"),
|
||||
modeKnowledge: document.querySelector("#admin-mode-knowledge"),
|
||||
modeNav: document.querySelector(".nodedc-expanded-nav-group"),
|
||||
@@ -287,6 +288,7 @@ const el = {
|
||||
mediaPreviewMeta: document.querySelector("#media-preview-meta"),
|
||||
mediaPreviewUsage: document.querySelector("#media-preview-usage"),
|
||||
mediaSelect: document.querySelector("#media-select"),
|
||||
mediaDownload: document.querySelector("#media-download"),
|
||||
mediaDelete: document.querySelector("#media-delete"),
|
||||
mediaContextMenu: document.querySelector("#media-context-menu"),
|
||||
mediaActionModal: document.querySelector("#media-action-modal"),
|
||||
@@ -2852,7 +2854,7 @@ function updateMediaFieldValue({ block, editableField, hiddenInput, urlInput, fi
|
||||
markDirty();
|
||||
}
|
||||
|
||||
async function uploadMediaFile({ block, editableField, hiddenInput, urlInput, fileName, preview, hint, error, setSource, afterUpload, onSelect, requiredKind, file }) {
|
||||
async function uploadMediaFile({ block, editableField, hiddenInput, urlInput, fileName, preview, hint, error, setSource, afterUpload, onSelect, requiredKind, mode, file }) {
|
||||
if (!file) return;
|
||||
if (requiredKind && mediaKindFromValue(file.name) !== requiredKind) {
|
||||
error.textContent = "Выберите файл изображения.";
|
||||
@@ -2872,7 +2874,7 @@ async function uploadMediaFile({ block, editableField, hiddenInput, urlInput, fi
|
||||
formData.append("file", file, file.name);
|
||||
formData.append("fileName", file.name);
|
||||
formData.append("mimeType", file.type || "application/octet-stream");
|
||||
formData.append("bucket", uploadBucketForField(block, editableField));
|
||||
formData.append("bucket", mode === "manage" ? "media/library" : uploadBucketForField(block, editableField));
|
||||
|
||||
const response = await siteFetch("/api/upload/asset", {
|
||||
method: "POST",
|
||||
@@ -2887,12 +2889,13 @@ async function uploadMediaFile({ block, editableField, hiddenInput, urlInput, fi
|
||||
throw new Error(payload.error || "Файл не удалось сохранить");
|
||||
}
|
||||
|
||||
if (!onSelect) {
|
||||
if (!onSelect && mode !== "manage") {
|
||||
updateMediaFieldValue({ block, editableField, hiddenInput, urlInput, fileName, preview, hint, value: payload.url });
|
||||
setSource("file");
|
||||
markDirty(`Файл сохранён: ${payload.url}. Нажмите «Сохранить», чтобы записать путь в content/pages/home.json.`);
|
||||
}
|
||||
if (typeof afterUpload === "function") await afterUpload(payload);
|
||||
if (mode === "manage") setStatus(`Файл загружен в медиатеку: ${payload.url}`);
|
||||
return payload;
|
||||
} catch (uploadError) {
|
||||
error.textContent = uploadError.message;
|
||||
@@ -3873,7 +3876,9 @@ function renderMediaPreviewPanel() {
|
||||
|
||||
renderMediaThumb(el.mediaPreview, file, { large: true });
|
||||
el.mediaSelect.textContent = state.mediaLibrary.trashMode ? "Восстановить" : "Выбрать";
|
||||
el.mediaSelect.classList.toggle("hidden", state.mediaLibrary.context?.mode === "manage" && !state.mediaLibrary.trashMode);
|
||||
el.mediaSelect.disabled = !file;
|
||||
el.mediaDownload.disabled = !file?.selectable || state.mediaLibrary.trashMode;
|
||||
el.mediaDelete.disabled = true;
|
||||
|
||||
if (!entry) {
|
||||
@@ -3971,7 +3976,8 @@ async function toggleMediaTrash() {
|
||||
async function openMediaLibrary(context) {
|
||||
const currentValue = context.currentUrl ?? context.hiddenInput?.value ?? "";
|
||||
const currentValuePath = pathFromUrl(currentValue);
|
||||
const suggestedPath = `assets/uploads/${uploadBucketForField(context.block, context.editableField)}`;
|
||||
const managing = context.mode === "manage";
|
||||
const suggestedPath = managing ? "assets" : `assets/uploads/${uploadBucketForField(context.block, context.editableField)}`;
|
||||
const lastPath = state.mediaLibrary.lastPath || readLastMediaDirectory();
|
||||
const startPath = (context.requiredKind && currentValuePath ? parentMediaPath(currentValuePath) : lastPath)
|
||||
|| (currentValuePath ? parentMediaPath(currentValuePath) : context.initialDirectory || suggestedPath);
|
||||
@@ -3986,8 +3992,9 @@ async function openMediaLibrary(context) {
|
||||
state.mediaLibrary.root = startPath;
|
||||
state.mediaLibrary.kind = context.requiredKind || "all";
|
||||
el.mediaSearch.value = "";
|
||||
el.mediaModalTitle.textContent = context.editableField.label || "Выбрать файл";
|
||||
el.mediaModalSubtitle.textContent = `${context.editableField.path} -> ${suggestedPath}`;
|
||||
el.mediaModalTitle.textContent = managing ? `Файлы — ${state.projectConfig?.name || state.projectConfig?.id || "текущий сайт"}` : context.editableField.label || "Выбрать файл";
|
||||
el.mediaModalSubtitle.textContent = managing ? "Изображения, видео и другие файлы выбранного сайта." : `${context.editableField.path} -> ${suggestedPath}`;
|
||||
el.mediaModalCancel.textContent = managing ? "Закрыть" : "Отмена";
|
||||
el.mediaModal.classList.remove("hidden");
|
||||
el.mediaSearch.focus();
|
||||
refreshMediaSiteSize().catch((error) => setStatus(`Ошибка размера сайта: ${error.message}`));
|
||||
@@ -4001,6 +4008,7 @@ async function openMediaLibrary(context) {
|
||||
}
|
||||
|
||||
function closeMediaLibrary() {
|
||||
const managing = state.mediaLibrary.context?.mode === "manage";
|
||||
closeMediaContextMenu();
|
||||
el.mediaModal.classList.add("hidden");
|
||||
delete el.mediaDropZone.dataset.dragActive;
|
||||
@@ -4009,6 +4017,18 @@ function closeMediaLibrary() {
|
||||
state.mediaLibrary.selectedUrl = "";
|
||||
state.mediaLibrary.selectedEntry = null;
|
||||
recoverEditorSurface();
|
||||
if (managing) el.modeFiles?.focus();
|
||||
}
|
||||
|
||||
function downloadSelectedMediaFile() {
|
||||
const file = selectedMediaFile();
|
||||
if (!file?.selectable || state.mediaLibrary.trashMode) return;
|
||||
const link = document.createElement("a");
|
||||
link.href = siteUrl(`/api/media/download?path=${encodeURIComponent(file.path)}`);
|
||||
link.download = file.name;
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
}
|
||||
|
||||
function matchesPickerKind(entry) {
|
||||
@@ -4025,7 +4045,7 @@ function chooseSelectedMediaFile() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!file.selectable || !matchesPickerKind(file)) return;
|
||||
if (context.mode === "manage" || !file.selectable || !matchesPickerKind(file)) return;
|
||||
if (typeof context.onSelect === "function") {
|
||||
context.onSelect(file.url, file);
|
||||
} else {
|
||||
@@ -6041,6 +6061,9 @@ for (const input of [el.id, el.label, el.anchor, el.enabled]) {
|
||||
el.modeContent?.addEventListener("click", () => setAdminMode("content"));
|
||||
el.modeSeo?.addEventListener("click", () => setAdminMode("seo"));
|
||||
el.modeKnowledge?.addEventListener("click", () => setAdminMode("knowledge"));
|
||||
el.modeFiles?.setAttribute("aria-haspopup", "dialog");
|
||||
el.modeFiles?.setAttribute("aria-controls", "media-modal");
|
||||
el.modeFiles?.addEventListener("click", () => openMediaLibrary({ mode: "manage", error: el.mediaModalSubtitle }));
|
||||
el.addProject?.addEventListener("click", () => openNewSite().catch(error => setStatus(error.message)));
|
||||
el.projectSettings?.addEventListener("click", openProjectSettings);
|
||||
|
||||
@@ -6104,6 +6127,7 @@ el.mediaUpload.addEventListener("click", () => {
|
||||
openMediaLibraryUploader();
|
||||
});
|
||||
el.mediaSelect.addEventListener("click", chooseSelectedMediaFile);
|
||||
el.mediaDownload.addEventListener("click", downloadSelectedMediaFile);
|
||||
el.mediaDelete.addEventListener("click", () => deleteSelectedMediaEntry().catch((error) => setStatus(`Ошибка удаления: ${error.message}`)));
|
||||
el.mediaTrashToggle.addEventListener("click", () => toggleMediaTrash().catch((error) => setStatus(`Ошибка корзины: ${error.message}`)));
|
||||
el.mediaDropZone.addEventListener("dragover", (event) => {
|
||||
|
||||
Reference in New Issue
Block a user