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|source)\b([^>]*)>`)
imgAltAttr = regexp.MustCompile(`(?i)\balt\s*=\s*"([^"]*)"`)
imgAnySrc = regexp.MustCompile(`(?i)\bsrc\s*=\s*"([^"]*)"`)
srcsetAttr = regexp.MustCompile(`(?i)\bsrcset\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
}
// remoteSrcset answers whether any candidate of a srcset names another
// origin.
func remoteSrcset(set string) bool {
for _, cand := range strings.Split(set, ",") {
if f := strings.Fields(cand); len(f) > 0 && isRemoteImage(f[0]) {
return true
}
}
return false
}
// 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, and drops a <source srcset> that points elsewhere. 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
}
if name == "source" {
// A <picture> source the browser would pick over the img.
if set := srcsetAttr.FindStringSubmatch(attrs); closing == "" && set != nil && remoteSrcset(gohtml.UnescapeString(set[1])) {
out.WriteString(s[last:m[0]])
last = m[1]
}
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())
}
// githubBlob is a GitHub file page: github.com/OWNER/REPO/blob/REF/PATH.
var githubBlob = regexp.MustCompile(`^https://github\.com/([^/?#]+)/([^/?#]+)/(?:blob|raw)/([^?#]+)(?:\?[^#]*)?$`)
// githubRawImage turns a GitHub file-page URL into the file itself, as
// GitHub does when a README embeds one: the page is HTML, so the proxy
// would fetch something no browser can draw (#505).
func githubRawImage(src string) string {
m := githubBlob.FindStringSubmatch(src)
if m == nil {
return src
}
return "https://raw.githubusercontent.com/" + m[1] + "/" + m[2] + "/" + m[3]
}