~james/core

core/web/src/lib/markup/sanitize.ts -rw-r--r-- 4.1 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import sanitizeHtml from "sanitize-html";
import { isRepoRelative, mediaSrcset, mediaUrl, treeUrl } from "#lib/markup/paths.ts";
import type { MarkupContext } from "#lib/markup/paths.ts";

const HEADINGS = ["h1", "h2", "h3", "h4", "h5", "h6"];

const ALLOWED_TAGS = [
	...HEADINGS,
	"p",
	"br",
	"hr",
	"div",
	"span",
	"section",
	"blockquote",
	"pre",
	"code",
	"kbd",
	"samp",
	"var",
	"tt",
	"b",
	"strong",
	"i",
	"em",
	"u",
	"s",
	"strike",
	"del",
	"ins",
	"sub",
	"sup",
	"small",
	"mark",
	"a",
	"img",
	"picture",
	"source",
	"video",
	"ul",
	"ol",
	"li",
	"dl",
	"dt",
	"dd",
	"table",
	"thead",
	"tbody",
	"tfoot",
	"tr",
	"th",
	"td",
	"caption",
	"colgroup",
	"col",
	"details",
	"summary",
	"figure",
	"figcaption",
	"abbr",
	"bdo",
	"cite",
	"dfn",
	"q",
	"ruby",
	"rt",
	"rp",
	"time",
	"wbr",
	"center",
	"input",
	"label"
];

// bluemonday's standard attributes
const GLOBAL_ATTRIBUTES = ["id", "title", "dir", "lang", "align"];

const ALLOWED_ATTRIBUTES: sanitizeHtml.IOptions["allowedAttributes"] = {
	"*": GLOBAL_ATTRIBUTES,
	a: ["href", "name", "rel", "aria-hidden"],
	img: ["src", "srcset", "alt", "width", "height", "loading", "decoding"],
	source: ["src", "srcset", "type", "media"],
	video: ["src", "poster", "controls", "autoplay", "loop", "muted", "width", "height"],
	// the tasklist plugin renders disabled checkboxes tied to their labels
	input: ["type", "checked", "disabled"],
	label: ["for"],
	th: ["colspan", "rowspan", "scope"],
	td: ["colspan", "rowspan"],
	col: ["span", "width"],
	colgroup: ["span"],
	ol: ["start", "type", "reversed"],
	details: ["open"],
	time: ["datetime"],
	abbr: ["title"]
};

// classes are allowlisted per tag, so a readme cannot reach the app's own styles
const ALLOWED_CLASSES: sanitizeHtml.IOptions["allowedClasses"] = {
	a: ["anchor", "mention", "footnote-ref", "footnote-backref", "footnote-anchor"],
	sup: ["footnote-ref"],
	hr: ["footnotes-sep"],
	section: ["footnotes"],
	ol: ["footnotes-list", "task-list-container"],
	ul: ["task-list-container"],
	li: ["footnote-item", "task-list-item"],
	input: ["task-list-item-checkbox"],
	label: ["task-list-item-label"],
	div: ["markdown-alert", "markdown-alert-*"],
	p: ["markdown-alert-title"],
	code: ["language-*"],
	pre: ["mermaid"]
};

const externalRel = (href: string): string | undefined =>
	isRepoRelative(href) || href.startsWith("#") ? undefined : "nofollow noopener noreferrer";

const optionsFor = (ctx: MarkupContext): sanitizeHtml.IOptions => ({
	allowedTags: ALLOWED_TAGS,
	allowedAttributes: ctx.sourceLines
		? { ...ALLOWED_ATTRIBUTES, "*": [...GLOBAL_ATTRIBUTES, "data-line"] }
		: ALLOWED_ATTRIBUTES,
	allowedClasses: ALLOWED_CLASSES,
	allowedSchemes: ["http", "https", "mailto"],
	allowedSchemesAppliedToAttributes: ["href", "src", "srcset", "poster"],
	// resolving urls here rather than in a renderer rule catches the ones
	// written as raw html too
	transformTags: {
		a: (tagName, attribs) => {
			const href = attribs.href ?? "";
			// a mention already points at a profile
			const rewritten =
				isRepoRelative(href) && attribs.class !== "mention" ? treeUrl(href, ctx) : href;
			const rel = externalRel(rewritten);
			return { tagName, attribs: { ...attribs, href: rewritten, ...(rel ? { rel } : {}) } };
		},
		img: (tagName, attribs) => ({
			tagName,
			attribs: { ...resolveMedia(attribs, ctx), loading: "lazy", decoding: "async" }
		}),
		source: (tagName, attribs) => ({ tagName, attribs: resolveMedia(attribs, ctx) }),
		video: (tagName, attribs) => ({ tagName, attribs: resolveMedia(attribs, ctx) })
	},
	// the tasklist checkboxes are the only inputs we render
	exclusiveFilter: (frame) => frame.tag === "input" && frame.attribs.type !== "checkbox"
});

const resolveMedia = (
	attribs: Record<string, string>,
	ctx: MarkupContext
): Record<string, string> => {
	const resolved = { ...attribs };
	for (const key of ["src", "poster"]) {
		const value = resolved[key];
		if (value) resolved[key] = mediaUrl(value, ctx);
	}
	if (resolved.srcset) resolved.srcset = mediaSrcset(resolved.srcset, ctx);
	return resolved;
};

export const sanitizeMarkup = (html: string, ctx: MarkupContext): string =>
	sanitizeHtml(html, optionsFor(ctx));