internal/httpd

namelast commitupdated
aasa.go httpd: serve apple-app-site-association 1 month ago
aasa_test.go httpd: serve apple-app-site-association 1 month ago
account.go control: self-service account deletion 1 month ago
account_test.go notify, mailin: reply to notification mail to comment 1 month ago
accountdelete.go control: self-service account deletion 1 month ago
accounts.go control: self-service account deletion 1 month ago
accounts_test.go web, store: final-review wording, header and range-diff fixes 1 month ago
activity.go httpd, web: month labels on the contribution grid 2 months ago
activity_test.go httpd, web: month labels on the contribution grid 2 months ago
admin.go control: the payloads other surfaces decode are named types 2 months ago
admin_test.go httpd, gitd: pack generation takes a slot; ls-refs does not 1 month ago
adminusers.go web: a stale session's mint or grant gets a sign-in link back to the form 1 month ago
anchors_test.go web: pinned queries on the dashboard, /{owner}/-/queries and /{owner}/-/queries/{name} 1 month ago
api.go httpd: a command a limiter turned away is 503 with Retry-After on the API 1 month ago
apibusy_test.go httpd: a command a limiter turned away is 503 with Retry-After on the API 1 month ago
apilimit.go http.trusted_proxies, and a cap on verification mail per account 2 months ago
apilimit_test.go httpd: rate limit the JSON API 3 months ago
apiread.go httpd: a command a limiter turned away is 503 with Retry-After on the API 1 month ago
atom.go web, store, policy, wiki: Atom feeds for releases, commits, and an owner's activity 2 months ago
atom_test.go web, store, policy, wiki: Atom feeds for releases, commits, and an owner's activity 2 months ago
authorclose_test.go web: close controls for an issue's or merge request's author 1 month ago
badge.go build cancel: withdraw a queued build 2 months ago
badgepng.go Serve build badges as PNG as well as SVG 2 months ago
badgepng_test.go Serve build badges as PNG as well as SVG 2 months ago
buildpages_test.go web: builds page offers an org-mode badge snippet 1 month ago
builds.go web: step fold shows the step's first line; changelog: deploy order 1 month ago
builds_test.go builds: separate runs queued at different times 2 months ago
checkorigin_test.go httpd, gitd: pack generation takes a slot; ls-refs does not 1 month ago
chip_test.go httpd, web: a chip tone per scheme, and an underline where a link shares its line 2 months ago
clientip_test.go httpd, gitd: pack generation takes a slot; ls-refs does not 1 month ago
compare.go web: side-by-side diff layout 1 month ago
compress.go build log --follow: end a queued follow, stream only on GET 2 months ago
compress_test.go httpd: gzipWriter passes a flush through 2 months ago
confirm.go web: resolve a snippet before checking its confirmation 2 months ago
control.go web: release assets, milestones and org label and milestone writes 1 month ago
cookieclear_test.go web: a suspended account cannot mail itself a session 2 months ago
crumbs_test.go web: directory crumbs on blob and blame pages link to the tree 2 months ago
dashpins.go web: the dashboard is three columns 2 months ago
dashpins_test.go web: pinned queries on the dashboard, /{owner}/-/queries and /{owner}/-/queries/{name} 1 month ago
depspage_test.go web: one timestamp format, with the zone named 2 months ago
diff.go Fold duplicated and deeply nested code into helpers 1 month ago
diff_test.go web: keep an added line's leading dash in the diff 2 months ago
difflayout_test.go web: keep no-newline markers in split rows 1 month ago
emptystates_test.go web: drop CLI commands from four empty states, per the register 1 month ago
explorepage_test.go web: explore by latest activity, paged; slim profile repo rows 1 month ago
facets.go web: a facet with nothing under it leaves the column 2 months ago
facets_test.go web: a facet with nothing under it leaves the column 2 months ago
facts.go store, control: build list gets --ref, --status and --job filters 2 months ago
filenav.go web: a file navigator beside blob, blame and edit 2 months ago
filenav_test.go web: a file navigator beside blob, blame and edit 2 months ago
filters.go issue list and mr list: filter by label, assignee, author, milestone 2 months ago
flash.go httpd: the login return path refuses a leading /\ 1 month ago
flash_test.go httpd: the login return path refuses a leading /\ 1 month ago
fonts_test.go httpd, gitd: pack generation takes a slot; ls-refs does not 1 month ago
footer_test.go web: footer links to the operator's abuse and terms pages 1 month ago
headings_test.go web: a rendered document's headings sit under the page's own 2 months ago
healthz.go http: /healthz 2 months ago
inputlabels_test.go web: the topics-remove field gets a label, and a test that would have caught it 2 months ago
issueactions.go web: a failed form action's reason rides a one-shot cookie, not the URL 2 months ago
issuecreate_test.go Web: reaction buttons under issue and merge request bodies and comments 1 month ago
labels.go web: the labels page hides an empty colour column 2 months ago
langs.go web: repository facts on the code page 3 months ago
lfs.go lfs: tokens carry the key's fingerprint pin beside its id 1 month ago
lfsauth_test.go store: AUTOINCREMENT ids for accounts, orgs, repos, keys, tokens, queues 1 month ago
logincookie_test.go tests: newer callers pass a nil pack limiter to New 1 month ago
logindisabled_test.go httpd, gitd: pack generation takes a slot; ls-refs does not 1 month ago
math.go web: linear inline math scan, per-document math budget, own math policy 1 month ago
math_test.go web: linear inline math scan, per-document math budget, own math policy 1 month ago
milestoneactions.go web: authorise release asset uploads before reading the body 1 month ago
mractions.go web: suggestions render as a diff in their thread, with an apply button or the CLI command; line ranges in the compose form 1 month ago
mrpage_test.go Web: reaction buttons under issue and merge request bodies and comments 1 month ago
mrrangediff.go web, store: final-review wording, header and range-diff fixes 1 month ago
mrrangediff_test.go web, store: final-review wording, header and range-diff fixes 1 month ago
mrslist_test.go web: fork owners can open an MR from mrs and compare pages 1 month ago
mrsrow_test.go web: fork owners can open an MR from mrs and compare pages 1 month ago
notfound_test.go web: the ten findings from the forge comparison 2 months ago
notifyweb.go web: mark-read dispatches notifications read 1 month ago
orglabels.go web: release assets, milestones and org label and milestone writes 1 month ago
orgrender_test.go web: the ten findings from the forge comparison 2 months ago
orgweb.go web: interface guidelines fixes 2 months ago
ownerpage_test.go control: move the feed-line sentence renderer from httpd, so the CLI can share it 1 month ago
packlimit_test.go httpd: web archives take a pack slot 1 month ago
page.go web: footer links to the operator's abuse and terms pages 1 month ago
pages.go pages: a directory redirect cannot leave the site 2 months ago
pagesredirect_test.go pages: a directory redirect cannot leave the site 2 months ago
palette_test.go web: rewrite the stylesheet on measured tokens 2 months ago
parity296b_test.go web: authorise release asset uploads before reading the body 1 month ago
preview.go web: preview markup before writing it 2 months ago
queries.go web: pinned queries on the dashboard, /{owner}/-/queries and /{owner}/-/queries/{name} 1 month ago
queries_test.go web: pinned queries on the dashboard, /{owner}/-/queries and /{owner}/-/queries/{name} 1 month ago
railanon_test.go web: explore by latest activity, paged; slim profile repo rows 1 month ago
rawcache_test.go web: ETag and Cache-Control on raw and wiki/_raw 1 month ago
reactions.go Web: reaction buttons under issue and merge request bodies and comments 1 month ago
reactions_test.go Reactions: e2e test, Parity, Users, changelog 1 month ago
readme.go Fold duplicated and deeply nested code into helpers 1 month ago
reauth_test.go web: a stale session's mint or grant gets a sign-in link back to the form 1 month ago
releaseactions.go release notes: one line per merge request since the previous release 1 month ago
rendered.go web: the ten findings from the forge comparison 2 months ago
rendered_test.go httpd: gofmt rendered_test.go 1 month ago
repohead_test.go web: watch button names all three states, muted included 1 month ago
routes.go control: self-service account deletion 1 month ago
routes_test.go httpd, gitd: pack generation takes a slot; ls-refs does not 1 month ago
searchweb.go web: the rail is an icon column 2 months ago
searchweb_test.go web: search scope caption is permanent; document the tab zero-count rule 1 month ago
settings.go Scheduled code scanning on the runners 25 days ago
settingsparity_test.go web: reauth for repo delete and rename, import form keeps input, flash after transfer and delete 1 month ago
sidecol_test.go web: the side column is a disclosure below 62rem 2 months ago
smart.go web: authorise release asset uploads before reading the body 1 month ago
snippets.go profile: reorder the tabs, and fold bookmarks and snippets in 2 months ago
suggestion_test.go web: suggestions render as a diff in their thread, with an apply button or the CLI command; line ranges in the compose form 1 month ago
symbols.go symbols: chunked builds, failure records, name and byte bounds 1 month ago
symbols_test.go symbols: chunked builds, failure records, name and byte bounds 1 month ago
theme.go web: the ten findings from the forge comparison 2 months ago
theme_test.go web: the ten findings from the forge comparison 2 months ago
topics.go web: topic and kind columns on explore and search 2 months ago
topics_test.go web: topic and kind columns on explore and search 2 months ago
trailingslash_test.go web: a trailing-slash redirect cannot leave the site 2 months ago
web.go web: ETag and Cache-Control on raw and wiki/_raw 1 month ago
wiki.go Fold duplicated and deeply nested code into helpers 1 month ago
wiki_test.go wiki: a link to an existing non-page file resolves to _raw, not the page route 1 month ago
package httpd

