krakenjs / lusca

Application security for express apps.
Other
1.79k stars 123 forks source link

Nonce is not being generated #136

Open danielcl opened 4 years ago

danielcl commented 4 years ago

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?

danielcl commented 4 years ago

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.

sujanadiga commented 4 years ago

@danielcl, nonce gets generated when using the module lusca directly. https://github.com/krakenjs/lusca/blob/0483eda77a6fcef08d9319369e1f2b6fd2a5dcba/index.js#L30-L51

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
    }
}));