如何校验使用 --user- 前缀的变量必须经过 sanitize?

解读

在国内前端团队面试中,这道题表面问“变量前缀校验”,实则考察三层能力:

  1. 是否理解 CSS 自定义属性(变量)一旦注入用户内容就可能成为 XSS 载体;
  2. 是否能把“业务安全规则”翻译成 Stylelint 的静态分析规则;
  3. 是否熟悉 Stylelint 插件机制、PostCSS AST 遍历以及自动修复(--fix)的完整闭环。

面试官期望听到“我不仅能把规则写出来,还能让规则在 CI、VS Code、Webpack 三端同时生效,并给出一键修复方案”。因此,答案必须包含:规则实现、插件包组织、配置注入、错误提示、自动修复、性能优化、文档与单元测试七个环节,缺一项都会扣分。

知识点

  1. Stylelint 规则运行流程:
    stylelint → postcss → Root→Rule→Decl→valueParser → report → context.fix ? fixFunc : warn
  2. PostCSS Value Parser:把 var(--user-name, fallback) 拆成函数节点,定位 --user-xxx 变量名。
  3. 自定义属性命名规范:
    --user-* 必须由 sanitize-css-var 函数包裹,例如 color: sanitize-css-var(var(--user-color))。
  4. 自动修复:利用 context.fix 回调,在报告错误的同时把声明值替换成合规形式。
  5. 插件包结构(npm 私有包):
    lib/rules/sanitize-user-var.js
    lib/index.js(导出插件数组)
    lib/rules/__tests__/index.test.js(使用 jest + stylelint-test-rule-ava 模板)
  6. 性能陷阱:避免在每次遍历中重复 new RegExp,把正则提为模块级常量;对不含 var( 的文件提前 return。
  7. 国内落地:
    • 私有 npm 源(verdaccio/cnpm)发布 @your-company/stylelint-plugin-security;
    • 在 @your-company/stylelint-config-base 里默认开启规则;
    • GitHub Actions / GitLab CI 里 stylelint --max-warnings 0 强制红线;
    • VS Code 插件 stylelint-plus 自动读取项目配置,保存即修复。

答案

  1. 创建插件包
    目录结构

    @your-company/stylelint-plugin-security
    ├─ lib/index.js
    ├─ lib/rules/sanitize-user-var.js
    └─ lib/rules/__tests__/sanitize-user-var.test.js
    
  2. 规则核心代码(lib/rules/sanitize-user-var.js)

    const valueParser = require('postcss-value-parser');
    const { utils } = require('stylelint');
    
    const ruleName = 'your-company/sanitize-user-var';
    const messages = utils.ruleMessages(ruleName, {
      expected: (unwrapped) => `CSS var "${unwrapped}" must be wrapped with sanitize-css-var()`,
    });
    
    const USER_VAR_RE = /^--user-/;
    
    function rule(primary, _, context) {
      return (root, result) => {
        const validOptions = utils.validateOptions(result, ruleName, {
          actual: primary,
          possible: [true],
        });
        if (!validOptions) return;
    
        root.walkDecls((decl) => {
          // 快速剪枝:没有 var( 直接跳过
          if (!decl.value.includes('var(')) return;
    
          const parsed = valueParser(decl.value);
          let needsFix = false;
          let fixedValue = '';
    
          parsed.walk((node) => {
            if (node.type === 'function' && node.value === 'var') {
              const varName = node.nodes[0]?.value || '';
              if (USER_VAR_RE.test(varName)) {
                // 判断是否已被 sanitize-css-var 包裹
                const parentFunc = node.parent;
                const isWrapped =
                  parentFunc &&
                  parentFunc.type === 'function' &&
                  parentFunc.value === 'sanitize-css-var';
    
                if (!isWrapped) {
                  if (context.fix) {
                    // 标记需要修复
                    needsFix = true;
                    // 把当前 var 节点替换成 sanitize-css-var(var(...))
                    const wrapper = valueParser({
                      type: 'function',
                      value: 'sanitize-css-var',
                      nodes: [node],
                    });
                    // 原地替换
                    const idx = parentFunc ? parentFunc.nodes.indexOf(node) : -1;
                    if (idx >= 0) parentFunc.nodes.splice(idx, 1, wrapper);
                  } else {
                    utils.report({
                      message: messages.expected(varName),
                      node: decl,
                      result,
                      ruleName,
                      word: varName,
                    });
                  }
                }
              }
            }
          });
    
          if (context.fix && needsFix) {
            decl.value = parsed.toString();
          }
        });
      };
    }
    
    rule.ruleName = ruleName;
    rule.messages = messages;
    module.exports = rule;
    
  3. 插件入口(lib/index.js)

    const sanitizeUserVar = require('./rules/sanitize-user-var');
    module.exports = [sanitizeUserVar];
    
  4. 单元测试(jest 示例节选)

    const { lint } = require('stylelint');
    test('reject bare --user-', async () => {
      const {
        results: [{ warnings }],
      } = await lint({
        code: 'a { color: var(--user-name); }',
        config: {
          plugins: ['./lib/index.js'],
          rules: { 'your-company/sanitize-user-var': true },
        },
      });
      expect(warnings).toHaveLength(1);
      expect(warnings[0].text).toContain('must be wrapped');
    });
    
    test('fix to wrapped', async () => {
      const { output } = await lint({
        code: 'a { color: var(--user-name); }',
        config: {
          plugins: ['./lib/index.js'],
          rules: { 'your-company/sanitize-user-var': true },
        },
        fix: true,
      });
      expect(output).toBe('a { color: sanitize-css-var(var(--user-name)); }');
    });
    
  5. 团队级配置(@your-company/stylelint-config-base/index.js)

    module.exports = {
      plugins: ['@your-company/stylelint-plugin-security'],
      rules: {
        'your-company/sanitize-user-var': true,
      },
    };
    
  6. 发布与集成

    • 私有源发布:
      npm publish --registry https://registry.your-company.cn
    • 项目侧 .stylelintrc.js
      module.exports = {
        extends: ['@your-company/stylelint-config-base'],
      };
      
    • CI 强制红线:
      npx stylelint "src/**/*.{css,scss,less}" --max-warnings 0

至此,任何包含 --user- 前缀的 CSS 变量若未经过 sanitize-css-var() 包裹,都会在开发阶段被实时标红,保存时自动修复,CI 阶段直接阻断合并,满足国内大厂对“安全左移”的硬性要求。

拓展思考

  1. 多前缀支持:把 USER_VAR_RE 做成数组可配,例如 --user-、--customer-,通过 secondaryOptions 传入,规则升级为 your-company/sanitize-var。
  2. 运行时 sanitize 函数注入:利用 Webpack 的 DefinePlugin 把 sanitize-css-var 在构建时替换成真正的 XSS 过滤实现,避免浏览器端再加载多余代码。
  3. 与 CSS Modules 结合:在 :export 块里如果导出 --user-* 变量,同样要校验;需要额外遍历 rule.selector === ':export'。
  4. 性能极致优化:对不含 var( 的文件做 postcss-plugin 级别短路,提前 return,在千文件级别 monorepo 中可节省 30% 时间。
  5. 规则复用到 Less/SCSS:由于 Stylelint 基于 PostCSS,变量语法一致,无需改动即可覆盖;但需注意 Sass 的 #{} 插值场景,可在正则里增加对 #{$var} 的否定预查,防止误杀。
  6. 安全审计闭环:在 GitLab MR 页面通过 stylelint-codequality-reporter 把错误转为 Code Climate JSON,GitLab 会直接在 diff 行高亮,实现“代码即审计”。

掌握以上延伸点,可在面试中从“写一条规则”进阶到“搭建企业级样式安全体系”,直接对标阿里、字节、美团等国内一线厂的技术标准。