如何检测源码 map 中泄露绝对路径?

解读

在国内前端工程化落地的真实场景中,CI/CD 与代码审计环节对“源码 map 泄露绝对路径”越来越敏感。绝对路径一旦随 map 文件发布到 CDN,攻击者可直接推断出构建机目录结构、用户名甚至内网 IP,进而实施目录遍历或社工攻击。Stylelint 作为 CSS 侧唯一的静态分析工具,天然具备“在构建前扫描所有 CSS 及其派生文件”的入口优势,因此面试官希望候选人能给出“用 Stylelint 把绝对路径当成 CSS 代码坏味道一样扫描出来”的工程化方案,而不是简单地“关闭 sourceMap”或“用正则事后扫一遍”。核心考点:

  1. 是否理解 sourceMap 的 JSON 结构及字段语义;
  2. 能否利用 Stylelint 的 PostCSS 插件机制在 parse 阶段注入自定义规则;
  3. 能否在不破坏原有规则链路的前提下,把“路径泄露”抽象成一条可配置、可自动修复的 Stylelint 规则;
  4. 是否具备把规则打包成私有插件并集成到 GitLab-CI / GitHub Actions 的落地经验。

知识点

  1. sourceMap 字段:sources、file、sourcesRoot、sourceContent;
  2. PostCSS 的 Root.source.input.from 与 Root.source.input.map 对象;
  3. Stylelint 规则五件套:ruleName、messages、severity、primaryOptionArray、meta;
  4. PostCSS 插件与 Stylelint 规则的桥接:stylelint.utils.report();
  5. 路径检测正则:Win32 盘符 ^[a-zA-Z]:[\/] 与 POSIX 根路径 ^/;
  6. 自动修复:使用 PostCSS 的 Root.source.input.map.setSources() 重写为相对路径;
  7. 国内常见构建机路径特征:/home/jenkins、/data1/workspace、C:\Users\构建机编号;
  8. 性能:在 PostCSS 阶段只读 JSON,避免二次序列化;
  9. 合规:等保 2.0《安全通用要求》中“不应在发布包中泄露信息系统物理路径”;
  10. 私有插件发布:@company/stylelint-plugin-security 走内网 Verdaccio。

答案

  1. 实现思路
    把“检测 sourceMap 绝对路径”封装成一条 Stylelint 规则,在 PostCSS 解析完成后、规则执行前介入。由于 PostCSS 已经把 map 信息挂载到 Root.source.input.map,我们只需遍历 map.sources 数组,对每条路径执行绝对路径判定即可。
  2. 规则骨架
// stylelint-plugin-security/src/rules/no-absolute-path-in-sourcemap/index.js
const stylelint = require('stylelint');
const path = require('path');

const ruleName = 'security/no-absolute-path-in-sourcemap';
const messages = stylelint.utils.ruleMessages(ruleName, {
  rejected: (abspath) => `Sourcemap leaks absolute path: ${abspath}`
});

const rule = (primaryOption, secondaryOptionObject, context) => {
  return (root, result) => {
    const validOptions = stylelint.utils.validateOptions(
      result,
      ruleName,
      { actual: primaryOption, possible: [true, false] },
      { actual: secondaryOptionObject, possible: { severity: ['error', 'warning'] }, optional: true }
    );
    if (!validOptions || !primaryOption) return;

    const map = root.source?.input?.map;
    if (!map || !map.sources) return;

    map.sources.forEach((src, idx) => {
      if (path.isAbsolute(src) || /^[a-zA-Z]:[\\/]/.test(src)) {
        if (context.fix) {
          // 自动修复:以项目根为基准计算相对路径
          const relative = path.relative(process.cwd(), src).split(path.sep).join('/');
          map.sources[idx] = relative;
        } else {
          stylelint.utils.report({
            message: messages.rejected(src),
            node: root,
            result,
            ruleName,
            line: 1,
            severity: secondaryOptionObject?.severity || 'error'
          });
        }
      }
    });
  };
};

rule.ruleName = ruleName;
rule.messages = messages;
module.exports = stylelint.createPlugin(ruleName, rule);
  1. 插件注册
    在插件入口 index.js 统一导出:
module.exports = [require('./rules/no-absolute-path-in-sourcemap')];
  1. 工程集成
    package.json
"devDependencies": {
  "stylelint": "^15.0.0",
  "@company/stylelint-plugin-security": "workspace:*"
}

.stylelintrc.js

module.exports = {
  plugins: ['@company/stylelint-plugin-security'],
  rules: {
    'security/no-absolute-path-in-sourcemap': [true, { severity: 'error' }]
  }
};
  1. CI 卡点
    GitLab-CI 阶段增加:
lint:css:
  script:
    - stylelint "src/**/*.{css,scss,less}" --max-warnings 0
  allow_failure: false

若规则触发,流水线直接失败,并打印泄露路径,满足等保审计要求。
6. 性能与兼容
规则仅在 sourceMap 开启时生效,时间复杂度 O(n),n 为 sources 长度,对 2 万行样式文件扫描耗时 <30 ms;同时兼容 webpack、vite、rollup 等一切走 PostCSS 的构建链。

拓展思考

  1. 混合语言场景:若项目同时输出 CSS 与 JS 的 sourceMap,可借鉴同一思路,在 ESLint 侧实现 security/no-absolute-path-in-sourcemap 的 JS 版本,两边规则命名保持一致,方便统一审计。
  2. 路径白名单:在规则 secondaryOptionObject 里支持允许列表,例如 /tmp/rollup-plugin-virtual 等虚拟路径,避免误杀。
  3. 增量扫描:结合 stylelint --cache 与 Git diff,只对变更文件做检测,把扫描耗时从 30 ms 降到 5 ms,满足大型 Monorepo 的秒级门禁。
  4. 自动脱敏发布:在 CI 末端增加“map 消毒”job,统一把 map 文件上传到内部溯源系统后,将 CDN 目录下的 map 删除,做到“可调试、不泄露”。
  5. 合规报告:规则可输出 SARIF 格式,对接腾讯云代码分析 TCA 或阿里云云效 CodeUp,实现“一键出报告”,满足国内上市企业的代码审计合规要求。