Skip to content

Instantly share code, notes, and snippets.

@phenan
Created December 3, 2018 05:50
Show Gist options
  • Save phenan/9e5fece462d2ba3feb9e74b8ef40afcb to your computer and use it in GitHub Desktop.
Save phenan/9e5fece462d2ba3feb9e74b8ef40afcb to your computer and use it in GitHub Desktop.
Simple HTML Sanitizer
object HTMLInterpolation {
// definition of tagged type
type Tagged[U] = { type Tag = U }
type @@[T, U] = T with Tagged[U]
trait Sanitized
// use tagged type to express sanitized string
type SanitizedString = String @@ Sanitized
private def sanitized (s: String): SanitizedString = s.asInstanceOf[SanitizedString]
implicit class HTMLContext (sc: StringContext) {
def html (args: SanitizedString*): SanitizedString = {
sanitized(sc.s(args:_*))
}
}
import scala.language.implicitConversions
implicit def autoStringSanitizer (string: String): SanitizedString = {
sanitized(string
.replaceAll("&", "&")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll("\"", "&quot;")
.replaceAll("'", "&#39;"))
}
implicit def autoIntSanitizer (n: Int): SanitizedString = sanitized(n.toString)
implicit def autoLongSanitizer (n: Long): SanitizedString = sanitized(n.toString)
implicit def autoDoubleSanitizer (d: Double): SanitizedString = sanitized(d.toString)
}
// usage
object Main {
def main (args: Array[String]): Unit = {
import HTMLInterpolation._
val a = html"<div>${"<script>alert(\"hello!\");</script>"}</div>"
println(a)
val b = html"<div>$a</div>"
println(b)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment