feat: public Markdown and isolated HTML landing pages (3.2.4)

This commit is contained in:
SantaSpeen committed 2026-10-30 16:00:55 +03:00
1 parent 9f777bafbc
commit 3bc62d2b69
50 files changed
+1065 -94

No files matched your search

+93
View File
@@ -0,0 +1,93 @@
# Публичные страницы (3.2.4)
Папка с `page.md` в корне открывается страницей по `/s/{key}`.
Одиночные `.md`, `.markdown`, `.html` и `.htm` также открываются страницей.
Без `page.md` папка сохраняет обычный файловый вид. HTML внутри папки
открывается страницей по ссылке на конкретный файл; `page.html` не заменяет `page.md`.
Внизу страницы есть File Browser и «Отобразить как файлы» (`?view=files`).
Кнопка «Вернуться к странице» возвращает документ без повторного ввода пароля.
Ключ и пароль действуют для всех вложений; срок и права проверяются сервером
при каждом запросе. Перезагрузка защищённой ссылки снова требует пароль.
## Markdown
Используется GFM (заголовки, списки, таблицы, fenced code, цитаты):
```markdown
# Мой проект
![Схема](images/схема.png)
[Инструкция](docs/guide.md)
[Скачать PDF](docs/manual.pdf)
[Открыть папку](docs/)
| Возможность | Статус |
| --- | --- |
| Мобильная версия | Готово |
```
Пути разрешаются относительно документа, `/images/a.png` — от корня шары.
`..` допустим только внутри шары. Кодированные обходы, обратные слеши,
вложенное кодирование и выходящие симлинки отклоняются. Одиночный документ
не получает доступа к соседям: для вложений расшарьте содержащую их папку.
Изображения загружаются только из шары (PNG/JPEG/GIF/WebP/AVIF/SVG),
до 32 изображений, до 5 МиБ каждое и до 20 МиБ суммарно.
Сам документ — до 5 МиБ. Внешние HTTP(S) и mailto ссылки открываются отдельно.
Изображения и активное содержимое внешних сайтов не загружаются.
HTML в Markdown очищается DOMPurify; скрипты, стили, формы и iframe удаляются.
Математика и исполняемые блоки Markdown в этой версии не расширяются.
## HTML, CSS и JS
Для интерактивной страницы используйте один HTML-файл с inline CSS/JS:
```html
<!doctype html>
<html lang="ru">
<meta charset="utf-8">
<style>
body { margin: 0; padding: 24px; font: 18px/1.6 system-ui; }
button { padding: 12px 20px; }
</style>
<h1>Привет!</h1>
<button id="counter">Нажатий: 0</button>
<script>
let count = 0;
document.querySelector('#counter').onclick = function () {
this.textContent = 'Нажатий: ' + ++count;
};
</script>
</html>
```
HTML выполняется в `sandbox="allow-scripts"` без `allow-same-origin`.
Отдельная CSP HTTP-ответа запрещает сеть, fetch/XHR, внешние скрипты,
CSS-файлы, CSS URL, вложенные фреймы, формы и плагины. Скрипт имеет доступ
к DOM своей страницы, но не к cookies, localStorage и DOM File Browser.
Родитель загружает разрешённые изображения и передаёт HTML-странице только data URI;
ссылки обрабатываются через ограниченный список идентификаторов.
Токены, пароли, SSO credentials и API загрузки не передаются скрипту.
В HTML допустимы те же статические `<img src="images/a.png">` и
`<a href="docs/">` в пределах папочной шары. Для одиночного HTML используйте
inline графику или data URI. Внешние `script src`, `link`, `base`, meta,
формы и embed удаляются. Якоря HTML остаются внутри iframe.
Пользовательский JS может менять свой DOM; динамическая загрузка вложений
не поддерживается. Скрипты должны быть короткими: sandbox не ограничивает CPU.
Общая CSP приложения и обработка обычного Markdown не ослабляются.
## Редактор
Сохранён существующий Ace: Markdown/HTML подсветка, номера строк, перенос,
поиск/замена, undo/redo, Ctrl+S, изменение размера шрифта. При ошибке сохранения
редактор не подтверждает выход. Live completion отключается после 200 000 символов.
Не добавлена вторая редакторская библиотека. Современный CodeMirror 6 модулен
и позволяет компактную сборку, но миграция требует новых модулей языков,
команд и обвязки; для уже работающего Ace это лишние загрузки и риск регрессий.
Оба используют оптимизации отображения, поэтому универсального утверждения
о скорости без замеров на конкретном старом ПК здесь нет.
Официальные источники: [Ace](https://ace.c9.io/),
[CodeMirror: устройство](https://codemirror.net/docs/guide/),
[минимальный редактор](https://codemirror.net/examples/basic/).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "filebrowser-frontend",
"version": "3.2.3",
"version": "3.2.4",
"private": true,
"type": "module",
"engines": {
@@ -0,0 +1,396 @@
<template>
<section class="landing" :aria-label="resource.name">
<p v-if="busy" role="status">{{ t("files.loading") }}</p>
<p v-else-if="failure" role="alert">{{ failure }}</p>
<iframe
v-else-if="htmlDocument"
ref="frame"
:src="shell"
sandbox="allow-scripts"
referrerpolicy="no-referrer"
:title="resource.name"
/>
<article
v-else
ref="article"
class="landing-markdown"
v-html="rendered"
@click="follow"
/>
<footer>
File Browser
<button class="button button--flat" @click="$emit('files')">
{{ t("files.landingFiles") }}
</button>
</footer>
</section>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { pub as api } from "@/api";
import { baseURL } from "@/utils/constants";
import { previewBuffer } from "@/utils/preview";
import { landingPath, externalLandingLink } from "@/utils/landing";
const props = defineProps<{
resource: Resource;
directoryShare: boolean;
shareRoot: string;
}>();
defineEmits<{ files: [] }>();
const { t } = useI18n(),
router = useRouter();
const frame = ref<HTMLIFrameElement>(),
article = ref<HTMLElement>();
const rendered = ref(""),
busy = ref(true),
failure = ref("");
const htmlDocument = computed(() => /\.html?$/i.test(props.resource.name));
const shell = baseURL + "/api/public/landing-shell";
let controller: AbortController | undefined;
let delivered = false;
let blobs: string[] = [],
links = new Map<string, string>();
function release() {
blobs.forEach(URL.revokeObjectURL);
blobs = [];
}
function navigate(id: string) {
const target = links.get(id);
if (!target) return;
if (target.startsWith("#")) {
article.value
?.querySelector(`[id="${CSS.escape(target.slice(1))}"]`)
?.scrollIntoView();
return;
}
if (externalLandingLink(target)) {
window.open(target, "_blank", "noopener,noreferrer");
return;
}
void router.push(target);
}
function follow(e: MouseEvent) {
const a = (e.target as Element).closest(
"a[data-landing-link]"
) as HTMLElement | null;
if (a) {
e.preventDefault();
navigate(a.dataset.landingLink!);
}
}
function message(e: MessageEvent) {
if (e.source !== frame.value?.contentWindow || e.origin !== "null") return;
if (e.data?.type === "landing-ready" && !delivered) {
delivered = true;
frame.value.contentWindow?.postMessage(
{ type: "landing-content", html: rendered.value },
"*"
);
}
if (e.data?.type === "landing-link" && typeof e.data.id === "string")
navigate(e.data.id);
}
onMounted(() => window.addEventListener("message", message));
onBeforeUnmount(() => {
controller?.abort();
release();
window.removeEventListener("message", message);
});
watch(
() => props.resource,
async (resource) => {
controller?.abort();
delivered = false;
release();
links = new Map();
rendered.value = "";
failure.value = "";
busy.value = true;
const request = (controller = new AbortController());
const localBlobs: string[] = [];
try {
const source = api.getDownloadURL(resource, true);
const content = new TextDecoder().decode(
await previewBuffer(source, request.signal)
);
const [{ marked }, { default: purify }] = await Promise.all([
import("marked"),
import("dompurify"),
]);
const html = htmlDocument.value
? content
: purify.sanitize(await marked(content), {
FORBID_TAGS: [
"style",
"link",
"iframe",
"object",
"embed",
"form",
"input",
"video",
"audio",
"svg",
"math",
],
FORBID_ATTR: ["style", "srcset", "background", "class"],
});
// Template contents are inert, including resource loading. Parse untrusted
// HTML here before any URL can reach a live document.
const template = document.createElement("template");
template.innerHTML = html;
const doc = template.content;
// HTML scripts and styles are inline only. No URL carrying share credentials
// is ever sent to the opaque frame. CSP also blocks URLs created at runtime.
doc
.querySelectorAll(
"base, meta, link, iframe, object, embed, form, script[src]"
)
.forEach((el) => el.remove());
doc.querySelectorAll("*").forEach((el) => {
for (const attr of [...el.attributes]) {
if (
[
"src",
"srcset",
"href",
"action",
"formaction",
"poster",
"background",
"ping",
"data",
"xlink:href",
"data-landing-link",
].includes(attr.name)
) {
if (attr.name === "src" && el.tagName === "IMG") continue;
if (attr.name === "href" && el.tagName === "A") continue;
el.removeAttribute(attr.name);
}
}
});
const nextLinks = new Map<string, string>();
doc.querySelectorAll("a").forEach((a) => {
const href = a.getAttribute("href") || "";
if (htmlDocument.value && href.startsWith("#")) return;
a.removeAttribute("href");
a.removeAttribute("target");
const path = landingPath(href, resource.path, props.directoryShare);
const target = href.startsWith("#")
? href
: externalLandingLink(href)
? href
: path
? props.shareRoot +
path +
(href.includes("#")
? "#" + href.split("#").slice(1).join("#")
: "")
: "";
if (!target) return;
const id = String(nextLinks.size);
nextLinks.set(id, target);
a.dataset.landingLink = id;
a.href = "#";
});
let total = 0;
const images = [...doc.querySelectorAll("img")];
for (let i = 0; i < images.length; i++) {
const img = images[i],
href = img.getAttribute("src") || "";
img.removeAttribute("src");
img.setAttribute("referrerpolicy", "no-referrer");
if (
htmlDocument.value &&
/^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/i.test(href)
) {
img.src = href;
continue;
}
const path = landingPath(href, resource.path, props.directoryShare);
if (!path || i >= 32 || total >= 20 * 1024 * 1024) continue;
try {
const data = await previewBuffer(
api.getDownloadURL(
{ ...resource, path: decodeURIComponent(path) },
true
),
request.signal,
Math.min(5 * 1024 * 1024, 20 * 1024 * 1024 - total)
);
total += data.byteLength;
const ext = path.split(".").pop()?.toLowerCase();
const mime = (
{
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
avif: "image/avif",
svg: "image/svg+xml",
} as Record<string, string>
)[ext || ""];
if (!mime) continue;
const image = new Blob([data], { type: mime });
if (htmlDocument.value) {
// A parent's blob URL is inaccessible from an opaque sandbox in
// Chromium. Send bounded image bytes, without an authenticated URL.
img.src = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(image);
});
} else {
const blob = URL.createObjectURL(image);
localBlobs.push(blob);
img.src = blob;
}
} catch (e) {
if (request.signal.aborted) throw e;
}
}
if (request.signal.aborted) return;
links = nextLinks;
blobs = localBlobs;
if (htmlDocument.value) {
rendered.value =
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
template.innerHTML;
} else {
doc.querySelectorAll("h1,h2,h3,h4,h5,h6").forEach((heading, index) => {
heading.id =
(heading.textContent || "")
.toLowerCase()
.trim()
.replace(/[^\p{L}\p{N}\s_-]/gu, "")
.replace(/\s+/g, "-") || `heading-${index}`;
});
rendered.value = template.innerHTML;
}
} catch (e) {
if (!request.signal.aborted) failure.value = String(e);
} finally {
if (request.signal.aborted) localBlobs.forEach(URL.revokeObjectURL);
if (controller === request) busy.value = false;
}
},
{ immediate: true }
);
</script>
<style scoped>
.landing {
position: fixed;
inset: 0;
overflow: auto;
background: var(--background, #fff);
color: var(--textSecondary, #24292f);
z-index: 20;
display: flex;
flex-direction: column;
}
.landing > p {
padding: 2rem;
}
iframe {
border: 0;
width: 100%;
flex: 1 0 calc(100vh - 64px);
flex: 1 0 calc(100dvh - 64px);
background: white;
}
footer {
margin-top: auto;
padding: 0.6rem 1rem;
display: flex;
align-items: center;
justify-content: center;
gap: 1rem;
font-size: 0.85rem;
border-top: 1px solid #8883;
}
.landing-markdown {
width: 100%;
max-width: 960px;
box-sizing: border-box;
padding: 24px;
padding: clamp(20px, 5vw, 64px);
margin: 0 auto;
font:
17px/1.7 system-ui,
sans-serif;
overflow-wrap: anywhere;
}
.landing-markdown :deep(h1),
.landing-markdown :deep(h2),
.landing-markdown :deep(h3) {
line-height: 1.25;
margin: 1.5em 0 0.6em;
font-weight: 650;
}
.landing-markdown :deep(h1) {
font-size: 2.25em;
border-bottom: 1px solid #8884;
padding-bottom: 0.3em;
}
.landing-markdown :deep(h2) {
font-size: 1.65em;
}
.landing-markdown :deep(p) {
margin: 1em 0;
}
.landing-markdown :deep(a) {
color: #0969da;
text-decoration: underline;
cursor: pointer;
}
.landing-markdown :deep(img) {
max-width: 100%;
height: auto;
}
.landing-markdown :deep(pre) {
padding: 1rem;
background: #8881;
overflow-x: auto;
border-radius: 6px;
overflow-wrap: normal;
}
.landing-markdown :deep(code) {
font:
0.88em/1.6 ui-monospace,
Consolas,
monospace;
background: #8881;
padding: 0.15em 0.3em;
border-radius: 3px;
}
.landing-markdown :deep(pre code) {
background: none;
padding: 0;
}
.landing-markdown :deep(table) {
display: block;
max-width: 100%;
overflow-x: auto;
border-collapse: collapse;
}
.landing-markdown :deep(th),
.landing-markdown :deep(td) {
border: 1px solid #8885;
padding: 0.5em 0.85em;
}
.landing-markdown :deep(tr:nth-child(even)) {
background: #8881;
}
.landing-markdown :deep(blockquote) {
margin-inline: 0;
padding-inline-start: 1em;
border-inline-start: 4px solid #8885;
color: #687078;
}
</style>
+6
View File
@@ -69,6 +69,12 @@
"connection": "لا يمكن اﻹتصال بالخادم."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "الصفحة",
"closePreview": "إغلاق العرض",
"files": "الملفات",
+6
View File
@@ -69,6 +69,12 @@
"connection": "Сървъра не може да бъде достигнат."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Тяло",
"closePreview": "Затвори прегледа",
"files": "Файлове",
+6
View File
@@ -69,6 +69,12 @@
"connection": "No es pot accedir al servidor."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Cos",
"closePreview": "Tancar vista prèvia",
"files": "Fitxers",
+6
View File
@@ -69,6 +69,12 @@
"connection": "Server nelze dosáhnout."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Tělo",
"closePreview": "Zavřít náhled",
"files": "Soubory",
+6
View File
@@ -71,6 +71,12 @@
"connection": "Der Server ist nicht erreichbar."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Inhalt",
"closePreview": "Vorschau schließen",
"files": "Dateien",
+6
View File
@@ -69,6 +69,12 @@
"connection": "Ο διακομιστής δεν είναι διαθέσιμος."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Περιεχόμενο",
"closePreview": "Κλείσιμο προεπισκόπησης",
"files": "Αρχεία",
+6
View File
@@ -72,6 +72,12 @@
"connection": "The server can't be reached."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Body",
"closePreview": "Close preview",
"files": "Files",
+6
View File
@@ -69,6 +69,12 @@
"connection": "No se puede acceder al servidor."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Cuerpo",
"closePreview": "Cerrar vista previa",
"files": "Archivos",
+6
View File
@@ -69,6 +69,12 @@
"connection": "سرور قابل دسترسی نیست"
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "بدنه",
"closePreview": "بستن نمایش",
"files": "فایل ها",
+6
View File
@@ -71,6 +71,12 @@
"connection": "Le serveur est injoignable."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Corps",
"closePreview": "Fermer la prévisualisation",
"files": "Fichiers",
+6
View File
@@ -69,6 +69,12 @@
"connection": "לא ניתן להגיע לשרת"
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "גוף",
"closePreview": "סגירת תצוגה מקדימה",
"files": "קבצים",
+6
View File
@@ -71,6 +71,12 @@
"connection": "Poslužitelj ne može biti dohvaćen."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Tijelo",
"closePreview": "Zatvori pregled",
"files": "Datoteke",
+6
View File
@@ -69,6 +69,12 @@
"connection": "A kiszolgáló nem érhető el."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Törzs",
"closePreview": "Előnézet bezárása",
"files": "Fájlok",
+6
View File
@@ -69,6 +69,12 @@
"connection": "The server can't be reached."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Meginmál",
"closePreview": "Loka forskoðun",
"files": "Skjöl",
+6
View File
@@ -69,6 +69,12 @@
"connection": "Il server non è raggiungibile"
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Contenuto",
"closePreview": "Chiudi anteprima",
"files": "File",
+6
View File
@@ -69,6 +69,12 @@
"connection": "サーバーに接続できませんでした。"
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "本文",
"closePreview": "プレビューを閉じる",
"files": "ファイル",
+6
View File
@@ -71,6 +71,12 @@
"connection": "서버에 연결할 수 없습니다."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "본문",
"closePreview": "미리보기 닫기",
"files": "파일",
+6
View File
@@ -71,6 +71,12 @@
"connection": "Ar serveri nevar sazināties."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Ķermenis",
"closePreview": "Aizvērt priekšskatījumu",
"files": "Faili",
+6
View File
@@ -69,6 +69,12 @@
"connection": "The server can't be reached."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Body",
"closePreview": "Voorvertoon sluiten",
"files": "Bestanden",
+6
View File
@@ -71,6 +71,12 @@
"connection": "De server kan niet worden bereikt."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Inoud",
"closePreview": "Voorbeeld sluiten",
"files": "Bestanden",
+6
View File
@@ -69,6 +69,12 @@
"connection": "Denne serveren kan ikkje nås."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Kropp",
"closePreview": "Lukk forhandsvisning",
"files": "Filer",
+6
View File
@@ -71,6 +71,12 @@
"connection": "Serwer jest nieosiągalny."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Zawartość",
"closePreview": "Zamknij podgląd",
"files": "Pliki",
+6
View File
@@ -69,6 +69,12 @@
"connection": "O servidor não pode ser alcançado."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Corpo",
"closePreview": "Fechar pré-visualização",
"files": "Arquivos",
+6
View File
@@ -71,6 +71,12 @@
"connection": "Este servidor não pôde ser alcançado."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Corpo",
"closePreview": "Fechar pré-visualização",
"files": "Ficheiros",
+6
View File
@@ -69,6 +69,12 @@
"connection": "The server can't be reached."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Corp",
"closePreview": "Închide previzualizarea",
"files": "Fișiere",
+6
View File
@@ -72,6 +72,12 @@
"connection": "Нет подключения к серверу."
},
"files": {
"editorUndo": "Отменить",
"editorRedo": "Повторить",
"editorFind": "Найти",
"editorReplace": "Заменить",
"landingFiles": "Отобразить как файлы",
"landingPage": "Вернуться к странице",
"body": "Тело",
"closePreview": "Закрыть",
"files": "Файлы",
+6
View File
@@ -69,6 +69,12 @@
"connection": "The server can't be reached."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Telo",
"closePreview": "Zavrieť náhľad",
"files": "Súbory",
+6
View File
@@ -69,6 +69,12 @@
"connection": "Servern går inte att nå."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Huvud",
"closePreview": "Stäng förhands granskningen",
"files": "Filer",
+6
View File
@@ -69,6 +69,12 @@
"connection": "Sunucuya ulaşılamıyor."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Sayfa",
"closePreview": "Önizlemeyi kapat",
"files": "Dosyalar",
+6
View File
@@ -69,6 +69,12 @@
"connection": "Немає підключення до сервера."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Тіло",
"closePreview": "Закрити",
"files": "Файли",
+6
View File
@@ -69,6 +69,12 @@
"connection": "Không thể kết nối đến máy chủ."
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "Nội dung",
"closePreview": "Đóng xem trước",
"files": "Tập tin",
+6
View File
@@ -71,6 +71,12 @@
"connection": "无法连接服务器"
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "内容",
"closePreview": "关闭预览",
"files": "文件",
+6
View File
@@ -69,6 +69,12 @@
"connection": "無法連接到伺服器。"
},
"files": {
"editorUndo": "Undo",
"editorRedo": "Redo",
"editorFind": "Find",
"editorReplace": "Replace",
"landingFiles": "Display as files",
"landingPage": "Return to page",
"body": "内容",
"closePreview": "關閉預覽",
"files": "檔案",
+2
View File
@@ -6,10 +6,12 @@ export const useLayoutStore = defineStore("layout", {
// convert to a function
state: (): {
loading: boolean;
publicLanding: boolean;
prompts: PopupProps[];
showShell: boolean | null;
} => ({
loading: false,
publicLanding: false,
prompts: [],
showShell: false,
}),
@@ -0,0 +1,29 @@
import { expect, it } from "vitest";
import { landingPath, externalLandingLink } from "../landing";
it("resolves attachments relative to the document inside a folder share", () => {
expect(landingPath("../images/кот.png", "/docs/page.md", true)).toBe(
"/images/%D0%BA%D0%BE%D1%82.png"
);
expect(landingPath("a%20b.pdf#x", "/page.md", true)).toBe("/a%20b.pdf");
expect(landingPath("my image.png", "/page.md", true)).toBe("/my%20image.png");
expect(landingPath("/docs/", "/page.md", true)).toBe("/docs/");
});
it("blocks traversal, nested encoding, alternate separators and protocols", () => {
for (const path of [
"../secret",
"%2e%2e/secret",
"%252e%252e/secret",
"a%2f../../secret",
"..\\secret",
"%5csecret",
"//host/a",
"https://host/a",
"javascript:alert(1)",
"/C:/secret",
"%00",
])
expect(landingPath(path, "/page.md", true), path).toBeNull();
expect(landingPath("neighbor.png", "/", false)).toBeNull();
expect(externalLandingLink("javascript:alert(1)")).toBe(false);
expect(externalLandingLink("https://example.org")).toBe(true);
});
+40
View File
@@ -0,0 +1,40 @@
// Resolve only share-relative paths. Never let URL normalization erase an
// attempted escape before we check it; decode once and reject nested escapes.
export function landingPath(
href: string,
documentPath: string,
directoryShare: boolean
): string | null {
if (
!directoryShare ||
/[\\\u0000-\u001f]/.test(href) ||
/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)
)
return null;
const path = href.split(/[?#]/)[0];
let decoded: string;
try {
decoded = decodeURIComponent(path);
} catch {
return null;
}
if (/[\\%:\u0000-\u001f]/.test(decoded)) return null;
const parts = decoded.startsWith("/")
? []
: documentPath.split("/").slice(0, -1).filter(Boolean);
for (const part of decoded.split("/")) {
if (part === "..") {
if (!parts.length) return null;
parts.pop();
} else if (part && part !== ".") parts.push(part);
}
return (
"/" +
parts.map(encodeURIComponent).join("/") +
(decoded.endsWith("/") && parts.length ? "/" : "")
);
}
export function externalLandingLink(href: string): boolean {
return /^(https?:\/\/|mailto:)/i.test(href) && !/[\u0000-\u0020]/.test(href);
}
+3 -1
View File
@@ -45,7 +45,9 @@ const authStore = useAuthStore();
const fileStore = useFileStore();
const uploadStore = useUploadStore();
const route = useRoute();
const hideSidebar = computed(() => route.name === "Share" && hideLoginButton);
const hideSidebar = computed(
() => route.name === "Share" && (hideLoginButton || layoutStore.publicLanding)
);
const sentPercent = computed(() =>
((uploadStore.sentBytes / uploadStore.totalBytes) * 100).toFixed(2)
+93 -10
View File
@@ -1,6 +1,17 @@
<template>
<div>
<header-bar :showMenu="!hideLoginButton" showLogo>
<ShareLanding
v-if="landing && !showFiles && !layoutStore.loading && !error"
:resource="landing"
:directoryShare="directoryShare"
:shareRoot="shareBase(route.path)"
@files="setFileView(true)"
/>
<header-bar
v-if="!landing || showFiles || error"
:showMenu="!hideLoginButton"
showLogo
>
<title />
<action
@@ -26,7 +37,17 @@
/>
</header-bar>
<breadcrumbs :base="shareBase(route.path)" />
<breadcrumbs
v-if="!landing || showFiles || error"
:base="shareBase(route.path)"
/>
<button
v-if="landing && showFiles"
class="button button--flat"
@click="setFileView(false)"
>
{{ t("files.landingPage") }}
</button>
<div v-if="layoutStore.loading">
<h2 class="message delayed" style="padding-top: 3em !important">
@@ -73,7 +94,7 @@
</div>
<errors v-else :errorCode="error.status" />
</div>
<div v-else-if="req !== null">
<div v-else-if="req !== null && (!landing || showFiles)">
<div
class="share"
:class="{
@@ -206,11 +227,12 @@ import Errors from "@/views/Errors.vue";
import Item from "@/components/files/ListingItem.vue";
import FileIcon from "@/components/files/FileIcon.vue";
import ResourcePreview from "@/components/files/ResourcePreview.vue";
import ShareLanding from "@/components/files/ShareLanding.vue";
import { previewKind } from "@/utils/preview";
import { useFileStore } from "@/stores/file";
import { useLayoutStore } from "@/stores/layout";
import { computed, inject, onMounted, onBeforeUnmount, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { StatusError } from "@/api/utils";
import { copy } from "@/utils/clipboard";
@@ -231,13 +253,34 @@ const $showSuccess = inject<IToastSuccess>("$showSuccess")!;
const { t } = useI18n({});
const route = useRoute();
const router = useRouter();
const landing = ref<Resource | null>(null);
const directoryShare = ref(false);
const showFiles = computed(() => route.query.view === "files");
const setFileView = (files: boolean) =>
router.push({
path: route.path,
query: { ...route.query, view: files ? "files" : undefined },
hash: route.hash,
});
const fileStore = useFileStore();
const layoutStore = useLayoutStore();
watch(
[landing, showFiles, () => layoutStore.loading, error],
() => {
layoutStore.publicLanding =
!!landing.value && !showFiles.value && !error.value;
},
{ immediate: true }
);
watch(route, () => {
showLimit.value = 100;
fetchData();
});
watch(
() => route.path,
() => {
showLimit.value = 100;
fetchData();
}
);
const req = computed(() => fileStore.req);
const sharedPreview = computed(
@@ -270,6 +313,14 @@ const modTime = computed(() =>
// Functions
const base64 = (name: any) => Base64.encodeURI(name);
const fetchData = async () => {
const generation = ++fetchGeneration;
if (activeHash !== hash.value) {
activeHash = hash.value;
password.value = "";
token.value = "";
attemptedPasswordLogin.value = false;
landing.value = null;
}
fileStore.reload = false;
fileStore.selected = [];
fileStore.multiple = false;
@@ -287,21 +338,51 @@ const fetchData = async () => {
if (url[0] !== "/") url = "/" + url;
try {
const file = await api.fetch(url, password.value);
const file = await api.fetch(url, password.value, { token: token.value });
if (generation !== fetchGeneration) return;
file.hash = hash.value;
token.value = file.token || "";
// Discover the root once per request, also when entering a nested URL.
const root =
file.isDir && url.replace(/\/+$/, "") === shareBase(url)
? file
: await api.fetch(shareBase(url), password.value, {
token: token.value,
});
if (generation !== fetchGeneration) return;
directoryShare.value = root.isDir;
landing.value = null;
if (!file.isDir && /\.(md|markdown|html?)$/i.test(file.name))
landing.value = file;
else if (root === file) {
const page = file.items.find(
(item) => item.name === "page.md" && !item.isDir
);
if (page)
landing.value = {
...file,
...page,
items: [],
hash: hash.value,
token: file.token,
};
}
fileStore.updateRequest(file);
document.title = `${file.name} - ${document.title}`;
} catch (err) {
if (generation !== fetchGeneration) return;
if (err instanceof Error) {
error.value = err;
}
} finally {
layoutStore.loading = false;
if (generation === fetchGeneration) layoutStore.loading = false;
}
};
let fetchGeneration = 0;
let activeHash = hash.value;
const keyEvent = (event: KeyboardEvent) => {
if (event.key === "Escape") {
@@ -368,6 +449,8 @@ onMounted(async () => {
});
onBeforeUnmount(() => {
fetchGeneration++;
layoutStore.publicLanding = false;
// Destroyed
window.removeEventListener("keydown", keyEvent);
});
+32 -2
View File
@@ -38,6 +38,34 @@
<Breadcrumbs base="/files" noLink />
<div>
<button
@click="executeEditorCommand('undo')"
:title="t('files.editorUndo')"
:aria-label="t('files.editorUndo')"
>
<AppIcon name="undo" />
</button>
<button
@click="executeEditorCommand('redo')"
:title="t('files.editorRedo')"
:aria-label="t('files.editorRedo')"
>
<AppIcon name="redo" />
</button>
<button
@click="executeEditorCommand('find')"
:title="t('files.editorFind')"
:aria-label="t('files.editorFind')"
>
<AppIcon name="search" />
</button>
<button
@click="executeEditorCommand('replace')"
:title="t('files.editorReplace')"
:aria-label="t('files.editorReplace')"
>
<AppIcon name="find_replace" />
</button>
<button
:disabled="isSelectionEmpty"
@click="executeEditorCommand('copy')"
@@ -207,7 +235,7 @@ onBeforeRouteUpdate((to, from, next) => {
next();
},
saveAction: async () => {
await save();
await save(true);
next();
},
});
@@ -221,13 +249,15 @@ const initEditor = (fileContent: string) => {
editor.value = ace.edit("editor", {
value: fileContent,
showPrintMargin: false,
showGutter: true,
showLineNumbers: true,
useWorker: false,
readOnly: fileStore.req?.type === "textImmutable",
theme: getEditorTheme(),
mode: modelist.getModeForPath(fileStore.req!.name).mode,
wrap: true,
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableLiveAutocompletion: fileContent.length < 200_000,
enableSnippets: true,
});
+1
View File
@@ -110,6 +110,7 @@ func NewHandler(
api.PathPrefix("/subtitle").Handler(monkey(subtitleHandler, "/api/subtitle")).Methods("GET")
public := api.PathPrefix("/public").Subrouter()
public.HandleFunc("/landing-shell", publicLandingShell).Methods("GET")
public.PathPrefix("/dl").Handler(monkey(publicDlHandler, "/api/public/dl/")).Methods("GET")
public.PathPrefix("/share").Handler(monkey(publicShareHandler, "/api/public/share/")).Methods("GET")
+10 -3
View File
@@ -17,6 +17,9 @@ import (
var withHashFile = func(fn handleFunc) handleFunc {
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
id, ifPath := ifPathWithName(r)
if !validSharePath(r.URL.Path) {
return http.StatusBadRequest, nil
}
link, err := d.store.Share.GetByHash(id)
if err != nil {
return errToStatus(err), err
@@ -62,14 +65,18 @@ var withHashFile = func(fn handleFunc) handleFunc {
if file.IsDir {
filePath = ifPath
} else if ifPath != "/" && ifPath != "." && ifPath != "/"+file.Name {
// Keep the legacy /key/original-filename download alias, but never
// interpret a suffix on a single-file share as an attachment path.
return http.StatusNotFound, nil
}
// set fs root to the shared file/folder. Unless external symlinks are
// explicitly allowed, this is a ScopedFs (not a bare BasePathFs) so the
// Set fs root to the shared file/folder. Public access always uses a
// ScopedFs (not a bare BasePathFs) so the
// share is also symlink-confined: a link inside the shared subtree that
// points elsewhere in the owner's scope — outside the share — must not be
// followed.
d.user.Fs = files.NewFs(d.user.Fs, basePath, d.server.FollowExternalSymlinks)
d.user.Fs = files.NewScopedFs(d.user.Fs, basePath)
// the filesystem is now rebased onto basePath, so paths handed to the
// rule checker are relative to it. Resolve them back to the user's
+52
View File
@@ -0,0 +1,52 @@
package fbhttp
import (
"net/http"
"strings"
)
// URL.Path has already been decoded once by net/http. Refuse alternate
// separators and residual escapes rather than interpreting a second time.
func validSharePath(p string) bool {
if strings.ContainsAny(p, "\\%\x00:") {
return false
}
depth := 0
for i, part := range strings.Split(p, "/") {
if i == 0 {
continue
}
if part == ".." {
depth--
if depth < 0 {
return false
}
} else if part != "" && part != "." {
depth++
}
}
return true
}
// This empty, credential-free shell is the only place user scripts execute.
// A response CSP (not an editable meta tag) survives document.write. The opaque
// sandbox origin cannot read cookies, storage, or the File Browser parent.
func publicLandingShell(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Security-Policy", "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src blob: data:; media-src blob: data:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'")
_, _ = w.Write([]byte(`<!doctype html><meta charset="utf-8"><script>
addEventListener('message', function receive(e) {
if(e.source !== parent || !e.data || typeof e.data !== 'object' || e.data.type !== 'landing-content' || typeof e.data.html !== 'string') return;
removeEventListener('message', receive);
document.open(); document.write(e.data.html); document.close();
document.addEventListener('click', function(e) {
var a=e.target && e.target.closest ? e.target.closest('a[data-landing-link]') : null;
if(a){e.preventDefault();parent.postMessage({type:'landing-link',id:a.dataset.landingLink}, '*');}
}, true);
});
parent.postMessage({type:'landing-ready'}, '*');
</script>`))
}
+97
View File
@@ -0,0 +1,97 @@
package fbhttp
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/asdine/storm/v3"
"github.com/filebrowser/filebrowser/v2/files"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/share"
"github.com/filebrowser/filebrowser/v2/storage/bolt"
"github.com/filebrowser/filebrowser/v2/users"
"github.com/spf13/afero"
)
func TestLandingSharePaths(t *testing.T) {
for _, p := range []string{"h/../secret", "h/a/../../secret", "h/%2e%2e/secret", "h/%252e/secret", "h/..\\secret", "h/C:/secret", "h/\x00"} {
if validSharePath(p) {
t.Errorf("accepted unsafe path %q", p)
}
}
for _, p := range []string{"h", "h/", "h/a/b.png", "h/a/../b.png", "h/фото.png"} {
if !validSharePath(p) {
t.Errorf("rejected safe path %q", p)
}
}
}
func TestLandingShellIsolation(t *testing.T) {
w := httptest.NewRecorder()
publicLandingShell(w, httptest.NewRequest("GET", "/api/public/landing-shell", nil))
csp := w.Header().Get("Content-Security-Policy")
for _, rule := range []string{"sandbox allow-scripts;", "default-src 'none'", "connect-src 'none'", "frame-src 'none'", "form-action 'none'", "frame-ancestors 'self'"} {
if !strings.Contains(csp, rule) {
t.Errorf("missing %q in CSP %q", rule, csp)
}
}
if strings.Contains(csp, "allow-same-origin") {
t.Fatal("shell can access session origin")
}
if strings.Contains(w.Body.String(), "token") {
t.Fatal("shell contains credentials")
}
}
func TestPublicLandingAttachmentBoundaries(t *testing.T) {
scope := t.TempDir()
if err := os.MkdirAll(filepath.Join(scope, "site", "images"), 0o755); err != nil {
t.Fatal(err)
}
for name, body := range map[string]string{"site/page.md": "# Landing", "site/images/a.svg": "<svg/>", "single.md": "# Single", "secret.txt": "private"} {
if err := os.WriteFile(filepath.Join(scope, filepath.FromSlash(name)), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
st, err := bolt.NewStorage(db)
if err != nil {
t.Fatal(err)
}
if err := st.Users.Save(&users.User{Username: "owner", Password: "unused", Perm: users.Permissions{Share: true, Download: true}}); err != nil {
t.Fatal(err)
}
if err := st.Settings.Save(&settings.Settings{Key: []byte("key")}); err != nil {
t.Fatal(err)
}
st.Users = &customFSUser{Store: st.Users, fs: files.NewScopedFs(afero.NewOsFs(), scope)}
for _, link := range []*share.Link{{Hash: "folder", UserID: 1, Path: "/site"}, {Hash: "single", UserID: 1, Path: "/single.md"}} {
if err := st.Share.Save(link); err != nil {
t.Fatal(err)
}
}
for _, tc := range []struct {
path string
status int
}{
{"folder/page.md", 200}, {"folder/images/a.svg", 200}, {"folder/../secret.txt", 400},
{"folder/%2e%2e/secret.txt", 400}, {"folder/%252e%252e/secret.txt", 400}, {"folder/..\\secret.txt", 400},
{"single/", 200}, {"single/single.md", 200}, {"single/secret.txt", 404},
} {
for _, handler := range []handleFunc{publicDlHandler, publicShareHandler} {
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = tc.path })
recorder := httptest.NewRecorder()
handle(handler, "", st, &settings.Server{}).ServeHTTP(recorder, req)
if recorder.Code != tc.status {
t.Errorf("%s: got %d, want %d: %s", tc.path, recorder.Code, tc.status, recorder.Body.String())
}
}
}
}
+15 -75
View File
@@ -126,83 +126,23 @@ func TestPublicShareSymlinkListingOmitsEscapingLink(t *testing.T) {
}
}
// With Server.FollowExternalSymlinks enabled (the opt-in for issue #5998), a
// symlink inside a public share that points outside it is followed: the file
// behind it downloads and the link shows up in the share listing. This is the
// inverse of TestPublicShareSymlinkDescendantDisclosure / ...ListingOmitsEscapingLink.
func TestPublicShareSymlinkFollowedWhenEnabled(t *testing.T) {
scope := t.TempDir()
if err := os.MkdirAll(filepath.Join(scope, "shared"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(scope, "outside"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(scope, "outside", "data.txt"), []byte("payload"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(scope, "outside"), filepath.Join(scope, "shared", "link")); err != nil {
t.Skipf("cannot create symlink on this platform: %v", err)
}
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
// Public shares remain confined even when an owner filesystem follows links.
func TestPublicShareSymlinkConfinedWhenEnabled(t *testing.T) {
st := symlinkShareStorage(t)
owner := st.Users.(*customFSUser)
root, err := files.BasePath(owner.fs).RealPath("/")
if err != nil {
t.Fatalf("failed to open db: %v", err)
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Close() })
st, err := bolt.NewStorage(db)
if err != nil {
t.Fatalf("failed to get storage: %v", err)
}
if err := st.Share.Save(&share.Link{Hash: "h", UserID: 1, Path: "/shared"}); err != nil {
t.Fatalf("failed to save share: %v", err)
}
if err := st.Users.Save(&users.User{
Username: "username",
Password: "pw",
Perm: users.Permissions{Share: true, Download: true},
}); err != nil {
t.Fatalf("failed to save user: %v", err)
}
if err := st.Settings.Save(&settings.Settings{Key: []byte("key")}); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
// Follow-external mode: the user filesystem is a bare BasePathFs.
st.Users = &customFSUser{
Store: st.Users,
fs: files.NewFs(afero.NewOsFs(), scope, true),
followExternal: true,
}
srv := &settings.Server{FollowExternalSymlinks: true}
// The file behind the symlink downloads.
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/link/data.txt" })
recorder := httptest.NewRecorder()
handle(publicDlHandler, "", st, srv).ServeHTTP(recorder, req)
result := recorder.Result()
defer result.Body.Close()
body, _ := io.ReadAll(result.Body)
if result.StatusCode != http.StatusOK {
t.Fatalf("expected to download file behind followed symlink, got status=%d body=%q", result.StatusCode, string(body))
}
if !strings.Contains(string(body), "payload") {
t.Fatalf("expected payload content, got %q", string(body))
}
// The link shows up in the share root listing.
req = newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/" })
recorder = httptest.NewRecorder()
handle(publicShareHandler, "", st, srv).ServeHTTP(recorder, req)
result = recorder.Result()
defer result.Body.Close()
body, _ = io.ReadAll(result.Body)
if result.StatusCode != http.StatusOK {
t.Fatalf("share root listing failed: status=%d body=%q", result.StatusCode, string(body))
}
if !strings.Contains(string(body), "\"link\"") {
t.Fatalf("expected followed symlink to appear in listing: %s", string(body))
owner.fs = files.NewFs(afero.NewOsFs(), root, true)
owner.followExternal = true
for _, handler := range []handleFunc{publicDlHandler, publicShareHandler} {
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/link/secret.txt" })
recorder := httptest.NewRecorder()
handle(handler, "", st, &settings.Server{FollowExternalSymlinks: true}).ServeHTTP(recorder, req)
if recorder.Code == http.StatusOK {
t.Fatal("public share followed escaping symlink")
}
}
}
+1
View File
@@ -35,6 +35,7 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
downloadPerm: true,
expectedStatusCode: 200,
},
"Expired share, 404": {share: &share.Link{Hash: "h", UserID: 1, Expire: 1}, req: newHTTPRequest(t), sharePerm: true, downloadPerm: true, expectedStatusCode: 404},
"Private share, no auth provided, 401": {
share: &share.Link{Hash: "h", UserID: 1, PasswordHash: passwordBcrypt, Token: "123"},
req: newHTTPRequest(t),
+1 -1
View File
@@ -1,4 +1,4 @@
param([string]$Version = '3.2.3')
param([string]$Version = '3.2.4')
$ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Push-Location $repo
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
VERSION="${VERSION:-3.2.3}"
VERSION="${VERSION:-3.2.4}"
COMMIT=$(git rev-parse --short HEAD)
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
mkdir -p build/release/linux-amd64