summaryrefslogtreecommitdiff
path: root/apps/web/lib/sanitize.ts
blob: 3a850168151b17e3160aafe31bae2d7b152806bc (plain) (blame)
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
import sanitizeHtml from "sanitize-html"

const TRACKING_PIXEL_DIMENSION_THRESHOLD = 3

function isTrackingPixel(tagName: string, attributes: Record<string, string>): boolean {
  if (tagName !== "img") return false

  const width = parseInt(attributes.width, 10)
  const height = parseInt(attributes.height, 10)

  if (!isNaN(width) && width <= TRACKING_PIXEL_DIMENSION_THRESHOLD) return true
  if (!isNaN(height) && height <= TRACKING_PIXEL_DIMENSION_THRESHOLD) return true

  return false
}

const SANITIZE_OPTIONS: sanitizeHtml.IOptions = {
  allowedTags: [
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "p",
    "a",
    "ul",
    "ol",
    "li",
    "blockquote",
    "pre",
    "code",
    "em",
    "strong",
    "del",
    "br",
    "hr",
    "img",
    "figure",
    "figcaption",
    "table",
    "thead",
    "tbody",
    "tr",
    "th",
    "td",
  ],
  allowedAttributes: {
    a: ["href", "title", "rel"],
    img: ["src", "alt", "title", "width", "height"],
  },
  allowedSchemes: ["http", "https"],
  exclusiveFilter: (frame) => isTrackingPixel(frame.tag, frame.attribs),
}

export function sanitizeEntryContent(htmlContent: string): string {
  return sanitizeHtml(htmlContent, SANITIZE_OPTIONS)
}