Skip to content

Instantly share code, notes, and snippets.

@plexus
Created October 12, 2016 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plexus/3a91e7cb399d22f6dcabcb35dd1e4204 to your computer and use it in GitHub Desktop.
Save plexus/3a91e7cb399d22f6dcabcb35dd1e4204 to your computer and use it in GitHub Desktop.
(ns lambdaisland.html.sanitize)
(defn sanitizer [allowed]
(fn sanitize [h]
(let [tag-ok? (set (keys allowed))]
(cond
(string? h) h
(vector? h) (let [[tag & xs] h
[attrs & cs] xs]
(if (tag-ok? tag)
(if (seq xs)
`[~tag
~(if (map? attrs)
(select-keys attrs (get allowed tag))
(sanitize attrs))
~@(keep sanitize cs)]
[tag])))
(seq? h) (keep sanitize h)))))
(def sanitize (sanitizer {:p []
:span []
:div []
:pre []
:code [:class]
:a [:href]
:li []
:ul []
:ol []
:del []
:em []
:strong []
:br []
:b []
:i []}))
(ns lambdaisland.html.sanitize-test
(:require [lambdaisland.html.sanitize :as sut]
[clojure.test :as t :refer [deftest is are]]))
(deftest test-sanitize-hiccup
(are [x] (= (sut/sanitize x) x)
[:p "foo"]
[:a {:href "bar"}]
[:a {:href "bar"} "foo"]
[:div
[:a {:href "bar"} "foo"]
[:a {:href "bar"} "baz"]]
'([:div
[:a {:href "bar"} "foo"]
[:a {:href "bar"} "baz"]]))
(are [x y] (= (sut/sanitize x) y)
[:script "foo"]
nil
[:a {:href "bar" :on-click "evil"}]
[:a {:href "bar"}]
'([:div
[:a {:href "bar"} "foo"]
[:script {:type "application/javascript"} "evil!"]
[:a {:href "bar" :on-click "not-allowed"} "baz"]])
'([:div
[:a {:href "bar"} "foo"]
[:a {:href "bar"} "baz"]])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment