jekyll-mathjax-csp
Render math on the server using MathJax-node, while maintaining a strict Content Security Policy (CSP) without 'unsafe-inline'.
While MathJax is well equipped to render beautiful math in a browser, letting it run in the client has two distinctive disadvantages: It is quite CPU-intensive and crucially relies on inline style attributes and elements. This Jekyll plugin aims to resolve both issues at once by rendering formulas to SVG images on the server, extracting all generated style attributes into a single <style> element in the head of the page and computing a hash over its content that can then be added as a CSP style-src.
The plugin runs the output of Jekyll's markdown parser kramdown through the CLI converter mjpage offered by the npm package mathjax-node-page and thus behaves exactly as client-side MathJax in SVG rendering mode would.
Usage
- Install the npm package
mathjax-node-pagefrom your top-level Jekyll directory:
npm init -f # only if you don't have a package.json yet
npm install [email protected]
- Install
jekyll-mathjax-csp:
gem install jekyll-mathjax-csp
- Ensure that your
_config.ymlcontains the following settings:
plugins:
- jekyll-mathjax-csp
exclude:
- node_modules
- package.json
- package-lock.json
Add the
{% mathjax_csp_sources %}Liquid tag where you want the CSP'sha256-...'hashes for<style>elements to be emitted. Don't forget to add the YAML front matter (two lines of---) to such files. If you specify your CSP in a different way, add thestyle-srcsources the plugins prints to the console during build.Include beautiful math in your posts!
Dependencies
mathjax-node-page(npm): 2.0+html-pipeline: 2.3+jekyll: 3.0+
Configuration
'mathjax-node-page' adds a fixed inline stylesheet to every page containing math. If you want to serve this stylesheet as an external .css, you can advise the plugin to strip it from the output by adding the following lines to your _config.yml:
mathjax_csp:
strip_css: true
Local testing
If you want to try out your CSP locally, you can specify headers in your _config.yml:
webrick:
headers:
Content-Security-Policy: >-
default-src 'none'; script-src ...
It is unfortunately not possible to have Liquid tags in _config.yml, so you will have to update your CSP manually. Don't forget to restart jekyll for it to pick up the config changes.
License
MIT