HTML/XSS Injection Protection With TLX

AnyWhichWay
2 min readNov 30, 2018

--

With TLX, the small (3.9K minified and gzipped), multi-paradigm front-end library you can now automatically protect your templated HTML from XSS injection attacks.

If a user tries to enter a JavaScript function as a first name, the code below will automatically reject it and set the field state to invalid.

<div id="message">Hello ${firstName}</div>
First Name: <input id="name" name="firstName" value="${firstName}">
<script src="https://unpkg.com/tlx/browser/tlx.js"></script><script>
// turn on automatic protection
tlx.protect()
// create an empty reactive model to share
const model = tlx.reactor();
// bind message area to model
tlx.view(document.getElementById("message"),{model});
// bind input field to firstName based on name attribute above tlx.view(document.getElementById("name"),{model,linkModel:true})
</script>

If you have a style set for invalid fields, then the display of the field will be changed accordingly, e.g. input:invalid { box-shadow: 0 0 5px 1px red; }

You can try this in JSFiddle.

If you want to protect only specific fields, then you just need to add the protectattribute to the fields and not call tlx.protect()at the start of your code, e.g.

<div id="message">Hello ${firstName}</div>
First Name: <input id="name" name="firstName" value="${firstName}" protect>
<script src="https://unpkg.com/tlx/browser/tlx.js"></script><script>
// create an empty reactive model to share
const model = tlx.reactor();
// bind message area to model
tlx.view(document.getElementById("message"),{model});
// bind input field to firstName based on name attribute above tlx.view(document.getElementById("name"),{model,linkModel:true})
</script>

This is also available in JSFiddle.

TLX protection works by intercepting data entry events and setAttribute with a function that implements this pseudocode:

type = typeof(data);
switch(data) {
case type=="number"||type=="boolean": return data;
case isServerExec(data): return; // e.g. <?php
case isEvalOrBlocking(data): return;
case consoleWrite(data): return; // might write nastiness to logs
case containsJavaScript(data): return; // e.g. javascript:
case containsFunction(data): return;
}
data = escapeQueryString(data);
data = escapeHTMLEntities(data); // e.g. >= becomes &gte;
return data

As an added bonus shown in this JSFiddle, a call to tlx.protect() also ensures that malicious code can’t be entered using prompt.

Give TLX a try, as you can see from this article, it supports direct HTML templating and automatic data binding, but it is also has components and custom HTML elements, a default router, extended lifecycle callbacks and more.

Don’t forget to clap if you like this article or TLX. Thanks!

--

--

AnyWhichWay

Changing Possible ... currently from the clouds around Seattle.