Skip to content
quarry Artifact [4e98cb3f88]
Login

Artifact [4e98cb3f88]

Artifact 4e98cb3f88dd3c1b9b8acda51c8071ac65b9882a48602cbbd826fcc70f034adf:


package markup

import (
	"bytes"
	gohtml "html"
	"regexp"
	"strconv"
	"strings"
)

// reservedIDs holds every id attribute used by page templates and scripts
// plus JS/DOM global and Object.prototype names that user-rendered content
// must never clobber (lowercase for case-insensitive matching).
var reservedIDs = map[string]bool{
	// Page templates, inline HTML builders, and scripts.
	"about":                      true,
	"about-forge":                true,
	"access":                     true,
	"acct":                       true,
	"acct-email-code":            true,
	"acct-email-input":           true,
	"act-view":                   true,
	"add-runner":                 true,
	"agent-grant-repo":           true,
	"agent-grant-role":           true,
	"agent-new-name":             true,
	"agent-new-scope":            true,
	"agents":                     true,
	"ap-code":                    true,
	"ap-site":                    true,
	"appearance":                 true,
	"asking":                     true,
	"attachments":                true,
	"attn-toasts":                true,
	"basic-description":          true,
	"basic-format":               true,
	"basic-frequency":            true,
	"basic-ignore":               true,
	"basic-license":              true,
	"basic-name":                 true,
	"basic-private":              true,
	"basic-readme":               true,
	"basic-source":               true,
	"basic-source-type":          true,
	"board":                      true,
	"bucket-cors-rule":           true,
	"calls":                      true,
	"capabilities":               true,
	"capability-letters":         true,
	"chat-bridge":                true,
	"chat-here":                  true,
	"chat-latest":                true,
	"chat-preview":               true,
	"chat-read":                  true,
	"chatlog":                    true,
	"check-names":                true,
	"ci":                         true,
	"ci-refs":                    true,
	"ci-reporters":               true,
	"ci-tags":                    true,
	"clone-cmd":                  true,
	"code-theme":                 true,
	"composer":                   true,
	"confirm":                    true,
	"confirm-ack":                true,
	"create":                     true,
	"danger":                     true,
	"dash-activity":              true,
	"dash-feed":                  true,
	"diff-more":                  true,
	"diffbody":                   true,
	"discussion":                 true,
	"disk":                       true,
	"dl":                         true,
	"docs":                       true,
	"email":                      true,
	"environments":               true,
	"explore":                    true,
	"f-posts":                    true,
	"file-body":                  true,
	"file-more":                  true,
	"find":                       true,
	"find-suggest":               true,
	"find-suggest-n":             true,
	"flat":                       true,
	"fleet-panel":                true,
	"fleetmore":                  true,
	"fn-title":                   true,
	"format-title":               true,
	"fossil-config":              true,
	"fossil-mirror":              true,
	"fossil-mirror-branch":       true,
	"fossil-mirror-branch-err":   true,
	"fossil-mirror-password":     true,
	"fossil-mirror-password-err": true,
	"fossil-mirror-remote":       true,
	"fossil-mirror-remote-err":   true,
	"fossil-mirror-user":         true,
	"fossil-mirror-user-err":     true,
	"fossil-rows":                true,
	"fossil-settings":            true,
	"fossil-users":               true,
	"frequency":                  true,
	"git-mirror":                 true,
	"git-mirror-branch":          true,
	"git-mirror-branch-err":      true,
	"git-mirror-key":             true,
	"git-mirror-password":        true,
	"git-mirror-password-err":    true,
	"git-mirror-remote":          true,
	"git-mirror-remote-err":      true,
	"git-mirror-user":            true,
	"git-mirror-user-err":        true,
	"hl-hour":                    true,
	"hl-names":                   true,
	"hl-tz":                      true,
	"home-slice":                 true,
	"homepage-err":               true,
	"hook-events":                true,
	"hook-nouns":                 true,
	"hook-secret":                true,
	"hook-url":                   true,
	"i-auto":                     true,
	"i-bell":                     true,
	"i-book":                     true,
	"i-branch":                   true,
	"i-bug":                      true,
	"i-caret-down":               true,
	"i-check":                    true,
	"i-clock":                    true,
	"i-comment":                  true,
	"i-commit":                   true,
	"i-copy":                     true,
	"i-dir":                      true,
	"i-download":                 true,
	"i-eye":                      true,
	"i-file":                     true,
	"i-gear":                     true,
	"i-history":                  true,
	"i-inbox":                    true,
	"i-info":                     true,
	"i-landing":                  true,
	"i-law":                      true,
	"i-link":                     true,
	"i-local":                    true,
	"i-moon":                     true,
	"i-more":                     true,
	"i-paperclip":                true,
	"i-pencil":                   true,
	"i-people":                   true,
	"i-person":                   true,
	"i-plus":                     true,
	"i-question":                 true,
	"i-reply":                    true,
	"i-search":                   true,
	"i-shield":                   true,
	"i-stamp":                    true,
	"i-strata":                   true,
	"i-sun":                      true,
	"i-sync":                     true,
	"i-tag":                      true,
	"i-tkt-done":                 true,
	"i-tkt-open":                 true,
	"i-up":                       true,
	"i-wide":                     true,
	"i-x":                        true,
	"identity":                   true,
	"import-status":              true,
	"inbox-dot":                  true,
	"inbox-error":                true,
	"inbox-live":                 true,
	"integrations":               true,
	"l-checks":                   true,
	"l-list":                     true,
	"l-live":                     true,
	"l-page":                     true,
	"l-stack-auto":               true,
	"l-update":                   true,
	"lanes":                      true,
	"lc":                         true,
	"lc-text":                    true,
	"logins":                     true,
	"maintenance":                true,
	"me-av":                      true,
	"memory":                     true,
	"mentions":                   true,
	"mirror":                     true,
	"mirror-form":                true,
	"mirror-form-head":           true,
	"mirror-name":                true,
	"mirror-token":               true,
	"name-check":                 true,
	"navmore":                    true,
	"new-owner":                  true,
	"new-token":                  true,
	"nl-branch":                  true,
	"nl-title":                   true,
	"notifications":              true,
	"notify-desktop":             true,
	"ops-controls":               true,
	"ops-hour":                   true,
	"opsbody":                    true,
	"participation":              true,
	"password":                   true,
	"people":                     true,
	"people-agents":              true,
	"people-suggest":             true,
	"people-suggest-n":           true,
	"person-live":                true,
	"person-preview":             true,
	"person-raw":                 true,
	"pp-invite":                  true,
	"private":                    true,
	"protected":                  true,
	"public":                     true,
	"push":                       true,
	"push-control":               true,
	"push-disable":               true,
	"push-enable":                true,
	"push-test":                  true,
	"quarry-mail":                true,
	"r-av":                       true,
	"rail-channels":              true,
	"refpop":                     true,
	"refs":                       true,
	"renders":                    true,
	"reply-band":                 true,
	"repo-agent-name":            true,
	"repo-agent-role":            true,
	"repo-agent-token":           true,
	"repo-settings":              true,
	"repo-tabs":                  true,
	"reporter-token":             true,
	"requests-btn":               true,
	"robot":                      true,
	"robot-events":               true,
	"robot-nouns":                true,
	"roster-suggest":             true,
	"routes":                     true,
	"rt-langs":                   true,
	"run-body":                   true,
	"run-wrap":                   true,
	"runners":                    true,
	"running":                    true,
	"schedule-title":             true,
	"sessions":                   true,
	"site-theme":                 true,
	"source-title":               true,
	"source-url":                 true,
	"storage":                    true,
	"stores":                     true,
	"sub":                        true,
	"summary-heading":            true,
	"t-av":                       true,
	"t-descr":                    true,
	"t-edit-desc":                true,
	"t-edit-title":               true,
	"t-opts-assigned_to":         true,
	"t-opts-author":              true,
	"t-opts-priority":            true,
	"t-opts-repo":                true,
	"t-opts-resolution":          true,
	"t-opts-severity":            true,
	"t-opts-status":              true,
	"t-opts-subsystem":           true,
	"t-opts-type":                true,
	"t-repo":                     true,
	"t-repos":                    true,
	"t-retitle-form":             true,
	"t-title":                    true,
	"team-agent-name":            true,
	"team-handle-why":            true,
	"ticket-tier":                true,
	"tkt-refs":                   true,
	"tkt-side":                   true,
	"tkt-timeline":               true,
	"tkt-view":                   true,
	"tl":                         true,
	"tl-found":                   true,
	"tl-suggest":                 true,
	"tl-suggest-n":               true,
	"tn-curl":                    true,
	"tn-similar":                 true,
	"tn-title":                   true,
	"toasts":                     true,
	"tokens":                     true,
	"topic-names":                true,
	"tr-globe":                   true,
	"tr-globe-data":              true,
	"trail":                      true,
	"trbody":                     true,
	"v-priority":                 true,
	"v-resolution":               true,
	"v-severity":                 true,
	"v-status":                   true,
	"v-subsystem":                true,
	"v-type":                     true,
	"visibility":                 true,
	"visibility-label":           true,
	"webhooks":                   true,
	"worker-token":               true,
	"worker-tokens":              true,
	"wq":                         true,
	"zit-only-ack":               true,

	// JS / Object.prototype / Window / Document globals (DOM clobbering).
	"__proto__":               true,
	"__definegetter__":        true,
	"__definesetter__":        true,
	"__lookupgetter__":        true,
	"__lookupsetter__":        true,
	"constructor":             true,
	"prototype":               true,
	"hasownproperty":          true,
	"isprototypeof":           true,
	"propertyisenumerable":    true,
	"tolocalestring":          true,
	"tostring":                true,
	"valueof":                 true,
	"window":                  true,
	"self":                    true,
	"document":                true,
	"location":                true,
	"history":                 true,
	"navigator":               true,
	"screen":                  true,
	"frames":                  true,
	"top":                     true,
	"parent":                  true,
	"opener":                  true,
	"length":                  true,
	"name":                    true,
	"status":                  true,
	"closed":                  true,
	"console":                 true,
	"crypto":                  true,
	"performance":             true,
	"localstorage":            true,
	"sessionstorage":          true,
	"indexeddb":               true,
	"caches":                  true,
	"fetch":                   true,
	"alert":                   true,
	"prompt":                  true,
	"open":                    true,
	"close":                   true,
	"focus":                   true,
	"blur":                    true,
	"scroll":                  true,
	"scrollto":                true,
	"scrollby":                true,
	"print":                   true,
	"stop":                    true,
	"postmessage":             true,
	"atob":                    true,
	"btoa":                    true,
	"settimeout":              true,
	"setinterval":             true,
	"cleartimeout":            true,
	"clearinterval":           true,
	"requestanimationframe":   true,
	"cancelanimationframe":    true,
	"getcomputedstyle":        true,
	"matchmedia":              true,
	"customelements":          true,
	"event":                   true,
	"origin":                  true,
	"issecurecontext":         true,
	"crossoriginisolated":     true,
	"visualviewport":          true,
	"devicepixelratio":        true,
	"innerwidth":              true,
	"innerheight":             true,
	"outerwidth":              true,
	"outerheight":             true,
	"scrollx":                 true,
	"scrolly":                 true,
	"pagexoffset":             true,
	"pageyoffset":             true,
	"screenx":                 true,
	"screeny":                 true,
	"screenleft":              true,
	"screentop":               true,
	"menubar":                 true,
	"locationbar":             true,
	"personalbar":             true,
	"scrollbars":              true,
	"statusbar":               true,
	"clientinformation":       true,
	"external":                true,
	"toolbar":                 true,
	"cookie":                  true,
	"domain":                  true,
	"title":                   true,
	"referrer":                true,
	"url":                     true,
	"documenturi":             true,
	"baseuri":                 true,
	"doctype":                 true,
	"documentelement":         true,
	"head":                    true,
	"body":                    true,
	"forms":                   true,
	"images":                  true,
	"links":                   true,
	"anchors":                 true,
	"scripts":                 true,
	"embeds":                  true,
	"plugins":                 true,
	"applets":                 true,
	"stylesheets":             true,
	"fonts":                   true,
	"children":                true,
	"all":                     true,
	"activeelement":           true,
	"currentscript":           true,
	"defaultview":             true,
	"implementation":          true,
	"readystate":              true,
	"visibilitystate":         true,
	"hidden":                  true,
	"compatmode":              true,
	"characterset":            true,
	"charset":                 true,
	"inputencoding":           true,
	"contenttype":             true,
	"lastmodified":            true,
	"designmode":              true,
	"dir":                     true,
	"adoptedstylesheets":      true,
	"fullscreenenabled":       true,
	"fullscreenelement":       true,
	"pointerlockelement":      true,
	"pictureinpictureelement": true,
	"pictureinpictureenabled": true,
	"scrollingelement":        true,
	"timeline":                true,
	"getelementbyid":          true,
	"getelementsbyclassname":  true,
	"getelementsbytagname":    true,
	"getelementsbyname":       true,
	"queryselector":           true,
	"queryselectorall":        true,
	"createelement":           true,
	"createtextnode":          true,
	"createdocumentfragment":  true,
	"importnode":              true,
	"adoptnode":               true,
	"write":                   true,
	"writeln":                 true,
	"execcommand":             true,
	"addeventlistener":        true,
	"removeeventlistener":     true,
	"dispatchevent":           true,
	"datastar":                true,
	"eval":                    true,
	"function":                true,
	"object":                  true,
	"array":                   true,
	"string":                  true,
	"number":                  true,
	"boolean":                 true,
	"symbol":                  true,
	"bigint":                  true,
	"math":                    true,
	"date":                    true,
	"regexp":                  true,
	"error":                   true,
	"promise":                 true,
	"map":                     true,
	"set":                     true,
	"weakmap":                 true,
	"weakset":                 true,
	"proxy":                   true,
	"reflect":                 true,
	"json":                    true,
	"intl":                    true,
	"webassembly":             true,
	"undefined":               true,
	"nan":                     true,
	"infinity":                true,
	"globalthis":              true,
}

