背景与价值样式内联易被滥用。使用nonce或哈希可在保证功能的同时提升安全。统一规范禁用unsafe-inline:统一移除style-src中的unsafe-inline。使用nonce:为受控内联样式分配nonce并插入。哈希支持:对固定样式片段使用sha256哈希。核心实现CSP头与nonce生成type Res = { setHeader: (k: string, v: string) => void } function genNonce(): string { const u = new Uint8Array(16); crypto.getRandomValues(u); let s=''; for (let i=0;i<u.length;i++) s += u[i].toString(16).padStart(2,'0'); return s } function setCspStyle(res: Res, nonce: string) { res.setHeader('Content-Security-Policy', `style-src 'nonce-${nonce}'`) } 受控样式插入function insertStyle(css: string, nonce: string): HTMLStyleElement { const el = document.createElement('style') el.setAttribute('nonce', nonce) el.textContent = css document.head.appendChild(el) return el } 落地建议为内联样式使用nonce或哈希并移除unsafe-inline,统一封装样式插入。验证清单是否启用style-src nonce或哈希;是否移除unsafe-inline并通过受控插入。

发表评论 取消回复