From 15938b489610ace2631cd84ef168416832f886da Mon Sep 17 00:00:00 2001 From: Cotton Hou Date: Tue, 22 Oct 2024 09:31:58 +0800 Subject: [PATCH] refactor(secure-headers): refine secureHeadersNonce init (#3535) --- src/middleware/secure-headers/secure-headers.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/middleware/secure-headers/secure-headers.ts b/src/middleware/secure-headers/secure-headers.ts index be84609f..55d7aa97 100644 --- a/src/middleware/secure-headers/secure-headers.ts +++ b/src/middleware/secure-headers/secure-headers.ts @@ -132,13 +132,12 @@ const generateNonce = () => { } export const NONCE: ContentSecurityPolicyOptionHandler = (ctx) => { - const nonce = - ctx.get('secureHeadersNonce') || - (() => { - const newNonce = generateNonce() - ctx.set('secureHeadersNonce', newNonce) - return newNonce - })() + const key = 'secureHeadersNonce' + const init = ctx.get(key) + const nonce = init || generateNonce() + if (init == null) { + ctx.set(key, nonce) + } return `'nonce-${nonce}'` }