Files
hfb_sys/backend/internal/filekey/filekey.go
T

55 lines
1.3 KiB
Go

package filekey
import (
"net/url"
"strings"
)
const objectEndpointSuffix = "/files/object"
// Canonical returns the stored object key for current and legacy file URLs.
func Canonical(raw string) string {
value := strings.TrimSpace(strings.Trim(raw, `"'`))
if value == "" || strings.Contains(value, "..") {
return ""
}
if parsed, err := url.Parse(value); err == nil {
if key := parsed.Query().Get("key"); key != "" && strings.HasSuffix(parsed.Path, objectEndpointSuffix) {
return normalizeKey(key)
}
if parsed.Scheme != "" || parsed.Host != "" {
return ""
}
}
if index := strings.Index(value, "?key="); index >= 0 {
query, err := url.ParseQuery(value[index+1:])
if err == nil && query.Get("key") != "" {
return normalizeKey(query.Get("key"))
}
}
return normalizeKey(value)
}
func normalizeKey(raw string) string {
key := strings.TrimSpace(raw)
for attempt := 0; attempt < 2; attempt++ {
decoded, err := url.QueryUnescape(key)
if err != nil || decoded == key {
break
}
key = decoded
}
key = strings.TrimLeft(strings.TrimSpace(key), "/")
if key == "" || strings.Contains(key, "..") {
return ""
}
for _, suffix := range []string{".medium.jpg", ".thumb.jpg"} {
if strings.HasSuffix(key, suffix) {
return strings.TrimSuffix(key, suffix)
}
}
return key
}