feat: polish workspace transfers and verify Craft server file workflows
This commit is contained in:
1 parent
7fd7ae6733
commit
c209f1effc
49 files changed
+1459
-670
No files matched your search
+21
-7
@@ -23,11 +23,14 @@ 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"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CompatibilityIssue string `json:"compatibilityIssue,omitempty"`
|
||||
}
|
||||
items := []entry{}
|
||||
for _, tool := range addons.Catalog {
|
||||
items = append(items, entry{manager.Status(tool.ID), addonEnabled(d, tool.ID)})
|
||||
status := manager.Status(tool.ID)
|
||||
issue := addons.CompatibilityIssue(tool.ID, status.Build)
|
||||
items = append(items, entry{status, addonEnabled(d, tool.ID) && issue == "", issue})
|
||||
}
|
||||
return renderJSON(w, r, items)
|
||||
})
|
||||
@@ -51,7 +54,8 @@ var addonToggleHandler = withAdmin(func(w http.ResponseWriter, r *http.Request,
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
var payload struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CompatibilityIssue string `json:"compatibilityIssue,omitempty"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024)).Decode(&payload); err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
@@ -90,8 +94,9 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
bridge := needsOfficeBridge(id) && name == "filebrowser-bridge.js"
|
||||
pickerBridge := name == "filebrowser-picker.js"
|
||||
lookup := name
|
||||
if bridge {
|
||||
if bridge || pickerBridge {
|
||||
lookup = "index.html"
|
||||
}
|
||||
file, err := manager.Open(id, vars["build"], lookup)
|
||||
@@ -99,8 +104,8 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
defer file.Close()
|
||||
adaptIndex := needsOfficeBridge(id) && name == "index.html" && r.URL.Query().Get("host") == "parent"
|
||||
if !bridge && !adaptIndex && acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
|
||||
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 {
|
||||
file.Close()
|
||||
file = compressed
|
||||
@@ -118,6 +123,11 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
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'`)
|
||||
if pickerBridge {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(craftPicker))
|
||||
return 0, nil
|
||||
}
|
||||
if bridge {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
tool, _ := addons.Find(id)
|
||||
@@ -138,7 +148,11 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
if !bytes.Contains(content, marker) {
|
||||
return http.StatusUnprocessableEntity, nil
|
||||
}
|
||||
content = bytes.Replace(content, marker, []byte(`<script src="./filebrowser-bridge.js"></script></head>`), 1)
|
||||
scripts := `<script src="./filebrowser-picker.js"></script>`
|
||||
if needsOfficeBridge(id) {
|
||||
scripts += `<script src="./filebrowser-bridge.js"></script>`
|
||||
}
|
||||
content = bytes.Replace(content, marker, []byte(scripts+`</head>`), 1)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(content))
|
||||
return 0, nil
|
||||
|
||||
+3
-2
@@ -258,10 +258,11 @@ func blankCraftDocument(id string) ([]byte, error) {
|
||||
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>`,
|
||||
"[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/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+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/_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"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>`,
|
||||
"xl/styles.xml": `<?xml version="1.0"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`,
|
||||
"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)
|
||||
|
||||
@@ -6,6 +6,9 @@ import "github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
//go:embed craft_bridge.js
|
||||
var officeBridge []byte
|
||||
|
||||
//go:embed craft_picker.js
|
||||
var craftPicker []byte
|
||||
|
||||
//go:embed deckcraft_compat.js
|
||||
var deckcraftCompat []byte
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// File selection stays inside the authenticated server scope. No vendor bundle
|
||||
// is modified: both the File System Access API and hidden file inputs are bridged.
|
||||
(() => {
|
||||
"use strict";
|
||||
const parts = location.pathname.split("/"), id = parts[parts.lastIndexOf("addons") + 1];
|
||||
if (parent === window || new URLSearchParams(location.search).get("host") !== "parent") return;
|
||||
const jobs = new Map(); let sequence = 0;
|
||||
const request = (accept, intent = "choose") => new Promise((resolve, reject) => {
|
||||
if (jobs.size) { reject(new DOMException("Selection already pending", "AbortError")); return; }
|
||||
const requestId = `picker-${++sequence}`;
|
||||
jobs.set(requestId, { resolve, reject });
|
||||
parent.postMessage({ type: id + ":pick-request", requestId, accept: String(accept || "").slice(0, 2048), intent }, location.origin);
|
||||
});
|
||||
addEventListener("message", event => {
|
||||
if (event.source !== parent || event.origin !== location.origin || event.data?.type !== id + ":pick-result") return;
|
||||
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)
|
||||
.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);
|
||||
});
|
||||
const chooseInput = input => {
|
||||
request(input.accept).then(files => {
|
||||
const transfer = new DataTransfer(); for (const file of files) transfer.items.add(file);
|
||||
input.files = transfer.files;
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
input.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
}).catch(() => input.dispatchEvent(new Event("cancel", { bubbles: true })));
|
||||
};
|
||||
const click = HTMLInputElement.prototype.click;
|
||||
HTMLInputElement.prototype.click = function () { if (this.type === "file") return chooseInput(this); return click.call(this); };
|
||||
if (HTMLInputElement.prototype.showPicker) {
|
||||
const show = HTMLInputElement.prototype.showPicker;
|
||||
HTMLInputElement.prototype.showPicker = function () { if (this.type === "file") return chooseInput(this); return show.call(this); };
|
||||
}
|
||||
addEventListener("click", event => { if (event.target instanceof HTMLInputElement && event.target.type === "file") { event.preventDefault(); event.stopImmediatePropagation(); chooseInput(event.target); } }, true);
|
||||
window.showOpenFilePicker = async options => {
|
||||
const accept = (options?.types || []).flatMap(t => Object.values(t.accept || {}).flat()).join(",");
|
||||
const files = await request(accept);
|
||||
return files.map(file => ({ kind: "file", name: file.name, getFile: async () => file, queryPermission: async () => "granted", requestPermission: async () => "granted" }));
|
||||
};
|
||||
addEventListener("keydown", event => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "o") {
|
||||
event.preventDefault(); event.stopImmediatePropagation(); request("", "open").catch(() => {});
|
||||
}
|
||||
}, true);
|
||||
})();
|
||||
@@ -365,3 +365,30 @@ func TestAddonRoutesAuthMIMECompressionAndDisable(t *testing.T) {
|
||||
t.Fatalf("disabled addon accessible %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlankSpreadsheetHasStylesRelationship(t *testing.T) {
|
||||
data, err := blankCraftDocument("gridcraft")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts := map[string]string{}
|
||||
for _, f := range reader.File {
|
||||
r, err := f.Open()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := io.ReadAll(r)
|
||||
r.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts[f.Name] = string(b)
|
||||
}
|
||||
if !strings.Contains(parts["xl/styles.xml"], "<cellXfs") || !strings.Contains(parts["xl/_rels/workbook.xml.rels"], `Target="styles.xml"`) || !strings.Contains(parts["[Content_Types].xml"], `/xl/styles.xml`) {
|
||||
t.Fatal("missing spreadsheet styles or relationship")
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -47,7 +47,7 @@ func NewHandler(
|
||||
r := mux.NewRouter()
|
||||
r.Use(func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Security-Policy", `default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'`)
|
||||
w.Header().Set("Content-Security-Policy", `default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'`)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
})
|
||||
|
||||
+1
-1
@@ -73,7 +73,7 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
|
||||
cached, _ = indexTemplates.LoadOrStore(contents, parsed)
|
||||
}
|
||||
index := cached.(*template.Template)
|
||||
w.Header().Set("Content-Security-Policy", fmt.Sprintf("default-src 'self'; script-src 'self' 'nonce-%s' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"]))
|
||||
w.Header().Set("Content-Security-Policy", fmt.Sprintf("default-src 'self'; script-src 'self' 'nonce-%s' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"]))
|
||||
err = index.Execute(w, data)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"github.com/filebrowser/filebrowser/v2/diskcache"
|
||||
"github.com/filebrowser/filebrowser/v2/frontend"
|
||||
"github.com/filebrowser/filebrowser/v2/img"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The browser operates on an isolated test filesystem through the production
|
||||
// HTTP handlers. Authentication is injected only in this test binary.
|
||||
func TestWorkspaceBrowserQA(t *testing.T) {
|
||||
if os.Getenv("FILEBROWSER_QA") != "1" {
|
||||
t.Skip("optional full browser QA")
|
||||
}
|
||||
root := t.TempDir()
|
||||
fixtures := os.Getenv("FILEBROWSER_QA_FIXTURES")
|
||||
if fixtures == "" {
|
||||
t.Fatal("missing fixture directory")
|
||||
}
|
||||
if err := os.CopyFS(root, os.DirFS(fixtures)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, id := range []string{"wordcraft", "gridcraft", "deckcraft", "pdfcraft"} {
|
||||
data, err := blankCraftDocument(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ext := map[string]string{"wordcraft": "docx", "gridcraft": "xlsx", "deckcraft": "pptx", "pdfcraft": "pdf"}[id]
|
||||
if err := os.WriteFile(filepath.Join(root, "document."+ext), data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if data, err := os.ReadFile("testdata/deckcraft-blank.deckcraft"); err == nil {
|
||||
os.WriteFile(filepath.Join(root, "native.deckcraft"), data, 0600)
|
||||
}
|
||||
st := scopedUserStorage(t, root, users.Permissions{Admin: true, Create: true, Modify: true, Rename: true, Delete: true, Share: true, Download: true}, []byte("qa-key"))
|
||||
config, _ := st.Settings.Get()
|
||||
config.Branding.Name = "File Browser"
|
||||
config.Tus.ChunkSize = 1 << 20
|
||||
config.Tus.RetryCount = 1
|
||||
config.DownloadArchiveFormat = "zip"
|
||||
st.Settings.Save(config)
|
||||
serverConfig := &settings.Server{Root: root, AddonsPath: os.Getenv("FILEBROWSER_QA_ADDONS"), EnableThumbnails: true, ResizePreview: true, TypeDetectionByHeader: true}
|
||||
assets, err := fs.Sub(frontend.Assets(), "dist")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cache := diskcache.NewNoOp()
|
||||
uploads, err := NewUploadCache("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer uploads.Close()
|
||||
handler, err := NewHandler(img.New(2), cache, uploads, st, serverConfig, assets)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r = authorizeTestRequest(r, testSession(1, "QA", true))
|
||||
if r.URL.Path == "/api/session" {
|
||||
u, err := st.Users.Get(root, false, uint(1))
|
||||
if err != nil {
|
||||
http.Error(w, "user", 500)
|
||||
return
|
||||
}
|
||||
u.DisplayName = "QA Account"
|
||||
renderJSON(w, r, ssoUserInfo(u))
|
||||
return
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
command := exec.Command("node", os.Getenv("FILEBROWSER_QA_SCRIPT"))
|
||||
command.Env = append(os.Environ(), "FILEBROWSER_QA_URL="+server.URL, "FILEBROWSER_QA_ROOT="+root)
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("%v\n%s", err, output)
|
||||
}
|
||||
t.Log(string(output))
|
||||
}
|
||||
Reference in new issue
Block a user