如何检测 style 属性而未使用 nonce?

解读

国内前端项目普遍采用 CSP(Content-Security-Policy)作为安全基线,其中“style-src”指令若启用严格模式(即不包含 'unsafe-inline'),则所有内联 style 属性必须携带服务端下发的 nonce 值,否则浏览器直接拒绝渲染。Stylelint 作为样式静态分析工具,核心职责是“扫描源码找问题”,而非“运行时注入 nonce”。因此,面试官真正想考察的是:

  1. 你是否理解 CSP nonce 机制与内联 style 的冲突点;
  2. 能否利用 Stylelint 的插件体系,编写一条“自定义规则”,在编译阶段就把“缺少 nonce 的 style 属性”标记为错误,并给出自动修复提示;
  3. 是否知道如何将该规则无缝接入国内主流工程化链路(Webpack/Vite + GitHub Actions/钉钉 CI + VS Code 实时反馈)。

知识点

  1. CSP nonce 原理:服务端生成一次性随机串,写入响应头 Content-Security-Policy: style-src 'nonce-xyz123',同时注入到 <div style="color:red" nonce="xyz123">。缺失即违规。
  2. PostCSS AST 节点类型:style 属性在 HTML 模板或 JSX 中对应的是 Attr 节点,而非 CSS 规则;Stylelint 默认只解析 <style> 标签或 .css 文件,因此需要“跨语言”扫描。
  3. Stylelint 插件三件套:
    • createPlugin:注册规则名;
    • root.walkDecls / walkRules:遍历 CSS AST;
    • context.fix:提供自动修复函数。
  4. 国内落地细节:
    • 模板文件后缀可能是 .vue、.tsx、.blade、.ejs;
    • 构建阶段通过 postcss-html、postcss-jsx 等语法解析器把非 CSS 代码转成 PostCSS 可识别的文档片段;
    • CI 阶段利用 stylelint --formatter github-actions-formatter 将错误直接注解到 PR 行内,符合国内团队“MR 门禁”习惯。

答案

步骤 1:安装依赖
npm i -D stylelint postcss-html postcss-jsx postcss postcss-selector-parser

步骤 2:编写自定义规则 plugins/stylelint-plugin-style-nonce.js

const stylelint = require('stylelint');
const postcssHtml = require('postcss-html');
const { parse } = require('postcss-selector-parser');

const ruleName = 'plugin/style-require-nonce';
const messages = stylelint.utils.ruleMessages(ruleName, {
  expected: (selector) => `内联 style 属性必须携带 nonce 值,避免 CSP 违规 (${selector})`,
});

module.exports = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOptions = {}, context) {
  return function(root, result) {
    // 只扫描 HTML/JSX/Vue 中的 style 属性
    root.walkDecls(decl => {
      const selector = decl.parent.selector;
      if (!selector) return;

      parse(selector).walkAttributes(attr => {
        if (attr.attribute !== 'style') return;

        // 检查是否已存在 nonce 属性
        const hasNonce = attr.parent.some(n => n.type === 'attribute' && n.attribute === 'nonce');
        if (hasNonce) return;

        const index = attr.sourceIndex;
        const line = decl.source.start.line;
        const column = decl.source.start.column + index;

        stylelint.utils.report({
          message: messages.expected(selector),
          node: decl,
          index,
          result,
          ruleName,
          line,
          column,
        });

        // 自动修复:在 style 属性前插入 nonce="$NONCE_PLACEHOLDER$"
        if (context.fix) {
          attr.parent.insertAfter(attr, {
            type: 'attribute',
            attribute: 'nonce',
            value: '"$NONCE_PLACEHOLDER$"',
            raws: { before: ' ' },
          });
        }
      });
    });
  };
});

步骤 3:在 stylelint.config.js 中注册

module.exports = {
  extends: ['stylelint-config-standard'],
  plugins: ['./plugins/stylelint-plugin-style-nonce'],
  overrides: [
    {
      files: ['**/*.{vue,tsx,jsx,html}'],
      customSyntax: 'postcss-html',
      rules: {
        'plugin/style-require-nonce': [true, { severity: 'error' }],
      },
    },
  ],
};

步骤 4:接入 CI

# .github/workflows/lint.yml
- run: npx stylelint "**/*.{vue,tsx,css}" --formatter github-actions-formatter

步骤 5:本地实时提示
VS Code 安装 stylelint 插件,settings.json 添加
"stylelint.validate": ["vue", "typescriptreact"]

运行效果:

  • 源码 <div style="color:red">Hello</div> 立即报错;
  • 一键修复后变为 <div style="color:red" nonce="$NONCE_PLACEHOLDER$">Hello</div>;
  • 服务端渲染时把占位符替换为真实 nonce 即可通过 CSP 校验。

拓展思考

  1. 占位符策略:NONCEPLACEHOLDERNONCE_PLACEHOLDER 仅用于编译期标记,真正上线需通过 webpack-html-plugin 或 vite-plugin-csp 在 emit 阶段做字符串替换,避免硬编码泄露。
  2. 性能优化:大型 Monorepo 可开启 stylelint cache,结合国内镜像源(npmmirror)缓存 node_modules,CI 耗时从 3 min 降到 30 s。
  3. 规则分级:把“缺失 nonce”设为 error,阻断合并;把“颜色值未使用变量”设为 warning,仅提示,符合国内“安全红线不可触碰,风格问题可渐进”的治理思路。
  4. 与框架结合:在 Next.js 中,通过 next/head 注入 nonce,自定义 Stylelint 规则可读取 next.config.js 的 generateBuildId 作为唯一随机源,实现“构建即合规”。