sanitizer.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package sanitizer // import "miniflux.app/v2/internal/reader/sanitizer"
  4. import (
  5. "io"
  6. "net/url"
  7. "slices"
  8. "strconv"
  9. "strings"
  10. "miniflux.app/v2/internal/config"
  11. "miniflux.app/v2/internal/reader/urlcleaner"
  12. "miniflux.app/v2/internal/urllib"
  13. "golang.org/x/net/html"
  14. )
  15. var (
  16. allowedHTMLTagsAndAttributes = map[string][]string{
  17. "a": {"href", "title", "id"},
  18. "abbr": {"title"},
  19. "acronym": {"title"},
  20. "aside": {},
  21. "audio": {"src"},
  22. "blockquote": {},
  23. "b": {},
  24. "br": {},
  25. "caption": {},
  26. "cite": {},
  27. "code": {},
  28. "dd": {"id"},
  29. "del": {},
  30. "dfn": {},
  31. "dl": {"id"},
  32. "dt": {"id"},
  33. "em": {},
  34. "figcaption": {},
  35. "figure": {},
  36. "h1": {"id"},
  37. "h2": {"id"},
  38. "h3": {"id"},
  39. "h4": {"id"},
  40. "h5": {"id"},
  41. "h6": {"id"},
  42. "hr": {},
  43. "iframe": {"width", "height", "frameborder", "src", "allowfullscreen"},
  44. "img": {"alt", "title", "src", "srcset", "sizes", "width", "height", "fetchpriority", "decoding"},
  45. "ins": {},
  46. "kbd": {},
  47. "li": {"id"},
  48. "ol": {"id"},
  49. "p": {},
  50. "picture": {},
  51. "pre": {},
  52. "q": {"cite"},
  53. "rp": {},
  54. "rt": {},
  55. "rtc": {},
  56. "ruby": {},
  57. "s": {},
  58. "samp": {},
  59. "source": {"src", "type", "srcset", "sizes", "media"},
  60. "strong": {},
  61. "sub": {},
  62. "sup": {"id"},
  63. "table": {},
  64. "td": {"rowspan", "colspan"},
  65. "tfoot": {},
  66. "th": {"rowspan", "colspan"},
  67. "thead": {},
  68. "time": {"datetime"},
  69. "tr": {},
  70. "u": {},
  71. "ul": {"id"},
  72. "var": {},
  73. "video": {"poster", "height", "width", "src"},
  74. "wbr": {},
  75. // MathML: https://w3c.github.io/mathml-core/ and https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element
  76. "annotation": {},
  77. "annotation-xml": {},
  78. "maction": {},
  79. "math": {"xmlns"},
  80. "merror": {},
  81. "mfrac": {},
  82. "mi": {},
  83. "mmultiscripts": {},
  84. "mn": {},
  85. "mo": {},
  86. "mover": {},
  87. "mpadded": {},
  88. "mphantom": {},
  89. "mprescripts": {},
  90. "mroot": {},
  91. "mrow": {},
  92. "ms": {},
  93. "mspace": {},
  94. "msqrt": {},
  95. "mstyle": {},
  96. "msub": {},
  97. "msubsup": {},
  98. "msup": {},
  99. "mtable": {},
  100. "mtd": {},
  101. "mtext": {},
  102. "mtr": {},
  103. "munder": {},
  104. "munderover": {},
  105. "semantics": {},
  106. }
  107. iframeAllowList = map[string]struct{}{
  108. "bandcamp.com": {},
  109. "cdn.embedly.com": {},
  110. "dailymotion.com": {},
  111. "open.spotify.com": {},
  112. "player.bilibili.com": {},
  113. "player.twitch.tv": {},
  114. "player.vimeo.com": {},
  115. "soundcloud.com": {},
  116. "vk.com": {},
  117. "w.soundcloud.com": {},
  118. "youtube-nocookie.com": {},
  119. "youtube.com": {},
  120. }
  121. blockedResourceURLSubstrings = []string{
  122. "api.flattr.com",
  123. "feeds.feedburner.com",
  124. "feedsportal.com",
  125. "pinterest.com/pin/create/button/",
  126. "stats.wordpress.com",
  127. "twitter.com/intent/tweet",
  128. "twitter.com/share",
  129. "facebook.com/sharer.php",
  130. "linkedin.com/shareArticle",
  131. }
  132. // See https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  133. validURISchemes = []string{
  134. // Most commong schemes on top.
  135. "https:",
  136. "http:",
  137. // Then the rest.
  138. "apt:",
  139. "bitcoin:",
  140. "callto:",
  141. "dav:",
  142. "davs:",
  143. "ed2k:",
  144. "facetime:",
  145. "feed:",
  146. "ftp:",
  147. "geo:",
  148. "git:",
  149. "gopher:",
  150. "irc:",
  151. "irc6:",
  152. "ircs:",
  153. "itms-apps:",
  154. "itms:",
  155. "magnet:",
  156. "mailto:",
  157. "news:",
  158. "nntp:",
  159. "rtmp:",
  160. "sftp:",
  161. "sip:",
  162. "sips:",
  163. "skype:",
  164. "spotify:",
  165. "ssh:",
  166. "steam:",
  167. "svn:",
  168. "svn+ssh:",
  169. "tel:",
  170. "webcal:",
  171. "xmpp:",
  172. // iOS Apps
  173. "opener:", // https://www.opener.link
  174. "hack:", // https://apps.apple.com/it/app/hack-for-hacker-news-reader/id1464477788?l=en-GB
  175. }
  176. dataAttributeAllowedPrefixes = []string{
  177. "data:image/avif",
  178. "data:image/apng",
  179. "data:image/png",
  180. "data:image/svg",
  181. "data:image/svg+xml",
  182. "data:image/jpg",
  183. "data:image/jpeg",
  184. "data:image/gif",
  185. "data:image/webp",
  186. }
  187. )
  188. type SanitizerOptions struct {
  189. OpenLinksInNewTab bool
  190. }
  191. func SanitizeHTML(baseURL, rawHTML string, sanitizerOptions *SanitizerOptions) string {
  192. var tagStack []string
  193. var parentTag string
  194. var blockedStack []string
  195. var buffer strings.Builder
  196. // Educated guess about how big the sanitized HTML will be,
  197. // to reduce the amount of buffer re-allocations in this function.
  198. estimatedRatio := len(rawHTML) * 3 / 4
  199. buffer.Grow(estimatedRatio)
  200. // Errors are a non-issue, so they're handled later in the function.
  201. parsedBaseUrl, _ := url.Parse(baseURL)
  202. tokenizer := html.NewTokenizer(strings.NewReader(rawHTML))
  203. for {
  204. if tokenizer.Next() == html.ErrorToken {
  205. err := tokenizer.Err()
  206. if err == io.EOF {
  207. return buffer.String()
  208. }
  209. return ""
  210. }
  211. token := tokenizer.Token()
  212. // Note: MathML elements are not fully supported by golang.org/x/net/html.
  213. // See https://github.com/golang/net/blob/master/html/atom/gen.go
  214. // and https://github.com/golang/net/blob/master/html/atom/table.go
  215. tagName := token.Data
  216. if tagName == "" {
  217. continue
  218. }
  219. switch token.Type {
  220. case html.TextToken:
  221. if len(blockedStack) > 0 {
  222. continue
  223. }
  224. // An iframe element never has fallback content.
  225. // See https://www.w3.org/TR/2010/WD-html5-20101019/the-iframe-element.html#the-iframe-element
  226. if parentTag == "iframe" {
  227. continue
  228. }
  229. buffer.WriteString(token.String())
  230. case html.StartTagToken:
  231. parentTag = tagName
  232. if isPixelTracker(tagName, token.Attr) {
  233. continue
  234. }
  235. if isBlockedTag(tagName) || slices.ContainsFunc(token.Attr, func(attr html.Attribute) bool { return attr.Key == "hidden" }) {
  236. blockedStack = append(blockedStack, tagName)
  237. continue
  238. }
  239. if len(blockedStack) == 0 && isValidTag(tagName) {
  240. attrNames, htmlAttributes := sanitizeAttributes(parsedBaseUrl, tagName, token.Attr, sanitizerOptions)
  241. if hasRequiredAttributes(tagName, attrNames) {
  242. if len(attrNames) > 0 {
  243. // Rewrite the start tag with allowed attributes.
  244. buffer.WriteString("<" + tagName + " " + htmlAttributes + ">")
  245. } else {
  246. // Rewrite the start tag without any attributes.
  247. buffer.WriteString("<" + tagName + ">")
  248. }
  249. tagStack = append(tagStack, tagName)
  250. }
  251. }
  252. case html.EndTagToken:
  253. if len(blockedStack) == 0 {
  254. if isValidTag(tagName) && slices.Contains(tagStack, tagName) {
  255. buffer.WriteString("</" + tagName + ">")
  256. }
  257. } else {
  258. if blockedStack[len(blockedStack)-1] == tagName {
  259. blockedStack = blockedStack[:len(blockedStack)-1]
  260. }
  261. }
  262. case html.SelfClosingTagToken:
  263. if isPixelTracker(tagName, token.Attr) {
  264. continue
  265. }
  266. if len(blockedStack) == 0 && isValidTag(tagName) {
  267. attrNames, htmlAttributes := sanitizeAttributes(parsedBaseUrl, tagName, token.Attr, sanitizerOptions)
  268. if hasRequiredAttributes(tagName, attrNames) {
  269. if len(attrNames) > 0 {
  270. buffer.WriteString("<" + tagName + " " + htmlAttributes + "/>")
  271. } else {
  272. buffer.WriteString("<" + tagName + "/>")
  273. }
  274. }
  275. }
  276. }
  277. }
  278. }
  279. func sanitizeAttributes(parsedBaseUrl *url.URL, tagName string, attributes []html.Attribute, sanitizerOptions *SanitizerOptions) ([]string, string) {
  280. var htmlAttrs, attrNames []string
  281. var err error
  282. var isAnchorLink bool
  283. for _, attribute := range attributes {
  284. if !isValidAttribute(tagName, attribute.Key) {
  285. continue
  286. }
  287. value := attribute.Val
  288. switch tagName {
  289. case "math":
  290. if attribute.Key == "xmlns" {
  291. if value != "http://www.w3.org/1998/Math/MathML" {
  292. value = "http://www.w3.org/1998/Math/MathML"
  293. }
  294. }
  295. case "img":
  296. switch attribute.Key {
  297. case "fetchpriority":
  298. if !isValidFetchPriorityValue(value) {
  299. continue
  300. }
  301. case "decoding":
  302. if !isValidDecodingValue(value) {
  303. continue
  304. }
  305. case "width", "height":
  306. if !isPositiveInteger(value) {
  307. continue
  308. }
  309. // Discard width and height attributes when width is larger than Miniflux layout (750px)
  310. if imgWidth := getIntegerAttributeValue("width", attributes); imgWidth > 750 {
  311. continue
  312. }
  313. case "srcset":
  314. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  315. }
  316. case "source":
  317. if attribute.Key == "srcset" {
  318. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  319. }
  320. }
  321. if isExternalResourceAttribute(attribute.Key) {
  322. switch {
  323. case tagName == "iframe":
  324. if !isValidIframeSource(attribute.Val) {
  325. continue
  326. }
  327. value = rewriteIframeURL(attribute.Val)
  328. case tagName == "img" && attribute.Key == "src" && isValidDataAttribute(attribute.Val):
  329. value = attribute.Val
  330. case tagName == "a" && attribute.Key == "href" && strings.HasPrefix(attribute.Val, "#"):
  331. value = attribute.Val
  332. isAnchorLink = true
  333. default:
  334. value, err = absoluteURLParsedBase(parsedBaseUrl, value)
  335. if err != nil {
  336. continue
  337. }
  338. if !hasValidURIScheme(value) || isBlockedResource(value) {
  339. continue
  340. }
  341. // TODO use feedURL instead of baseURL twice.
  342. parsedValueUrl, _ := url.Parse(value)
  343. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(parsedBaseUrl, parsedBaseUrl, parsedValueUrl); err == nil {
  344. value = cleanedURL
  345. }
  346. }
  347. }
  348. attrNames = append(attrNames, attribute.Key)
  349. htmlAttrs = append(htmlAttrs, attribute.Key+`="`+html.EscapeString(value)+`"`)
  350. }
  351. if !isAnchorLink {
  352. extraAttrNames, extraHTMLAttributes := getExtraAttributes(tagName, sanitizerOptions)
  353. if len(extraAttrNames) > 0 {
  354. attrNames = append(attrNames, extraAttrNames...)
  355. htmlAttrs = append(htmlAttrs, extraHTMLAttributes...)
  356. }
  357. }
  358. return attrNames, strings.Join(htmlAttrs, " ")
  359. }
  360. func getExtraAttributes(tagName string, sanitizerOptions *SanitizerOptions) ([]string, []string) {
  361. switch tagName {
  362. case "a":
  363. attributeNames := []string{"rel", "referrerpolicy"}
  364. htmlAttributes := []string{`rel="noopener noreferrer"`, `referrerpolicy="no-referrer"`}
  365. if sanitizerOptions.OpenLinksInNewTab {
  366. attributeNames = append(attributeNames, "target")
  367. htmlAttributes = append(htmlAttributes, `target="_blank"`)
  368. }
  369. return attributeNames, htmlAttributes
  370. case "video", "audio":
  371. return []string{"controls"}, []string{"controls"}
  372. case "iframe":
  373. return []string{"sandbox", "loading"}, []string{`sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"`, `loading="lazy"`}
  374. case "img":
  375. return []string{"loading"}, []string{`loading="lazy"`}
  376. default:
  377. return nil, nil
  378. }
  379. }
  380. func isValidTag(tagName string) bool {
  381. _, ok := allowedHTMLTagsAndAttributes[tagName]
  382. return ok
  383. }
  384. func isValidAttribute(tagName, attributeName string) bool {
  385. if attributes, ok := allowedHTMLTagsAndAttributes[tagName]; ok {
  386. return slices.Contains(attributes, attributeName)
  387. }
  388. return false
  389. }
  390. func isExternalResourceAttribute(attribute string) bool {
  391. switch attribute {
  392. case "src", "href", "poster", "cite":
  393. return true
  394. default:
  395. return false
  396. }
  397. }
  398. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  399. if tagName != "img" {
  400. return false
  401. }
  402. hasHeight := false
  403. hasWidth := false
  404. for _, attribute := range attributes {
  405. if attribute.Val == "1" || attribute.Val == "0" {
  406. switch attribute.Key {
  407. case "height":
  408. hasHeight = true
  409. case "width":
  410. hasWidth = true
  411. }
  412. }
  413. }
  414. return hasHeight && hasWidth
  415. }
  416. func hasRequiredAttributes(tagName string, attributes []string) bool {
  417. switch tagName {
  418. case "a":
  419. return slices.Contains(attributes, "href")
  420. case "iframe":
  421. return slices.Contains(attributes, "src")
  422. case "source", "img":
  423. return slices.Contains(attributes, "src") || slices.Contains(attributes, "srcset")
  424. default:
  425. return true
  426. }
  427. }
  428. func hasValidURIScheme(absoluteURL string) bool {
  429. for _, scheme := range validURISchemes {
  430. if strings.HasPrefix(absoluteURL, scheme) {
  431. return true
  432. }
  433. }
  434. return false
  435. }
  436. func isBlockedResource(absoluteURL string) bool {
  437. for _, blockedURL := range blockedResourceURLSubstrings {
  438. if strings.Contains(absoluteURL, blockedURL) {
  439. return true
  440. }
  441. }
  442. return false
  443. }
  444. func isValidIframeSource(iframeSourceURL string) bool {
  445. iframeSourceDomain := urllib.DomainWithoutWWW(iframeSourceURL)
  446. if _, ok := iframeAllowList[iframeSourceDomain]; ok {
  447. return true
  448. }
  449. if ytDomain := config.Opts.YouTubeEmbedDomain(); ytDomain != "" && iframeSourceDomain == strings.TrimPrefix(ytDomain, "www.") {
  450. return true
  451. }
  452. if invidiousInstance := config.Opts.InvidiousInstance(); invidiousInstance != "" && iframeSourceDomain == strings.TrimPrefix(invidiousInstance, "www.") {
  453. return true
  454. }
  455. return false
  456. }
  457. func rewriteIframeURL(link string) string {
  458. u, err := url.Parse(link)
  459. if err != nil {
  460. return link
  461. }
  462. switch strings.TrimPrefix(u.Hostname(), "www.") {
  463. case "youtube.com":
  464. if pathWithoutEmbed, ok := strings.CutPrefix(u.Path, "/embed/"); ok {
  465. if len(u.RawQuery) > 0 {
  466. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed + "?" + u.RawQuery
  467. }
  468. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed
  469. }
  470. case "player.vimeo.com":
  471. // See https://help.vimeo.com/hc/en-us/articles/12426260232977-About-Player-parameters
  472. if strings.HasPrefix(u.Path, "/video/") {
  473. if len(u.RawQuery) > 0 {
  474. return link + "&dnt=1"
  475. }
  476. return link + "?dnt=1"
  477. }
  478. }
  479. return link
  480. }
  481. func isBlockedTag(tagName string) bool {
  482. switch tagName {
  483. case "noscript", "script", "style":
  484. return true
  485. }
  486. return false
  487. }
  488. func sanitizeSrcsetAttr(parsedBaseURL *url.URL, value string) string {
  489. imageCandidates := ParseSrcSetAttribute(value)
  490. for _, imageCandidate := range imageCandidates {
  491. if absoluteURL, err := absoluteURLParsedBase(parsedBaseURL, imageCandidate.ImageURL); err == nil {
  492. imageCandidate.ImageURL = absoluteURL
  493. }
  494. }
  495. return imageCandidates.String()
  496. }
  497. func isValidDataAttribute(value string) bool {
  498. for _, prefix := range dataAttributeAllowedPrefixes {
  499. if strings.HasPrefix(value, prefix) {
  500. return true
  501. }
  502. }
  503. return false
  504. }
  505. func isPositiveInteger(value string) bool {
  506. if value == "" {
  507. return false
  508. }
  509. if number, err := strconv.Atoi(value); err == nil {
  510. return number > 0
  511. }
  512. return false
  513. }
  514. func getIntegerAttributeValue(name string, attributes []html.Attribute) int {
  515. for _, attribute := range attributes {
  516. if attribute.Key == name {
  517. number, _ := strconv.Atoi(attribute.Val)
  518. return number
  519. }
  520. }
  521. return 0
  522. }
  523. func isValidFetchPriorityValue(value string) bool {
  524. switch value {
  525. case "high", "low", "auto":
  526. return true
  527. }
  528. return false
  529. }
  530. func isValidDecodingValue(value string) bool {
  531. switch value {
  532. case "sync", "async", "auto":
  533. return true
  534. }
  535. return false
  536. }
  537. // absoluteURLParsedBase is used instead of urllib.AbsoluteURL to avoid parsing baseURL over and over.
  538. func absoluteURLParsedBase(parsedBaseURL *url.URL, input string) (string, error) {
  539. absURL, u, err := urllib.GetAbsoluteURL(input)
  540. if err != nil {
  541. return "", err
  542. }
  543. if absURL != "" {
  544. return absURL, nil
  545. }
  546. if parsedBaseURL == nil {
  547. return "", nil
  548. }
  549. return parsedBaseURL.ResolveReference(u).String(), nil
  550. }