refactor: improve nonce extraction from Content Security Policy in Google Analytics component

This commit is contained in:
CodingOnStar 2025-10-20 12:45:05 +08:00
parent 00af0ed63c
commit 9a362d9ac6
2 changed files with 17 additions and 3 deletions

View File

@ -18,14 +18,29 @@ export type IGAProps = {
gaType: GaType
}
// 从 CSP header 中提取 nonce
const extractNonceFromCSP = (cspHeader: string | null): string | undefined => {
if (!cspHeader)
return undefined
const nonceMatch = cspHeader.match(/'nonce-([^']+)'/)
return nonceMatch ? nonceMatch[1] : undefined
}
const GA: FC<IGAProps> = ({
gaType,
}) => {
if (IS_CE_EDITION)
return null
const nonceValue = process.env.NODE_ENV === 'production' ? (headers() as unknown as UnsafeUnwrappedHeaders).get('x-nonce') : null
const nonce = nonceValue || undefined
// 从 CSP header 中提取 nonce而不是直接读取 x-nonce
const cspHeader = process.env.NODE_ENV === 'production'
? (headers() as unknown as UnsafeUnwrappedHeaders).get('content-security-policy')
: null
const nonce = extractNonceFromCSP(cspHeader)
// 服务端日志:验证 nonce 提取
if (typeof window === 'undefined')
console.log('[GA SSR] CSP header:', cspHeader ? 'exists' : 'MISSING', '| nonce:', nonce ? `extracted (${nonce.substring(0, 10)}...)` : 'NOT FOUND')
return (
<>

View File

@ -56,7 +56,6 @@ export function middleware(request: NextRequest) {
contentSecurityPolicyHeaderValue,
)
response.headers.set('x-nonce', nonce)
response.headers.set(
'Content-Security-Policy',
contentSecurityPolicyHeaderValue,