Add WordCraft and DeckCraft office editors with protected server saves

This commit is contained in:
SantaSpeen committed 2026-10-22 19:25:22 +03:00
1 parent bc9709e500
commit 6e36b6c4b7
20 files changed
+582 -40

No files matched your search

+29 -2
View File
@@ -1,7 +1,9 @@
package fbhttp
import (
"bytes"
"encoding/json"
"io"
"net/http"
"os"
"path"
@@ -84,12 +86,18 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
if !ok {
return http.StatusNotFound, nil
}
file, err := manager.Open(id, vars["build"], name)
bridge := needsOfficeBridge(id) && name == "filebrowser-bridge.js"
lookup := name
if bridge {
lookup = "index.html"
}
file, err := manager.Open(id, vars["build"], lookup)
if err != nil {
return http.StatusNotFound, nil
}
defer file.Close()
if acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
adaptIndex := needsOfficeBridge(id) && name == "index.html" && r.URL.Query().Get("host") == "parent"
if !bridge && !adaptIndex && acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
if compressed, e := manager.Open(id, vars["build"], name+".gz"); e == nil {
file.Close()
file = compressed
@@ -107,6 +115,25 @@ 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 bridge {
w.Header().Set("Cache-Control", "no-store")
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(officeBridge))
return 0, nil
}
if adaptIndex {
content, readErr := io.ReadAll(io.LimitReader(file, (4<<20)+1))
if readErr != nil || len(content) > 4<<20 {
return http.StatusUnprocessableEntity, readErr
}
marker := []byte("</head>")
if !bytes.Contains(content, marker) {
return http.StatusUnprocessableEntity, nil
}
content = bytes.Replace(content, marker, []byte(`<script src="./filebrowser-bridge.js"></script></head>`), 1)
w.Header().Set("Cache-Control", "no-store")
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(content))
return 0, nil
}
http.ServeContent(w, r, name, info.ModTime(), file)
return 0, nil
})
+24 -10
View File
@@ -62,7 +62,7 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
return http.StatusBadRequest, nil
}
extension := strings.ToLower(path.Ext(requested))
if extension != tool.Extension && !(id == "gridcraft" && r.Method == "PUT" && extension == ".pdf") {
if extension != tool.Extension && !(id != "pdfcraft" && r.Method == "PUT" && extension == ".pdf") {
return http.StatusUnsupportedMediaType, nil
}
if !d.Check(requested) {
@@ -191,32 +191,43 @@ func validateCraftDocument(extension string, data []byte) error {
}
return nil
}
mainPart, ok := map[string]string{".xlsx": "xl/workbook.xml", ".docx": "word/document.xml", ".pptx": "ppt/presentation.xml"}[extension]
if !ok {
return errors.New("unsupported document format")
}
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")
return errors.New("Office entry limit")
}
var total uint64
workbook, types := false, false
main, types := false, false
seen := map[string]bool{}
for _, file := range reader.File {
if file.UncompressedSize64 > 64<<20 || file.UncompressedSize64 > (256<<20)-total {
return errors.New("Office expanded size limit")
}
total += file.UncompressedSize64
if total > 256<<20 || file.UncompressedSize64 > 64<<20 {
return errors.New("XLSX expanded size limit")
name := strings.TrimSuffix(file.Name, "/")
if name == "" || strings.ContainsAny(name, "\\\x00") || path.IsAbs(name) || path.Clean(name) != name || name == ".." || strings.HasPrefix(name, "../") || seen[strings.ToLower(name)] || file.Mode()&os.ModeSymlink != 0 || file.Flags&1 != 0 {
return errors.New("unsafe Office archive entry")
}
if file.Name == "xl/workbook.xml" {
workbook = true
seen[strings.ToLower(name)] = true
if file.Name == mainPart && file.UncompressedSize64 > 0 {
main = true
}
if file.Name == "[Content_Types].xml" {
if file.Name == "[Content_Types].xml" && file.UncompressedSize64 > 0 {
types = true
}
}
if !workbook || !types {
return errors.New("invalid XLSX workbook")
if !main || !types {
return errors.New("invalid Office document")
}
return nil
}
func blankCraftDocument(id string) ([]byte, error) {
if id == "pdfcraft" {
var b bytes.Buffer
@@ -234,6 +245,9 @@ func blankCraftDocument(id string) ([]byte, error) {
fmt.Fprintf(&b, "trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", xref)
return b.Bytes(), nil
}
if id == "wordcraft" || id == "deckcraft" {
return blankOfficeDocument(id)
}
if id != "gridcraft" {
return nil, errors.New("unsupported editor")
}
+8
View File
@@ -0,0 +1,8 @@
package fbhttp
import _ "embed"
//go:embed craft_bridge.js
var officeBridge []byte
func needsOfficeBridge(id string) bool { return id == "wordcraft" || id == "deckcraft" }
+108
View File
@@ -0,0 +1,108 @@
// Adapter for official office builds without a native parent-host protocol.
// Loaded before WASM starts; vendor files on disk remain checksum-verifiable.
(() => {
"use strict";
const segments = location.pathname.split("/");
const id = segments[segments.lastIndexOf("addons") + 1];
if (!["wordcraft", "deckcraft"].includes(id) || parent === window || new URLSearchParams(location.search).get("host") !== "parent") return;
const extension = id === "wordcraft" ? ".docx" : ".pptx";
const origin = location.origin;
const limit = 64 * 1024 * 1024;
const jobs = new Map();
const blobs = new Map();
let opened = false, dirty = false, revision = 0, sequence = 0;
const send = (type, data = {}, transfer = []) => parent.postMessage({ type: id + ":" + type, ...data }, origin, transfer);
const managed = name => typeof name === "string" && (name.toLowerCase().endsWith(extension) || name.toLowerCase().endsWith(".pdf"));
const markDirty = () => { dirty = true; revision++; send("dirty", { dirty: true }); };
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");
// 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;
dirty = true;
send("dirty", { dirty: true });
return new Promise((resolve, reject) => {
jobs.set(requestId, { resolve, reject, revision: savedRevision });
blob.arrayBuffer().then(bytes => {
send("save", { name, bytes, requestId }, [bytes]);
}).catch(error => { jobs.delete(requestId); reject(error); });
});
}
const click = HTMLAnchorElement.prototype.click;
HTMLAnchorElement.prototype.click = function () {
const blob = blobs.get(this.href);
if (blob && managed(this.download)) {
save(this.download, blob).catch(error => send("failed", { error: String(error) }));
return;
}
return click.call(this);
};
const picker = window.showSaveFilePicker?.bind(window);
window.showSaveFilePicker = async options => {
const name = options?.suggestedName;
if (!managed(name)) {
if (picker) return picker(options);
throw new DOMException("Use browser download for this format", "NotSupportedError");
}
return {
kind: "file", name,
async createWritable() {
let chunks = [], size = 0;
return {
async write(data) {
// This build writes sequential Uint8Array chunks, never random-access data.
const chunk = new Blob([data]);
if (size + chunk.size > limit) throw new Error("Document exceeds 64 MiB");
size += chunk.size; chunks.push(chunk);
},
async close() { const blob = new Blob(chunks); chunks = []; await save(name, blob); },
async abort() { chunks = []; }
};
}
};
};
window.addEventListener("message", event => {
if (event.source !== parent || event.origin !== origin || !event.data) return;
const message = event.data;
if (message.type === id + ":open" && !opened && message.bytes instanceof ArrayBuffer && message.bytes.byteLength <= limit && typeof message.name === "string" && message.name.toLowerCase().endsWith(extension)) {
const canvas = document.getElementById(id + "_canvas");
if (!canvas) { send("failed", { error: "Editor canvas unavailable" }); return; }
opened = true;
const transfer = new DataTransfer();
transfer.items.add(new File([message.bytes], message.name));
canvas.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: transfer }));
canvas.focus();
} else if (message.type === id + ":saved" || message.type === id + ":save-error") {
const job = jobs.get(message.requestId);
if (!job) return;
jobs.delete(message.requestId);
if (message.type === id + ":saved") {
if (revision === job.revision && jobs.size === 0) { dirty = false; send("dirty", { dirty: false }); }
job.resolve();
} else job.reject(new Error("Server could not save the document; use the recovery controls"));
}
});
// Conservative fallback for builds without dirty-state notifications. Only real
// editing input counts; synthetic file loading and ordinary pointer movement don't.
window.addEventListener("keydown", event => {
if (!opened || !event.isTrusted) return;
if ((event.ctrlKey || event.metaKey) && ["s", "c", "a", "f", "p"].includes(event.key.toLowerCase())) return;
if (event.key.length === 1 || ["Backspace", "Delete", "Enter"].includes(event.key)) markDirty();
}, true);
window.addEventListener("pointerdown", event => { if (opened && event.isTrusted) markDirty(); }, true);
window.addEventListener("beforeunload", event => { if (dirty || jobs.size) event.preventDefault(); });
function ready() {
const loading = document.getElementById(id + "_loading");
if (loading) {
if (/failed to start/i.test(loading.textContent || "")) { send("failed", { error: loading.textContent }); observer.disconnect(); }
return;
}
if (document.getElementById(id + "_canvas")) { observer.disconnect(); send("ready"); }
}
const observer = new MutationObserver(ready);
observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true });
ready();
})();
+60
View File
@@ -0,0 +1,60 @@
package fbhttp
import (
"archive/zip"
"bytes"
"fmt"
"sort"
)
// Small standards-based packages, with no macros, external links or sample data.
func blankOfficeDocument(id string) ([]byte, error) {
const relsNS = `http://schemas.openxmlformats.org/package/2006/relationships`
const officeNS = `http://schemas.openxmlformats.org/officeDocument/2006/relationships/`
entries := map[string]string{}
main := "word/document.xml"
contentType := "wordprocessingml.document"
if id == "wordcraft" {
entries[main] = `<?xml version="1.0" encoding="UTF-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p/><w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>`
} else {
main, contentType = "ppt/presentation.xml", "presentationml.presentation"
const pns = `xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"`
const tree = `<p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr></p:spTree>`
entries[main] = `<p:presentation ` + pns + `><p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst><p:sldIdLst><p:sldId id="256" r:id="rId2"/></p:sldIdLst><p:sldSz cx="12192000" cy="6858000"/><p:notesSz cx="6858000" cy="9144000"/></p:presentation>`
entries["ppt/_rels/presentation.xml.rels"] = `<Relationships xmlns="` + relsNS + `"><Relationship Id="rId1" Type="` + officeNS + `slideMaster" Target="slideMasters/slideMaster1.xml"/><Relationship Id="rId2" Type="` + officeNS + `slide" Target="slides/slide1.xml"/></Relationships>`
entries["ppt/slides/slide1.xml"] = `<p:sld ` + pns + `><p:cSld>` + tree + `</p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>`
entries["ppt/slides/_rels/slide1.xml.rels"] = `<Relationships xmlns="` + relsNS + `"><Relationship Id="rId1" Type="` + officeNS + `slideLayout" Target="../slideLayouts/slideLayout1.xml"/></Relationships>`
entries["ppt/slideLayouts/slideLayout1.xml"] = `<p:sldLayout ` + pns + ` type="blank" preserve="1"><p:cSld name="Blank">` + tree + `</p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>`
entries["ppt/slideLayouts/_rels/slideLayout1.xml.rels"] = `<Relationships xmlns="` + relsNS + `"><Relationship Id="rId1" Type="` + officeNS + `slideMaster" Target="../slideMasters/slideMaster1.xml"/></Relationships>`
entries["ppt/slideMasters/slideMaster1.xml"] = `<p:sldMaster ` + pns + `><p:cSld>` + tree + `</p:cSld><p:clrMap accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" bg1="lt1" bg2="lt2" folHlink="folHlink" hlink="hlink" tx1="dk1" tx2="dk2"/><p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst><p:txStyles><p:titleStyle/><p:bodyStyle/><p:otherStyle/></p:txStyles></p:sldMaster>`
entries["ppt/slideMasters/_rels/slideMaster1.xml.rels"] = `<Relationships xmlns="` + relsNS + `"><Relationship Id="rId1" Type="` + officeNS + `slideLayout" Target="../slideLayouts/slideLayout1.xml"/><Relationship Id="rId2" Type="` + officeNS + `theme" Target="../theme/theme1.xml"/></Relationships>`
entries["ppt/theme/theme1.xml"] = `<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office"><a:themeElements><a:clrScheme name="Office"><a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="1F2937"/></a:dk2><a:lt2><a:srgbClr val="F3F4F6"/></a:lt2><a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2><a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4><a:accent5><a:srgbClr val="5B9BD5"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6><a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink></a:clrScheme><a:fontScheme name="Office"><a:majorFont><a:latin typeface="Arial"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont><a:minorFont><a:latin typeface="Arial"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont></a:fontScheme><a:fmtScheme name="Office"><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:fillStyleLst><a:lnStyleLst><a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements></a:theme>`
}
entries["_rels/.rels"] = `<Relationships xmlns="` + relsNS + `"><Relationship Id="rId1" Type="` + officeNS + `officeDocument" Target="` + main + `"/></Relationships>`
types := `<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="/` + main + `" ContentType="application/vnd.openxmlformats-officedocument.` + contentType + `.main+xml"/>`
if id == "deckcraft" {
for part, kind := range map[string]string{"slides/slide1.xml": "slide", "slideMasters/slideMaster1.xml": "slideMaster", "slideLayouts/slideLayout1.xml": "slideLayout"} {
types += fmt.Sprintf(`<Override PartName="/ppt/%s" ContentType="application/vnd.openxmlformats-officedocument.presentationml.%s+xml"/>`, part, kind)
}
types += `<Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>`
}
entries["[Content_Types].xml"] = types + `</Types>`
var output bytes.Buffer
writer := zip.NewWriter(&output)
keys := make([]string, 0, len(entries))
for name := range entries {
keys = append(keys, name)
}
sort.Strings(keys)
for _, name := range keys {
file, err := writer.Create(name)
if err != nil {
return nil, err
}
if _, err = file.Write([]byte(entries[name])); err != nil {
return nil, err
}
}
err := writer.Close()
return output.Bytes(), err
}
+138 -2
View File
@@ -1,9 +1,12 @@
package fbhttp
import (
"archive/zip"
"bytes"
"compress/gzip"
"encoding/binary"
"encoding/json"
"encoding/xml"
"io"
"net/http/httptest"
"net/url"
@@ -23,7 +26,7 @@ import (
func installedTestManager(t *testing.T) *addons.Manager {
t.Helper()
root := t.TempDir()
for _, id := range []string{"gridcraft", "pdfcraft"} {
for _, id := range []string{"wordcraft", "gridcraft", "deckcraft", "pdfcraft"} {
dir := filepath.Join(root, id, "versions", "test-123")
if err := os.MkdirAll(dir, 0750); err != nil {
t.Fatal(err)
@@ -124,7 +127,7 @@ func TestAddonAssetsProtectedFromFileAPI(t *testing.T) {
}
}
func TestCraftBlankFormats(t *testing.T) {
for id, ext := range map[string]string{"gridcraft": ".xlsx", "pdfcraft": ".pdf"} {
for id, ext := range map[string]string{"wordcraft": ".docx", "gridcraft": ".xlsx", "deckcraft": ".pptx", "pdfcraft": ".pdf"} {
data, err := blankCraftDocument(id)
if err != nil || validateCraftDocument(ext, data) != nil {
t.Fatalf("invalid %s template", id)
@@ -134,6 +137,139 @@ func TestCraftBlankFormats(t *testing.T) {
}
}
}
func TestOfficeCreateSaveAndFormatIsolation(t *testing.T) {
for _, tool := range []string{"wordcraft", "deckcraft"} {
t.Run(tool, func(t *testing.T) {
root := t.TempDir()
key := []byte("office-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(installedTestManager(t), nil), "", store, &settings.Server{})
catalog, _ := addons.Find(tool)
name := "/office" + catalog.Extension
request := func(method, target string, body []byte, tag string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, "/api/craft/"+tool+"/document?path="+url.QueryEscape(target), bytes.NewReader(body))
r = mux.SetURLVars(r, map[string]string{"addon": tool})
r.Header.Set("If-Match", tag)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, authorizeTestRequest(r, token))
return rec
}
if rec := request("POST", name, nil, ""); rec.Code != 204 {
t.Fatalf("create %d %s", rec.Code, rec.Body.String())
}
if rec := request("POST", name, nil, ""); rec.Code != 409 {
t.Fatalf("overwritten %d", rec.Code)
}
loaded := request("GET", name, nil, "")
if loaded.Code != 200 {
t.Fatalf("load %d", loaded.Code)
}
body, err := zip.NewReader(bytes.NewReader(loaded.Body.Bytes()), int64(loaded.Body.Len()))
if err != nil {
t.Fatal(err)
}
for _, part := range body.File {
f, err := part.Open()
if err != nil {
t.Fatal(err)
}
decoder := xml.NewDecoder(f)
for {
_, err = decoder.Token()
if err != nil {
break
}
}
f.Close()
if err != io.EOF {
t.Fatalf("invalid XML %s: %v", part.Name, err)
}
}
wrong, _ := blankCraftDocument("gridcraft")
if rec := request("PUT", name, wrong, loaded.Header().Get("ETag")); rec.Code != 422 {
t.Fatalf("wrong format accepted %d", rec.Code)
}
if rec := request("PUT", name, loaded.Body.Bytes(), loaded.Header().Get("ETag")); rec.Code != 204 {
t.Fatalf("save %d %s", rec.Code, rec.Body.String())
}
if rec := request("PUT", name, loaded.Body.Bytes(), `"stale"`); rec.Code != 412 {
t.Fatalf("stale overwrite %d", rec.Code)
}
})
}
}
func TestOfficeBridgeDelivery(t *testing.T) {
manager := installedTestManager(t)
root := t.TempDir()
key := []byte("office-route-test")
perm := users.Permissions{Download: true, Modify: true}
store := scopedUserStorage(t, root, perm, key)
handler := handle(addonStaticHandler(manager), "", store, &settings.Server{})
for _, id := range []string{"wordcraft", "deckcraft"} {
index := filepath.Join(manager.Root, id, "versions", "test-123", "index.html")
original := []byte("<html><head></head><body>vendor</body></html>")
if err := os.WriteFile(index, original, 0600); err != nil {
t.Fatal(err)
}
for _, name := range []string{"index.html", "filebrowser-bridge.js"} {
r := httptest.NewRequest("GET", "/addons/"+id+"/test-123/"+name+"?host=parent", nil)
r.Header.Set("Accept-Encoding", "gzip")
r = mux.SetURLVars(r, map[string]string{"addon": id, "build": "test-123", "asset": name})
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, authorizeTestRequest(r, signToken(t, perm, key)))
if rec.Code != 200 || rec.Header().Get("Content-Encoding") != "" || rec.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("bridge %s: %d %v", name, rec.Code, rec.Header())
}
if name == "index.html" && !strings.Contains(rec.Body.String(), `src="./filebrowser-bridge.js"`) {
t.Fatal("missing adapter")
}
if name != "index.html" && !bytes.Equal(rec.Body.Bytes(), officeBridge) {
t.Fatal("wrong bridge")
}
}
unchanged, _ := os.ReadFile(index)
if !bytes.Equal(original, unchanged) {
t.Fatal("modified checksum-verified bundle")
}
}
}
func TestOfficeArchiveLimitsWithoutInflating(t *testing.T) {
valid, err := blankCraftDocument("wordcraft")
if err != nil {
t.Fatal(err)
}
// Falsify the central-directory expanded size. Validation must reject it
// using only the directory, without allocating or inflating that data.
bomb := append([]byte(nil), valid...)
offset := bytes.Index(bomb, []byte{'P', 'K', 1, 2})
if offset < 0 {
t.Fatal("missing ZIP directory")
}
binary.LittleEndian.PutUint32(bomb[offset+24:offset+28], 0x7fffffff)
if validateCraftDocument(".docx", bomb) == nil {
t.Fatal("accepted oversized Office part")
}
var unsafe bytes.Buffer
writer := zip.NewWriter(&unsafe)
for _, name := range []string{"[Content_Types].xml", "word/document.xml", "../outside.xml"} {
f, err := writer.Create(name)
if err != nil {
t.Fatal(err)
}
f.Write([]byte("<xml/>"))
}
if err := writer.Close(); err != nil {
t.Fatal(err)
}
if validateCraftDocument(".docx", unsafe.Bytes()) == nil {
t.Fatal("accepted traversal")
}
}
func TestAddonRoutesAuthMIMECompressionAndDisable(t *testing.T) {
manager := installedTestManager(t)
root := t.TempDir()