package files import ( "path" "strings" "unicode" "unicode/utf8" ) const ( maxOriginalNameBytes = 255 // maxKeptExtensionBytes keeps a normal extension visible after truncation. maxKeptExtensionBytes = 16 ) // SanitizeOriginalName turns a client-supplied file name into display // metadata. It keeps only the last path element and removes invalid UTF-8, // control, format (including bidirectional overrides), line and paragraph // separator, and private-use characters, and leading or trailing dots and // spaces. It does not apply Unicode normalization, so visually equal names // may differ in bytes; never compare names for identity. The result may still // contain personal data, so it is never used in object keys, logs, or // employer-facing output. It returns an empty string when nothing usable // remains. func SanitizeOriginalName(name string) string { name = strings.ToValidUTF8(name, "") name = strings.ReplaceAll(name, `\`, "/") name = name[strings.LastIndexByte(name, '/')+1:] name = strings.Map(func(char rune) rune { if removedFromName(char) { return -1 } return char }, name) return trimName(truncateName(trimName(name))) } func removedFromName(char rune) bool { return unicode.IsControl(char) || unicode.In(char, unicode.Cf, unicode.Co, unicode.Zl, unicode.Zp) } func trimName(name string) string { return strings.TrimFunc(name, func(char rune) bool { return char == '.' || unicode.IsSpace(char) }) } // truncateName keeps a short extension and cuts the stem at a rune boundary. // Trailing dots and spaces exposed by the cut are removed from the stem. func truncateName(name string) string { if len(name) <= maxOriginalNameBytes { return name } extension := path.Ext(name) if len(extension) > maxKeptExtensionBytes { extension = "" } stem := strings.TrimSuffix(name, extension) stem = stem[:maxOriginalNameBytes-len(extension)] for !utf8.ValidString(stem) { stem = stem[:len(stem)-1] } return trimName(stem) + extension }