Maintaining a strict Content Security Policy (CSP) can be quite challenging. Ensuring a robust linting policy is in place can help keep your codebase free from CSP violations.
In pursuit of this objective, a tool designed to scrutinize HTML and identify potential breaches becomes indispensable. The ultimate aim is to safeguard your codebase against CSP violations that may occur during the build process.
To address this need, I’ve developed an NPM package specifically for this purpose. The core package can be found at: csp-html-linter. All of the following extensions / plugins use it.
Visual Studio Code Extension
The following vscode extension will highlight violations as a developer writes code. It works with HTML found in .html , .ts and .js files.
https://marketplace.visualstudio.com/items?itemName=MauriceDownes.vscode-csp-html-linter
Rollup / Webpack plugins
In addition, I’ve also created two more packages to seamlessly integrate with both Rollup and Webpack builds:
By default, these tools will prevent the use of the following elements or attributes in your HTML:
- Usage of the style attribute
- Style tags with no nonce value
- Script tags with no nonce value
- Inline JavaScript code, such as javascript:void(0) and javascript:doSomthing()
- Inline events using attributes with JavaScript content, like
onclick="doSomething()"
They can be customised with the following options, if the defaults are too strict.
{
allowInlineStyles: true,
allowInlineJs: true,
allowStyleTagWithoutNonce: true,
allowScriptTagWithoutNonce: true
}
In Conclusion
These packages are designed to bolster your codebase’s security and maintain the integrity of your Content Security Policy.
To see how to lint your JavaScript files for CSP see the following articles:
- Preventing Content Security Policy Violations With ESlint
- Enhancing CSP With ESlint Preventing Unsafe SetAttribute Style Usage