Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions packages/express-csp-header/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function expressCspHeader(params?: ExpressCSPParams): RequestHandler {

const { domainOptions } = params;
let cspString = getCspString(req, res, params);
cspString = applyNonce(req, cspString);
cspString = applyNonce(req ,res, cspString);
cspString = applyAutoTld(req, cspString, domainOptions);

res.set(params.reportOnly ? CSP_REPORT_ONLY_HEADER : CSP_HEADER, cspString);
Expand Down Expand Up @@ -83,11 +83,13 @@ function getCspString(req: Request, res: Response, params: ExpressCSPParams): st
return getCSP(cspHeaderParams);
}

function applyNonce(req: Request, cspString: string): string {
function applyNonce(req: Request, res: Response, cspString: string): string {
if (cspString.includes(NONCE)) {
req.nonce = randomBytes(16).toString('base64');
const nonceValue = randomBytes(16).toString('base64');
req.nonce = nonceValue;
res.locals.nonce = nonceValue;

return cspString.replace(new RegExp(NONCE, 'g'), nonce(req.nonce));
return cspString.replace(new RegExp(NONCE, 'g'), nonce(nonceValue));
}

return cspString;
Expand Down
9 changes: 6 additions & 3 deletions packages/express-csp-header/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { expressCspHeader, ExpressCSPParams, SELF, INLINE, NONE, NONCE, TLD } fr
function execMiddleware(params?: ExpressCSPParams, req: Partial<Request> = {}) {
const res = {
headers: {} as Record<string, string>,
locals: {} as Record<string, string>,
set(headerName: string, headerVal: string) {
this.headers[headerName] = headerVal;
}
Expand Down Expand Up @@ -36,15 +37,17 @@ test('should not set header with no params', () => {
expect(res.headers['Content-Security-Policy']).toStrictEqual(undefined);
});

test('should set req.nonce', () => {
const { req, res} = execMiddleware({
test('should set req.nonce and res.locals.nonce', () => {
const { req, res } = execMiddleware({
directives: {
'script-src': [NONCE]
}
});

expect(res.headers['Content-Security-Policy']).toMatch(/^script-src 'nonce-.+';/);
expect(res.locals).toHaveProperty('nonce');
expect(req).toHaveProperty('nonce');
expect(req.nonce).toEqual(res.locals.nonce);
expect(res.headers['Content-Security-Policy']).toMatch(new RegExp(`^script-src \'nonce-${req.nonce}\';`));
});

describe('report-uri', () => {
Expand Down