feat: validate image type on server-side upload

Ultraworked with Sisyphus (https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
2026-05-31 10:55:09 +01:00
co-authored by Sisyphus
parent 965b8b2794
commit 453fd0dc1d
2 changed files with 63 additions and 22 deletions
+34
View File
@@ -0,0 +1,34 @@
package images
import (
"bytes"
"fmt"
)
var allowedImageMagic = []struct {
magic []byte
ext string
}{
{[]byte{0xff, 0xd8, 0xff}, ".jpg"},
{[]byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}, ".png"},
{[]byte{'G', 'I', 'F', '8', '7', 'a'}, ".gif"},
{[]byte{'G', 'I', 'F', '8', '9', 'a'}, ".gif"},
}
// ValidateImageBytes checks that data begins with a known image magic number
// and returns the appropriate file extension. Supports JPEG, PNG, WebP, and GIF.
func ValidateImageBytes(data []byte) (string, error) {
if len(data) < 12 {
return "", fmt.Errorf("file too small to be a valid image")
}
for _, m := range allowedImageMagic {
if bytes.HasPrefix(data, m.magic) {
return m.ext, nil
}
}
// WebP: bytes 0-3 = RIFF, bytes 8-11 = WEBP
if len(data) >= 12 && bytes.Equal(data[0:4], []byte("RIFF")) && bytes.Equal(data[8:12], []byte("WEBP")) {
return ".webp", nil
}
return "", fmt.Errorf("file is not a supported image type (jpeg, png, webp, gif)")
}