feat: improve ArtCraft integration and configurable file opening
This commit is contained in:
1 parent
3bc62d2b69
commit
80bc2c458d
60 files changed
+1738
-232
No files matched your search
+10
-4
@@ -93,20 +93,26 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
if !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
bridge := needsOfficeBridge(id) && name == "filebrowser-bridge.js"
|
||||
bridge := needsOfficeBridge(id, vars["build"]) && name == "filebrowser-bridge.js"
|
||||
pickerBridge := name == "filebrowser-picker.js"
|
||||
lookup := name
|
||||
if bridge || pickerBridge {
|
||||
lookup = "index.html"
|
||||
}
|
||||
file, err := manager.Open(id, vars["build"], lookup)
|
||||
// PhotoCraft's split WASM release keeps snippets at the bundle root,
|
||||
// while app/photocraft-web.js imports them relative to app/.
|
||||
if err != nil && id == "photocraft" && strings.HasPrefix(lookup, "app/snippets/") {
|
||||
lookup = strings.TrimPrefix(lookup, "app/")
|
||||
file, err = manager.Open(id, vars["build"], lookup)
|
||||
}
|
||||
if err != nil {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
defer file.Close()
|
||||
adaptIndex := name == "index.html" && r.URL.Query().Get("host") == "parent"
|
||||
if !bridge && !pickerBridge && !adaptIndex && acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
|
||||
if compressed, e := manager.Open(id, vars["build"], name+".gz"); e == nil {
|
||||
if compressed, e := manager.Open(id, vars["build"], lookup+".gz"); e == nil {
|
||||
file.Close()
|
||||
file = compressed
|
||||
defer compressed.Close()
|
||||
@@ -122,7 +128,7 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
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'`)
|
||||
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' blob:; worker-src 'self' blob:; media-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'`)
|
||||
if pickerBridge {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(craftPicker))
|
||||
@@ -149,7 +155,7 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
return http.StatusUnprocessableEntity, nil
|
||||
}
|
||||
scripts := `<script src="./filebrowser-picker.js"></script>`
|
||||
if needsOfficeBridge(id) {
|
||||
if needsOfficeBridge(id, vars["build"]) {
|
||||
scripts += `<script src="./filebrowser-bridge.js"></script>`
|
||||
}
|
||||
content = bytes.Replace(content, marker, []byte(scripts+`</head>`), 1)
|
||||
|
||||
@@ -12,6 +12,7 @@ type userInfo struct {
|
||||
Locale string `json:"locale"`
|
||||
ViewMode users.ViewMode `json:"viewMode"`
|
||||
SingleClick bool `json:"singleClick"`
|
||||
AutoOpen map[string]string `json:"autoOpen"`
|
||||
RedirectAfterCopyMove bool `json:"redirectAfterCopyMove"`
|
||||
Perm users.Permissions `json:"perm"`
|
||||
Commands []string `json:"commands"`
|
||||
|
||||
+24
-8
@@ -20,7 +20,7 @@ import (
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
const maxCraftDocument = 64 << 20
|
||||
const maxCraftDocument = 256 << 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.
|
||||
@@ -33,8 +33,11 @@ func readCraftFile(d *data, name string) ([]byte, os.FileInfo, error) {
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > maxCraftDocument {
|
||||
return nil, nil, errors.New("unsupported document size or type")
|
||||
if !info.Mode().IsRegular() {
|
||||
return nil, nil, os.ErrInvalid
|
||||
}
|
||||
if info.Size() > maxCraftDocument {
|
||||
return nil, nil, errCraftDocumentSize
|
||||
}
|
||||
f, err := d.user.Fs.Open(name)
|
||||
if err != nil {
|
||||
@@ -43,10 +46,13 @@ func readCraftFile(d *data, name string) ([]byte, os.FileInfo, error) {
|
||||
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 nil, nil, errCraftDocumentSize
|
||||
}
|
||||
return data, info, err
|
||||
}
|
||||
|
||||
var errCraftDocumentSize = errors.New("file is too large: editors support files up to 256 MiB")
|
||||
|
||||
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"]
|
||||
@@ -54,7 +60,8 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
if !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
if !addonEnabled(d, id) || manager.Status(id).Build == "" || !d.user.Perm.Download || !d.user.Perm.Modify {
|
||||
status := manager.Status(id)
|
||||
if !addonEnabled(d, id) || status.Build == "" || addons.CompatibilityIssue(id, status.Build) != "" || !d.user.Perm.Download || !d.user.Perm.Modify {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
requested := r.URL.Query().Get("path")
|
||||
@@ -62,7 +69,7 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
extension := strings.ToLower(path.Ext(requested))
|
||||
if (r.Method == "PUT" && !tool.CanSave(extension)) || (r.Method != "PUT" && !tool.CanOpen(extension)) {
|
||||
if (r.Method == "PUT" && !tool.CanSave(extension)) || (r.Method == "POST" && !tool.CanOpen(extension)) || (r.Method == "GET" && !tool.CanOpen(extension) && !tool.CanSave(extension)) {
|
||||
return http.StatusUnsupportedMediaType, nil
|
||||
}
|
||||
if !d.Check(requested) {
|
||||
@@ -79,6 +86,12 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
data, _, err := readCraftFile(d, requested)
|
||||
craftMutationMu.Unlock()
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrInvalid) {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
if errors.Is(err, errCraftDocumentSize) {
|
||||
return http.StatusRequestEntityTooLarge, err
|
||||
}
|
||||
return errToStatus(err), err
|
||||
}
|
||||
if err = validateCraftDocument(extension, data); err != nil {
|
||||
@@ -117,14 +130,17 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
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")
|
||||
err = errCraftDocumentSize
|
||||
}
|
||||
if err == nil {
|
||||
err = temp.Sync()
|
||||
}
|
||||
if err != nil {
|
||||
temp.Close()
|
||||
return http.StatusRequestEntityTooLarge, err
|
||||
if errors.Is(err, errCraftDocumentSize) {
|
||||
return http.StatusRequestEntityTooLarge, err
|
||||
}
|
||||
return errToStatus(err), err
|
||||
}
|
||||
if _, err = temp.Seek(0, io.SeekStart); err != nil {
|
||||
temp.Close()
|
||||
|
||||
+20
-3
@@ -1,7 +1,12 @@
|
||||
package fbhttp
|
||||
|
||||
import _ "embed"
|
||||
import "github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
import (
|
||||
_ "embed"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
)
|
||||
|
||||
//go:embed craft_bridge.js
|
||||
var officeBridge []byte
|
||||
@@ -18,7 +23,19 @@ func deckcraftNeedsCompat(id, build string) bool {
|
||||
return id == "deckcraft" && build == "v0.9.0-38076027b9c1"
|
||||
}
|
||||
|
||||
func needsOfficeBridge(id string) bool {
|
||||
func needsOfficeBridge(id string, build ...string) bool {
|
||||
// WordCraft 0.14 added the official parent protocol. Injecting the drop
|
||||
// adapter too announces readiness before Rust is listening and loses the file.
|
||||
if id == "wordcraft" && len(build) > 0 {
|
||||
parts := strings.Split(strings.TrimPrefix(build[0], "v"), ".")
|
||||
if len(parts) >= 2 {
|
||||
major, _ := strconv.Atoi(parts[0])
|
||||
minor, _ := strconv.Atoi(parts[1])
|
||||
if major > 0 || minor >= 14 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
tool, ok := addons.Find(id)
|
||||
return ok && tool.Bridge == "drop"
|
||||
}
|
||||
+34
-13
@@ -9,7 +9,7 @@
|
||||
if (!config || config.id !== id || parent === window || new URLSearchParams(location.search).get("host") !== "parent") return;
|
||||
const accepts = (name, list) => typeof name === "string" && list.some(extension => name.toLowerCase().endsWith(extension));
|
||||
const origin = location.origin;
|
||||
const limit = 64 * 1024 * 1024;
|
||||
const limit = 256 * 1024 * 1024;
|
||||
const jobs = new Map();
|
||||
const blobs = new Map();
|
||||
let opened = false, dirty = false, revision = 0, sequence = 0;
|
||||
@@ -19,8 +19,8 @@
|
||||
const createURL = URL.createObjectURL.bind(URL), revokeURL = URL.revokeObjectURL.bind(URL);
|
||||
URL.createObjectURL = blob => { const url = createURL(blob); blobs.set(url, blob); return url; };
|
||||
URL.revokeObjectURL = url => { blobs.delete(url); revokeURL(url); };
|
||||
async function save(name, blob) {
|
||||
if (blob.size > limit) throw new Error("Document exceeds 64 MiB");
|
||||
async function save(name, blob, saveAs = false) {
|
||||
if (blob.size > limit) throw new Error("Document exceeds 256 MiB");
|
||||
// Bound in-flight copies even if the user repeatedly clicks Save.
|
||||
if (jobs.size >= 2) throw new Error("A save is already pending");
|
||||
const requestId = String(++sequence), savedRevision = revision;
|
||||
@@ -29,7 +29,7 @@
|
||||
return new Promise((resolve, reject) => {
|
||||
jobs.set(requestId, { resolve, reject, revision: savedRevision });
|
||||
blob.arrayBuffer().then(bytes => {
|
||||
send("save", { name, bytes, requestId }, [bytes]);
|
||||
send("save", { name, bytes, requestId, saveAs }, [bytes]);
|
||||
}).catch(error => { jobs.delete(requestId); reject(error); });
|
||||
});
|
||||
}
|
||||
@@ -51,17 +51,36 @@
|
||||
}
|
||||
return {
|
||||
kind: "file", name,
|
||||
queryPermission: async () => "granted",
|
||||
requestPermission: async () => "granted",
|
||||
async createWritable() {
|
||||
let chunks = [], size = 0;
|
||||
let content = new Blob(), position = 0;
|
||||
const offset = value => {
|
||||
if (!Number.isSafeInteger(value) || value < 0 || value > limit) throw new RangeError("Document exceeds 256 MiB or invalid position");
|
||||
return value;
|
||||
};
|
||||
const seek = async value => { position = offset(value); };
|
||||
const truncate = async value => {
|
||||
const size = offset(value);
|
||||
content = size <= content.size ? content.slice(0, size) : new Blob([content, new Uint8Array(size - content.size)]);
|
||||
position = Math.min(position, size);
|
||||
};
|
||||
return {
|
||||
async write(data) {
|
||||
// This build writes sequential Uint8Array chunks, never random-access data.
|
||||
if (data && typeof data === "object" && ["write", "seek", "truncate"].includes(data.type)) {
|
||||
if (data.type === "seek") return seek(data.position);
|
||||
if (data.type === "truncate") return truncate(data.size);
|
||||
if (data.position !== undefined) await seek(data.position);
|
||||
data = data.data;
|
||||
}
|
||||
const chunk = new Blob([data]);
|
||||
if (size + chunk.size > limit) throw new Error("Document exceeds 64 MiB");
|
||||
size += chunk.size; chunks.push(chunk);
|
||||
if (position + chunk.size > limit) throw new Error("Document exceeds 256 MiB");
|
||||
content = new Blob([content.slice(0, position), ...(position > content.size ? [new Uint8Array(position - content.size)] : []), chunk, content.slice(position + chunk.size)]);
|
||||
position += chunk.size;
|
||||
},
|
||||
async close() { const blob = new Blob(chunks); chunks = []; await save(name, blob); },
|
||||
async abort() { chunks = []; }
|
||||
seek, truncate,
|
||||
async close() { const blob = content; content = new Blob(); await save(name, blob, true); },
|
||||
async abort() { content = new Blob(); }
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -99,19 +118,21 @@
|
||||
window.addEventListener("pointerdown", event => { if (opened && event.isTrusted) markDirty(); }, true);
|
||||
window.addEventListener("beforeunload", event => { if (dirty || jobs.size) event.preventDefault(); });
|
||||
let announced = false;
|
||||
let domReady = document.readyState !== "loading";
|
||||
const reportFailure = error => send("failed", { error: String(error?.message || error || "Editor failed to start") });
|
||||
window.addEventListener("error", event => { if (!announced) reportFailure(event.error || event.message); });
|
||||
window.addEventListener("unhandledrejection", event => { if (!announced) reportFailure(event.reason); });
|
||||
function ready() {
|
||||
if (announced) return;
|
||||
if (announced || !domReady) return;
|
||||
const loading = document.getElementById(id + "_loading");
|
||||
if (loading) {
|
||||
if (loading && loading.textContent.trim() && !loading.hidden && loading.style.display !== "none" && (!window.getComputedStyle || getComputedStyle(loading).display !== "none")) {
|
||||
if (/failed to start/i.test(loading.textContent || "")) { send("failed", { error: loading.textContent }); observer.disconnect(); }
|
||||
return;
|
||||
}
|
||||
if (document.getElementById(id + "_canvas")) { announced = true; observer.disconnect(); send("ready"); }
|
||||
}
|
||||
const observer = new MutationObserver(ready);
|
||||
observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true });
|
||||
window.addEventListener("DOMContentLoaded", () => { domReady = true; ready(); }, { once: true });
|
||||
observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["style", "class", "hidden"] });
|
||||
ready();
|
||||
})();
|
||||
@@ -16,7 +16,7 @@
|
||||
const message = event.data, job = jobs.get(message.requestId); if (!job) return;
|
||||
jobs.delete(message.requestId);
|
||||
if (!Array.isArray(message.files)) { job.reject(new DOMException("Selection cancelled", "AbortError")); return; }
|
||||
const files = message.files.filter(f => typeof f.name === "string" && f.bytes instanceof ArrayBuffer && f.bytes.byteLength <= 64 * 1024 * 1024)
|
||||
const files = message.files.filter(f => typeof f.name === "string" && f.bytes instanceof ArrayBuffer && f.bytes.byteLength <= 256 * 1024 * 1024)
|
||||
.map(f => new File([f.bytes], f.name, { type: typeof f.mime === "string" ? f.mime : "" }));
|
||||
if (!files.length) job.reject(new DOMException("No file selected", "AbortError")); else job.resolve(files);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func TestLargePSDAndOversizeResponse(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
manager := installedTestManager(t)
|
||||
key := []byte("large-psd-test")
|
||||
perm := users.Permissions{Download: true, Modify: true}
|
||||
store := scopedUserStorage(t, root, perm, key)
|
||||
handler := handle(craftDocumentHandler(manager, nil), "", store, &settings.Server{})
|
||||
for _, size := range []int64{149355372, maxCraftDocument + 1} {
|
||||
file, err := os.Create(filepath.Join(root, "large.psd"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
header := make([]byte, 26)
|
||||
copy(header, "8BPS")
|
||||
binary.BigEndian.PutUint16(header[4:6], 1)
|
||||
binary.BigEndian.PutUint32(header[14:18], 2528)
|
||||
binary.BigEndian.PutUint32(header[18:22], 1696)
|
||||
file.Write(header)
|
||||
file.Truncate(size)
|
||||
file.Close()
|
||||
r := httptest.NewRequest("GET", "/api/craft/photocraft/document?path="+url.QueryEscape("/large.psd"), nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"addon": "photocraft"})
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, authorizeTestRequest(r, signToken(t, perm, key)))
|
||||
if size <= maxCraftDocument {
|
||||
if rec.Code != 200 || int64(rec.Body.Len()) != size || rec.Header().Get("ETag") == "" {
|
||||
t.Fatalf("large PSD: status %d, size %d", rec.Code, rec.Body.Len())
|
||||
}
|
||||
} else if rec.Code != 413 {
|
||||
t.Fatalf("oversize must be 413, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPhotoCraftSplitModuleAndPrintPolicy(t *testing.T) {
|
||||
manager := installedTestManager(t)
|
||||
key := []byte("split-module-test")
|
||||
perm := users.Permissions{Download: true, Modify: true}
|
||||
store := scopedUserStorage(t, t.TempDir(), perm, key)
|
||||
dir := filepath.Join(manager.Root, "photocraft", "versions", "test-123", "snippets", "eframe-test")
|
||||
os.MkdirAll(dir, 0700)
|
||||
os.WriteFile(filepath.Join(dir, "inline0.js"), []byte("export const ready = true;"), 0600)
|
||||
handler := handle(addonStaticHandler(manager), "", store, &settings.Server{})
|
||||
r := httptest.NewRequest("GET", "/addons/photocraft/test-123/app/snippets/eframe-test/inline0.js", nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"addon": "photocraft", "build": "test-123", "asset": "app/snippets/eframe-test/inline0.js"})
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, authorizeTestRequest(r, signToken(t, perm, key)))
|
||||
if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte("export const ready")) {
|
||||
t.Fatalf("split module: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(rec.Header().Get("Content-Security-Policy"), "frame-src 'self' blob:") {
|
||||
t.Fatal("PDF print iframe blocked")
|
||||
}
|
||||
if needsOfficeBridge("wordcraft", "v0.14.0-afbb7fb0d7c0") {
|
||||
t.Fatal("native WordCraft must not receive duplicate drop bridge")
|
||||
}
|
||||
if !needsOfficeBridge("wordcraft", "v0.9.0-710d2f4dd95a") {
|
||||
t.Fatal("legacy WordCraft still needs adapter")
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,8 @@ func NewHandler(
|
||||
r.Handle("/addons/{addon}/{build}/{asset:.*}", monkey(addonStaticHandler(addonManager), "")).Methods("GET", "HEAD")
|
||||
|
||||
api.PathPrefix("/raw").Handler(monkey(rawHandler, "/api/raw")).Methods("GET")
|
||||
api.Handle("/media/play", monkey(mediaHandler, "")).Methods("GET")
|
||||
api.Handle("/media/status", monkey(mediaStatusHandler, "")).Methods("GET")
|
||||
api.PathPrefix("/preview/{size}/{path:.*}").
|
||||
Handler(monkey(previewHandler(imgSvc, fileCache, server.EnableThumbnails, server.ResizePreview), "/api/preview")).Methods("GET")
|
||||
api.PathPrefix("/search").Handler(monkey(searchHandler, "/api/search")).Methods("GET")
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var mediaStreams = make(chan struct{}, 2)
|
||||
|
||||
var mediaStatusHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
status := struct {
|
||||
Available bool `json:"available"`
|
||||
Version string `json:"version,omitempty"`
|
||||
}{}
|
||||
binary, err := exec.LookPath("ffmpeg")
|
||||
if err == nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
output, runErr := exec.CommandContext(ctx, binary, "-version").Output()
|
||||
if runErr == nil && strings.HasPrefix(string(output), "ffmpeg version ") {
|
||||
status.Available = true
|
||||
status.Version = strings.SplitN(string(output), "\n", 2)[0]
|
||||
}
|
||||
}
|
||||
return renderJSON(w, r, status)
|
||||
})
|
||||
|
||||
// The browser uses the original file first. This optional fallback converts
|
||||
// codecs the browser cannot decode, without changing or copying the original.
|
||||
var mediaHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if !d.user.Perm.Download {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
name := r.URL.Query().Get("path")
|
||||
if name == "" || !strings.HasPrefix(name, "/") || path.Clean(name) != name || strings.ContainsAny(name, "\\\x00") {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
if !d.Check(name) {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
ext := strings.ToLower(path.Ext(name))
|
||||
if !strings.Contains("|.mp4|.m4v|.mkv|.webm|.mov|.avi|.wmv|.mpg|.mpeg|.ts|.mts|.m2ts|.flv|.ogv|.mp3|.wav|.ogg|.oga|.flac|.m4a|.aac|.opus|.aif|.aiff|.wma|.ac3|.dts|", "|"+ext+"|") {
|
||||
return http.StatusUnsupportedMediaType, nil
|
||||
}
|
||||
input, err := d.user.Fs.Open(name)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
defer input.Close()
|
||||
info, err := input.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
binary, err := exec.LookPath("ffmpeg")
|
||||
if err != nil {
|
||||
return http.StatusServiceUnavailable, errors.New("install FFmpeg on the server to play this codec")
|
||||
}
|
||||
select {
|
||||
case mediaStreams <- struct{}{}:
|
||||
defer func() { <-mediaStreams }()
|
||||
default:
|
||||
return http.StatusTooManyRequests, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Hour)
|
||||
defer cancel()
|
||||
// Give FFmpeg seekable HTTP access to this already authorized, open handle.
|
||||
// No filesystem path, credentials or caller-controlled URL enters its args.
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
secret := make([]byte, 32)
|
||||
if _, err = rand.Read(secret); err != nil {
|
||||
listener.Close()
|
||||
return 500, err
|
||||
}
|
||||
token := "/" + hex.EncodeToString(secret)
|
||||
var readMu sync.Mutex
|
||||
relay := &http.Server{ReadHeaderTimeout: 5 * time.Second, Handler: http.HandlerFunc(func(out http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path != token || (request.Method != "GET" && request.Method != "HEAD") {
|
||||
http.NotFound(out, request)
|
||||
return
|
||||
}
|
||||
// ServeContent seeks the shared handle; FFmpeg issues sequential range requests.
|
||||
readMu.Lock()
|
||||
defer readMu.Unlock()
|
||||
http.ServeContent(out, request, info.Name(), info.ModTime(), input)
|
||||
})}
|
||||
go relay.Serve(listener) //nolint:errcheck
|
||||
defer relay.Close()
|
||||
args := []string{"-nostdin", "-hide_banner", "-loglevel", "error", "-protocol_whitelist", "http,tcp", "-format_whitelist", "mov,matroska,webm,avi,asf,mpeg,mpegts,flv,ogg,wav,mp3,flac,aac,aiff,ac3,eac3,dts", "-threads", "2", "-i", "http://" + listener.Addr().String() + token}
|
||||
if r.URL.Query().Get("audio") == "true" {
|
||||
args = append(args, "-map", "0:a:0", "-vn", "-c:a", "libmp3lame", "-b:a", "192k", "-f", "mp3", "pipe:1")
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
} else {
|
||||
args = append(args, "-map", "0:v:0", "-map", "0:a:0?", "-c:v", "libx264", "-threads", "2", "-preset", "veryfast", "-crf", "23", "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", "pipe:1")
|
||||
w.Header().Set("Content-Type", "video/mp4")
|
||||
}
|
||||
command := exec.CommandContext(ctx, binary, args...)
|
||||
stream, err := command.StdoutPipe()
|
||||
if err != nil {
|
||||
return 500, err
|
||||
}
|
||||
if err = command.Start(); err != nil {
|
||||
return http.StatusServiceUnavailable, err
|
||||
}
|
||||
defer command.Wait() //nolint:errcheck
|
||||
// Do not report success when FFmpeg rejects the container or codec.
|
||||
first := make([]byte, 32*1024)
|
||||
n, err := stream.Read(first)
|
||||
if n == 0 {
|
||||
return http.StatusUnsupportedMediaType, errors.New("FFmpeg could not decode this media file")
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
if _, err = w.Write(first[:n]); err == nil {
|
||||
_, err = io.Copy(w, stream)
|
||||
}
|
||||
if err != nil {
|
||||
cancel()
|
||||
}
|
||||
return 0, err
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
func TestMediaStatusIsAdminOnlyAndChecksExecutable(t *testing.T) {
|
||||
perm := users.Permissions{Admin: true}
|
||||
key := []byte("media-status-test")
|
||||
store := scopedUserStorage(t, t.TempDir(), perm, key)
|
||||
handler := handle(mediaStatusHandler, "", store, &settings.Server{})
|
||||
request := func(admin bool) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", "/api/media/status", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, authorizeTestRequest(r, signToken(t, users.Permissions{Admin: admin}, key)))
|
||||
return rec
|
||||
}
|
||||
if rec := request(false); rec.Code != 403 {
|
||||
t.Fatalf("nonadmin: %d", rec.Code)
|
||||
}
|
||||
_, ffmpegErr := exec.LookPath("ffmpeg")
|
||||
rec := request(true)
|
||||
var status struct {
|
||||
Available bool `json:"available"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &status) != nil {
|
||||
t.Fatalf("status: %d", rec.Code)
|
||||
}
|
||||
if ffmpegErr == nil && (!status.Available || status.Version == "") {
|
||||
t.Fatal("installed FFmpeg was not detected")
|
||||
}
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
rec = request(true)
|
||||
if json.Unmarshal(rec.Body.Bytes(), &status) != nil || status.Available {
|
||||
t.Fatal("missing FFmpeg reported as available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaPermissionsAndConversion(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
key := []byte("media-test")
|
||||
perm := users.Permissions{Download: true}
|
||||
store := scopedUserStorage(t, root, perm, key)
|
||||
handler := handle(mediaHandler, "", store, &settings.Server{})
|
||||
request := func(target string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", target, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, authorizeTestRequest(r, signToken(t, perm, key)))
|
||||
return rec
|
||||
}
|
||||
for target, status := range map[string]int{
|
||||
"/api/media/play?path=/../private.wav": 400,
|
||||
"/api/media/play?path=/playlist.m3u": 415,
|
||||
"/api/media/play?path=https://example.com/test.mp3": 400,
|
||||
"/api/media/play?path=/missing.wav": 404,
|
||||
} {
|
||||
if rec := request(target); rec.Code != status {
|
||||
t.Fatalf("%s: want %d, got %d", target, status, rec.Code)
|
||||
}
|
||||
}
|
||||
wave := make([]byte, 44+9600)
|
||||
copy(wave, "RIFF")
|
||||
binary.LittleEndian.PutUint32(wave[4:], uint32(len(wave)-8))
|
||||
copy(wave[8:], "WAVEfmt ")
|
||||
binary.LittleEndian.PutUint32(wave[16:], 16)
|
||||
binary.LittleEndian.PutUint16(wave[20:], 1)
|
||||
binary.LittleEndian.PutUint16(wave[22:], 1)
|
||||
binary.LittleEndian.PutUint32(wave[24:], 48000)
|
||||
binary.LittleEndian.PutUint32(wave[28:], 96000)
|
||||
binary.LittleEndian.PutUint16(wave[32:], 2)
|
||||
binary.LittleEndian.PutUint16(wave[34:], 16)
|
||||
copy(wave[36:], "data")
|
||||
binary.LittleEndian.PutUint32(wave[40:], 9600)
|
||||
os.WriteFile(filepath.Join(root, "audio.wav"), wave, 0600)
|
||||
user, _ := store.Users.Get("", false, uint(1))
|
||||
user.Perm.Download = false
|
||||
store.Users.Save(user)
|
||||
if rec := request("/api/media/play?path=/audio.wav&audio=true"); rec.Code != 403 {
|
||||
t.Fatalf("download denied: %d", rec.Code)
|
||||
}
|
||||
user.Perm.Download = true
|
||||
store.Users.Save(user)
|
||||
if _, err := exec.LookPath("ffmpeg"); err != nil {
|
||||
if rec := request("/api/media/play?path=/audio.wav&audio=true"); rec.Code != 503 {
|
||||
t.Fatalf("missing FFmpeg: %d", rec.Code)
|
||||
}
|
||||
return
|
||||
}
|
||||
rec := request("/api/media/play?path=/audio.wav&audio=true")
|
||||
if rec.Code != 200 || rec.Body.Len() < 100 || rec.Header().Get("Content-Type") != "audio/mpeg" {
|
||||
t.Fatalf("audio transcode: %d, %d bytes, %s", rec.Code, rec.Body.Len(), rec.Body.String())
|
||||
}
|
||||
original, _ := os.ReadFile(filepath.Join(root, "audio.wav"))
|
||||
if !bytes.Equal(original, wave) {
|
||||
t.Fatal("original changed")
|
||||
}
|
||||
video := filepath.Join(root, "video.avi")
|
||||
if output, err := exec.Command("ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=size=64x64:rate=10:color=blue", "-t", "0.2", "-c:v", "mpeg4", video).CombinedOutput(); err != nil {
|
||||
t.Fatalf("fixture: %v %s", err, output)
|
||||
}
|
||||
rec = request("/api/media/play?path=/video.avi")
|
||||
if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte("ftyp")) || rec.Header().Get("Content-Type") != "video/mp4" {
|
||||
t.Fatalf("video transcode: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -225,5 +225,5 @@ func applySSOIdentity(u *users.User, i sessionIdentity) {
|
||||
u.DisplayName = i.Name
|
||||
}
|
||||
func ssoUserInfo(u *users.User) userInfo {
|
||||
return userInfo{ID: u.ID, Username: u.DisplayName, ProfileName: u.ProfileName, Email: u.Email, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, HidePreviews: u.HidePreviews, Dicom3D: u.Dicom3D.Normalized(), DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
|
||||
return userInfo{ID: u.ID, Username: u.DisplayName, ProfileName: u.ProfileName, Email: u.Email, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, AutoOpen: u.AutoOpen, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, HidePreviews: u.HidePreviews, Dicom3D: u.Dicom3D.Normalized(), DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
|
||||
}
|
||||
+1
-1
@@ -130,7 +130,7 @@ var userPutHandler = withSelfOrAdmin(func(w http.ResponseWriter, r *http.Request
|
||||
if req.Data == nil || req.Data.ID != d.raw.(uint) || len(req.Which) == 0 || req.Data.Password != "" {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
allowed := map[string]string{"scope": "Scope", "perm": "Perm", "rules": "Rules", "locale": "Locale", "viewmode": "ViewMode", "singleclick": "SingleClick", "redirectaftercopymove": "RedirectAfterCopyMove", "hidedotfiles": "HideDotfiles", "hidepreviews": "HidePreviews", "dicom3d": "Dicom3D", "dateformat": "DateFormat", "aceeditortheme": "AceEditorTheme", "sorting": "Sorting"}
|
||||
allowed := map[string]string{"autoopen": "AutoOpen", "scope": "Scope", "perm": "Perm", "rules": "Rules", "locale": "Locale", "viewmode": "ViewMode", "singleclick": "SingleClick", "redirectaftercopymove": "RedirectAfterCopyMove", "hidedotfiles": "HideDotfiles", "hidepreviews": "HidePreviews", "dicom3d": "Dicom3D", "dateformat": "DateFormat", "aceeditortheme": "AceEditorTheme", "sorting": "Sorting"}
|
||||
for i, field := range req.Which {
|
||||
canonical, ok := allowed[strings.ToLower(field)]
|
||||
if !ok {
|
||||
|
||||
Reference in new issue
Block a user