167 lines
5.4 KiB
Go
167 lines
5.4 KiB
Go
package fbhttp
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"io/fs"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/filebrowser/filebrowser/v2/settings"
|
|
"github.com/filebrowser/filebrowser/v2/storage"
|
|
"github.com/filebrowser/filebrowser/v2/version"
|
|
)
|
|
|
|
var indexTemplates sync.Map
|
|
|
|
func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys fs.FS, file, contentType string) (int, error) {
|
|
w.Header().Set("Content-Type", contentType)
|
|
|
|
data := map[string]interface{}{
|
|
"Name": d.settings.Branding.Name,
|
|
"DisableExternal": d.settings.Branding.DisableExternal,
|
|
"DisableUsedPercentage": d.settings.Branding.DisableUsedPercentage,
|
|
"Color": d.settings.Branding.Color,
|
|
"BaseURL": d.server.BaseURL,
|
|
"Version": version.Version,
|
|
"StaticURL": path.Join(d.server.BaseURL, "/static"),
|
|
"Signup": false,
|
|
"NoAuth": d.server.NoSSO,
|
|
"AuthMethod": "sso",
|
|
"SSOIssuer": d.server.SSOIssuer,
|
|
"SSOClientID": d.server.SSOClientID,
|
|
"LogoutPage": "/auth/logout",
|
|
"LoginPage": true,
|
|
"ReCaptcha": false,
|
|
"Theme": d.settings.Branding.Theme,
|
|
"EnableThumbs": d.server.EnableThumbnails,
|
|
"ResizePreview": d.server.ResizePreview,
|
|
"EnableExec": false,
|
|
"TusSettings": d.settings.Tus,
|
|
"HideLoginButton": d.settings.HideLoginButton,
|
|
"Nonce": randomSecret(),
|
|
}
|
|
|
|
b, err := json.Marshal(data)
|
|
if err != nil {
|
|
return http.StatusInternalServerError, err
|
|
}
|
|
|
|
frameSource := ""
|
|
if d.server.SSOIssuer != "" && !d.server.NoSSO {
|
|
if issuer, e := url.Parse(d.server.SSOIssuer); e == nil {
|
|
frameSource = " " + issuer.Scheme + "://" + issuer.Host
|
|
}
|
|
}
|
|
data["FrameSource"] = frameSource
|
|
data["Json"] = template.JS(strings.ReplaceAll(string(b), `'`, `\'`))
|
|
|
|
fileContents, err := fs.ReadFile(fSys, file)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return http.StatusNotFound, err
|
|
}
|
|
return http.StatusInternalServerError, err
|
|
}
|
|
// Build templates once. A per-response nonce permits the bootstrap without
|
|
// enabling arbitrary inline scripts; the configuration JSON stays escaped.
|
|
contents := strings.ReplaceAll(string(fileContents), "<script", `<script nonce="[{[ .Nonce ]}]"`)
|
|
cached, ok := indexTemplates.Load(contents)
|
|
if !ok {
|
|
parsed, parseErr := template.New("index").Delims("[{[", "]}]").Parse(contents)
|
|
if parseErr != nil {
|
|
return http.StatusInternalServerError, parseErr
|
|
}
|
|
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'; 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:%s; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"], frameSource))
|
|
err = index.Execute(w, data)
|
|
if err != nil {
|
|
return http.StatusInternalServerError, err
|
|
}
|
|
|
|
return 0, nil
|
|
}
|
|
|
|
func getStaticHandlers(store *storage.Storage, server *settings.Server, assetsFs fs.FS) (index, static http.Handler) {
|
|
index = handle(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
|
if r.Method != http.MethodGet {
|
|
return http.StatusNotFound, nil
|
|
}
|
|
|
|
w.Header().Set("x-xss-protection", "1; mode=block")
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
return handleWithStaticData(w, r, d, assetsFs, "public/index.html", "text/html; charset=utf-8")
|
|
}, "", store, server)
|
|
|
|
static = handle(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
|
if r.Method != http.MethodGet {
|
|
return http.StatusNotFound, nil
|
|
}
|
|
|
|
if strings.HasSuffix(r.URL.Path, "/") {
|
|
return http.StatusNotFound, nil
|
|
}
|
|
|
|
const maxAge = 86400 // 1 day
|
|
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%v", maxAge))
|
|
if strings.HasPrefix(r.URL.Path, "assets/") {
|
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
|
}
|
|
w.Header().Add("Vary", "Accept-Encoding")
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
|
|
if !strings.HasSuffix(r.URL.Path, ".js") {
|
|
http.FileServer(http.FS(assetsFs)).ServeHTTP(w, r)
|
|
return 0, nil
|
|
}
|
|
|
|
f, err := assetsFs.Open(r.URL.Path + ".gz")
|
|
if err != nil {
|
|
// Compression may skip tiny chunks when gzip would make them larger.
|
|
// Their original JavaScript is still part of the distribution.
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
http.FileServer(http.FS(assetsFs)).ServeHTTP(w, r)
|
|
return 0, nil
|
|
}
|
|
return http.StatusNotFound, err
|
|
}
|
|
defer f.Close()
|
|
|
|
acceptEncoding := r.Header.Get("Accept-Encoding")
|
|
if strings.Contains(acceptEncoding, "gzip") {
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
|
|
|
if _, err := io.Copy(w, f); err != nil {
|
|
return http.StatusInternalServerError, err
|
|
}
|
|
} else {
|
|
gzReader, err := gzip.NewReader(f)
|
|
if err != nil {
|
|
return http.StatusInternalServerError, err
|
|
}
|
|
defer gzReader.Close()
|
|
|
|
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
|
|
|
if _, err := io.Copy(w, gzReader); err != nil {
|
|
return http.StatusInternalServerError, err
|
|
}
|
|
}
|
|
|
|
return 0, nil
|
|
}, "/static/", store, server)
|
|
|
|
return index, static
|
|
}
|