From 9a362d9ac658d8c8812f116e1949c3c65b9cf895 Mon Sep 17 00:00:00 2001 From: CodingOnStar Date: Mon, 20 Oct 2025 12:45:05 +0800 Subject: [PATCH] refactor: improve nonce extraction from Content Security Policy in Google Analytics component --- web/app/components/base/ga/index.tsx | 19 +++++++++++++++++-- web/middleware.ts | 1 - 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/web/app/components/base/ga/index.tsx b/web/app/components/base/ga/index.tsx index 759a91d18e..be2d330610 100644 --- a/web/app/components/base/ga/index.tsx +++ b/web/app/components/base/ga/index.tsx @@ -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 = ({ 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 ( <> diff --git a/web/middleware.ts b/web/middleware.ts index 7db0e4fab2..3fee535ea4 100644 --- a/web/middleware.ts +++ b/web/middleware.ts @@ -56,7 +56,6 @@ export function middleware(request: NextRequest) { contentSecurityPolicyHeaderValue, ) - response.headers.set('x-nonce', nonce) response.headers.set( 'Content-Security-Policy', contentSecurityPolicyHeaderValue,