// reservedPattern matches dynamic template id forms. When appending "-N"
// stays inside a reserved pattern, reserveIDWithNext switches to a "doc-"
// stem so allocation always terminates outside the reserved set.
var reservedPattern = regexp.MustCompile(
	`^(?:` +
		`l[0-9]+|` +
		`l[0-9a-f]{8}-[on][0-9]+|` +
		`chat(?:msg|body)-[0-9]+|` +
		`(?:p|vote)-[0-9a-f]{12}|` +
		`(?:km|pa|pm|ps)[0-9]+|` +
		`m[0-9]+-c[0-9]+|` +
		`mt[fz]-[0-9a-f]+|` +
		`mv-[0-9a-f]+|` +
		`exc-[0-9a-f]+|` +
		`a-[0-9a-f]+-[a-z0-9_.-]+-[0-9]+|` +
		`s-[0-9a-f]+-(?:[0-9]+-)?[0-9]+|` +
		`approve-[0-9a-z]+|` +
		`attn-.*|` +
		`release-.*|` +
		`f-.*|` +
		`mf-.*` +
		`)$`,
)

func isReservedID(id string) bool {
	if id == "" {
		return false
	}
	low := strings.ToLower(id)
	return reservedIDs[low] || reservedPattern.MatchString(low)
}

