insert-nonces
v1.0.7
Published
insert a string (nonce) for each script, style, and link (rel="stylesheet" only) element in a HTML file.
Downloads
10
Readme
What is insert-nonces ?
This package is a function which takes a string of html and a nonce value as inputs and returns the html with nonce attributes with the given nonce value for each inline style, script, and link rel="stylesheet" element. You must provide the html and nonce value.
<style>/*some style*/</style>
becomes <style nonce="your-nonce-value">/*some style*/</style>
Why ?
To be able to use inline styles/scripts securely, by setting a whitelisting Content Security Policy (CSP). It is recommended to not use 'unsafe-inline' due to the potential for an XSS attack, and instead use a nonce or hash. This solution uses nonces.
How ?
- Set the CSP using the same nonce you use in the HTML. I recommend Helmet which allows you to easily set CSP headers.
- Insert the same nonce into your HTML on request. Change the nonce value for each request, or else an attacker can just use the static nonce when attempting to inject code. Follow the usage instructions below to complete this step.
Usage
insertNonces(htmlString, nonceString);
or
insertNonces({html:htmlString, nonce:nonceString});
If you use an object, you can disable style, script, and/or link nonces from being generated.
//this will only generate nonces on style elements in your html file
insertNonces({html:htmlString, nonce:nonceString, script:false, link:false});
Example:
It makes more sense to use a stream, than to read the whole html file into memory, but here is a naive example to get you started.
const fs = require('fs'); //to obtain your html as a string
const uuidV4 = require('uuid/v4'); //to generate a unique nonce
const insertNonces = require('insert-nonces'); //to insert this nonce into your html
let nonce;
//the below should be run on each request, to generate a new nonce and insert it into the html.
nonce = uuidV4();
//a stream would make more sense here...
fs.readFile('index.html', 'utf-8', (err, html) => {
if (err) return err;
let noncifiedHTML = insertNonces(html, nonce);
console.log("nocifiedHTML:", noncifiedHTML);
//For example in Express you may want to use: res.send(noncifiedHTML);
}));
Installation
npm install --save insert-nonces
For newbies:
- Install NodeJS if not already done.
- Open your chosen CLI and navigate to your project folder.
- If you have not yet initialized the project, use
npm init
to generate apackage.json
- Use
npm install --save insert-nonces
to save this package as a dependency of your project. - Require the package in your javascript with
const insertNonces = require("insert-nonces");
- Run the project via CLI using
node yourFile.js
Limitations
When setting nonce for link css elements, it must be exactly: '<link rel="stylesheet"'
in order for it to insert the nonce ('<link nonce="your-nonce-value" rel="stylesheet"'
).