krakenjs/lusca

Nonce is not being generated

Opened this issue · 2 comments

The documentation for lusca.csp says this:

options.scriptNonce Boolean - Enable nonce for inline script-src, access from res.locals.nonce

Which, to me, sounds like lusca would generate the nonces it self.

I do this:

app.use(lusca.csp({
	policy: {
		"default-src": "'self'",
		"img-src": "'self'",
		"style-src": "'self' 'unsafe-inline'",
		"script-src": "'self' 'unsafe-eval'"
	},
	styleNonce: true,
	scriptNonce: true
}));

app.use((req, res, next) => 
{
	console.log("res.locals", res.locals);
	return next();
});

Console logs this:

res.locals.nonce undefined

So now i am generating the nonce with the nonce package myself like this:

const n = require('nonce')();

app.use((req, res, next) => 
{
	res.locals.nonce = n();
	return next();
})

Is this the way to go or should lusca generate nonces on its own?

I just saw that on npmjs is says res.locals.nonce and here on github it says req.locals.nonce

I suspect that it should be res.locals.nonce since req.locals does not exists.

But still both are undefined for me.

@danielcl, nonce gets generated when using the module lusca directly.

lusca/index.js

Lines 30 to 51 in 0483eda

if (options) {
Object.keys(lusca).forEach(function (key) {
var config = options[key];
if (key === "csp" && options[key] && (options[key]['styleNonce'] || options[key]['scriptNonce'])) {
nonce = true;
}
if (config) {
headers.push(lusca[key](config));
}
});
}
return function lusca(req, res, next) {
var chain = next;
if (nonce) {
Object.defineProperty(res.locals, 'nonce', {
value: crypto.pseudoRandomBytes(36).toString('base64'),
enumerable: true
});
}

If you change your implementation like below, you should be able to find the nonce under res.locals

app.use(lusca({
	csp: {
		policy: {
			"default-src": "'self'",
			"img-src": "'self'",
			"style-src": "'self' 'unsafe-inline'",
			"script-src": "'self' 'unsafe-eval'"
		},
		styleNonce: true,
		scriptNonce: true
	}
}));