// reserveID returns base when it is free and not reserved, else a
// non-colliding, non-reserved id (preferring base-1, base-2, ...).
func reserveID(base string, used map[string]bool) string {
	return reserveIDWithNext(base, used, nil)
}

// reserveIDWithNext allocates a safe id using next (when non-nil) to avoid
// quadratic rescanning on repeated headings, switching to a doc- stem when
// suffixing -N stays inside a prefix-matched reserved pattern.
func reserveIDWithNext(base string, used map[string]bool, next map[string]int) string {
	if !used[base] && !isReservedID(base) {
		used[base] = true
		return base
	}
	stem := base
	if isReservedID(base + "-1") {
		stem = "doc-" + base
		if isReservedID(stem) {
			stem = "id-" + base
		}
		if !used[stem] && !isReservedID(stem) {
			used[stem] = true
			return stem
		}
	}
	start := 1
	if next != nil && next[stem] > start {
		start = next[stem]
	}
	const maxProbe = 1_000_000
	for i := start; i < start+maxProbe; i++ {
		id := stem + "-" + strconv.Itoa(i)
		if !used[id] && !isReservedID(id) {
			used[id] = true
			if next != nil {
				next[stem] = i + 1
			}
			return id
		}
	}
	return "doc-" + base + "-overflow"
}