import (
	"html/template"
	"path"
	"strings"

	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"

	"gitbay.org/gitbay/internal/gitutil"
)

// rewriteRelativeLinks makes relative hrefs and srcs in rendered repo
// content resolve on the forge: links go to blob pages, images to raw.
// go-org exports .org links as .html, so an .html target whose .org (or
// .md) source exists in the tree maps back to the source file.
func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) template.HTML {
	return rewriteRelativeTargets(rendered, func(v string, src bool) (string, bool) {
		target := path.Clean(path.Join(baseDir, v))
		if strings.HasPrefix(target, "..") {
			return "", false
		}
		if src {
			return "/" + p.Repo.Path() + "/raw/" + p.Ref + "/" + target, true
		}
		return "/" + p.Repo.Path() + "/blob/" + p.Ref + "/" + exportSource(p, target), true
	})
}

// exportSource maps an .html target back to the .org or .md file in the
// tree it was exported from, if there is one.
func exportSource(p repoPage, target string) string {
	stem, ok := strings.CutSuffix(target, ".html")
	if !ok {
		return target
	}
	for _, ext := range []string{".org", ".md"} {
		if _, err := gitutil.ReadBlob(p.Dir, p.Ref, stem+ext, 1); err == nil {
			return stem + ext
		}
	}
	return target
}

