sanitizer.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. htmlAttrs := make([]string, 0, len(attributes))
  281. attrNames := make([]string, 0, len(attributes))
  282. var err error
  283. var isAnchorLink bool
  284. for _, attribute := range attributes {
  285. if !isValidAttribute(tagName, attribute.Key) {
  286. continue
  287. }
  288. value := attribute.Val
  289. switch tagName {
  290. case "math":
  291. if attribute.Key == "xmlns" {
  292. if value != "http://www.w3.org/1998/Math/MathML" {
  293. value = "http://www.w3.org/1998/Math/MathML"
  294. }
  295. }
  296. case "img":
  297. switch attribute.Key {
  298. case "fetchpriority":
  299. if !isValidFetchPriorityValue(value) {
  300. continue
  301. }
  302. case "decoding":
  303. if !isValidDecodingValue(value) {
  304. continue
  305. }
  306. case "width", "height":
  307. if !isPositiveInteger(value) {
  308. continue
  309. }
  310. // Discard width and height attributes when width is larger than Miniflux layout (750px)
  311. if imgWidth := getIntegerAttributeValue("width", attributes); imgWidth > 750 {
  312. continue
  313. }
  314. case "srcset":
  315. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  316. }
  317. case "source":
  318. if attribute.Key == "srcset" {
  319. value = sanitizeSrcsetAttr(parsedBaseUrl, value)
  320. }
  321. }
  322. if isExternalResourceAttribute(attribute.Key) {
  323. switch {
  324. case tagName == "iframe":
  325. if !isValidIframeSource(attribute.Val) {
  326. continue
  327. }
  328. value = rewriteIframeURL(attribute.Val)
  329. case tagName == "img" && attribute.Key == "src" && isValidDataAttribute(attribute.Val):
  330. value = attribute.Val
  331. case tagName == "a" && attribute.Key == "href" && strings.HasPrefix(attribute.Val, "#"):
  332. value = attribute.Val
  333. isAnchorLink = true
  334. default:
  335. value, err = absoluteURLParsedBase(parsedBaseUrl, value)
  336. if err != nil {
  337. continue
  338. }
  339. if !hasValidURIScheme(value) || isBlockedResource(value) {
  340. continue
  341. }
  342. // TODO use feedURL instead of baseURL twice.
  343. parsedValueUrl, _ := url.Parse(value)
  344. if cleanedURL, err := urlcleaner.RemoveTrackingParameters(parsedBaseUrl, parsedBaseUrl, parsedValueUrl); err == nil {
  345. value = cleanedURL
  346. }
  347. }
  348. }
  349. attrNames = append(attrNames, attribute.Key)
  350. htmlAttrs = append(htmlAttrs, attribute.Key+`="`+html.EscapeString(value)+`"`)
  351. }
  352. if !isAnchorLink {
  353. extraAttrNames, extraHTMLAttributes := getExtraAttributes(tagName, sanitizerOptions)
  354. if len(extraAttrNames) > 0 {
  355. attrNames = append(attrNames, extraAttrNames...)
  356. htmlAttrs = append(htmlAttrs, extraHTMLAttributes...)
  357. }
  358. }
  359. return attrNames, strings.Join(htmlAttrs, " ")
  360. }
  361. func getExtraAttributes(tagName string, sanitizerOptions *SanitizerOptions) ([]string, []string) {
  362. switch tagName {
  363. case "a":
  364. attributeNames := []string{"rel", "referrerpolicy"}
  365. htmlAttributes := []string{`rel="noopener noreferrer"`, `referrerpolicy="no-referrer"`}
  366. if sanitizerOptions.OpenLinksInNewTab {
  367. attributeNames = append(attributeNames, "target")
  368. htmlAttributes = append(htmlAttributes, `target="_blank"`)
  369. }
  370. return attributeNames, htmlAttributes
  371. case "video", "audio":
  372. return []string{"controls"}, []string{"controls"}
  373. case "iframe":
  374. return []string{"sandbox", "loading"}, []string{`sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"`, `loading="lazy"`}
  375. case "img":
  376. return []string{"loading"}, []string{`loading="lazy"`}
  377. default:
  378. return nil, nil
  379. }
  380. }
  381. func isValidTag(tagName string) bool {
  382. _, ok := allowedHTMLTagsAndAttributes[tagName]
  383. return ok
  384. }
  385. func isValidAttribute(tagName, attributeName string) bool {
  386. if attributes, ok := allowedHTMLTagsAndAttributes[tagName]; ok {
  387. return slices.Contains(attributes, attributeName)
  388. }
  389. return false
  390. }
  391. func isExternalResourceAttribute(attribute string) bool {
  392. switch attribute {
  393. case "src", "href", "poster", "cite":
  394. return true
  395. default:
  396. return false
  397. }
  398. }
  399. func isPixelTracker(tagName string, attributes []html.Attribute) bool {
  400. if tagName != "img" {
  401. return false
  402. }
  403. hasHeight := false
  404. hasWidth := false
  405. for _, attribute := range attributes {
  406. if attribute.Val == "1" || attribute.Val == "0" {
  407. switch attribute.Key {
  408. case "height":
  409. hasHeight = true
  410. case "width":
  411. hasWidth = true
  412. }
  413. }
  414. }
  415. return hasHeight && hasWidth
  416. }
  417. func hasRequiredAttributes(tagName string, attributes []string) bool {
  418. switch tagName {
  419. case "a":
  420. return slices.Contains(attributes, "href")
  421. case "iframe":
  422. return slices.Contains(attributes, "src")
  423. case "source", "img":
  424. for _, attribute := range attributes {
  425. if attribute == "src" || attribute == "srcset" {
  426. return true
  427. }
  428. }
  429. return false
  430. default:
  431. return true
  432. }
  433. }
  434. func hasValidURIScheme(absoluteURL string) bool {
  435. for _, scheme := range validURISchemes {
  436. if strings.HasPrefix(absoluteURL, scheme) {
  437. return true
  438. }
  439. }
  440. return false
  441. }
  442. func isBlockedResource(absoluteURL string) bool {
  443. for _, blockedURL := range blockedResourceURLSubstrings {
  444. if strings.Contains(absoluteURL, blockedURL) {
  445. return true
  446. }
  447. }
  448. return false
  449. }
  450. func isValidIframeSource(iframeSourceURL string) bool {
  451. iframeSourceDomain := urllib.DomainWithoutWWW(iframeSourceURL)
  452. if _, ok := iframeAllowList[iframeSourceDomain]; ok {
  453. return true
  454. }
  455. if ytDomain := config.Opts.YouTubeEmbedDomain(); ytDomain != "" && iframeSourceDomain == strings.TrimPrefix(ytDomain, "www.") {
  456. return true
  457. }
  458. if invidiousInstance := config.Opts.InvidiousInstance(); invidiousInstance != "" && iframeSourceDomain == strings.TrimPrefix(invidiousInstance, "www.") {
  459. return true
  460. }
  461. return false
  462. }
  463. func rewriteIframeURL(link string) string {
  464. u, err := url.Parse(link)
  465. if err != nil {
  466. return link
  467. }
  468. switch strings.TrimPrefix(u.Hostname(), "www.") {
  469. case "youtube.com":
  470. if pathWithoutEmbed, ok := strings.CutPrefix(u.Path, "/embed/"); ok {
  471. if len(u.RawQuery) > 0 {
  472. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed + "?" + u.RawQuery
  473. }
  474. return config.Opts.YouTubeEmbedUrlOverride() + pathWithoutEmbed
  475. }
  476. case "player.vimeo.com":
  477. // See https://help.vimeo.com/hc/en-us/articles/12426260232977-About-Player-parameters
  478. if strings.HasPrefix(u.Path, "/video/") {
  479. if len(u.RawQuery) > 0 {
  480. return link + "&dnt=1"
  481. }
  482. return link + "?dnt=1"
  483. }
  484. }
  485. return link
  486. }
  487. func isBlockedTag(tagName string) bool {
  488. switch tagName {
  489. case "noscript", "script", "style":
  490. return true
  491. }
  492. return false
  493. }
  494. func sanitizeSrcsetAttr(parsedBaseURL *url.URL, value string) string {
  495. imageCandidates := ParseSrcSetAttribute(value)
  496. for _, imageCandidate := range imageCandidates {
  497. if absoluteURL, err := absoluteURLParsedBase(parsedBaseURL, imageCandidate.ImageURL); err == nil {
  498. imageCandidate.ImageURL = absoluteURL
  499. }
  500. }
  501. return imageCandidates.String()
  502. }
  503. func isValidDataAttribute(value string) bool {
  504. for _, prefix := range dataAttributeAllowedPrefixes {
  505. if strings.HasPrefix(value, prefix) {
  506. return true
  507. }
  508. }
  509. return false
  510. }
  511. func isPositiveInteger(value string) bool {
  512. if value == "" {
  513. return false
  514. }
  515. if number, err := strconv.Atoi(value); err == nil {
  516. return number > 0
  517. }
  518. return false
  519. }
  520. func getIntegerAttributeValue(name string, attributes []html.Attribute) int {
  521. for _, attribute := range attributes {
  522. if attribute.Key == name {
  523. number, _ := strconv.Atoi(attribute.Val)
  524. return number
  525. }
  526. }
  527. return 0
  528. }
  529. func isValidFetchPriorityValue(value string) bool {
  530. switch value {
  531. case "high", "low", "auto":
  532. return true
  533. }
  534. return false
  535. }
  536. func isValidDecodingValue(value string) bool {
  537. switch value {
  538. case "sync", "async", "auto":
  539. return true
  540. }
  541. return false
  542. }
  543. // absoluteURLParsedBase is used instead of urllib.AbsoluteURL to avoid parsing baseURL over and over.
  544. func absoluteURLParsedBase(parsedBaseURL *url.URL, input string) (string, error) {
  545. absURL, u, err := urllib.GetAbsoluteURL(input)
  546. if err != nil {
  547. return "", err
  548. }
  549. if absURL != "" {
  550. return absURL, nil
  551. }
  552. if parsedBaseURL == nil {
  553. return "", nil
  554. }
  555. return parsedBaseURL.ResolveReference(u).String(), nil
  556. }