normalize mime types; application/octet-stream returns an attachment

This commit is contained in:
2026-11-14 16:11:51 -05:00
parent d84b6433f5
commit 270a296817
5 changed files with 61 additions and 18 deletions
+34 -1
View File
@@ -332,11 +332,22 @@ func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker) http.Handle
if upload.ExpiresAt != nil {
ttl = int(*upload.ExpiresAt - now)
}
mimetype := upload.MIMEType
if cfg.NormalizeMIMETypes {
mimetype = normalizeMIMEType(mimetype)
}
if mimetype == "application/octet-stream" {
w.Header().Set(
"Content-Disposition",
fmt.Sprintf("attachment; filename=\"%s%s\"", upload.ID, filepath.Ext(upload.Filename)),
)
}
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d, must-revalidate", ttl))
w.Header().Set("ETag", "\""+hex.EncodeToString(upload.SHA256)+"\"")
w.Header().Set("Content-Security-Policy", "sandbox")
w.Header().Set("Content-Type", upload.MIMEType)
w.Header().Set("Content-Type", mimetype)
w.Header().Set("X-Content-Type-Options", "nosniff")
http.ServeContent(w, r, upload.Filename, time.Unix(upload.CreatedAt, 0), file)
}
@@ -427,3 +438,25 @@ func detectMimeType(file io.ReadSeeker) (string, error) {
return mtype.String(), nil
}
func normalizeMIMEType(contentType string) string {
const plaintext = "text/plain; charset=utf-8"
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return plaintext
}
if strings.HasSuffix(mediaType, "+xml") {
return plaintext
}
switch mediaType {
case "text/html", "text/javascript", "application/javascript",
"application/ecmascript", "text/ecmascript", "application/xml",
"text/xml", "text/xsl",
"text/css", "application/wasm":
return plaintext
case "application/pdf":
return "application/octet-stream"
default:
return contentType
}
}