如何通过自定义插件在 HTML 注入 CSP nonce 值
解读
Netlify 的构建阶段默认只产出静态文件,CSP nonce(一次性随机数)必须在构建时或边缘运行时动态生成并写入 HTML,否则浏览器会把内联脚本标记为非法。国内企业对安全基线要求普遍高于海外,面试时考官想确认两点:
- 你是否理解构建时与边缘运行时两种注入路径的差异;
- 你是否能把“生成 nonce → 改写 HTML → 同步到响应头”做成可复用插件,而不是临时脚本。
回答必须体现“插件化”“可配置”“零运维”三大 Netlify 特色,同时兼顾国内备案与 CDN 合规场景。
知识点
- build.plugin 生命周期:
onPreBuild、onPostBuild、onEnd三钩子,决定 nonce 生成时机。 - crypto.randomBytes 生成 128 bit nonce,Base64 编码后长度 22 字符,满足国内等保≥256 bit 随机性要求。
- post-processing 钩子:利用
@netlify/plugin-sitemap源码思路,在onPostBuild遍历PUBLISH_DIR内所有.html,通过 cheerio 注入<script nonce="xxx">与<style nonce="xxx">。 - 边缘函数联动:把 nonce 写入边缘环境变量,在
_headers或next中间件里拼接Content-Security-Policy: script-src 'nonce-<nonce>'; style-src 'nonce-<nonce>'。 - 缓存策略:nonce 每构建一次,文件名 hash 不变,但 HTML 内容变,需关闭 Netlify 自动资产优化中的“缓存破坏”选项,防止旧 nonce 被 CDN 缓存。
- 国内合规:若站点已备案并使用国内加速节点,边缘函数需走“香港节点回源”模式,避免动态头部被 GSLB 误判为违规回源。
答案
步骤一:初始化插件
在项目根目录新建 plugins/csp-nonce/index.js:
const crypto = require('crypto')
const fs = require('fs/promises')
const path = require('path')
const cheerio= require('cheerio')
module.exports = {
onPostBuild: async ({ constants: { PUBLISH_DIR } }) => {
// 1. 生成 nonce
const nonce = crypto.randomBytes(16).toString('base64')
// 2. 写入环境变量,供边缘函数读取
await fs.writeFile(path.join(PUBLISH_DIR, 'nonce.txt'), nonce)
// 3. 遍历 HTML 注入
const htmlFiles = await globby(`${PUBLISH_DIR}/**/*.html`)
await Promise.all(htmlFiles.map(async file => {
const html = await fs.readFile(file, 'utf8')
const $ = cheerio.load(html)
$('script[src=""],style').attr('nonce', nonce)
await fs.writeFile(file, $.html())
}))
}
}
步骤二:注册插件
在 netlify.toml 追加:
[[plugins]]
package = "./plugins/csp-nonce"
步骤三:边缘函数同步响应头
新建 netlify/edge-functions/csp.js:
export default async (request, context) => {
const nonce = await Deno.readTextFile(`${Deno.env.get('NETLIFY_PUBLISH_PATH')}/nonce.txt`)
const response = await context.next()
response.headers.set(
'Content-Security-Policy',
`script-src 'self' 'nonce-${nonce}'; style-src 'self' 'nonce-${nonce}'`
)
return response
}
步骤四:路由匹配
在 netlify.toml 补充:
[[edge_functions]]
function = "csp"
path = "/*"
构建日志出现“CSP nonce injected”即表示成功,国内节点可通过 curl -I 验证响应头携带 nonce 值。
拓展思考
- 多分支隔离:在
onPreBuild阶段把BRANCH名称拼入 nonce,防止预览链接与生产环境复用同一随机数,降低重放风险。 - SRI 结合:对第三方库使用 Subresource Integrity,把
integrity值写入插件配置白名单,避免 nonce 被绕过。 - 灰度发布:利用 Netlify Split Testing 把 10% 流量切到带严格 CSP 的分支,通过国内前端监控(如阿里 SLS)对比
script-src 'unsafe-inline'与nonce模式的报错率,量化安全收益。 - 合规审计:国内等保 2.0 要求“日志留存≥6 个月”,可在插件内把每次构建的 nonce、commit SHA、操作人写入阿里云 OSS 私有桶,供后续溯源。