Skip to content

Commit

Permalink
Only allow UnsafeHtml values for :dangerouslySetInnerHTML
Browse files Browse the repository at this point in the history
  • Loading branch information
Deraen committed Jan 31, 2025
1 parent 07bc86c commit 03c9357
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
8 changes: 8 additions & 0 deletions src/reagent/core.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -372,3 +372,11 @@
:superseded-by "reagent.dom/render"}
[& _]
(throw (js/Error. "Reagent.core/render function was moved to reagent.dom namespace in Reagent v1.0.")))

(defn unsafe-html
"Create a tagged value for use with :dangerouslySetInnerHTML.
Reagent doesn't allow other values to be used with the property,
to ensure EDN and Transit data can't be used to accidentally
create arbitrary HTML."
[s]
(tmpl/UnsafeHTML. s))
15 changes: 11 additions & 4 deletions src/reagent/impl/template.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
[reagent.debug :refer-macros [dev? warn]]
[goog.object :as gobj]))

(deftype UnsafeHTML [__html])

;; From Weavejester's Hiccup, via pump:
(def ^{:doc "Regular expression that parses a CSS-style id and class
from a tag name."}
Expand Down Expand Up @@ -118,10 +120,15 @@
(let [class (:class props)
props (-> props
(cond-> class (assoc :class (util/class-names class)))
(set-id-class id-class))]
(if (.-custom id-class)
(convert-custom-prop-value props)
(convert-prop-value props))))
(set-id-class id-class))
^js js-props (if (.-custom id-class)
(convert-custom-prop-value props)
(convert-prop-value props))]
;; Ensure only tagged values are used for dangerouslySetInnerHTML
(when-let [d (and js-props (.-dangerouslySetInnerHTML js-props))]
(when-not (instance? UnsafeHTML d)
(js-delete js-props "dangerouslySetInnerHTML")))
js-props))

;;; Conversion from Hiccup forms

Expand Down
11 changes: 10 additions & 1 deletion test/reagenttest/testreagent.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@
(as-string [:div.bar [:p "foo"]])))
(is (= "<div class=\"bar\"><p>foobar</p></div>"
(as-string [:div.bar {:dangerously-set-inner-HTML
{:__html "<p>foobar</p>"}}]))))
(r/unsafe-html "<p>foobar</p>")}]))))

(u/deftest ^:dom test-return-class
(let [ran (atom 0)
Expand Down Expand Up @@ -1525,3 +1525,12 @@
16))))
[really-simple]]
u/fn-compiler)))))))

(u/deftest test-unsafe-html
(testing "Regular value is ignored"
(is (= "<div></div>"
(as-string (r/as-element [:div {:dangerouslySetInnerHTML {:__html "<img/>"}}])))))

(testing "Tagged value is allowed"
(is (= "<div><img/></div>"
(as-string (r/as-element [:div {:dangerouslySetInnerHTML (r/unsafe-html "<img/>")}]))))))

0 comments on commit 03c9357

Please sign in to comment.