package imagefile import ( "backend/internal/domain/model" "backend/internal/domain/port" "bytes" "context" "crypto/sha256" "encoding/hex" "fmt" "image" "io" "os" "os/exec" ) func FitDimensions(w, h, max int) (int, int) { if w <= max && h <= max { return w, h } if w >= h { return max, maxInt(1, h*max/w) } return maxInt(1, w*max/h), max } func maxInt(a, b int) int { if a > b { return a } return b } type Transformer struct{} func NewTransformer() port.Transformer { return Transformer{} } // ImageMagick is a constrained subprocess; no input names or shell fragments are accepted. func (Transformer) Transform(ctx context.Context, r io.Reader) ([]port.ProcessedVariant, error) { input, err := os.CreateTemp("", "pipeline-original-*") if err != nil { return nil, err } defer func() { _ = input.Close(); _ = os.Remove(input.Name()) }() n, err := io.Copy(input, io.LimitReader(r, model.MaxImageBytes+1)) if err != nil { return nil, err } if n > model.MaxImageBytes { return nil, model.ErrInvalidImage } if _, err = input.Seek(0, 0); err != nil { return nil, err } config, _, err := image.DecodeConfig(input) if err != nil || int64(config.Width)*int64(config.Height) > model.MaxImagePixels { return nil, model.ErrInvalidImage } probe := exec.CommandContext(ctx, "convert", "-limit", "memory", "256MiB", "-limit", "map", "256MiB", "-limit", "disk", "0", input.Name()+"[0]", "-auto-orient", "-format", "%w %h", "info:") raw, err := probe.Output() if err != nil { return nil, fmt.Errorf("image subprocess unavailable: %w", err) } var originalW, originalH int if _, err = fmt.Sscanf(string(raw), "%d %d", &originalW, &originalH); err != nil || int64(originalW)*int64(originalH) > model.MaxImagePixels { return nil, model.ErrInvalidImage } var variants []port.ProcessedVariant for _, v := range []struct { name, mime, geometry, format string crop bool }{{"thumbnail", "image/jpeg", "256x256>", "jpeg", false}, {"crop", "image/jpeg", "128x128^", "jpeg", true}, {"optimized", "image/webp", "1280x1280>", "webp", false}} { geometry := v.geometry if !v.crop { max := 256 if v.name == "optimized" { max = 1280 } w, h := FitDimensions(originalW, originalH, max) geometry = fmt.Sprintf("%dx%d!", w, h) } args := []string{"-limit", "memory", "256MiB", "-limit", "map", "256MiB", "-limit", "disk", "0", "-limit", "thread", "1", input.Name() + "[0]", "-auto-orient", "-background", "white", "-alpha", "remove", "-alpha", "off", "-strip", "-resize", geometry} if v.crop { args = append(args, "-gravity", "center", "-extent", "128x128") } args = append(args, "-quality", "82", v.format+":-") cmd := exec.CommandContext(ctx, "convert", args...) var out limitedBuffer cmd.Stdout = &out if err = cmd.Run(); err != nil { return nil, fmt.Errorf("image subprocess failed: %w", err) } b := out.Bytes() if len(b) == 0 { return nil, fmt.Errorf("empty variant") } w, h := 0, 0 if v.format == "webp" { // Read only geometry through the native decoder; never dump diagnostics/payload. probe := exec.CommandContext(ctx, "identify", "-format", "%w %h", "webp:-") probe.Stdin = bytes.NewReader(b) raw, e := probe.Output() if e != nil { return nil, fmt.Errorf("invalid generated WebP") } if _, e = fmt.Sscanf(string(raw), "%d %d", &w, &h); e != nil { return nil, e } } else { // JPEG dimensions are read through the same strict decoder used for uploads. cfg, _, e := image.DecodeConfig(bytes.NewReader(b)) if e != nil { return nil, e } w, h = cfg.Width, cfg.Height } sum := sha256.Sum256(b) variants = append(variants, port.ProcessedVariant{Metadata: model.Variant{Name: v.name, ContentType: v.mime, SHA256: hex.EncodeToString(sum[:]), SizeBytes: int64(len(b)), Width: w, Height: h}, Bytes: b}) } return variants, nil } type limitedBuffer struct{ bytes.Buffer } func (b *limitedBuffer) Write(p []byte) (int, error) { if b.Len()+len(p) > 16*1024*1024 { return 0, fmt.Errorf("variant too large") } return b.Buffer.Write(p) }