Aperçu : détection automatique des fichiers texte et réglages
- Hors liste blanche, reniflage du contenu (UTF-8 valide, sans NUL, peu de caractères de contrôle) : .pem, .csr, fichiers sans extension... servis en text/plain avec les mêmes protections - Langage deviné côté client (highlight.js), sauf blocs PEM/PGP - Paramètres > Aperçu : préférences d'affichage par navigateur (coloration, numéros de ligne, retour à la ligne, Markdown rendu/source, CSV) ; réglages administrateur (détection, plafond 1-50 Mo, extensions texte, extensions exclues, aperçu dans les partages) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d4da3db132
commit
ca53cedc32
12 files changed
+806
-85
No files matched your search
+1
-4
@@ -65,7 +65,7 @@ type Handler struct {
|
||||
Accounts *auth.Accounts // nil : pas de comptes (AUTH_MODE=none)
|
||||
|
||||
MaxJSON int64 // taille maximale d'un corps JSON (octets)
|
||||
// PreviewMaxText : octets de texte servis au plus par /api/preview.
|
||||
// PreviewMaxText : si > 0, remplace le plafond de texte des paramètres (tests).
|
||||
PreviewMaxText int64
|
||||
Mode string // none, local, oidc ou both
|
||||
OIDCName string // libellé du bouton de connexion OIDC
|
||||
@@ -86,9 +86,6 @@ func (h *Handler) Init() *Handler {
|
||||
if h.MaxJSON == 0 {
|
||||
h.MaxJSON = 1 << 20
|
||||
}
|
||||
if h.PreviewMaxText == 0 {
|
||||
h.PreviewMaxText = DefaultPreviewMaxText
|
||||
}
|
||||
h.unlocks = auth.NewLimiter(10, 15*time.Minute)
|
||||
return h
|
||||
}
|
||||
|
||||
@@ -102,6 +102,8 @@ type settingsReq struct {
|
||||
Registration *string `json:"registration"`
|
||||
QuotaMB *int64 `json:"quotaMB"`
|
||||
CommonReadonly *bool `json:"commonReadonly"`
|
||||
|
||||
Preview *storage.PreviewPatch `json:"preview"`
|
||||
}
|
||||
|
||||
func (h *Handler) writeSettings(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -125,6 +127,9 @@ func (h *Handler) writeSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if err == nil && req.CommonReadonly != nil {
|
||||
st, err = h.Store.WriteCommonReadonly(*req.CommonReadonly)
|
||||
}
|
||||
if err == nil && req.Preview != nil {
|
||||
st, err = h.Store.WritePreview(*req.Preview)
|
||||
}
|
||||
if err == nil && req.TrashDays != nil {
|
||||
if st, err = h.Store.WriteTrashDays(*req.TrashDays); err == nil {
|
||||
if perr := h.Spaces.PurgeTrash(); perr != nil {
|
||||
|
||||
+123
-15
@@ -23,10 +23,20 @@ import (
|
||||
// Content-Disposition: inline, avec nosniff et une CSP stricte. Le contenu
|
||||
// texte n'est jamais servi avec un type actif (HTML, XML, JavaScript) : un
|
||||
// fichier .html part en text/plain et s'affiche comme du code. Le texte est
|
||||
// plafonné à Handler.PreviewMaxText ; au-delà, seul le début est envoyé.
|
||||
// plafonné (2 Mo par défaut, réglable) ; au-delà, seul le début est envoyé.
|
||||
//
|
||||
// Hors liste blanche, le contenu est reniflé (sniffText) : un fichier lisible
|
||||
// en texte (.pem, .csr, .crt, fichier sans extension...) est servi en
|
||||
// text/plain avec les mêmes protections, genre "text" et X-Preview-Detected: 1.
|
||||
// Les formats exclus (excludedExts) ne sont jamais reniflés.
|
||||
//
|
||||
// Réglages de l'administrateur (storage.PreviewSettings) : reniflage actif ou
|
||||
// non, plafond du texte, extensions toujours en texte, extensions exclues,
|
||||
// aperçu dans les liens de partage.
|
||||
//
|
||||
// En-têtes de réponse : X-Preview-Kind (text, csv, markdown, code, pdf),
|
||||
// X-Preview-Size (taille réelle du fichier), X-Preview-Truncated (1 si coupé).
|
||||
// X-Preview-Size (taille réelle du fichier), X-Preview-Truncated (1 si coupé),
|
||||
// X-Preview-Detected (1 si le genre vient du reniflage du contenu).
|
||||
|
||||
// Genres d'aperçu.
|
||||
const (
|
||||
@@ -37,9 +47,6 @@ const (
|
||||
PreviewPDF = "pdf"
|
||||
)
|
||||
|
||||
// DefaultPreviewMaxText : plafond par défaut du texte servi en aperçu.
|
||||
const DefaultPreviewMaxText = 2 << 20
|
||||
|
||||
// previewExts : liste blanche des extensions prévisualisables.
|
||||
var previewExts = map[string]string{
|
||||
".txt": PreviewText, ".log": PreviewText, ".rst": PreviewText, ".srt": PreviewText, ".sub": PreviewText,
|
||||
@@ -65,7 +72,12 @@ func init() {
|
||||
}
|
||||
}
|
||||
|
||||
// PreviewKind renvoie le genre d'aperçu d'un fichier ("" : non prévisualisable).
|
||||
// excludedExts : formats texte ou binaires exclus de l'aperçu, même reniflés
|
||||
// (RTF/DOC/DOCX hors périmètre ; SVG servi par /api/file).
|
||||
var excludedExts = map[string]bool{".rtf": true, ".doc": true, ".docx": true, ".svg": true}
|
||||
|
||||
// PreviewKind renvoie le genre d'aperçu d'un fichier d'après son nom ("" :
|
||||
// hors liste blanche, à renifler sauf extension exclue).
|
||||
func PreviewKind(name string) string {
|
||||
base := strings.ToLower(path.Base(name))
|
||||
if k, ok := previewNames[base]; ok {
|
||||
@@ -101,8 +113,12 @@ func (h *Handler) preview(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
cfg, ok := h.previewSettings(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
p := r.URL.Query().Get("path")
|
||||
if PreviewKind(p) == "" {
|
||||
if cfg.excluded(p) {
|
||||
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
|
||||
return
|
||||
}
|
||||
@@ -112,7 +128,7 @@ func (h *Handler) preview(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
h.servePreview(w, r, f, fi)
|
||||
h.servePreview(w, r, f, fi, cfg)
|
||||
}
|
||||
|
||||
func (h *Handler) publicPreview(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -120,22 +136,90 @@ func (h *Handler) publicPreview(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
cfg, ok := h.previewSettings(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !cfg.Shares {
|
||||
writeErr(w, http.StatusForbidden, "aperçu désactivé pour les liens de partage")
|
||||
return
|
||||
}
|
||||
f, fi, err := st.Open(full)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
h.servePreview(w, r, f, fi)
|
||||
h.servePreview(w, r, f, fi, cfg)
|
||||
}
|
||||
|
||||
func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.File, fi fs.FileInfo) {
|
||||
// previewConfig : réglages de l'aperçu (paramètres de l'administrateur).
|
||||
type previewConfig struct {
|
||||
storage.PreviewSettings
|
||||
text, excl map[string]bool // extensions avec le point, en minuscules
|
||||
}
|
||||
|
||||
func (h *Handler) previewSettings(w http.ResponseWriter) (previewConfig, bool) {
|
||||
st, err := h.Store.ReadSettings()
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return previewConfig{}, false
|
||||
}
|
||||
c := previewConfig{PreviewSettings: st.Preview, text: map[string]bool{}, excl: map[string]bool{}}
|
||||
for _, e := range st.Preview.TextExts {
|
||||
c.text["."+e] = true
|
||||
}
|
||||
for _, e := range st.Preview.ExcludedExts {
|
||||
c.excl["."+e] = true
|
||||
}
|
||||
return c, true
|
||||
}
|
||||
|
||||
// excluded : extension exclue d'office (RTF, DOC...) ou par l'administrateur.
|
||||
func (c previewConfig) excluded(name string) bool {
|
||||
e := strings.ToLower(path.Ext(name))
|
||||
return excludedExts[e] || c.excl[e]
|
||||
}
|
||||
|
||||
// kind : genre d'après le nom (liste blanche, puis extensions texte de l'administrateur).
|
||||
func (c previewConfig) kind(name string) string {
|
||||
if k := PreviewKind(name); k != "" {
|
||||
return k
|
||||
}
|
||||
if c.text[strings.ToLower(path.Ext(name))] {
|
||||
return PreviewText
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c previewConfig) maxText() int64 {
|
||||
if c.MaxTextMB < 1 {
|
||||
return int64(storage.DefaultPreview.MaxTextMB) << 20
|
||||
}
|
||||
return int64(c.MaxTextMB) << 20
|
||||
}
|
||||
|
||||
func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.File, fi fs.FileInfo, cfg previewConfig) {
|
||||
name := fi.Name()
|
||||
kind := PreviewKind(name)
|
||||
if kind == "" || fi.IsDir() {
|
||||
kind := cfg.kind(name)
|
||||
if fi.IsDir() || cfg.excluded(name) || (kind == "" && !cfg.Sniff) {
|
||||
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
|
||||
return
|
||||
}
|
||||
detected := false
|
||||
if kind == "" {
|
||||
head := make([]byte, sniffLen)
|
||||
n, _ := io.ReadFull(f, head)
|
||||
if !sniffText(head[:n], int64(n) < fi.Size()) {
|
||||
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
|
||||
return
|
||||
}
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
kind, detected = PreviewText, true
|
||||
}
|
||||
hd := w.Header()
|
||||
hd.Set("Content-Type", previewType[kind])
|
||||
hd.Set("Content-Disposition", contentDisposition(true, name))
|
||||
@@ -144,6 +228,7 @@ func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.Fil
|
||||
hd.Set("ETag", storage.ETag(fi))
|
||||
hd.Set("X-Preview-Kind", kind)
|
||||
hd.Set("X-Preview-Size", strconv.FormatInt(fi.Size(), 10))
|
||||
hd.Set("X-Preview-Detected", map[bool]string{true: "1", false: "0"}[detected])
|
||||
|
||||
if kind == PreviewPDF {
|
||||
hd.Set("Content-Security-Policy", cspPreviewPDF)
|
||||
@@ -153,9 +238,9 @@ func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.Fil
|
||||
}
|
||||
|
||||
hd.Set("Content-Security-Policy", cspPreviewText)
|
||||
max := h.PreviewMaxText
|
||||
if max <= 0 {
|
||||
max = DefaultPreviewMaxText
|
||||
max := cfg.maxText()
|
||||
if h.PreviewMaxText > 0 { // tests
|
||||
max = h.PreviewMaxText
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(f, max))
|
||||
if err != nil {
|
||||
@@ -178,6 +263,29 @@ func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.Fil
|
||||
http.ServeContent(w, r, name, fi.ModTime(), bytes.NewReader(b))
|
||||
}
|
||||
|
||||
// sniffLen : octets examinés pour reconnaître un fichier texte.
|
||||
const sniffLen = 8192
|
||||
|
||||
// sniffText indique si un début de fichier est du texte lisible : UTF-8 valide
|
||||
// (un caractère coupé en fin d'échantillon est toléré si partial), aucun octet
|
||||
// NUL, et au plus 1 % de caractères de contrôle hors \t \n \r \f et ESC.
|
||||
// Un fichier vide est du texte.
|
||||
func sniffText(b []byte, partial bool) bool {
|
||||
if partial {
|
||||
b = trimPartialRune(b)
|
||||
}
|
||||
if !utf8.Valid(b) || bytes.IndexByte(b, 0) >= 0 {
|
||||
return false
|
||||
}
|
||||
ctrl := 0
|
||||
for _, c := range b {
|
||||
if (c < 0x20 && c != '\t' && c != '\n' && c != '\r' && c != '\f' && c != 0x1b) || c == 0x7f {
|
||||
ctrl++
|
||||
}
|
||||
}
|
||||
return ctrl*100 <= len(b)
|
||||
}
|
||||
|
||||
// trimPartialRune retire un caractère UTF-8 coupé en fin d'extrait.
|
||||
func trimPartialRune(b []byte) []byte {
|
||||
for i := 1; i <= utf8.UTFMax && i <= len(b); i++ {
|
||||
|
||||
@@ -88,7 +88,7 @@ func TestPublicPreview(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
want(t, s.put("dir/a.go", "package a"), 200)
|
||||
want(t, s.put("dir/b.zip", "PK"), 200)
|
||||
want(t, s.put("dir/b.zip", "PK\x03\x04\x00\x00"), 200)
|
||||
sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "dir", "days": 1}))
|
||||
v := f.session()
|
||||
w := v.get("/api/public/" + sh.Token + "/preview?sub=a.go")
|
||||
@@ -99,3 +99,123 @@ func TestPublicPreview(t *testing.T) {
|
||||
want(t, v.get("/api/public/"+sh.Token+"/preview?sub=b.zip"), 415)
|
||||
want(t, v.get("/api/public/nope/preview?sub=a.go"), 404)
|
||||
}
|
||||
|
||||
func TestPreviewSniffUnknownExtensions(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
pem := "-----BEGIN CERTIFICATE-----\nMIIBszCCAVmgAwIBAgIUQ==\n-----END CERTIFICATE-----\n"
|
||||
want(t, s.put("certs/server.pem", pem), 200)
|
||||
want(t, s.put("certs/hosts", "127.0.0.1 localhost\n"), 200)
|
||||
want(t, s.put("certs/vide.cfgx", ""), 200)
|
||||
want(t, s.put("bin/blob.bin", "\x7fELF\x02\x01\x01\x00\x00"), 200)
|
||||
want(t, s.put("bin/latin1.dat", "caf\xe9 cr\xe8me"), 200)
|
||||
want(t, s.put("bin/ctrl.dat", strings.Repeat("ab\x01\x02", 50)), 200)
|
||||
want(t, s.put("doc/lettre.rtf", `{\rtf1\ansi Bonjour}`), 200)
|
||||
|
||||
for p, body := range map[string]string{"certs/server.pem": pem, "certs/hosts": "127.0.0.1 localhost\n", "certs/vide.cfgx": ""} {
|
||||
w := s.get("/api/preview?path=" + p)
|
||||
want(t, w, 200)
|
||||
h := w.Header()
|
||||
if w.Body.String() != body || h.Get("Content-Type") != "text/plain; charset=utf-8" || h.Get("X-Preview-Kind") != PreviewText ||
|
||||
h.Get("X-Preview-Detected") != "1" || !strings.HasPrefix(h.Get("Content-Security-Policy"), "sandbox") || h.Get("X-Content-Type-Options") != "nosniff" {
|
||||
t.Errorf("%s : %q %v", p, w.Body, h)
|
||||
}
|
||||
}
|
||||
// Liste blanche : pas de reniflage.
|
||||
if w := s.get("/api/preview?path=certs/../certs/server.pem"); w.Header().Get("X-Preview-Detected") != "1" {
|
||||
t.Errorf("chemin normalisé : %v", w.Header())
|
||||
}
|
||||
want(t, s.put("a.json", "{}"), 200)
|
||||
if w := s.get("/api/preview?path=a.json"); w.Header().Get("X-Preview-Detected") != "0" {
|
||||
t.Errorf("liste blanche : %v", w.Header())
|
||||
}
|
||||
for _, p := range []string{"bin/blob.bin", "bin/latin1.dat", "bin/ctrl.dat", "doc/lettre.rtf"} {
|
||||
want(t, s.get("/api/preview?path="+p), 415)
|
||||
}
|
||||
// Reniflage aussi via un lien de partage.
|
||||
sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "certs", "days": 1}))
|
||||
w := f.session().get("/api/public/" + sh.Token + "/preview?sub=server.pem")
|
||||
want(t, w, 200)
|
||||
if w.Body.String() != pem {
|
||||
t.Errorf("public : %q", w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSniffText(t *testing.T) {
|
||||
long := strings.Repeat("é", 4096) // 8192 octets
|
||||
for name, c := range map[string]struct {
|
||||
b string
|
||||
partial bool
|
||||
ok bool
|
||||
}{
|
||||
"ascii": {"hello\n", false, true},
|
||||
"utf8": {"café ☕", false, true},
|
||||
"coupé toléré": {long[:8191], true, true},
|
||||
"coupé final": {long[:8191], false, false},
|
||||
"nul": {"a\x00b", false, false},
|
||||
"esc couleurs": {"\x1b[31mrouge\x1b[0m\n", false, true},
|
||||
"trop de ctrl": {"\x01\x02\x03abc", false, false},
|
||||
"vide": {"", false, true},
|
||||
} {
|
||||
if got := sniffText([]byte(c.b), c.partial); got != c.ok {
|
||||
t.Errorf("%s : %v, attendu %v", name, got, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewSettings(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
admin := f.register("alice")
|
||||
want(t, admin.put("k/server.pem", "-----BEGIN CERTIFICATE-----\n"), 200)
|
||||
want(t, admin.put("k/notes.mylog", "ligne\n"), 200)
|
||||
want(t, admin.put("k/app.log", "log\n"), 200)
|
||||
want(t, admin.put("k/gros.txt", strings.Repeat("a", 3<<20)), 200)
|
||||
|
||||
st := decode[storage.Settings](t, admin.get("/api/settings"))
|
||||
if p := st.Preview; !p.Sniff || p.MaxTextMB != 2 || !p.Shares || len(p.TextExts) != 0 || len(p.ExcludedExts) != 0 {
|
||||
t.Fatalf("défauts : %+v", p)
|
||||
}
|
||||
if w := admin.get("/api/preview?path=k/gros.txt"); w.Body.Len() != 2<<20 || w.Header().Get("X-Preview-Truncated") != "1" {
|
||||
t.Errorf("plafond 2 Mo : %d", w.Body.Len())
|
||||
}
|
||||
|
||||
// Validation.
|
||||
want(t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"maxTextMB": 0}}), 400)
|
||||
want(t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"maxTextMB": 51}}), 400)
|
||||
want(t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"textExts": []string{"a/b"}}}), 400)
|
||||
|
||||
st = decode[storage.Settings](t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{
|
||||
"sniff": false, "maxTextMB": 3, "textExts": []string{".MyLog", "mylog", " pem "}, "excludedExts": []string{"log"}, "shares": false,
|
||||
}}))
|
||||
if p := st.Preview; p.Sniff || p.MaxTextMB != 3 || p.Shares || strings.Join(p.TextExts, ",") != "mylog,pem" || strings.Join(p.ExcludedExts, ",") != "log" {
|
||||
t.Fatalf("réglages : %+v", p)
|
||||
}
|
||||
// Un patch partiel ne touche pas aux autres champs.
|
||||
st = decode[storage.Settings](t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"maxTextMB": 4}}))
|
||||
if p := st.Preview; p.MaxTextMB != 4 || p.Sniff || strings.Join(p.TextExts, ",") != "mylog,pem" {
|
||||
t.Fatalf("patch partiel : %+v", p)
|
||||
}
|
||||
|
||||
w := admin.get("/api/preview?path=k/notes.mylog") // extension texte de l'administrateur
|
||||
want(t, w, 200)
|
||||
if w.Header().Get("X-Preview-Detected") != "0" || w.Header().Get("X-Preview-Kind") != PreviewText {
|
||||
t.Errorf("textExts : %v", w.Header())
|
||||
}
|
||||
want(t, admin.get("/api/preview?path=k/app.log"), 415) // exclue
|
||||
if w := admin.get("/api/preview?path=k/gros.txt"); w.Body.Len() != 3<<20 || w.Header().Get("X-Preview-Truncated") != "0" {
|
||||
t.Errorf("plafond 4 Mo : %d", w.Body.Len())
|
||||
}
|
||||
|
||||
// Reniflage désactivé : extension inconnue refusée.
|
||||
want(t, admin.put("k/hosts", "127.0.0.1 localhost\n"), 200)
|
||||
want(t, admin.get("/api/preview?path=k/hosts"), 415)
|
||||
|
||||
// Aperçu désactivé dans les partages.
|
||||
sh := decode[storage.Share](t, admin.json("POST", "/api/shares", map[string]any{"path": "k", "days": 1}))
|
||||
want(t, f.session().get("/api/public/"+sh.Token+"/preview?sub=server.pem"), 403)
|
||||
|
||||
// Réservé aux administrateurs.
|
||||
want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "open"}), 200)
|
||||
bob := f.register("bob")
|
||||
want(t, bob.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"sniff": true}}), 403)
|
||||
}
|
||||
@@ -73,14 +73,60 @@ type Settings struct {
|
||||
Registration string `json:"registration"`
|
||||
QuotaMB int64 `json:"quotaMB"`
|
||||
CommonReadonly bool `json:"commonReadonly"`
|
||||
|
||||
Preview PreviewSettings `json:"preview"`
|
||||
}
|
||||
|
||||
// PreviewSettings : réglages de l'aperçu des fichiers (/api/preview).
|
||||
type PreviewSettings struct {
|
||||
// Sniff : un fichier hors liste blanche est prévisualisé si son contenu est
|
||||
// du texte lisible (.pem, .csr, fichiers sans extension...).
|
||||
Sniff bool `json:"sniff"`
|
||||
// MaxTextMB : plafond du texte servi (au-delà, seul le début est affiché).
|
||||
MaxTextMB int `json:"maxTextMB"`
|
||||
// TextExts : extensions toujours affichées en texte, sans reniflage.
|
||||
TextExts []string `json:"textExts"`
|
||||
// ExcludedExts : extensions jamais prévisualisées.
|
||||
ExcludedExts []string `json:"excludedExts"`
|
||||
// Shares : aperçu texte et PDF dans les liens de partage.
|
||||
Shares bool `json:"shares"`
|
||||
}
|
||||
|
||||
// Bornes des réglages de l'aperçu.
|
||||
const (
|
||||
MaxPreviewTextMB = 50
|
||||
maxPreviewExts = 100
|
||||
maxPreviewExtLen = 16
|
||||
)
|
||||
|
||||
// DefaultPreview : reniflage actif, 2 Mo de texte, aperçu dans les partages.
|
||||
var DefaultPreview = PreviewSettings{Sniff: true, MaxTextMB: 2, TextExts: []string{}, ExcludedExts: []string{}, Shares: true}
|
||||
|
||||
// previewDisk : champs absents = valeur par défaut.
|
||||
type previewDisk struct {
|
||||
Sniff *bool `json:"sniff,omitempty"`
|
||||
MaxTextMB *int `json:"maxTextMB,omitempty"`
|
||||
TextExts []string `json:"textExts,omitempty"`
|
||||
ExcludedExts []string `json:"excludedExts,omitempty"`
|
||||
Shares *bool `json:"shares,omitempty"`
|
||||
}
|
||||
|
||||
// PreviewPatch : seuls les champs non nil sont modifiés.
|
||||
type PreviewPatch struct {
|
||||
Sniff *bool `json:"sniff"`
|
||||
MaxTextMB *int `json:"maxTextMB"`
|
||||
TextExts *[]string `json:"textExts"`
|
||||
ExcludedExts *[]string `json:"excludedExts"`
|
||||
Shares *bool `json:"shares"`
|
||||
}
|
||||
|
||||
type settingsDisk struct {
|
||||
Title string `json:"title"`
|
||||
TrashDays *int `json:"trashDays,omitempty"`
|
||||
Registration *string `json:"registration,omitempty"`
|
||||
QuotaMB *int64 `json:"quotaMB,omitempty"`
|
||||
CommonReadonly *bool `json:"commonReadonly,omitempty"`
|
||||
Preview *previewDisk `json:"preview,omitempty"`
|
||||
Title string `json:"title"`
|
||||
TrashDays *int `json:"trashDays,omitempty"`
|
||||
Registration *string `json:"registration,omitempty"`
|
||||
QuotaMB *int64 `json:"quotaMB,omitempty"`
|
||||
CommonReadonly *bool `json:"commonReadonly,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Store) readSettingsDisk() (settingsDisk, error) {
|
||||
@@ -148,6 +194,24 @@ func (s *Store) readSettings() (Settings, error) {
|
||||
if d.CommonReadonly != nil {
|
||||
st.CommonReadonly = *d.CommonReadonly
|
||||
}
|
||||
st.Preview = DefaultPreview
|
||||
if p := d.Preview; p != nil {
|
||||
if p.Sniff != nil {
|
||||
st.Preview.Sniff = *p.Sniff
|
||||
}
|
||||
if p.MaxTextMB != nil && *p.MaxTextMB >= 1 && *p.MaxTextMB <= MaxPreviewTextMB {
|
||||
st.Preview.MaxTextMB = *p.MaxTextMB
|
||||
}
|
||||
if p.TextExts != nil {
|
||||
st.Preview.TextExts = p.TextExts
|
||||
}
|
||||
if p.ExcludedExts != nil {
|
||||
st.Preview.ExcludedExts = p.ExcludedExts
|
||||
}
|
||||
if p.Shares != nil {
|
||||
st.Preview.Shares = *p.Shares
|
||||
}
|
||||
}
|
||||
if fi, err := os.Stat(filepath.Join(s.root, logoFile)); err == nil {
|
||||
st.Logo = strconv.FormatInt(fi.ModTime().UnixNano(), 36)
|
||||
}
|
||||
@@ -183,6 +247,70 @@ func (s *Store) WriteCommonReadonly(ro bool) (Settings, error) {
|
||||
return s.updateSettings(func(d *settingsDisk) { d.CommonReadonly = &ro })
|
||||
}
|
||||
|
||||
// WritePreview modifie les réglages de l'aperçu (champs non nil seulement).
|
||||
// Les extensions sont normalisées : minuscules, sans point, [a-z0-9_+-].
|
||||
func (s *Store) WritePreview(p PreviewPatch) (Settings, error) {
|
||||
if p.MaxTextMB != nil && (*p.MaxTextMB < 1 || *p.MaxTextMB > MaxPreviewTextMB) {
|
||||
return Settings{}, fmt.Errorf("%w : plafond de 1 à %d Mo", ErrInvalidPath, MaxPreviewTextMB)
|
||||
}
|
||||
var text, excl []string
|
||||
var err error
|
||||
if p.TextExts != nil {
|
||||
if text, err = NormalizeExts(*p.TextExts); err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
}
|
||||
if p.ExcludedExts != nil {
|
||||
if excl, err = NormalizeExts(*p.ExcludedExts); err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
}
|
||||
return s.updateSettings(func(d *settingsDisk) {
|
||||
if d.Preview == nil {
|
||||
d.Preview = &previewDisk{}
|
||||
}
|
||||
if p.Sniff != nil {
|
||||
d.Preview.Sniff = p.Sniff
|
||||
}
|
||||
if p.MaxTextMB != nil {
|
||||
d.Preview.MaxTextMB = p.MaxTextMB
|
||||
}
|
||||
if p.TextExts != nil {
|
||||
d.Preview.TextExts = text
|
||||
}
|
||||
if p.ExcludedExts != nil {
|
||||
d.Preview.ExcludedExts = excl
|
||||
}
|
||||
if p.Shares != nil {
|
||||
d.Preview.Shares = p.Shares
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// NormalizeExts nettoie une liste d'extensions (« .PEM », « crt »...) : minuscules,
|
||||
// sans point, sans doublon ; refuse les caractères hors [a-z0-9_+-].
|
||||
func NormalizeExts(in []string) ([]string, error) {
|
||||
out := []string{}
|
||||
seen := map[string]bool{}
|
||||
for _, e := range in {
|
||||
e = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(e)), ".")
|
||||
if e == "" || seen[e] {
|
||||
continue
|
||||
}
|
||||
if len(e) > maxPreviewExtLen || strings.IndexFunc(e, func(r rune) bool {
|
||||
return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' || r == '+' || r == '-')
|
||||
}) >= 0 {
|
||||
return nil, fmt.Errorf("%w : extension %q", ErrInvalidPath, e)
|
||||
}
|
||||
seen[e] = true
|
||||
out = append(out, e)
|
||||
}
|
||||
if len(out) > maxPreviewExts {
|
||||
return nil, fmt.Errorf("%w : %d extensions au plus", ErrInvalidPath, maxPreviewExts)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// WriteTitle enregistre le titre affiché ("" = titre par défaut).
|
||||
func (s *Store) WriteTitle(title string) (Settings, error) {
|
||||
title = strings.TrimSpace(title)
|
||||
|
||||
Reference in new issue
Block a user