Created
October 12, 2016 12:29
-
-
Save plexus/3a91e7cb399d22f6dcabcb35dd1e4204 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 []})) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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