Files
tenant-registry/internal/branding/image.go
T
sharang 9685ec0475
ci / shared (push) Successful in 14s
ci / test (push) Successful in 8m17s
ci / image (push) Successful in 46s
feat(branding): tenant branding store, endpoints and check field (#155, part 1) (#156)
2026-12-01 13:13:22 +00:00

226 lines
6.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package branding derives and normalises a workspace's branding (#155):
// the CI colour and the logo every Breakpilot frontend shows.
package branding
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
"image/color"
"image/draw"
_ "image/gif" // registered for image.DecodeConfig / image.Decode
_ "image/jpeg" // registered for image.DecodeConfig / image.Decode
"image/png"
xdraw "golang.org/x/image/draw"
)
// LogoSize is the edge of the stored logo: always a 256×256 PNG.
const LogoSize = 256
// MaxImageBytes caps an image as fetched or uploaded.
const MaxImageBytes = 1 << 20
// maxSourcePixels caps the decoded size of a source image, checked from its
// header before decoding.
const maxSourcePixels = 4096 * 4096
var (
ErrNotImage = errors.New("not a PNG, JPEG, GIF or ICO image")
ErrSVG = errors.New("SVG is not supported")
ErrImageTooLarge = errors.New("image too large")
)
// NormalizeLogo decodes a PNG, JPEG, GIF or ICO image and returns it fitted
// into a transparent 256×256 square as PNG, with that PNG's sha256 (hex).
// The same input always gives the same bytes.
func NormalizeLogo(data []byte) (pngBytes []byte, etag string, err error) {
img, err := DecodeImage(data)
if err != nil {
return nil, "", err
}
out := fit(img, LogoSize)
var buf bytes.Buffer
if err := (&png.Encoder{CompressionLevel: png.DefaultCompression}).Encode(&buf, out); err != nil {
return nil, "", err
}
sum := sha256.Sum256(buf.Bytes())
return buf.Bytes(), hex.EncodeToString(sum[:]), nil
}
// DecodeImage decodes one image, refusing SVG and oversized ones.
func DecodeImage(data []byte) (image.Image, error) {
if len(data) > MaxImageBytes {
return nil, ErrImageTooLarge
}
if looksLikeSVG(data) {
return nil, ErrSVG
}
if isICO(data) {
return decodeICO(data)
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return nil, ErrNotImage
}
if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width*cfg.Height > maxSourcePixels {
return nil, ErrImageTooLarge
}
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, ErrNotImage
}
return img, nil
}
// fit scales img to fit a size×size square, centred on transparency.
func fit(img image.Image, size int) *image.NRGBA {
b := img.Bounds()
w, h := b.Dx(), b.Dy()
dw, dh := size, size
if w > h {
dh = max(1, (h*size+w/2)/w)
} else if h > w {
dw = max(1, (w*size+h/2)/h)
}
out := image.NewNRGBA(image.Rect(0, 0, size, size))
x0, y0 := (size-dw)/2, (size-dh)/2
xdraw.CatmullRom.Scale(out, image.Rect(x0, y0, x0+dw, y0+dh), img, b, draw.Over, nil)
return out
}
func looksLikeSVG(data []byte) bool {
head := bytes.ToLower(bytes.TrimSpace(data[:min(len(data), 512)]))
return bytes.HasPrefix(head, []byte("<svg")) || (bytes.HasPrefix(head, []byte("<?xml")) && bytes.Contains(head, []byte("<svg"))) ||
bytes.Contains(head, []byte("<!doctype svg"))
}
// ─── ICO ───────────────────────────────────────────────────────────────────
var pngMagic = []byte("\x89PNG\r\n\x1a\n")
func isICO(data []byte) bool {
return len(data) >= 6 && data[0] == 0 && data[1] == 0 && data[2] == 1 && data[3] == 0 && le16(data[4:]) > 0
}
// decodeICO decodes the largest image of an ICO file (PNG or BMP entry).
func decodeICO(data []byte) (image.Image, error) {
n := int(le16(data[4:]))
if len(data) < 6+16*n {
return nil, ErrNotImage
}
best, bestArea, bestBits := -1, 0, 0
for i := 0; i < n; i++ {
e := data[6+16*i:]
w, h := int(e[0]), int(e[1])
if w == 0 {
w = 256
}
if h == 0 {
h = 256
}
bits := int(le16(e[6:]))
if a := w * h; a > bestArea || (a == bestArea && bits > bestBits) {
best, bestArea, bestBits = i, a, bits
}
}
e := data[6+16*best:]
size, off := int(le32(e[8:])), int(le32(e[12:]))
if off < 0 || size <= 0 || off > len(data) || size > len(data)-off {
return nil, ErrNotImage
}
entry := data[off : off+size]
if bytes.HasPrefix(entry, pngMagic) {
return DecodeImage(entry)
}
return decodeDIB(entry)
}
// decodeDIB decodes an ICO's BMP entry: BITMAPINFOHEADER, optional palette,
// bottom-up XOR rows, then the 1-bit AND (transparency) mask.
func decodeDIB(d []byte) (image.Image, error) {
if len(d) < 40 || le32(d) < 40 {
return nil, ErrNotImage
}
hdr := int(le32(d))
w, h2 := int(int32(le32(d[4:]))), int(int32(le32(d[8:])))
bpp, compression := int(le16(d[14:])), le32(d[16:])
h := h2 / 2
if w <= 0 || h <= 0 || w > 1024 || h > 1024 || compression != 0 {
return nil, ErrNotImage
}
var palette []color.NRGBA
pos := hdr
switch bpp {
case 1, 4, 8:
count := int(le32(d[32:]))
if count == 0 || count > 1<<bpp {
count = 1 << bpp
}
if len(d) < pos+4*count {
return nil, ErrNotImage
}
for i := 0; i < count; i++ {
p := d[pos+4*i:]
palette = append(palette, color.NRGBA{R: p[2], G: p[1], B: p[0], A: 255})
}
pos += 4 * count
case 24, 32:
default:
return nil, ErrNotImage
}
stride := ((w*bpp + 31) / 32) * 4
maskStride := ((w + 31) / 32) * 4
if len(d) < pos+stride*h {
return nil, ErrNotImage
}
pix, mask := d[pos:pos+stride*h], []byte(nil)
if len(d) >= pos+stride*h+maskStride*h {
mask = d[pos+stride*h : pos+stride*h+maskStride*h]
}
img := image.NewNRGBA(image.Rect(0, 0, w, h))
anyAlpha := false
for y := 0; y < h; y++ {
row := pix[(h-1-y)*stride:]
for x := 0; x < w; x++ {
var c color.NRGBA
switch bpp {
case 32:
c = color.NRGBA{R: row[4*x+2], G: row[4*x+1], B: row[4*x], A: row[4*x+3]}
anyAlpha = anyAlpha || c.A != 0
case 24:
c = color.NRGBA{R: row[3*x+2], G: row[3*x+1], B: row[3*x], A: 255}
default:
bit := x * bpp
idx := int(row[bit/8]>>(8-bpp-bit%8)) & (1<<bpp - 1)
if idx < len(palette) {
c = palette[idx]
}
}
img.SetNRGBA(x, y, c)
}
}
// The AND mask applies unless a 32-bit entry carries its own alpha.
if mask != nil && (bpp != 32 || !anyAlpha) {
for y := 0; y < h; y++ {
row := mask[(h-1-y)*maskStride:]
for x := 0; x < w; x++ {
c := img.NRGBAAt(x, y)
c.A = 255
if row[x/8]&(0x80>>(x%8)) != 0 {
c.A = 0
}
img.SetNRGBA(x, y, c)
}
}
}
return img, nil
}
func le16(b []byte) uint16 { return uint16(b[0]) | uint16(b[1])<<8 }
func le32(b []byte) uint32 {
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}