package be.simplenotes.domain.security import be.simplenotes.types.LoggedInUser import org.owasp.html.HtmlChangeListener import org.owasp.html.HtmlPolicyBuilder import org.slf4j.LoggerFactory import javax.inject.Singleton @Singleton class HtmlSanitizer { private val htmlPolicy = HtmlPolicyBuilder() .allowElements("a") .allowCommonBlockElements() .allowCommonInlineFormattingElements() .allowElements("pre") .allowAttributes("class").onElements("code") .allowUrlProtocols("http", "https") .allowAttributes("href").onElements("a") .allowElements("input") .allowAttributes("type", "checked", "disabled", "readonly").onElements("input") .requireRelNofollowOnLinks() .toFactory()!! private val logger = LoggerFactory.getLogger(javaClass) private val htmlChangeListener = object : HtmlChangeListener { override fun discardedTag(context: LoggedInUser?, elementName: String) { logger.warn("Discarded tag $elementName for user $context") } override fun discardedAttributes(context: LoggedInUser?, tagName: String, vararg attributeNames: String) { logger.warn("Discarded attributes ${attributeNames.contentToString()} on tag $tagName for user $context") } } fun sanitize(userId: LoggedInUser, unsafeHtml: String) = htmlPolicy.sanitize(unsafeHtml, htmlChangeListener, userId)!! }