// rewriteRelativeTargets passes each relative link href and img, video or
// source src in rendered to rewrite (src is true for the media), and sets
// the attribute to what it returns when ok.
func rewriteRelativeTargets(rendered template.HTML, rewrite func(v string, src bool) (string, bool)) template.HTML {
	ctx := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div}
	nodes, err := html.ParseFragment(strings.NewReader(string(rendered)), ctx)
	if err != nil {
		return rendered
	}
	var walk func(*html.Node)
	walk = func(n *html.Node) {
		if n.Type == html.ElementNode {
			for i, a := range n.Attr {
				isHref := a.Key == "href" && n.Data == "a"
				isSrc := a.Key == "src" && (n.Data == "img" || n.Data == "video" || n.Data == "source")
				if (!isHref && !isSrc) || !isRelativeTarget(a.Val) {
					continue
				}
				if v, ok := rewrite(a.Val, isSrc); ok {
					n.Attr[i].Val = v
				}
			}
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			walk(c)
		}
	}
	var out strings.Builder
	for _, n := range nodes {
		walk(n)
		if err := html.Render(&out, n); err != nil {
			return rendered
		}
	}
	return template.HTML(out.String())
}

// isRelativeTarget is false for empty targets, absolute URLs, rooted
// paths, fragments, mailto: and data:.
func isRelativeTarget(v string) bool {
	if v == "" || strings.Contains(v, "://") {
		return false
	}
	for _, prefix := range []string{"/", "#", "mailto:", "data:"} {
		if strings.HasPrefix(v, prefix) {
			return false
		}
	}
	return true
}