Add managed Craft addons with secure installation and document editing
This commit is contained in:
1 parent
1afa755d4f
commit
5cb1b463ea
31 files changed
+2274
-15
No files matched your search
@@ -41,3 +41,7 @@ Dockerfile.dev
|
||||
# SSO secrets and local setup
|
||||
.filebrowser.json
|
||||
.filebrowser.*.json
|
||||
|
||||
# Downloaded optional editor bundles
|
||||
/addons/*
|
||||
!/addons/.gitkeep
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Craft-аддоны
|
||||
|
||||
В «Панель управления → Аддоны» доступны GridCraft (XLSX) и PdfCraft (PDF): скачать/обновить, включить/отключить, увидеть версию, этап загрузки и ошибку. Настройки доступны администратору; для редактирования нужны права скачивания и изменения файла. Создание и «Сохранить как» дополнительно требуют права создания.
|
||||
|
||||
Веб-сборки хранятся в `addons` относительно рабочего каталога процесса. Для штатного Debian systemd unit это `/var/lib/filebrowser/addons`. Папка не входит в бинарник и архивы релиза: на другом сервере инструменты скачиваются кнопкой или переносится вся готовая папка `addons` с сохранением структуры. Отдельных служб редакторов нет.
|
||||
|
||||
Структура: `addons/<id>/active.json` — активная версия; `addons/<id>/versions/<tag>-<sha>/` — неизменяемые веб-файлы и оригинальные лицензии. Установка берёт только стабильный официальный GitHub Release из фиксированного каталога `storytold/gridcraft` и `storytold/pdfcraft`. Проверяются размер и SHA-256 из метаданных GitHub, затем ZIP распаковывается в отдельную временную папку. Ограничения: архив 128 МиБ, распакованные файлы суммарно 512 МиБ, отдельный файл 128 МиБ, 4096 записей, 16 уровней. Запрещены ссылки, пути наружу и совпадающие без учёта регистра имена. После успешной проверки указатель версии заменяется атомарно. Неудачное обновление оставляет прежнюю версию. Повторная проверка уже установленного релиза не скачивает архив заново.
|
||||
|
||||
Для HTML, JS и WASM создаются gzip-копии; корректные MIME, CSP для WASM и same-origin iframe задаются только страницам аддонов. Основная CSP File Browser не ослабляется. Старые версии остаются на диске: открытые редакторы продолжают загружать свои файлы. Удалять старые версии и оставшиеся после аварийной остановки `.install-*` можно вручную при остановленном сервере. Каталог `addons` закрыт от чтения/изменения через обычный файловый API, включая псевдонимы через ссылки и операции над родительскими папками.
|
||||
|
||||
В ПКМ и панели предпросмотра появляется «Открыть в GridCraft/PdfCraft». В «Создать» — XLSX/PDF, если соответствующий аддон установлен и включён; сервер генерирует корректные пустые документы. Предпросмотр PDF остаётся прежним быстрым просмотрщиком.
|
||||
|
||||
Обмен идёт через официальный `?host=parent`/`postMessage`: проверяются origin и конкретное окно iframe. Данные передаются без токенов SSO. Файлы загружаются и сохраняются через собственный API File Browser, с проверкой области доступа, правил и текущих разрешений. Размер документа ограничен 64 МиБ; XLSX дополнительно ограничен 4096 записями и суммарно 256 МиБ заявленного распакованного содержимого. Одновременно обрабатываются не более двух запросов документов.
|
||||
|
||||
Сохранение сначала пишет временный файл и выполняет Sync; затем проверяет SHA-256 ETag и заменяет оригинал. Если документ изменился, возвращается 412; «Сохранить как» не перезаписывает занятое имя (409). Проверка и замена синхронизированы с файловыми операциями данного процесса File Browser. Изменения сторонними процессами не блокируются. Успех показывается только после ответа сервера, а при ошибке доступны повтор, другое имя и скачивание копии. При истечении сессии можно войти в соседней вкладке и повторить запись без автоматического ухода из редактора. Активность пользователя в iframe поддерживает текущую сессию, но простаивающая вкладка её не продлевает.
|
||||
|
||||
Инструменты исполняются в браузере: нужны современный браузер и WebGL2/WebGPU. Совместного редактирования в реальном времени нет. WordCraft и остальные приложения не входят в каталог, пока для них не добавлена и проверена совместимая интеграция открытия/сохранения.
|
||||
|
||||
Проверка официальных сборок вручную: установить `FB_TEST_OFFICIAL_ADDONS=1`, при необходимости `FB_TEST_ADDONS_DIR` в абсолютный путь целевого `addons`, затем выполнить `go test ./internal/addons -run TestOfficialBundles -v -count=1`. Обычно тест пропускается и не использует сеть.
|
||||
@@ -0,0 +1,36 @@
|
||||
<template>
|
||||
<Action
|
||||
v-if="tool"
|
||||
icon="edit_note"
|
||||
:label="t('addons.openWith', { name: tool.name })"
|
||||
@action="router.push({ path: file!.url, query: { craft: tool!.id } })"
|
||||
/>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import Action from "@/components/header/Action.vue";
|
||||
const props = defineProps<{
|
||||
file?: { name: string; url: string; isDir: boolean } | null;
|
||||
}>();
|
||||
const store = useAddonsStore(),
|
||||
auth = useAuthStore(),
|
||||
router = useRouter(),
|
||||
{ t } = useI18n();
|
||||
const tool = computed(() =>
|
||||
!props.file?.isDir && auth.user?.perm.download && auth.user?.perm.modify
|
||||
? store.items.find(
|
||||
(item) =>
|
||||
item.enabled &&
|
||||
item.build &&
|
||||
props.file!.name.toLowerCase().endsWith(item.extension)
|
||||
)
|
||||
: undefined
|
||||
);
|
||||
onMounted(() => {
|
||||
store.refresh().catch(() => {});
|
||||
});
|
||||
</script>
|
||||
@@ -4,7 +4,7 @@
|
||||
</button>
|
||||
<div class="context-menu-separator" />
|
||||
<button
|
||||
v-for="template in fileTemplates"
|
||||
v-for="template in templates"
|
||||
:key="template.id"
|
||||
type="button"
|
||||
class="action"
|
||||
@@ -19,6 +19,23 @@
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
import { fileTemplates } from "@/utils/file-templates";
|
||||
import { computed, onMounted } from "vue";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
const addons = useAddonsStore(),
|
||||
auth = useAuthStore();
|
||||
const templates = computed(() =>
|
||||
fileTemplates.filter(
|
||||
(template) =>
|
||||
!template.craft ||
|
||||
(addons.available(template.craft) &&
|
||||
auth.user?.perm.modify &&
|
||||
auth.user?.perm.download)
|
||||
)
|
||||
);
|
||||
onMounted(() => {
|
||||
addons.refresh().catch(() => {});
|
||||
});
|
||||
const { t } = useI18n(),
|
||||
layout = useLayoutStore();
|
||||
function open(prompt: string, template?: string) {
|
||||
|
||||
@@ -47,6 +47,7 @@ import { useLayoutStore } from "@/stores/layout";
|
||||
import CreateFilePath from "@/components/prompts/CreateFilePath.vue";
|
||||
|
||||
import { files as api } from "@/api";
|
||||
import { fetchURL, removePrefix } from "@/api/utils";
|
||||
import url from "@/utils/url";
|
||||
|
||||
const $showError = inject<IToastError>("$showError")!;
|
||||
@@ -88,13 +89,26 @@ const submit = async (event: Event) => {
|
||||
uri = uri.replace("//", "/");
|
||||
|
||||
try {
|
||||
await api.post(
|
||||
uri,
|
||||
new Blob([template.value.content], { type: "text/plain;charset=utf-8" })
|
||||
);
|
||||
if (template.value.craft) {
|
||||
await fetchURL(
|
||||
"/api/craft/" +
|
||||
template.value.craft +
|
||||
"/document?path=" +
|
||||
encodeURIComponent(decodeURIComponent(removePrefix(uri))),
|
||||
{ method: "POST" }
|
||||
);
|
||||
} else
|
||||
await api.post(
|
||||
uri,
|
||||
new Blob([template.value.content], { type: "text/plain;charset=utf-8" })
|
||||
);
|
||||
await router.push({
|
||||
path: uri,
|
||||
query: template.value.id === "other" ? {} : { edit: "true" },
|
||||
query: template.value.craft
|
||||
? { craft: template.value.craft }
|
||||
: template.value.id === "other"
|
||||
? {}
|
||||
: { edit: "true" },
|
||||
});
|
||||
layoutStore.closeHovers();
|
||||
} catch (e) {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<template>
|
||||
<section class="card settings-section settings-wide addons-settings">
|
||||
<h2><AppIcon name="package" />{{ t("addons.title") }}</h2>
|
||||
<p class="field-hint">{{ t("addons.description") }}</p>
|
||||
<p v-if="error" class="document-error" role="alert">{{ error }}</p>
|
||||
<div v-for="addon in store.items" :key="addon.id" class="addon-row">
|
||||
<div>
|
||||
<strong>{{ addon.name }}</strong
|
||||
><small
|
||||
>{{ addon.version || t("addons.notInstalled") }} ·
|
||||
{{ addon.extension }}</small
|
||||
><small v-if="busy(addon)"
|
||||
>{{ t("addons.states." + addon.state)
|
||||
}}<template v-if="addon.total">
|
||||
·
|
||||
{{ Math.round((addon.downloaded / addon.total) * 100) }}%</template
|
||||
></small
|
||||
><small v-if="addon.error" role="alert" class="document-error">{{
|
||||
addon.error
|
||||
}}</small>
|
||||
</div>
|
||||
<label v-if="addon.build" class="addon-enabled"
|
||||
><input
|
||||
type="checkbox"
|
||||
:checked="addon.enabled"
|
||||
:disabled="changing === addon.id"
|
||||
@change="toggle(addon, ($event.target as HTMLInputElement).checked)"
|
||||
/>{{ t("addons.enabled") }}</label
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="button"
|
||||
:disabled="busy(addon) || changing === addon.id"
|
||||
@click="install(addon)"
|
||||
>
|
||||
<AppIcon :name="addon.build ? 'refresh' : 'download'" />{{
|
||||
addon.build ? t("addons.update") : t("addons.install")
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
<p class="field-hint">{{ t("addons.directory") }} <code>./addons</code></p>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { fetchURL } from "@/api/utils";
|
||||
import { useAddonsStore, type Addon } from "@/stores/addons";
|
||||
const store = useAddonsStore(),
|
||||
{ t } = useI18n(),
|
||||
error = ref(""),
|
||||
changing = ref("");
|
||||
let timer: ReturnType<typeof setTimeout> | undefined,
|
||||
disposed = false;
|
||||
const busy = (addon: Addon) =>
|
||||
["checking", "downloading", "verifying", "extracting"].includes(addon.state);
|
||||
async function refresh(force = false) {
|
||||
try {
|
||||
await store.refresh(force);
|
||||
} catch (failure) {
|
||||
error.value = String(failure);
|
||||
}
|
||||
if (!disposed && store.items.some(busy)) timer = setTimeout(refresh, 1500);
|
||||
}
|
||||
async function install(addon: Addon) {
|
||||
changing.value = addon.id;
|
||||
error.value = "";
|
||||
try {
|
||||
await fetchURL("/api/addons/" + addon.id + "/install", { method: "POST" });
|
||||
clearTimeout(timer);
|
||||
await refresh(true);
|
||||
} catch (failure) {
|
||||
error.value = String(failure);
|
||||
} finally {
|
||||
changing.value = "";
|
||||
}
|
||||
}
|
||||
async function toggle(addon: Addon, enabled: boolean) {
|
||||
changing.value = addon.id;
|
||||
error.value = "";
|
||||
try {
|
||||
await fetchURL("/api/addons/" + addon.id + "/enabled", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ enabled }),
|
||||
});
|
||||
await refresh();
|
||||
} catch (failure) {
|
||||
error.value = String(failure);
|
||||
} finally {
|
||||
changing.value = "";
|
||||
}
|
||||
}
|
||||
onMounted(refresh);
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true;
|
||||
clearTimeout(timer);
|
||||
});
|
||||
</script>
|
||||
@@ -389,3 +389,104 @@
|
||||
padding: 14px;
|
||||
}
|
||||
}
|
||||
.addon-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 16px 0;
|
||||
border-top: 1px solid var(--borderPrimary);
|
||||
}
|
||||
.addon-row > div {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.addon-row strong,
|
||||
.addon-row small {
|
||||
display: block;
|
||||
}
|
||||
.addon-row small {
|
||||
margin-top: 5px;
|
||||
font-size: 12px;
|
||||
color: var(--textSecondary);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.addon-enabled {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.addon-row .button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.craft-editor {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 9000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-top: 64px;
|
||||
background: var(--background);
|
||||
}
|
||||
.craft-frame {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
border: 0;
|
||||
background: var(--surfacePrimary);
|
||||
}
|
||||
.craft-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
padding: 8px 16px;
|
||||
font-size: 12px;
|
||||
border-bottom: 1px solid var(--borderPrimary);
|
||||
}
|
||||
.craft-status strong {
|
||||
color: var(--blue);
|
||||
}
|
||||
.craft-status > span {
|
||||
flex: 1;
|
||||
}
|
||||
.craft-error {
|
||||
margin: 0;
|
||||
padding: 10px 16px;
|
||||
color: var(--red);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.craft-save-as {
|
||||
display: flex;
|
||||
align-items: end;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid var(--borderPrimary);
|
||||
}
|
||||
.craft-save-as label {
|
||||
flex: 1;
|
||||
min-width: 180px;
|
||||
}
|
||||
.craft-save-as input {
|
||||
width: 100%;
|
||||
margin-top: 6px;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.addon-row {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.addon-row > div {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.addon-row .button {
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
.craft-status {
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
@@ -410,6 +410,39 @@
|
||||
"json": "JSON file",
|
||||
"html": "HTML page",
|
||||
"xml": "XML file",
|
||||
"other": "Other file"
|
||||
"other": "Other file",
|
||||
"xlsx": "Excel workbook",
|
||||
"pdf": "PDF document"
|
||||
},
|
||||
"addons": {
|
||||
"title": "Addons",
|
||||
"description": "Editors run in your browser. Install official Artcraft releases with SHA-256 verification.",
|
||||
"notInstalled": "Not installed",
|
||||
"enabled": "Enabled",
|
||||
"install": "Download",
|
||||
"update": "Update",
|
||||
"directory": "Addon directory:",
|
||||
"openWith": "Open in {name}",
|
||||
"saving": "Saving to server…",
|
||||
"saved": "Saved to server",
|
||||
"loaded": "File opened",
|
||||
"unsaved": "Unsaved changes",
|
||||
"retrySave": "Retry save",
|
||||
"downloadCopy": "Download a copy",
|
||||
"saveAs": "Save as",
|
||||
"leaveUnsaved": "Changes have not been saved to the server. Leave the editor?",
|
||||
"conflict": "The server file changed or the name already exists. Save under another name or download a copy; the original was not overwritten.",
|
||||
"saveFailed": "Could not save to the server.",
|
||||
"invalidName": "Enter a valid .xlsx or .pdf filename without a path.",
|
||||
"tooLarge": "Documents are limited to 64 MiB.",
|
||||
"unavailable": "Editor is not installed, disabled, or editing is not permitted.",
|
||||
"startFailed": "Editor failed to start. Check WebGL2/WebGPU support and the installed addon version.",
|
||||
"states": {
|
||||
"checking": "Checking release",
|
||||
"downloading": "Downloading",
|
||||
"verifying": "Verifying SHA-256",
|
||||
"extracting": "Installing"
|
||||
},
|
||||
"sessionExpired": "Session expired. Sign in in another tab, then retry saving."
|
||||
}
|
||||
}
|
||||
@@ -407,6 +407,39 @@
|
||||
"json": "Файл JSON",
|
||||
"html": "Страница HTML",
|
||||
"xml": "Файл XML",
|
||||
"other": "Другой файл"
|
||||
"other": "Другой файл",
|
||||
"xlsx": "Таблица Excel",
|
||||
"pdf": "Документ PDF"
|
||||
},
|
||||
"addons": {
|
||||
"title": "Аддоны",
|
||||
"description": "Редакторы работают в браузере. Установка и обновление — из официальных релизов Artcraft с проверкой SHA-256.",
|
||||
"notInstalled": "Не установлен",
|
||||
"enabled": "Включён",
|
||||
"install": "Скачать",
|
||||
"update": "Обновить",
|
||||
"directory": "Каталог аддонов:",
|
||||
"openWith": "Открыть в {name}",
|
||||
"saving": "Сохранение на сервер…",
|
||||
"saved": "Сохранено на сервере",
|
||||
"loaded": "Файл открыт",
|
||||
"unsaved": "Есть несохранённые изменения",
|
||||
"retrySave": "Повторить сохранение",
|
||||
"downloadCopy": "Скачать копию",
|
||||
"saveAs": "Сохранить как",
|
||||
"leaveUnsaved": "Изменения ещё не сохранены на сервере. Покинуть редактор?",
|
||||
"conflict": "Файл изменился на сервере или имя уже занято. Сохраните под другим именем либо скачайте копию; исходный файл не перезаписан.",
|
||||
"saveFailed": "Не удалось сохранить на сервере.",
|
||||
"invalidName": "Укажите корректное имя с расширением .xlsx или .pdf, без пути.",
|
||||
"tooLarge": "Документы ограничены 64 МиБ.",
|
||||
"unavailable": "Редактор не установлен, отключён или нет разрешения на редактирование.",
|
||||
"startFailed": "Редактор не запустился. Проверьте поддержку WebGL2/WebGPU и установленную версию аддона.",
|
||||
"states": {
|
||||
"checking": "Проверка релиза",
|
||||
"downloading": "Скачивание",
|
||||
"verifying": "Проверка SHA-256",
|
||||
"extracting": "Установка"
|
||||
},
|
||||
"sessionExpired": "Сессия истекла. Войдите в соседней вкладке, затем повторите сохранение."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { fetchJSON } from "@/api/utils";
|
||||
export interface Addon {
|
||||
id: string;
|
||||
name: string;
|
||||
extension: string;
|
||||
version: string;
|
||||
build: string;
|
||||
enabled: boolean;
|
||||
state: string;
|
||||
error?: string;
|
||||
downloaded: number;
|
||||
total: number;
|
||||
}
|
||||
let request: Promise<void> | undefined;
|
||||
export const useAddonsStore = defineStore("addons", {
|
||||
state: () => ({ items: [] as Addon[], loaded: false }),
|
||||
actions: {
|
||||
async refresh(force = false): Promise<void> {
|
||||
if (request)
|
||||
return request.then(() => (force ? this.refresh() : undefined));
|
||||
request = fetchJSON<Addon[]>("/api/addons")
|
||||
.then((items) => {
|
||||
this.items = items;
|
||||
this.loaded = true;
|
||||
})
|
||||
.finally(() => {
|
||||
request = undefined;
|
||||
});
|
||||
return request;
|
||||
},
|
||||
available(id: string) {
|
||||
return this.items.some(
|
||||
(item) => item.id === id && item.enabled && !!item.build
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { craftMessage, safeCraftName } from "../craft";
|
||||
it("accepts messages only from the specific same-origin editor frame", () => {
|
||||
const frame = {} as Window,
|
||||
origin = "https://files.test";
|
||||
const message = {
|
||||
origin,
|
||||
source: frame,
|
||||
data: {
|
||||
type: "gridcraft:save",
|
||||
name: "book.xlsx",
|
||||
bytes: new ArrayBuffer(1),
|
||||
},
|
||||
} as MessageEvent;
|
||||
expect(craftMessage(message, frame, "gridcraft", origin)?.name).toBe(
|
||||
"book.xlsx"
|
||||
);
|
||||
expect(
|
||||
craftMessage(
|
||||
{ ...message, origin: "https://evil.test" } as MessageEvent,
|
||||
frame,
|
||||
"gridcraft",
|
||||
origin
|
||||
)
|
||||
).toBeNull();
|
||||
expect(
|
||||
craftMessage(
|
||||
{ ...message, source: {} } as MessageEvent,
|
||||
frame,
|
||||
"gridcraft",
|
||||
origin
|
||||
)
|
||||
).toBeNull();
|
||||
expect(craftMessage(message, frame, "pdfcraft", origin)).toBeNull();
|
||||
expect(craftMessage(message, null, "gridcraft", origin)).toBeNull();
|
||||
expect(
|
||||
craftMessage(
|
||||
{ ...message, data: null } as MessageEvent,
|
||||
frame,
|
||||
"gridcraft",
|
||||
origin
|
||||
)
|
||||
).toBeNull();
|
||||
});
|
||||
it("validates save-as filenames without allowing paths or another file type", () => {
|
||||
expect(safeCraftName("Report.XLSX", ".xlsx")).toBe("Report.XLSX");
|
||||
for (const name of [
|
||||
"../book.xlsx",
|
||||
"a/book.xlsx",
|
||||
"a\\book.xlsx",
|
||||
"C:book.xlsx",
|
||||
"book.xlsx\u0000",
|
||||
"book.html",
|
||||
"book.xlsx/",
|
||||
"a?.xlsx",
|
||||
])
|
||||
expect(safeCraftName(name, ".xlsx")).toBeNull();
|
||||
});
|
||||
@@ -20,7 +20,7 @@ it("provides valid starter content and a safe fallback for unknown template IDs"
|
||||
);
|
||||
expect(
|
||||
fileTemplates.some((template) =>
|
||||
[".docx", ".xlsx", ".pptx"].includes(template.extension)
|
||||
[".docx", ".pptx"].includes(template.extension)
|
||||
)
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
export function safeCraftName(name: unknown, extension: string): string | null {
|
||||
if (
|
||||
typeof name !== "string" ||
|
||||
!name.trim() ||
|
||||
name.length > 240 ||
|
||||
/[\\/\x00-\x1f\x7f]/.test(name) ||
|
||||
name === "." ||
|
||||
name === ".." ||
|
||||
/[<>:"|?*]/.test(name)
|
||||
)
|
||||
return null;
|
||||
const value = name.trim();
|
||||
return value.toLowerCase().endsWith(extension) ? value : null;
|
||||
}
|
||||
export function craftMessage(
|
||||
event: MessageEvent,
|
||||
frame: Window | null,
|
||||
id: string,
|
||||
origin: string
|
||||
) {
|
||||
if (
|
||||
event.origin !== origin ||
|
||||
event.source !== frame ||
|
||||
!frame ||
|
||||
!event.data ||
|
||||
typeof event.data.type !== "string" ||
|
||||
!event.data.type.startsWith(id + ":")
|
||||
)
|
||||
return null;
|
||||
return event.data as {
|
||||
type: string;
|
||||
name?: string;
|
||||
bytes?: ArrayBuffer;
|
||||
dirty?: boolean;
|
||||
saveAs?: boolean;
|
||||
error?: string;
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,25 @@
|
||||
export const fileTemplates = [
|
||||
interface FileTemplate {
|
||||
id: string;
|
||||
extension: string;
|
||||
icon: string;
|
||||
content: string;
|
||||
craft?: string;
|
||||
}
|
||||
export const fileTemplates: readonly FileTemplate[] = [
|
||||
{
|
||||
id: "xlsx",
|
||||
extension: ".xlsx",
|
||||
icon: "table",
|
||||
content: "",
|
||||
craft: "gridcraft",
|
||||
},
|
||||
{
|
||||
id: "pdf",
|
||||
extension: ".pdf",
|
||||
icon: "picture_as_pdf",
|
||||
content: "",
|
||||
craft: "pdfcraft",
|
||||
},
|
||||
{ id: "text", extension: ".txt", icon: "article", content: "" },
|
||||
{ id: "markdown", extension: ".md", icon: "edit_note", content: "" },
|
||||
{ id: "csv", extension: ".csv", icon: "table", content: "" },
|
||||
@@ -17,7 +38,7 @@ export const fileTemplates = [
|
||||
content: '<?xml version="1.0" encoding="UTF-8"?>\n<root />\n',
|
||||
},
|
||||
{ id: "other", extension: "", icon: "note_add", content: "" },
|
||||
] as const;
|
||||
];
|
||||
export function fileTemplate(id: unknown) {
|
||||
return (
|
||||
fileTemplates.find((template) => template.id === id) ||
|
||||
|
||||
@@ -7,7 +7,11 @@
|
||||
/>
|
||||
|
||||
<errors v-if="error" :errorCode="error.status" />
|
||||
<component v-else-if="currentView" :is="currentView"></component>
|
||||
<component
|
||||
v-else-if="currentView"
|
||||
:is="currentView"
|
||||
:key="route.query.craft ? route.fullPath : undefined"
|
||||
></component>
|
||||
<div v-else>
|
||||
<h2 class="message delayed">
|
||||
<div class="spinner">
|
||||
@@ -46,6 +50,9 @@ import { name } from "../utils/constants";
|
||||
|
||||
const Editor = defineAsyncComponent(() => import("@/views/files/Editor.vue"));
|
||||
const Preview = defineAsyncComponent(() => import("@/views/files/Preview.vue"));
|
||||
const CraftEditor = defineAsyncComponent(
|
||||
() => import("@/views/files/CraftEditor.vue")
|
||||
);
|
||||
|
||||
const layoutStore = useLayoutStore();
|
||||
const fileStore = useFileStore();
|
||||
@@ -61,6 +68,7 @@ let fetchDataController = new AbortController();
|
||||
const error = ref<StatusError | null>(null);
|
||||
|
||||
const currentView = computed(() => {
|
||||
if (route.query.craft && layoutStore.loading) return null;
|
||||
if (fileStore.req?.type === undefined) {
|
||||
return null;
|
||||
}
|
||||
@@ -68,6 +76,8 @@ const currentView = computed(() => {
|
||||
if (fileStore.req.isDir) {
|
||||
return FileListing;
|
||||
}
|
||||
if (["gridcraft", "pdfcraft"].includes(String(route.query.craft)))
|
||||
return CraftEditor;
|
||||
if (
|
||||
route.query.edit === "true" &&
|
||||
["text", "textImmutable"].includes(fileStore.req.type)
|
||||
@@ -100,6 +110,10 @@ watch(route, () => {
|
||||
fetchData();
|
||||
});
|
||||
watch(reload, (newValue) => {
|
||||
if (newValue && route.query.craft) {
|
||||
fileStore.reload = false;
|
||||
return;
|
||||
}
|
||||
newValue && fetchData();
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
<template>
|
||||
<div class="craft-editor">
|
||||
<header-bar
|
||||
><Action
|
||||
icon="close"
|
||||
:label="t('buttons.close')"
|
||||
@action="close"
|
||||
/><title>{{ currentName }}</title></header-bar
|
||||
>
|
||||
<div class="craft-status" role="status">
|
||||
<strong>{{ title }}</strong
|
||||
><span>{{
|
||||
saving
|
||||
? t("addons.saving")
|
||||
: pending
|
||||
? t("addons.unsaved")
|
||||
: frameDirty
|
||||
? t("addons.unsaved")
|
||||
: status
|
||||
}}</span
|
||||
><button
|
||||
v-if="pending && !saveAs && !saving"
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
@click="persist"
|
||||
>
|
||||
{{ t("addons.retrySave") }}</button
|
||||
><button
|
||||
v-if="pending && !saveAs && !saving"
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
@click="
|
||||
newName = pending.name;
|
||||
saveAs = true;
|
||||
"
|
||||
>
|
||||
{{ t("addons.saveAs") }}</button
|
||||
><button
|
||||
v-if="pending"
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
@click="downloadCopy"
|
||||
>
|
||||
{{ t("addons.downloadCopy") }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="error" class="craft-error" role="alert">
|
||||
{{ error }}
|
||||
<a
|
||||
v-if="authExpired"
|
||||
:href="baseURL + '/auth/login'"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{ t("sidebar.login") }}</a
|
||||
>
|
||||
</p>
|
||||
<form v-if="saveAs" class="craft-save-as" @submit.prevent="confirmSaveAs">
|
||||
<label
|
||||
>{{ t("addons.saveAs")
|
||||
}}<input class="input" v-model.trim="newName" required /></label
|
||||
><button class="button" :disabled="saving">{{ t("buttons.save") }}</button
|
||||
><button
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
@click="saveAs = false"
|
||||
>
|
||||
{{ t("buttons.cancel") }}
|
||||
</button>
|
||||
</form>
|
||||
<iframe
|
||||
v-if="frameURL"
|
||||
ref="frame"
|
||||
class="craft-frame"
|
||||
:src="frameURL"
|
||||
:title="title"
|
||||
allow="clipboard-read; clipboard-write; fullscreen"
|
||||
@load="connectActivity"
|
||||
sandbox="allow-scripts allow-same-origin allow-downloads allow-modals allow-popups"
|
||||
/>
|
||||
<p v-else-if="!error" role="status">{{ t("files.loading") }}</p>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, onMounted, onBeforeUnmount } from "vue";
|
||||
import {
|
||||
useRoute,
|
||||
useRouter,
|
||||
onBeforeRouteLeave,
|
||||
onBeforeRouteUpdate,
|
||||
} from "vue-router";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import HeaderBar from "@/components/header/HeaderBar.vue";
|
||||
import Action from "@/components/header/Action.vue";
|
||||
import { useFileStore } from "@/stores/file";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { fetchURL, StatusError } from "@/api/utils";
|
||||
import { craftMessage, safeCraftName } from "@/utils/craft";
|
||||
const route = useRoute(),
|
||||
router = useRouter(),
|
||||
store = useAddonsStore(),
|
||||
files = useFileStore(),
|
||||
auth = useAuthStore(),
|
||||
{ t } = useI18n();
|
||||
// Bind the editor to the file opened at mount; later store navigation must not redirect a save.
|
||||
const file = files.req,
|
||||
id = String(route.query.craft || ""),
|
||||
sourcePath = file?.path || "";
|
||||
const currentPath = ref(sourcePath),
|
||||
currentName = ref(file?.name || "");
|
||||
const title = computed(
|
||||
() => store.items.find((item) => item.id === id)?.name || id
|
||||
);
|
||||
const frame = ref<HTMLIFrameElement>(),
|
||||
frameURL = ref(""),
|
||||
error = ref(""),
|
||||
status = ref(""),
|
||||
frameDirty = ref(false),
|
||||
saving = ref(false),
|
||||
saveAs = ref(false),
|
||||
newName = ref("");
|
||||
interface Save {
|
||||
bytes: ArrayBuffer;
|
||||
name: string;
|
||||
path: string;
|
||||
create: boolean;
|
||||
revision: number;
|
||||
}
|
||||
const pending = ref<Save>();
|
||||
const authExpired = ref(false);
|
||||
let activityDocument: Document | null = null,
|
||||
lastActivity = 0;
|
||||
const activityEvents = [
|
||||
"keydown",
|
||||
"pointerdown",
|
||||
"input",
|
||||
"wheel",
|
||||
"touchstart",
|
||||
];
|
||||
function disconnectActivity() {
|
||||
for (const name of activityEvents)
|
||||
activityDocument?.removeEventListener(name, activity, true);
|
||||
activityDocument = null;
|
||||
}
|
||||
function connectActivity() {
|
||||
disconnectActivity();
|
||||
activityDocument = frame.value?.contentDocument || null;
|
||||
for (const name of activityEvents)
|
||||
activityDocument?.addEventListener(name, activity, {
|
||||
capture: true,
|
||||
passive: true,
|
||||
});
|
||||
}
|
||||
function activity(event: Event) {
|
||||
if (
|
||||
!event.isTrusted ||
|
||||
document.visibilityState !== "visible" ||
|
||||
Date.now() - lastActivity < 60000
|
||||
)
|
||||
return;
|
||||
lastActivity = Date.now();
|
||||
fetchURL("/api/session", { signal: controller.signal }, false)
|
||||
.then((response) => {
|
||||
authExpired.value = false;
|
||||
response.body?.cancel();
|
||||
})
|
||||
.catch((failure) => {
|
||||
if (failure instanceof StatusError && failure.status === 401) {
|
||||
authExpired.value = true;
|
||||
error.value = t("addons.sessionExpired");
|
||||
}
|
||||
});
|
||||
}
|
||||
let tag = "",
|
||||
revision = 0,
|
||||
disposed = false,
|
||||
opened = false,
|
||||
startup: ReturnType<typeof setTimeout> | undefined;
|
||||
const controller = new AbortController();
|
||||
let original: ArrayBuffer | undefined;
|
||||
function endpoint(path: string) {
|
||||
return "/api/craft/" + id + "/document?path=" + encodeURIComponent(path);
|
||||
}
|
||||
const unsaved = computed(
|
||||
() => !!pending.value || saving.value || frameDirty.value
|
||||
);
|
||||
function mayLeave() {
|
||||
return !unsaved.value || window.confirm(t("addons.leaveUnsaved"));
|
||||
}
|
||||
onBeforeRouteLeave(mayLeave);
|
||||
onBeforeRouteUpdate(mayLeave);
|
||||
function beforeUnload(event: BeforeUnloadEvent) {
|
||||
if (unsaved.value) event.preventDefault();
|
||||
}
|
||||
function close() {
|
||||
router.push({
|
||||
path: file?.url.slice(0, file.url.lastIndexOf("/") + 1) || "/files/",
|
||||
});
|
||||
}
|
||||
async function persist() {
|
||||
const payload = pending.value;
|
||||
if (!payload || saving.value) return;
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
let success = false;
|
||||
try {
|
||||
const response = await fetchURL(
|
||||
endpoint(payload.path),
|
||||
{
|
||||
method: "PUT",
|
||||
headers: payload.create
|
||||
? { "If-None-Match": "*" }
|
||||
: { "If-Match": tag },
|
||||
body: payload.bytes,
|
||||
signal: controller.signal,
|
||||
},
|
||||
false
|
||||
);
|
||||
if (disposed) return;
|
||||
success = true;
|
||||
authExpired.value = false;
|
||||
if (
|
||||
payload.path.toLowerCase().endsWith(id === "gridcraft" ? ".xlsx" : ".pdf")
|
||||
) {
|
||||
tag = response.headers.get("ETag") || "";
|
||||
currentPath.value = payload.path;
|
||||
currentName.value = payload.name;
|
||||
}
|
||||
if (pending.value === payload) {
|
||||
pending.value = undefined;
|
||||
status.value = t("addons.saved");
|
||||
if (revision === payload.revision) frameDirty.value = false;
|
||||
}
|
||||
} catch (failure) {
|
||||
if (!disposed) {
|
||||
if (failure instanceof StatusError && failure.status === 401)
|
||||
authExpired.value = true;
|
||||
error.value =
|
||||
failure instanceof StatusError &&
|
||||
[409, 412].includes(failure.status || 0)
|
||||
? t("addons.conflict")
|
||||
: t("addons.saveFailed") + " " + String(failure);
|
||||
}
|
||||
} finally {
|
||||
saving.value = false;
|
||||
if (success && pending.value && pending.value !== payload && !saveAs.value)
|
||||
queueMicrotask(persist);
|
||||
}
|
||||
}
|
||||
function confirmSaveAs() {
|
||||
if (!pending.value) return;
|
||||
const ext = pending.value.name.toLowerCase().endsWith(".pdf")
|
||||
? ".pdf"
|
||||
: id === "gridcraft"
|
||||
? ".xlsx"
|
||||
: ".pdf";
|
||||
const name = safeCraftName(newName.value, ext);
|
||||
if (!name) {
|
||||
error.value = t("addons.invalidName");
|
||||
return;
|
||||
}
|
||||
pending.value = {
|
||||
...pending.value,
|
||||
name,
|
||||
path:
|
||||
currentPath.value.slice(0, currentPath.value.lastIndexOf("/") + 1) + name,
|
||||
create: true,
|
||||
};
|
||||
saveAs.value = false;
|
||||
persist();
|
||||
}
|
||||
function downloadCopy() {
|
||||
if (!pending.value) return;
|
||||
const url = URL.createObjectURL(new Blob([pending.value.bytes]));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = pending.value.name;
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
function receive(event: MessageEvent) {
|
||||
const message = craftMessage(
|
||||
event,
|
||||
frame.value?.contentWindow || null,
|
||||
id,
|
||||
window.location.origin
|
||||
);
|
||||
if (!message) return;
|
||||
if (message.type === id + ":ready") {
|
||||
if (opened || !original) return;
|
||||
opened = true;
|
||||
clearTimeout(startup);
|
||||
frame.value!.contentWindow!.postMessage(
|
||||
{ type: id + ":open", name: file!.name, bytes: original },
|
||||
window.location.origin,
|
||||
[original]
|
||||
);
|
||||
original = undefined;
|
||||
status.value = t("addons.loaded");
|
||||
} else if (message.type === id + ":failed") {
|
||||
clearTimeout(startup);
|
||||
error.value = String(message.error || t("addons.startFailed"));
|
||||
} else if (message.type === id + ":dirty") {
|
||||
frameDirty.value = message.dirty === true;
|
||||
if (frameDirty.value) revision++;
|
||||
} else if (message.type === id + ":save") {
|
||||
if (
|
||||
!(message.bytes instanceof ArrayBuffer) ||
|
||||
message.bytes.byteLength > 64 * 1024 * 1024
|
||||
) {
|
||||
error.value = t("addons.tooLarge");
|
||||
return;
|
||||
}
|
||||
const extension = message.name?.toLowerCase().endsWith(".pdf")
|
||||
? ".pdf"
|
||||
: id === "gridcraft"
|
||||
? ".xlsx"
|
||||
: ".pdf";
|
||||
const name = safeCraftName(message.name, extension);
|
||||
if (!name) {
|
||||
error.value = t("addons.invalidName");
|
||||
return;
|
||||
}
|
||||
const create = !!message.saveAs || name !== currentName.value;
|
||||
pending.value = {
|
||||
bytes: message.bytes,
|
||||
name,
|
||||
path: currentPath.value,
|
||||
create,
|
||||
revision,
|
||||
};
|
||||
if (create) {
|
||||
newName.value = name;
|
||||
saveAs.value = true;
|
||||
} else persist();
|
||||
}
|
||||
}
|
||||
onMounted(async () => {
|
||||
window.addEventListener("message", receive);
|
||||
window.addEventListener("beforeunload", beforeUnload);
|
||||
try {
|
||||
await store.refresh();
|
||||
const addon = store.items.find(
|
||||
(item) => item.id === id && item.enabled && item.build
|
||||
);
|
||||
if (
|
||||
!addon ||
|
||||
!auth.user?.perm.modify ||
|
||||
!auth.user?.perm.download ||
|
||||
!sourcePath.toLowerCase().endsWith(addon.extension)
|
||||
)
|
||||
throw new Error(t("addons.unavailable"));
|
||||
// Bound streamed data even when Content-Length is missing.
|
||||
const response = await fetchURL(endpoint(sourcePath), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
tag = response.headers.get("ETag") || "";
|
||||
if (!tag) throw new Error("Missing document version");
|
||||
if (Number(response.headers.get("Content-Length")) > 64 * 1024 * 1024) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(t("addons.tooLarge"));
|
||||
}
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new Error("Empty document");
|
||||
let length = 0;
|
||||
const chunks: Uint8Array[] = [];
|
||||
while (true) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
length += part.value.length;
|
||||
if (length > 64 * 1024 * 1024) {
|
||||
await reader.cancel();
|
||||
throw new Error(t("addons.tooLarge"));
|
||||
}
|
||||
chunks.push(part.value);
|
||||
}
|
||||
const data = new Uint8Array(length);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
data.set(chunk, offset);
|
||||
offset += chunk.length;
|
||||
}
|
||||
original = data.buffer;
|
||||
if (disposed) return;
|
||||
frameURL.value =
|
||||
baseURL +
|
||||
"/addons/" +
|
||||
id +
|
||||
"/" +
|
||||
addon.build +
|
||||
"/index.html?host=parent&author=" +
|
||||
encodeURIComponent(auth.user.profileName || auth.user.username);
|
||||
startup = setTimeout(() => {
|
||||
error.value = t("addons.startFailed");
|
||||
}, 45000);
|
||||
} catch (failure) {
|
||||
if (!disposed) error.value = String(failure);
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
disconnectActivity();
|
||||
disposed = true;
|
||||
controller.abort();
|
||||
clearTimeout(startup);
|
||||
window.removeEventListener("message", receive);
|
||||
window.removeEventListener("beforeunload", beforeUnload);
|
||||
});
|
||||
</script>
|
||||
@@ -176,6 +176,13 @@
|
||||
:pos="contextMenuPos"
|
||||
@hide="hideContextMenu"
|
||||
>
|
||||
<CraftAction
|
||||
:file="
|
||||
fileStore.selectedCount === 1
|
||||
? fileStore.req?.items[fileStore.selected[0]]
|
||||
: null
|
||||
"
|
||||
/>
|
||||
<action
|
||||
v-if="headerButtons.share"
|
||||
icon="share"
|
||||
@@ -284,6 +291,7 @@ import Search from "@/components/Search.vue";
|
||||
import Item from "@/components/files/ListingItem.vue";
|
||||
import CreateMenu from "@/components/files/CreateMenu.vue";
|
||||
import ContextMenu from "@/components/ContextMenu.vue";
|
||||
import CraftAction from "@/components/files/CraftAction.vue";
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
/>
|
||||
|
||||
<template #actions>
|
||||
<CraftAction :file="fileStore.req" />
|
||||
<action
|
||||
:disabled="layoutStore.loading"
|
||||
v-if="authStore.user?.perm.rename"
|
||||
@@ -179,6 +180,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import CraftAction from "@/components/files/CraftAction.vue";
|
||||
import { useStorage } from "@vueuse/core";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useFileStore } from "@/stores/file";
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
><small>{{ t("explorer.usersHint") }}</small></span
|
||||
><AppIcon name="chevron_right" />
|
||||
</button>
|
||||
<Addons />
|
||||
<section class="card settings-section">
|
||||
<h2><AppIcon name="archive" />{{ t("settings.downloadsTitle") }}</h2>
|
||||
<label class="settings-field"
|
||||
@@ -131,6 +132,7 @@
|
||||
<script setup lang="ts">
|
||||
import { useRoute } from "vue-router";
|
||||
import { settings as api } from "@/api";
|
||||
import Addons from "@/components/settings/Addons.vue";
|
||||
import { StatusError } from "@/api/utils";
|
||||
import Rules from "@/components/settings/Rules.vue";
|
||||
import Themes from "@/components/settings/Themes.vue";
|
||||
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func addonEnabled(d *data, id string) bool {
|
||||
enabled, exists := d.settings.AddonEnabled[id]
|
||||
return !exists || enabled
|
||||
}
|
||||
func addonListHandler(manager *addons.Manager) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
type entry struct {
|
||||
addons.Status
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
items := []entry{}
|
||||
for _, tool := range addons.Catalog {
|
||||
items = append(items, entry{manager.Status(tool.ID), addonEnabled(d, tool.ID)})
|
||||
}
|
||||
return renderJSON(w, r, items)
|
||||
})
|
||||
}
|
||||
func addonInstallHandler(manager *addons.Manager) handleFunc {
|
||||
return withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
id := mux.Vars(r)["addon"]
|
||||
if _, ok := addons.Find(id); !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
if err := manager.Start(id); err != nil {
|
||||
return http.StatusConflict, err
|
||||
}
|
||||
return renderJSON(w, r, manager.Status(id))
|
||||
})
|
||||
}
|
||||
|
||||
var addonToggleHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
id := mux.Vars(r)["addon"]
|
||||
if _, ok := addons.Find(id); !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
var payload struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024)).Decode(&payload); err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
if d.settings.AddonEnabled == nil {
|
||||
d.settings.AddonEnabled = map[string]bool{}
|
||||
}
|
||||
d.settings.AddonEnabled[id] = payload.Enabled
|
||||
if err := d.store.Settings.Save(d.settings); err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
return renderJSON(w, r, payload)
|
||||
})
|
||||
|
||||
func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
vars := mux.Vars(r)
|
||||
id := vars["addon"]
|
||||
if !addonEnabled(d, id) || !d.user.Perm.Download || !d.user.Perm.Modify {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
name := vars["asset"]
|
||||
if name == "" {
|
||||
name = "index.html"
|
||||
}
|
||||
if strings.HasSuffix(name, "/") {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
extension := strings.ToLower(path.Ext(name))
|
||||
types := map[string]string{".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".wasm": "application/wasm", ".css": "text/css", ".ico": "image/x-icon", ".png": "image/png", ".svg": "image/svg+xml", ".webp": "image/webp", ".jpg": "image/jpeg", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf", ".json": "application/json", ".map": "application/json", ".txt": "text/plain"}
|
||||
contentType, ok := types[extension]
|
||||
if !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
file, err := manager.Open(id, vars["build"], name)
|
||||
if err != nil {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
defer file.Close()
|
||||
if acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
|
||||
if compressed, e := manager.Open(id, vars["build"], name+".gz"); e == nil {
|
||||
file.Close()
|
||||
file = compressed
|
||||
defer compressed.Close()
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
}
|
||||
}
|
||||
w.Header().Add("Vary", "Accept-Encoding")
|
||||
info, err := file.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400")
|
||||
// Only installed, checksum-verified vendor pages get WASM and framing permissions.
|
||||
w.Header().Set("Content-Security-Policy", `default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:; media-src 'self' blob:; frame-src 'none'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'`)
|
||||
http.ServeContent(w, r, name, info.ModTime(), file)
|
||||
return 0, nil
|
||||
})
|
||||
}
|
||||
func acceptsAddonGzip(header string) bool {
|
||||
for _, token := range strings.Split(header, ",") {
|
||||
parts := strings.Split(token, ";")
|
||||
if !strings.EqualFold(strings.TrimSpace(parts[0]), "gzip") {
|
||||
continue
|
||||
}
|
||||
for _, option := range parts[1:] {
|
||||
pair := strings.SplitN(strings.TrimSpace(option), "=", 2)
|
||||
if len(pair) == 2 && pair[0] == "q" {
|
||||
quality, err := strconv.ParseFloat(pair[1], 64)
|
||||
return err == nil && quality > 0 && quality <= 1
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Keep executable addon assets outside the user-controlled file namespace, even
|
||||
// when the workspace root includes the program's working directory.
|
||||
func addonPathDenied(d *data, name string, ancestors bool) bool {
|
||||
if d.server.AddonsPath == "" || d.user == nil {
|
||||
return false
|
||||
}
|
||||
realFS, ok := d.user.Fs.(interface{ RealPath(string) (string, error) })
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
actual, err := realFS.RealPath(name)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
actual = resolveExisting(actual)
|
||||
root := resolveExisting(d.server.AddonsPath)
|
||||
inside := func(parent, child string) bool {
|
||||
rel, e := filepath.Rel(strings.ToLower(parent), strings.ToLower(child))
|
||||
return e == nil && (rel == "." || rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))
|
||||
}
|
||||
return inside(root, actual) || (ancestors && inside(actual, root))
|
||||
}
|
||||
func resolveExisting(name string) string {
|
||||
return resolveExistingDepth(name, 0)
|
||||
}
|
||||
func resolveExistingDepth(name string, hops int) string {
|
||||
absolute, err := filepath.Abs(name)
|
||||
if err != nil {
|
||||
return name
|
||||
}
|
||||
tail := []string{}
|
||||
probe := absolute
|
||||
for {
|
||||
resolved, err := filepath.EvalSymlinks(probe)
|
||||
if err == nil {
|
||||
for i := len(tail) - 1; i >= 0; i-- {
|
||||
resolved = filepath.Join(resolved, tail[i])
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
if info, linkErr := os.Lstat(probe); linkErr == nil && info.Mode()&os.ModeSymlink != 0 && hops < 40 {
|
||||
if target, linkErr := os.Readlink(probe); linkErr == nil {
|
||||
if !filepath.IsAbs(target) {
|
||||
target = filepath.Join(filepath.Dir(probe), target)
|
||||
}
|
||||
resolved = resolveExistingDepth(target, hops+1)
|
||||
for i := len(tail) - 1; i >= 0; i-- {
|
||||
resolved = filepath.Join(resolved, tail[i])
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
parent := filepath.Dir(probe)
|
||||
if parent == probe {
|
||||
return absolute
|
||||
}
|
||||
tail = append(tail, filepath.Base(probe))
|
||||
probe = parent
|
||||
}
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
const maxCraftDocument = 64 << 20
|
||||
|
||||
// Normal uploads/moves take a shared lock; editor commit/read takes the exclusive
|
||||
// lock so the version check and replacement cannot race our own file API.
|
||||
var craftMutationMu sync.RWMutex
|
||||
var craftRequests = make(chan struct{}, 2)
|
||||
|
||||
func documentETag(data []byte) string { return fmt.Sprintf(`"%x"`, sha256.Sum256(data)) }
|
||||
func readCraftFile(d *data, name string) ([]byte, os.FileInfo, error) {
|
||||
info, err := d.user.Fs.Stat(name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > maxCraftDocument {
|
||||
return nil, nil, errors.New("unsupported document size or type")
|
||||
}
|
||||
f, err := d.user.Fs.Open(name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(f, maxCraftDocument+1))
|
||||
if len(data) > maxCraftDocument {
|
||||
return nil, nil, errors.New("document exceeds 64 MiB")
|
||||
}
|
||||
return data, info, err
|
||||
}
|
||||
func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
id := mux.Vars(r)["addon"]
|
||||
tool, ok := addons.Find(id)
|
||||
if !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
if !addonEnabled(d, id) || manager.Status(id).Build == "" || !d.user.Perm.Download || !d.user.Perm.Modify {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
requested := r.URL.Query().Get("path")
|
||||
if requested == "" || strings.ContainsAny(requested, "\\\x00") || !strings.HasPrefix(requested, "/") || path.Clean(requested) != requested {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
extension := strings.ToLower(path.Ext(requested))
|
||||
if extension != tool.Extension && !(id == "gridcraft" && r.Method == "PUT" && extension == ".pdf") {
|
||||
return http.StatusUnsupportedMediaType, nil
|
||||
}
|
||||
if !d.Check(requested) {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
select {
|
||||
case craftRequests <- struct{}{}:
|
||||
defer func() { <-craftRequests }()
|
||||
default:
|
||||
return http.StatusTooManyRequests, nil
|
||||
}
|
||||
if r.Method == "GET" {
|
||||
craftMutationMu.Lock()
|
||||
data, _, err := readCraftFile(d, requested)
|
||||
craftMutationMu.Unlock()
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
if err = validateCraftDocument(extension, data); err != nil {
|
||||
return http.StatusUnprocessableEntity, err
|
||||
}
|
||||
w.Header().Set("ETag", documentETag(data))
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Disposition", "attachment")
|
||||
_, err = w.Write(data)
|
||||
return 0, err
|
||||
}
|
||||
var body io.Reader = r.Body
|
||||
if r.Method == "POST" {
|
||||
if !d.user.Perm.Create {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
blank, err := blankCraftDocument(id)
|
||||
if err != nil {
|
||||
return 500, err
|
||||
}
|
||||
body = bytes.NewReader(blank)
|
||||
}
|
||||
if r.Method == "PUT" && r.Header.Get("If-Match") == "" && r.Header.Get("If-None-Match") != "*" {
|
||||
return http.StatusPreconditionRequired, nil
|
||||
}
|
||||
// Stage the complete body before touching the original. A failed upload cannot truncate it.
|
||||
temp, err := afero.TempFile(d.user.Fs, path.Dir(requested), ".filebrowser-craft-")
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
tempName := temp.Name()
|
||||
defer d.user.Fs.Remove(tempName)
|
||||
n, err := io.Copy(temp, io.LimitReader(body, maxCraftDocument+1))
|
||||
if err == nil && n > maxCraftDocument {
|
||||
err = errors.New("document exceeds 64 MiB")
|
||||
}
|
||||
if err == nil {
|
||||
err = temp.Sync()
|
||||
}
|
||||
if err != nil {
|
||||
temp.Close()
|
||||
return http.StatusRequestEntityTooLarge, err
|
||||
}
|
||||
if _, err = temp.Seek(0, io.SeekStart); err != nil {
|
||||
temp.Close()
|
||||
return 500, err
|
||||
}
|
||||
payload, err := io.ReadAll(io.LimitReader(temp, maxCraftDocument+1))
|
||||
closeErr := temp.Close()
|
||||
if err != nil {
|
||||
return 500, err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return 500, closeErr
|
||||
}
|
||||
if err = validateCraftDocument(extension, payload); err != nil {
|
||||
return http.StatusUnprocessableEntity, err
|
||||
}
|
||||
craftMutationMu.Lock()
|
||||
defer craftMutationMu.Unlock()
|
||||
current, info, err := readCraftFile(d, requested)
|
||||
exists := err == nil
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return http.StatusConflict, err
|
||||
}
|
||||
create := r.Method == "POST" || r.Header.Get("If-None-Match") == "*"
|
||||
if create {
|
||||
if !d.user.Perm.Create {
|
||||
return 403, nil
|
||||
}
|
||||
if exists {
|
||||
return http.StatusConflict, nil
|
||||
}
|
||||
} else {
|
||||
if !exists || r.Header.Get("If-Match") != documentETag(current) {
|
||||
return http.StatusPreconditionFailed, nil
|
||||
}
|
||||
}
|
||||
mode := d.settings.FileMode
|
||||
if mode == 0 {
|
||||
mode = 0640
|
||||
}
|
||||
if exists {
|
||||
mode = info.Mode().Perm()
|
||||
}
|
||||
if err = d.user.Fs.Chmod(tempName, mode); err != nil {
|
||||
return 500, err
|
||||
}
|
||||
err = d.RunHook(func() error { return d.user.Fs.Rename(tempName, requested) }, "save", requested, "", d.user)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
if cache != nil {
|
||||
if file, e := files.NewFileInfo(&files.FileOptions{Fs: d.user.Fs, Path: requested, Checker: d}); e == nil {
|
||||
if e = delThumbs(r.Context(), cache, file); e != nil {
|
||||
log.Printf("craft thumbnail invalidation: %v", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
w.Header().Set("ETag", documentETag(payload))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return 0, nil
|
||||
})
|
||||
}
|
||||
func validateCraftDocument(extension string, data []byte) error {
|
||||
if extension == ".pdf" {
|
||||
if !bytes.HasPrefix(data, []byte("%PDF-")) {
|
||||
return errors.New("invalid PDF")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(reader.File) > 4096 {
|
||||
return errors.New("XLSX entry limit")
|
||||
}
|
||||
var total uint64
|
||||
workbook, types := false, false
|
||||
for _, file := range reader.File {
|
||||
total += file.UncompressedSize64
|
||||
if total > 256<<20 || file.UncompressedSize64 > 64<<20 {
|
||||
return errors.New("XLSX expanded size limit")
|
||||
}
|
||||
if file.Name == "xl/workbook.xml" {
|
||||
workbook = true
|
||||
}
|
||||
if file.Name == "[Content_Types].xml" {
|
||||
types = true
|
||||
}
|
||||
}
|
||||
if !workbook || !types {
|
||||
return errors.New("invalid XLSX workbook")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func blankCraftDocument(id string) ([]byte, error) {
|
||||
if id == "pdfcraft" {
|
||||
var b bytes.Buffer
|
||||
b.WriteString("%PDF-1.4\n")
|
||||
offsets := []int{0}
|
||||
for i, obj := range []string{"<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << >> >>"} {
|
||||
offsets = append(offsets, b.Len())
|
||||
fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", i+1, obj)
|
||||
}
|
||||
xref := b.Len()
|
||||
fmt.Fprintf(&b, "xref\n0 4\n0000000000 65535 f \n")
|
||||
for _, offset := range offsets[1:] {
|
||||
fmt.Fprintf(&b, "%010d 00000 n \n", offset)
|
||||
}
|
||||
fmt.Fprintf(&b, "trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", xref)
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
if id != "gridcraft" {
|
||||
return nil, errors.New("unsupported editor")
|
||||
}
|
||||
entries := map[string]string{
|
||||
"[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>`,
|
||||
"_rels/.rels": `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
|
||||
"xl/workbook.xml": `<?xml version="1.0"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>`,
|
||||
"xl/_rels/workbook.xml.rels": `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>`,
|
||||
"xl/worksheets/sheet1.xml": `<?xml version="1.0"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>`}
|
||||
var b bytes.Buffer
|
||||
writer := zip.NewWriter(&b)
|
||||
for name, content := range entries {
|
||||
f, err := writer.Create(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = f.Write([]byte(content)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
err := writer.Close()
|
||||
return b.Bytes(), err
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func installedTestManager(t *testing.T) *addons.Manager {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
for _, id := range []string{"gridcraft", "pdfcraft"} {
|
||||
dir := filepath.Join(root, id, "versions", "test-123")
|
||||
if err := os.MkdirAll(dir, 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(dir, "index.html"), []byte("index"), 0600)
|
||||
manifest, _ := json.Marshal(addons.Manifest{Version: "test", Build: "test-123"})
|
||||
os.WriteFile(filepath.Join(root, id, "active.json"), manifest, 0600)
|
||||
}
|
||||
return addons.New(root)
|
||||
}
|
||||
func TestCraftSaveConflictPermissionsAndOriginalPreserved(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
manager := installedTestManager(t)
|
||||
initial, _ := blankCraftDocument("gridcraft")
|
||||
os.WriteFile(filepath.Join(root, "book.xlsx"), initial, 0640)
|
||||
key := []byte("craft-test-key")
|
||||
perm := users.Permissions{Download: true, Modify: true, Create: true}
|
||||
store := scopedUserStorage(t, root, perm, key)
|
||||
token := signToken(t, perm, key)
|
||||
handler := handle(craftDocumentHandler(manager, nil), "", store, &settings.Server{})
|
||||
request := func(method, id, name string, body []byte, headers map[string]string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, "/api/craft/"+id+"/document?path="+url.QueryEscape(name), bytes.NewReader(body))
|
||||
r = mux.SetURLVars(r, map[string]string{"addon": id})
|
||||
for k, v := range headers {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
r = authorizeTestRequest(r, token)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, r)
|
||||
return rec
|
||||
}
|
||||
got := request("GET", "gridcraft", "/book.xlsx", nil, nil)
|
||||
if got.Code != 200 || !bytes.Equal(got.Body.Bytes(), initial) {
|
||||
t.Fatalf("load: %d %s", got.Code, got.Body.String())
|
||||
}
|
||||
tag := got.Header().Get("ETag")
|
||||
if tag == "" {
|
||||
t.Fatal("missing ETag")
|
||||
}
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", initial, nil); rec.Code != 428 {
|
||||
t.Fatalf("missing precondition: %d", rec.Code)
|
||||
}
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", []byte("broken"), map[string]string{"If-Match": tag}); rec.Code != 422 {
|
||||
t.Fatalf("invalid workbook accepted: %d", rec.Code)
|
||||
}
|
||||
if data, _ := os.ReadFile(filepath.Join(root, "book.xlsx")); !bytes.Equal(data, initial) {
|
||||
t.Fatal("invalid save truncated original")
|
||||
}
|
||||
changed, _ := blankCraftDocument("gridcraft") // Different ZIP ordering/content may be equal, so add a valid ZIP comment.
|
||||
changed = append([]byte(nil), changed...)
|
||||
changed[len(changed)-2] = 1
|
||||
changed = append(changed, 'x')
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", changed, map[string]string{"If-Match": tag}); rec.Code != 204 {
|
||||
t.Fatalf("save: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", initial, map[string]string{"If-Match": tag}); rec.Code != 412 {
|
||||
t.Fatalf("stale save: %d", rec.Code)
|
||||
}
|
||||
if rec := request("POST", "pdfcraft", "/new.pdf", nil, nil); rec.Code != 204 {
|
||||
t.Fatalf("create PDF: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := request("POST", "pdfcraft", "/new.pdf", nil, nil); rec.Code != 409 {
|
||||
t.Fatalf("overwrote existing PDF: %d", rec.Code)
|
||||
}
|
||||
if rec := request("GET", "gridcraft", "/../book.xlsx", nil, nil); rec.Code != 400 {
|
||||
t.Fatalf("accepted traversal: %d", rec.Code)
|
||||
}
|
||||
user, _ := store.Users.Get("", false, uint(1))
|
||||
user.Perm.Modify = false
|
||||
if err := store.Users.Save(user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec := request("PUT", "gridcraft", "/book.xlsx", initial, map[string]string{"If-Match": tag}); rec.Code != 403 {
|
||||
t.Fatalf("write without permission: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
func TestAddonAssetsProtectedFromFileAPI(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
addonRoot := filepath.Join(root, "app", "addons")
|
||||
os.MkdirAll(addonRoot, 0750)
|
||||
user := &users.User{Fs: files.NewFs(nil, root, false)}
|
||||
d := &data{server: &settings.Server{AddonsPath: addonRoot}, settings: &settings.Settings{}, user: user}
|
||||
for _, name := range []string{"/app/addons", "/app/addons/gridcraft/code.js"} {
|
||||
if d.CheckRules(name) {
|
||||
t.Fatalf("addon exposed: %s", name)
|
||||
}
|
||||
}
|
||||
if !d.CheckRules("/documents") {
|
||||
t.Fatal("ordinary files denied")
|
||||
}
|
||||
if err := checkDescendants(d, "/app", ""); err == nil {
|
||||
t.Fatal("ancestor deletion allowed")
|
||||
}
|
||||
if err := os.Symlink(addonRoot, filepath.Join(root, "alias")); err == nil {
|
||||
if d.CheckRules("/alias/evil.js") {
|
||||
t.Fatal("addon symlink alias allowed")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestCraftBlankFormats(t *testing.T) {
|
||||
for id, ext := range map[string]string{"gridcraft": ".xlsx", "pdfcraft": ".pdf"} {
|
||||
data, err := blankCraftDocument(id)
|
||||
if err != nil || validateCraftDocument(ext, data) != nil {
|
||||
t.Fatalf("invalid %s template", id)
|
||||
}
|
||||
if id == "pdfcraft" && !strings.HasSuffix(string(data), "%%EOF\n") {
|
||||
t.Fatal("PDF trailer missing")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestAddonRoutesAuthMIMECompressionAndDisable(t *testing.T) {
|
||||
manager := installedTestManager(t)
|
||||
root := t.TempDir()
|
||||
key := []byte("addon-route-test")
|
||||
permission := users.Permissions{Download: true, Modify: true}
|
||||
store := scopedUserStorage(t, root, permission, key)
|
||||
handler, err := NewHandler(nil, nil, nil, store, &settings.Server{Root: root, AddonsPath: manager.Root}, fstest.MapFS{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
directory := filepath.Join(manager.Root, "gridcraft", "versions", "test-123")
|
||||
os.WriteFile(filepath.Join(directory, "app.wasm"), []byte("wasm"), 0600)
|
||||
var packed bytes.Buffer
|
||||
zipper := gzip.NewWriter(&packed)
|
||||
zipper.Write([]byte("index"))
|
||||
zipper.Close()
|
||||
os.WriteFile(filepath.Join(directory, "index.html.gz"), packed.Bytes(), 0600)
|
||||
request := func(method, target, token, encoding string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, target, nil)
|
||||
if token != "" {
|
||||
r = authorizeTestRequest(r, token)
|
||||
}
|
||||
r.Header.Set("Accept-Encoding", encoding)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, r)
|
||||
return rec
|
||||
}
|
||||
regular := signToken(t, permission, key)
|
||||
if rec := request("GET", "/api/addons", "", " "); rec.Code != 401 {
|
||||
t.Fatalf("anonymous catalog %d", rec.Code)
|
||||
}
|
||||
if rec := request("POST", "/api/addons/gridcraft/install", regular, ""); rec.Code != 403 {
|
||||
t.Fatalf("nonadmin installation %d", rec.Code)
|
||||
}
|
||||
if rec := request("GET", "/addons/gridcraft/test-123/app.wasm", regular, ""); rec.Code != 200 || rec.Header().Get("Content-Type") != "application/wasm" {
|
||||
t.Fatalf("wasm: %d %s", rec.Code, rec.Header().Get("Content-Type"))
|
||||
}
|
||||
compressed := request("GET", "/addons/gridcraft/test-123/index.html", regular, "gzip")
|
||||
if compressed.Code != 200 || compressed.Header().Get("Content-Encoding") != "gzip" || !strings.Contains(compressed.Header().Get("Content-Security-Policy"), "frame-ancestors 'self'") {
|
||||
t.Fatalf("addon page headers: %v", compressed.Header())
|
||||
}
|
||||
reader, err := gzip.NewReader(compressed.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := io.ReadAll(reader)
|
||||
reader.Close()
|
||||
if string(data) != "index" {
|
||||
t.Fatal("bad compressed response")
|
||||
}
|
||||
if rec := request("GET", "/addons/gridcraft/test-123/index.html", regular, "gzip;q=0"); rec.Header().Get("Content-Encoding") != "" {
|
||||
t.Fatal("ignored disabled gzip")
|
||||
}
|
||||
configuration, _ := store.Settings.Get()
|
||||
configuration.AddonEnabled = map[string]bool{"gridcraft": false}
|
||||
store.Settings.Save(configuration)
|
||||
if rec := request("GET", "/addons/gridcraft/test-123/index.html", regular, ""); rec.Code != 403 {
|
||||
t.Fatalf("disabled addon accessible %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,9 @@ func (d *data) Check(path string) bool {
|
||||
// Check, it ignores HideDotfiles: hiding dotfiles is a display preference, so
|
||||
// it must not stop a user from operating on a tree that contains one.
|
||||
func (d *data) CheckRules(path string) bool {
|
||||
if addonPathDenied(d, path, false) {
|
||||
return false
|
||||
}
|
||||
path = d.rulePath(path)
|
||||
|
||||
allow := true
|
||||
|
||||
+26
-1
@@ -3,11 +3,14 @@ package fbhttp
|
||||
import (
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/spf13/afero"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
)
|
||||
@@ -29,6 +32,16 @@ func NewHandler(
|
||||
server.EnableExec = false
|
||||
server.FollowExternalSymlinks = false
|
||||
server.Clean()
|
||||
addonDirectory := server.AddonsPath
|
||||
if addonDirectory == "" {
|
||||
addonDirectory = "addons"
|
||||
}
|
||||
addonRoot, err := filepath.Abs(addonDirectory)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
server.AddonsPath = addonRoot
|
||||
addonManager := addons.New(addonRoot)
|
||||
server.CaseInsensitiveFs = files.CaseInsensitive(afero.NewOsFs(), server.Root)
|
||||
|
||||
r := mux.NewRouter()
|
||||
@@ -41,7 +54,14 @@ func NewHandler(
|
||||
index, static := getStaticHandlers(store, server, assetsFs)
|
||||
|
||||
monkey := func(fn handleFunc, prefix string) http.Handler {
|
||||
return handle(fn, prefix, store, server)
|
||||
handler := handle(fn, prefix, store, server)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" && r.Method != "HEAD" && (strings.HasPrefix(prefix, "/api/resources") || strings.HasPrefix(prefix, "/api/tus")) {
|
||||
craftMutationMu.RLock()
|
||||
defer craftMutationMu.RUnlock()
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
r.HandleFunc("/health", healthHandler)
|
||||
@@ -77,6 +97,11 @@ func NewHandler(
|
||||
|
||||
api.Handle("/settings", monkey(settingsGetHandler, "")).Methods("GET")
|
||||
api.Handle("/settings", monkey(settingsPutHandler, "")).Methods("PUT")
|
||||
api.Handle("/addons", monkey(addonListHandler(addonManager), "")).Methods("GET")
|
||||
api.Handle("/addons/{addon}/install", monkey(addonInstallHandler(addonManager), "")).Methods("POST")
|
||||
api.Handle("/addons/{addon}/enabled", monkey(addonToggleHandler, "")).Methods("PUT")
|
||||
api.Handle("/craft/{addon}/document", monkey(craftDocumentHandler(addonManager, fileCache), "")).Methods("GET", "PUT", "POST")
|
||||
r.Handle("/addons/{addon}/{build}/{asset:.*}", monkey(addonStaticHandler(addonManager), "")).Methods("GET", "HEAD")
|
||||
|
||||
api.PathPrefix("/raw").Handler(monkey(rawHandler, "/api/raw")).Methods("GET")
|
||||
api.PathPrefix("/preview/{size}/{path:.*}").
|
||||
|
||||
@@ -281,6 +281,9 @@ func resourcePatchHandler(fileCache FileCache) handleFunc {
|
||||
// delete then recurse through the whole subtree, so a rule denying a descendant
|
||||
// of an allowed directory would be bypassed by operating on the parent instead.
|
||||
func checkDescendants(d *data, src, dst string) error {
|
||||
if addonPathDenied(d, src, true) || (dst != "" && addonPathDenied(d, dst, true)) {
|
||||
return fberrors.ErrPermissionDenied
|
||||
}
|
||||
if len(d.settings.Rules) == 0 && len(d.user.Rules) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
package addons
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxArchive = 128 << 20
|
||||
const MaxExpanded = 512 << 20
|
||||
|
||||
var safeBuild = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$`)
|
||||
|
||||
type Tool struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Extension string `json:"extension"`
|
||||
}
|
||||
|
||||
var Catalog = []Tool{{"gridcraft", "GridCraft", ".xlsx"}, {"pdfcraft", "PdfCraft", ".pdf"}}
|
||||
|
||||
func Find(id string) (Tool, bool) {
|
||||
for _, tool := range Catalog {
|
||||
if tool.ID == id {
|
||||
return tool, true
|
||||
}
|
||||
}
|
||||
return Tool{}, false
|
||||
}
|
||||
|
||||
type Manifest struct {
|
||||
Version string `json:"version"`
|
||||
Build string `json:"build"`
|
||||
SHA256 string `json:"sha256"`
|
||||
InstalledAt time.Time `json:"installedAt"`
|
||||
}
|
||||
type Status struct {
|
||||
Tool
|
||||
Manifest
|
||||
State string `json:"state"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Downloaded int64 `json:"downloaded"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
type Manager struct {
|
||||
Root string
|
||||
mu sync.Mutex
|
||||
jobs map[string]Status
|
||||
client *http.Client
|
||||
api string
|
||||
}
|
||||
|
||||
func New(root string) *Manager {
|
||||
return &Manager{Root: root, jobs: make(map[string]Status), api: "https://api.github.com", client: &http.Client{Timeout: 4 * time.Minute, CheckRedirect: func(r *http.Request, via []*http.Request) error {
|
||||
if len(via) > 5 || !allowedURL(r.URL) {
|
||||
return errors.New("untrusted download redirect")
|
||||
}
|
||||
return nil
|
||||
}}}
|
||||
}
|
||||
func allowedURL(u *url.URL) bool {
|
||||
return u.Scheme == "https" && u.User == nil && u.Port() == "" && (u.Hostname() == "api.github.com" || u.Hostname() == "github.com" || u.Hostname() == "release-assets.githubusercontent.com" || u.Hostname() == "objects.githubusercontent.com")
|
||||
}
|
||||
func (m *Manager) manifest(id string) Manifest {
|
||||
var manifest Manifest
|
||||
root, err := os.OpenRoot(m.Root)
|
||||
if err != nil {
|
||||
return manifest
|
||||
}
|
||||
defer root.Close()
|
||||
f, err := root.Open(id + "/active.json")
|
||||
if err != nil {
|
||||
return manifest
|
||||
}
|
||||
defer f.Close()
|
||||
if json.NewDecoder(io.LimitReader(f, 16384)).Decode(&manifest) != nil || !safeBuild.MatchString(manifest.Build) {
|
||||
return Manifest{}
|
||||
}
|
||||
f2, err := root.Open(id + "/versions/" + manifest.Build + "/index.html")
|
||||
if err != nil {
|
||||
return Manifest{}
|
||||
}
|
||||
f2.Close()
|
||||
return manifest
|
||||
}
|
||||
func (m *Manager) Status(id string) Status {
|
||||
tool, _ := Find(id)
|
||||
manifest := m.manifest(id)
|
||||
m.mu.Lock()
|
||||
job, ok := m.jobs[id]
|
||||
m.mu.Unlock()
|
||||
if ok {
|
||||
job.Manifest = manifest
|
||||
return job
|
||||
}
|
||||
state := "not-installed"
|
||||
if manifest.Build != "" {
|
||||
state = "ready"
|
||||
}
|
||||
return Status{Tool: tool, Manifest: manifest, State: state}
|
||||
}
|
||||
func (m *Manager) set(id, state string, downloaded, total int64, failure error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
tool, _ := Find(id)
|
||||
s := Status{Tool: tool, State: state, Downloaded: downloaded, Total: total}
|
||||
if failure != nil {
|
||||
s.Error = failure.Error()
|
||||
}
|
||||
m.jobs[id] = s
|
||||
}
|
||||
func (m *Manager) Start(id string) error {
|
||||
if _, ok := Find(id); !ok {
|
||||
return errors.New("unknown addon")
|
||||
}
|
||||
m.mu.Lock()
|
||||
if s, ok := m.jobs[id]; ok && s.State != "ready" && s.State != "error" {
|
||||
m.mu.Unlock()
|
||||
return errors.New("installation already running")
|
||||
}
|
||||
tool, _ := Find(id)
|
||||
m.jobs[id] = Status{Tool: tool, State: "checking"}
|
||||
m.mu.Unlock()
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
if err := m.install(ctx, id); err != nil {
|
||||
m.set(id, "error", 0, 0, err)
|
||||
} else {
|
||||
m.set(id, "ready", 0, 0, nil)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
type asset struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Digest string `json:"digest"`
|
||||
URL string `json:"browser_download_url"`
|
||||
}
|
||||
type release struct {
|
||||
Tag string `json:"tag_name"`
|
||||
Draft bool `json:"draft"`
|
||||
Prerelease bool `json:"prerelease"`
|
||||
Assets []asset `json:"assets"`
|
||||
}
|
||||
|
||||
func (m *Manager) get(ctx context.Context, address string) (*http.Response, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", address, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", "FileBrowser-Craft-addons")
|
||||
resp, err := m.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != 200 {
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("upstream HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
func (m *Manager) install(ctx context.Context, id string) error {
|
||||
resp, err := m.get(ctx, m.api+"/repos/storytold/"+id+"/releases/latest")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var rel release
|
||||
err = json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&rel)
|
||||
resp.Body.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rel.Draft || rel.Prerelease || !safeBuild.MatchString(rel.Tag) {
|
||||
return errors.New("invalid stable release")
|
||||
}
|
||||
name := id + "-web-" + strings.TrimPrefix(rel.Tag, "v") + ".zip"
|
||||
var selected asset
|
||||
for _, a := range rel.Assets {
|
||||
if a.Name == name {
|
||||
selected = a
|
||||
break
|
||||
}
|
||||
}
|
||||
digest := strings.TrimPrefix(selected.Digest, "sha256:")
|
||||
decoded, err := hex.DecodeString(digest)
|
||||
if selected.Size < 1 || selected.Size > MaxArchive || err != nil || len(decoded) != 32 || !strings.HasPrefix(selected.Digest, "sha256:") {
|
||||
return errors.New("web bundle or SHA-256 digest unavailable")
|
||||
}
|
||||
expected := "https://github.com/storytold/" + id + "/releases/download/" + rel.Tag + "/" + name
|
||||
if selected.URL != expected {
|
||||
return errors.New("unexpected release download URL")
|
||||
}
|
||||
build := rel.Tag + "-" + digest[:12]
|
||||
if m.manifest(id).Build == build {
|
||||
return precompress(filepath.Join(m.Root, id, "versions", build))
|
||||
}
|
||||
if err = os.MkdirAll(m.Root, 0750); err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := os.Lstat(m.Root)
|
||||
if err != nil || info.Mode()&os.ModeSymlink != 0 {
|
||||
return errors.New("addons directory must not be a symlink")
|
||||
}
|
||||
stage, err := os.MkdirTemp(m.Root, ".install-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(stage)
|
||||
archive, err := os.Create(filepath.Join(stage, "bundle.zip"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err = m.get(ctx, selected.URL)
|
||||
if err != nil {
|
||||
archive.Close()
|
||||
return err
|
||||
}
|
||||
hash := sha256.New()
|
||||
downloaded := int64(0)
|
||||
m.set(id, "downloading", 0, selected.Size, nil)
|
||||
writer := io.MultiWriter(archive, hash)
|
||||
buffer := make([]byte, 128<<10)
|
||||
for {
|
||||
n, readErr := resp.Body.Read(buffer)
|
||||
if n > 0 {
|
||||
downloaded += int64(n)
|
||||
if downloaded > selected.Size || downloaded > MaxArchive {
|
||||
err = errors.New("download exceeds declared size")
|
||||
break
|
||||
}
|
||||
if _, err = writer.Write(buffer[:n]); err != nil {
|
||||
break
|
||||
}
|
||||
m.set(id, "downloading", downloaded, selected.Size, nil)
|
||||
}
|
||||
if readErr != nil {
|
||||
if readErr != io.EOF {
|
||||
err = readErr
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
resp.Body.Close()
|
||||
closeErr := archive.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
m.set(id, "verifying", downloaded, selected.Size, nil)
|
||||
if downloaded != selected.Size || !strings.EqualFold(hex.EncodeToString(hash.Sum(nil)), digest) {
|
||||
return errors.New("SHA-256 or size mismatch")
|
||||
}
|
||||
m.set(id, "extracting", downloaded, selected.Size, nil)
|
||||
unpacked := filepath.Join(stage, "web")
|
||||
if err = extract(filepath.Join(stage, "bundle.zip"), unpacked); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = precompress(unpacked); err != nil {
|
||||
return err
|
||||
}
|
||||
versions := filepath.Join(m.Root, id, "versions")
|
||||
if err = os.MkdirAll(versions, 0750); err != nil {
|
||||
return err
|
||||
}
|
||||
// Version directories never change; existing open editors retain their exact bundle.
|
||||
destination := filepath.Join(versions, build)
|
||||
if _, err = os.Stat(destination); errors.Is(err, os.ErrNotExist) {
|
||||
if err = os.Rename(unpacked, destination); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
manifest := Manifest{Version: rel.Tag, Build: build, SHA256: strings.ToLower(digest), InstalledAt: time.Now().UTC()}
|
||||
data, _ := json.Marshal(manifest)
|
||||
pointer, err := os.CreateTemp(filepath.Join(m.Root, id), ".active-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(pointer.Name())
|
||||
if _, err = pointer.Write(data); err == nil {
|
||||
err = pointer.Sync()
|
||||
}
|
||||
closeErr = pointer.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
return os.Rename(pointer.Name(), filepath.Join(m.Root, id, "active.json"))
|
||||
}
|
||||
func precompress(directory string) error {
|
||||
return filepath.WalkDir(directory, func(name string, entry os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
ext := filepath.Ext(name)
|
||||
if ext != ".wasm" && ext != ".js" && ext != ".html" {
|
||||
return nil
|
||||
}
|
||||
if _, err = os.Stat(name + ".gz"); err == nil {
|
||||
return nil
|
||||
}
|
||||
in, err := os.Open(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
out, err := os.CreateTemp(filepath.Dir(name), ".gzip-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(out.Name())
|
||||
writer := gzip.NewWriter(out)
|
||||
_, err = io.Copy(writer, in)
|
||||
closeErr := writer.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
closeErr = out.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(out.Name(), name+".gz")
|
||||
})
|
||||
}
|
||||
func extract(archive, destination string) error {
|
||||
reader, err := zip.OpenReader(archive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
if len(reader.File) == 0 || len(reader.File) > 4096 {
|
||||
return errors.New("archive entry limit")
|
||||
}
|
||||
prefix := ""
|
||||
hasIndex := false
|
||||
for _, f := range reader.File {
|
||||
if f.Name == "index.html" {
|
||||
hasIndex = true
|
||||
}
|
||||
}
|
||||
if !hasIndex {
|
||||
prefix = strings.Split(reader.File[0].Name, "/")[0] + "/"
|
||||
for _, f := range reader.File {
|
||||
if f.Name == prefix+"index.html" {
|
||||
hasIndex = true
|
||||
}
|
||||
if !strings.HasPrefix(f.Name, prefix) {
|
||||
return errors.New("invalid web bundle layout")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !hasIndex {
|
||||
return errors.New("missing index.html")
|
||||
}
|
||||
if err = os.Mkdir(destination, 0750); err != nil {
|
||||
return err
|
||||
}
|
||||
root, err := os.OpenRoot(destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Close()
|
||||
seen := map[string]bool{}
|
||||
var total uint64
|
||||
for _, f := range reader.File {
|
||||
original := f.Name
|
||||
name := strings.TrimPrefix(original, prefix)
|
||||
name = strings.TrimSuffix(name, "/")
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
if len(name) > 1024 || strings.ContainsAny(original, "\\:\x00") || strings.HasPrefix(original, "/") || path.Clean(name) != name || name == ".." || strings.HasPrefix(name, "../") || strings.Count(name, "/") > 16 || seen[strings.ToLower(name)] {
|
||||
return errors.New("unsafe or duplicate archive path")
|
||||
}
|
||||
seen[strings.ToLower(name)] = true
|
||||
if f.Mode()&os.ModeSymlink != 0 || (!f.FileInfo().IsDir() && !f.Mode().IsRegular()) {
|
||||
return errors.New("archive links are forbidden")
|
||||
}
|
||||
if f.UncompressedSize64 > MaxArchive || total+f.UncompressedSize64 > MaxExpanded {
|
||||
return errors.New("expanded archive size limit")
|
||||
}
|
||||
total += f.UncompressedSize64
|
||||
if f.FileInfo().IsDir() {
|
||||
if err = root.MkdirAll(name, 0750); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err = root.MkdirAll(path.Dir(name), 0750); err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0640)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
in, err := f.Open()
|
||||
if err != nil {
|
||||
out.Close()
|
||||
return err
|
||||
}
|
||||
n, err := io.Copy(out, io.LimitReader(in, MaxArchive+1))
|
||||
in.Close()
|
||||
cerr := out.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cerr != nil {
|
||||
return cerr
|
||||
}
|
||||
if n > MaxArchive || uint64(n) != f.UncompressedSize64 {
|
||||
return errors.New("invalid expanded file size")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (m *Manager) Open(id, build, name string) (*os.File, error) {
|
||||
if _, ok := Find(id); !ok || !safeBuild.MatchString(build) || path.Clean(name) != name || strings.ContainsAny(name, "\\:\x00") || strings.HasPrefix(name, "/") || strings.HasPrefix(name, "../") {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
root, err := os.OpenRoot(m.Root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer root.Close()
|
||||
return root.Open(id + "/versions/" + build + "/" + name)
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package addons
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func bundle(t *testing.T, names ...string) []byte {
|
||||
t.Helper()
|
||||
var data bytes.Buffer
|
||||
writer := zip.NewWriter(&data)
|
||||
for _, name := range names {
|
||||
f, err := writer.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fmt.Fprint(f, "test bundle data")
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data.Bytes()
|
||||
}
|
||||
|
||||
type rewriteTransport struct {
|
||||
base string
|
||||
transport http.RoundTripper
|
||||
}
|
||||
|
||||
func (r rewriteTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
clone := request.Clone(request.Context())
|
||||
u := *request.URL
|
||||
clone.URL = &u
|
||||
if u.Host == "github.com" {
|
||||
target := r.base + "/bundle"
|
||||
newRequest, _ := http.NewRequestWithContext(request.Context(), "GET", target, nil)
|
||||
return r.transport.RoundTrip(newRequest)
|
||||
}
|
||||
return r.transport.RoundTrip(clone)
|
||||
}
|
||||
func TestInstallVerifiesAndPreservesActiveOnFailure(t *testing.T) {
|
||||
archive := bundle(t, "index.html", "app.js", "app_bg.wasm")
|
||||
tag := "v1.0.0"
|
||||
badDigest := false
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/bundle" {
|
||||
w.Write(archive)
|
||||
return
|
||||
}
|
||||
digest := fmt.Sprintf("sha256:%x", sha256.Sum256(archive))
|
||||
if badDigest {
|
||||
digest = "sha256:" + strings.Repeat("0", 64)
|
||||
}
|
||||
json.NewEncoder(w).Encode(release{Tag: tag, Assets: []asset{{Name: "gridcraft-web-" + strings.TrimPrefix(tag, "v") + ".zip", Size: int64(len(archive)), Digest: digest, URL: "https://github.com/storytold/gridcraft/releases/download/" + tag + "/gridcraft-web-" + strings.TrimPrefix(tag, "v") + ".zip"}}})
|
||||
}))
|
||||
defer server.Close()
|
||||
manager := New(t.TempDir())
|
||||
manager.api = server.URL
|
||||
manager.client = server.Client()
|
||||
manager.client.Transport = rewriteTransport{server.URL, http.DefaultTransport}
|
||||
if err := manager.install(context.Background(), "gridcraft"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := manager.Status("gridcraft")
|
||||
if first.Version != "v1.0.0" || first.Build == "" {
|
||||
t.Fatalf("not installed: %+v", first)
|
||||
}
|
||||
file, err := manager.Open("gridcraft", first.Build, "index.html")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file.Close()
|
||||
badDigest = true
|
||||
tag = "v1.1.0"
|
||||
if err = manager.install(context.Background(), "gridcraft"); err == nil {
|
||||
t.Fatal("accepted corrupted bundle")
|
||||
}
|
||||
if manager.Status("gridcraft").Build != first.Build {
|
||||
t.Fatal("failed update replaced active version")
|
||||
}
|
||||
for _, name := range []string{"../active.json", "/index.html", "a/../../active.json", "a\\index.html"} {
|
||||
if f, err := manager.Open("gridcraft", first.Build, name); err == nil {
|
||||
f.Close()
|
||||
t.Fatalf("exposed unsafe path %q", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestArchiveSafety(t *testing.T) {
|
||||
for _, names := range [][]string{{"index.html", "../evil.js"}, {"index.html", "/evil.js"}, {"index.html", "x\\evil.js"}, {"index.html", "APP.js", "app.js"}, {"missing.js"}} {
|
||||
root := t.TempDir()
|
||||
archive := filepath.Join(root, "test.zip")
|
||||
if err := os.WriteFile(archive, bundle(t, names...), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := extract(archive, filepath.Join(root, "out")); err == nil {
|
||||
t.Fatalf("accepted unsafe bundle %v", names)
|
||||
}
|
||||
}
|
||||
root := t.TempDir()
|
||||
archive := filepath.Join(root, "valid.zip")
|
||||
os.WriteFile(archive, bundle(t, "web/index.html", "web/app.js"), 0600)
|
||||
if err := extract(archive, filepath.Join(root, "out")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func TestRejectArchiveSymlinkAndBomb(t *testing.T) {
|
||||
for _, kind := range []string{"symlink", "bomb"} {
|
||||
var b bytes.Buffer
|
||||
w := zip.NewWriter(&b)
|
||||
f, _ := w.Create("index.html")
|
||||
io.WriteString(f, "index")
|
||||
header := zip.FileHeader{Name: "evil"}
|
||||
if kind == "symlink" {
|
||||
header.SetMode(os.ModeSymlink | 0777)
|
||||
}
|
||||
f, _ = w.CreateHeader(&header)
|
||||
io.WriteString(f, "payload")
|
||||
w.Close()
|
||||
data := b.Bytes()
|
||||
if kind == "bomb" {
|
||||
at := bytes.LastIndex(data, []byte{'P', 'K', 1, 2})
|
||||
if at < 0 {
|
||||
t.Fatal("missing directory")
|
||||
} // Claim a huge expanded size; reject without inflating.
|
||||
data[at+24] = 0xff
|
||||
data[at+25] = 0xff
|
||||
data[at+26] = 0xff
|
||||
data[at+27] = 0x7f
|
||||
}
|
||||
root := t.TempDir()
|
||||
archive := filepath.Join(root, "bundle.zip")
|
||||
os.WriteFile(archive, data, 0600)
|
||||
if err := extract(archive, filepath.Join(root, "out")); err == nil {
|
||||
t.Fatalf("accepted %s", kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestOfficialBundles(t *testing.T) {
|
||||
if os.Getenv("FB_TEST_OFFICIAL_ADDONS") != "1" {
|
||||
t.Skip("explicit network integration test")
|
||||
}
|
||||
root := t.TempDir()
|
||||
if configured := os.Getenv("FB_TEST_ADDONS_DIR"); configured != "" {
|
||||
root = configured
|
||||
}
|
||||
manager := New(root)
|
||||
for _, tool := range Catalog {
|
||||
t.Run(tool.ID, func(t *testing.T) {
|
||||
if err := manager.install(context.Background(), tool.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
status := manager.Status(tool.ID)
|
||||
if status.Build == "" {
|
||||
t.Fatal("missing active bundle")
|
||||
}
|
||||
t.Logf("verified %s %s %s", tool.ID, status.Version, status.SHA256)
|
||||
file, err := manager.Open(tool.ID, status.Build, "index.html")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
index, err := io.ReadAll(file)
|
||||
if err != nil || !bytes.Contains(index, []byte(".js")) {
|
||||
t.Fatal("missing web loader")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
param([string]$Version = '3.0.0-sso.19')
|
||||
param([string]$Version = '3.0.0-sso.20')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
Push-Location $repo
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
VERSION="${VERSION:-3.0.0-sso.19}"
|
||||
VERSION="${VERSION:-3.0.0-sso.20}"
|
||||
COMMIT=$(git rev-parse --short HEAD)
|
||||
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
|
||||
mkdir -p build/release/linux-amd64
|
||||
|
||||
@@ -21,6 +21,7 @@ type AuthMethod string
|
||||
|
||||
// Settings contain the main settings of the application.
|
||||
type Settings struct {
|
||||
AddonEnabled map[string]bool `json:"addonEnabled,omitempty"`
|
||||
DownloadArchiveFormat string `json:"downloadArchiveFormat"`
|
||||
Key []byte `json:"key"`
|
||||
Signup bool `json:"signup"`
|
||||
@@ -63,6 +64,7 @@ func (s *Settings) GetRules() []rules.Rule {
|
||||
|
||||
// Server specific settings.
|
||||
type Server struct {
|
||||
AddonsPath string `json:"-"`
|
||||
Root string `json:"root"`
|
||||
BaseURL string `json:"baseURL"`
|
||||
Socket string `json:"socket"`
|
||||
|
||||
Reference in new issue
Block a user