Skip to content

Instantly share code, notes, and snippets.

@jaysoo
Created June 1, 2013 19:36
Show Gist options
  • Save jaysoo/5691492 to your computer and use it in GitHub Desktop.
Save jaysoo/5691492 to your computer and use it in GitHub Desktop.

Revisions

  1. jaysoo created this gist Jun 1, 2013.
    30 changes: 30 additions & 0 deletions csp_nonce_demo.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    var express = require('express');
    var app = express();

    app.use(express.methodOverride());

    // Naive nonce using just timestamp.
    var nonce = new Date().valueOf();

    var contentSecurityPolicy = function(req, res, next) {
    res.header('Content-Security-Policy', "script-src 'self' 'nonce-" + nonce + "' http://ajax.googleapis.com");
    next();
    };

    app.use(contentSecurityPolicy);

    app.get('/', function(req, res){
    // Only inline scripts with a valid nonce should execute.
    var body = '<!doctype html><body>'
    + '<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>\n\n'
    + '<script nonce="' + nonce + '">$("body").append("<p>This should work with a valid nonce.");</script>\n\n'
    + '<script>$("body").append("<p>This should not work because nonce is missing.");</script>\n\n'
    + '<script nonce="bad">$("body").append("<p>This should not work because nonce is invalid.");</script>\n\n'
    + '<script nonce="' + nonce + '">$("body").append("<p>This should also work with a valid nonce.");</script>\n\n';
    res.setHeader('Content-Type', 'text/html');
    res.setHeader('Content-Length', body.length);
    res.end(body);
    });

    app.listen(3000);
    console.log('Listening on port 3000');