Skip to content

Commit 1e4cc72

Browse files
authored
Merge pull request #13 from frux/res-locals
Add nonce to res.locals as well / closes #12
2 parents 873a5ec + a8c07e0 commit 1e4cc72

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

packages/express-csp-header/src/index.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ export function expressCspHeader(params?: ExpressCSPParams): RequestHandler {
4444

4545
const { domainOptions } = params;
4646
let cspString = getCspString(req, res, params);
47-
cspString = applyNonce(req, cspString);
47+
cspString = applyNonce(req ,res, cspString);
4848
cspString = applyAutoTld(req, cspString, domainOptions);
4949

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

86-
function applyNonce(req: Request, cspString: string): string {
86+
function applyNonce(req: Request, res: Response, cspString: string): string {
8787
if (cspString.includes(NONCE)) {
88-
req.nonce = randomBytes(16).toString('base64');
88+
const nonceValue = randomBytes(16).toString('base64');
89+
req.nonce = nonceValue;
90+
res.locals.nonce = nonceValue;
8991

90-
return cspString.replace(new RegExp(NONCE, 'g'), nonce(req.nonce));
92+
return cspString.replace(new RegExp(NONCE, 'g'), nonce(nonceValue));
9193
}
9294

9395
return cspString;

packages/express-csp-header/tests/index.test.ts

+6-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { expressCspHeader, ExpressCSPParams, SELF, INLINE, NONE, NONCE, TLD } fr
44
function execMiddleware(params?: ExpressCSPParams, req: Partial<Request> = {}) {
55
const res = {
66
headers: {} as Record<string, string>,
7+
locals: {} as Record<string, string>,
78
set(headerName: string, headerVal: string) {
89
this.headers[headerName] = headerVal;
910
}
@@ -36,15 +37,17 @@ test('should not set header with no params', () => {
3637
expect(res.headers['Content-Security-Policy']).toStrictEqual(undefined);
3738
});
3839

39-
test('should set req.nonce', () => {
40-
const { req, res} = execMiddleware({
40+
test('should set req.nonce and res.locals.nonce', () => {
41+
const { req, res } = execMiddleware({
4142
directives: {
4243
'script-src': [NONCE]
4344
}
4445
});
4546

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

5053
describe('report-uri', () => {

0 commit comments

Comments
 (0)