Skip to content
quarry Artifact [186f0bf24d]
Login

Artifact [186f0bf24d]

Artifact 186f0bf24de9d36ed6f45319e2ca381832b4f9b64cf6e4d53af5026afd6c0e18:


package markup

import (
	gohtml "html"
	"net/url"
	"path"
	"regexp"
	"strings"
	"sync/atomic"
)

// Every page is served with img-src 'self' (see internal/web/csp.go), so
// an <img> pointing at another origin is a broken-image box. The image
// proxy normally rewrites such sources to this forge before this pass
// runs; what is left is an image the proxy is off for or refused, and
// the reader is better served by a link to it than by the box.

// selfOrigin is the forge's own public origin (scheme://host), so an
// absolute URL to this forge still counts as same-origin.
var selfOrigin atomic.Pointer[string]

// SetOrigin tells the renderer the forge's public origin. Images under
// it stay images; "" forgets it.
func SetOrigin(origin string) {
	origin = strings.TrimSuffix(origin, "/")
	if origin == "" {
		selfOrigin.Store(nil)
		return
	}
	selfOrigin.Store(&origin)
}

var (
	imgOrAnchor = regexp.MustCompile(`(?is)<(/?)(a|img)\b([^>]*)>`)
	imgAltAttr  = regexp.MustCompile(`(?i)\balt\s*=\s*"([^"]*)"`)
	imgAnySrc   = regexp.MustCompile(`(?i)\bsrc\s*=\s*"([^"]*)"`)
)

// isRemoteImage answers whether src names another origin: an absolute
// http(s) URL or a protocol-relative one, other than this forge's own.
func isRemoteImage(src string) bool {
	low := strings.ToLower(src)
	if !strings.HasPrefix(low, "http://") && !strings.HasPrefix(low, "https://") && !strings.HasPrefix(low, "//") {
		return false // relative, site-relative or data:
	}
	if o := selfOrigin.Load(); o != nil {
		if low == strings.ToLower(*o) || strings.HasPrefix(low, strings.ToLower(*o)+"/") {
			return false
		}
	}
	return true
}

// imageLabel is the link text for a replaced image: its alt text, else
// the file name its URL ends in, else the host.
func imageLabel(alt, src string) string {
	if strings.TrimSpace(alt) != "" {
		return alt
	}
	u, err := url.Parse(src)
	if err != nil {
		return escapeAttr(src)
	}
	if base := path.Base(u.Path); u.Path != "" && base != "/" && base != "." {
		return escapeAttr(base)
	}
	return escapeAttr(u.Host)
}

// remoteImagesToLinks replaces each remote <img> with a link to the
// image. Inside an existing link it becomes that link's plain text, so
// no anchor is nested in another.
func remoteImagesToLinks(h []byte) []byte {
	if !strings.Contains(string(h), "<img") {
		return h
	}
	depth := 0 // open <a> elements
	var out strings.Builder
	last := 0
	s := string(h)
	for _, m := range imgOrAnchor.FindAllStringSubmatchIndex(s, -1) {
		closing, name, attrs := s[m[2]:m[3]], strings.ToLower(s[m[4]:m[5]]), s[m[6]:m[7]]
		if name == "a" {
			if closing == "/" {
				depth = max(depth-1, 0)
			} else {
				depth++
			}
			continue
		}
		src := imgAnySrc.FindStringSubmatch(attrs)
		if closing == "/" || src == nil || !isRemoteImage(gohtml.UnescapeString(src[1])) {
			continue
		}
		alt := ""
		if a := imgAltAttr.FindStringSubmatch(attrs); a != nil {
			alt = a[1]
		}
		label := imageLabel(alt, gohtml.UnescapeString(src[1]))
		out.WriteString(s[last:m[0]])
		if depth > 0 {
			out.WriteString(label)
		} else {
			out.WriteString(`<a href="` + src[1] + `" rel="nofollow">` + label + `</a>`)
		}
		last = m[1]
	}
	out.WriteString(s[last:])
	return []byte(out.String())
}