summaryrefslogtreecommitdiff
path: root/apps/web/lib/sanitize.test.ts
blob: 266b8af80793531206e79fdc6332ce1ebf5a288f (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
import { describe, it, expect } from "vitest"
import { sanitizeEntryContent } from "./sanitize"

describe("sanitizeEntryContent", () => {
  it("allows safe html tags", () => {
    const input = "<p>hello <strong>world</strong></p>"
    expect(sanitizeEntryContent(input)).toBe(input)
  })

  it("strips script tags", () => {
    const input = '<p>safe</p><script>alert("xss")</script>'
    expect(sanitizeEntryContent(input)).toBe("<p>safe</p>")
  })

  it("strips event handlers", () => {
    const input = '<p onclick="alert(1)">click me</p>'
    expect(sanitizeEntryContent(input)).toBe("<p>click me</p>")
  })

  it("allows img tags with safe attributes", () => {
    const input = '<img src="https://example.com/img.jpg" alt="photo">'
    const result = sanitizeEntryContent(input)
    expect(result).toContain("src=")
    expect(result).toContain("alt=")
  })

  it("strips iframe tags", () => {
    const input = '<iframe src="https://evil.com"></iframe>'
    expect(sanitizeEntryContent(input)).toBe("")
  })

  it("strips javascript: urls from links", () => {
    const input = '<a href="javascript:alert(1)">click</a>'
    const result = sanitizeEntryContent(input)
    expect(result).not.toContain("javascript:")
  })

  it("allows https links", () => {
    const input = '<a href="https://example.com">link</a>'
    expect(sanitizeEntryContent(input)).toBe(input)
  })

  it("preserves code blocks", () => {
    const input = "<pre><code>const x = 1</code></pre>"
    expect(sanitizeEntryContent(input)).toBe(input)
  })
})