var hrefFragAttr = regexp.MustCompile(`\bhref="#([^"]*)"`)

// rewriteReservedHTML rewrites reserved id="..." attributes and updates
// matching in-document href="#..." fragments.
func rewriteReservedHTML(h []byte) []byte {
	remapped := map[string]string{}
	return rewriteReservedHrefs(rewriteReservedIDs(h, remapped), remapped)
}

// rewriteReservedIDs rewrites any reserved id="..." attribute in sanitized
// HTML to a non-colliding safe id and records old->new in remapped.
func rewriteReservedIDs(h []byte, remapped map[string]string) []byte {
	if !bytes.Contains(h, []byte(`id="`)) {
		return h
	}
	matches := sanitizedID.FindAllSubmatch(h, -1)
	needsRewrite := false
	for _, m := range matches {
		if isReservedID(gohtml.UnescapeString(string(m[1]))) {
			needsRewrite = true
			break
		}
	}
	if !needsRewrite {
		return h
	}
	taken := make(map[string]bool, len(matches))
	for _, m := range matches {
		taken[gohtml.UnescapeString(string(m[1]))] = true
	}
	return sanitizedID.ReplaceAllFunc(h, func(m []byte) []byte {
		sub := sanitizedID.FindSubmatch(m)
		id := gohtml.UnescapeString(string(sub[1]))
		if !isReservedID(id) {
			return m
		}
		next := reserveID(id, taken)
		if remapped != nil {
			if _, exists := remapped[id]; !exists {
				remapped[id] = next
			}
		}
		return []byte(`id="` + gohtml.EscapeString(next) + `"`)
	})
}

// rewriteReservedHrefs updates in-document href="#..." links whose target
// was remapped away from a reserved id so links still land on their heading,
// anchor, or footnote.
func rewriteReservedHrefs(h []byte, remapped map[string]string) []byte {
	if len(remapped) == 0 || !bytes.Contains(h, []byte(`href="#`)) {
		return h
	}
	return hrefFragAttr.ReplaceAllFunc(h, func(m []byte) []byte {
		sub := hrefFragAttr.FindSubmatch(m)
		target := gohtml.UnescapeString(string(sub[1]))
		if next, ok := remapped[target]; ok {
			return []byte(`href="#` + gohtml.EscapeString(next) + `"`)
		}
		return m
	})
}