如何扫描注释中的 192.168.x.x 地址?
解读
在国内前端团队的代码审查流程里,经常要求“上线前必须清理内网 IP、测试域名等敏感信息”。Stylelint 作为样式静态分析工具,本身只识别 CSS 语法节点,而注释(/* … */)在 PostCSS 解析后属于 Comment 节点,并不受常规“声明-值”规则约束。因此,要“扫注释里的 192.168.x.x”,必须:
- 自定义一条 Stylelint 规则(plugin),监听 Comment 节点;
- 用正则精准匹配私有网段(192.168.0.0/16);
- 给出可一键 autofix 的修复方案(替换成占位符或空串);
- 把插件打包进公司私有 preset,在 VS Code / GitLab CI 中零配置生效。
面试时,考官不仅看“能不能写正则”,更关注“你对 PostCSS AST 的理解、对 Stylelint 插件生命周期的掌握、对国内安全合规流程的落地经验”。
知识点
- PostCSS AST 节点类型:Root、Rule、Decl、Comment
- Stylelint 插件范式:
stylelint.createPlugin(ruleName, (primaryOption, secondaryOption) => (root, result) => { … }) - 遍历注释的两种写法:
①root.walkComments(node => …)
② 直接监听Comment事件 - 正则匹配 192.168.0.0/16:
/\b192\.168(?:\.\d{1,3}){2}\b/g - 报告违规:
stylelint.utils.report({ message, node, result, ruleName }) - 提供自动修复:
在node.text = node.text.replace(...)后调用stylelint.utils.validateOptions并开启context.fix分支 - 国内合规场景:
代码上线前通过 git-hooks + husky + lint-staged 强制运行 stylelint,阻断含内网 IP 的 MR;同时把插件发布到私有 npm(verdaccio),避免外泄
答案
- 初始化插件文件
stylelint-plugin-no-private-ip/index.js
const stylelint = require('stylelint');
const ruleName = 'plugin/no-private-ip';
const messages = stylelint.utils.ruleMessages(ruleName, {
rejected: ip => `Comment contains private IP ${ip}, please remove before merge`
});
const privateIpRE = /\b192\.168(?:\.\d{1,3}){2}\b/g;
module.exports = stylelint.createPlugin(ruleName, (primary, _, context) => {
return (root, result) => {
root.walkComments(comment => {
const matches = comment.text.match(privateIpRE);
if (!matches) return;
if (context.fix) {
comment.text = comment.text.replace(privateIpRE, '<PRIVATE_IP>');
return;
}
matches.forEach(ip => {
stylelint.utils.report({
message: messages.rejected(ip),
node: comment,
result,
ruleName,
line: comment.source.start.line,
column: comment.source.start.column
});
});
});
};
});
module.exports.ruleName = ruleName;
- 在
.stylelintrc.js中启用
module.exports = {
plugins: ['./stylelint-plugin-no-private-ip'],
rules: {
'plugin/no-private-ip': [true, { severity: 'error' }]
}
};
- 验证
/* 192.168.3.21 测试环境地址 */
运行 npx stylelint src/**/*.scss 会立即报错,并提示行号;加 --fix 后自动变成
/* <PRIVATE_IP> 测试环境地址 */
- 集成到国内 CI
在.gitlab-ci.yml里加:
lint:
script:
- npm i --production=false
- npx stylelint 'src/**/*.{css,scss,less}' --max-warnings 0
only:
- merge_requests
若检测失败,MR 无法合并,符合国内“代码安全红线”要求。
拓展思考
- 范围扩大:把 10.0.0.0/8、172.16.0.0/12、localhost、*.local、内网域名也纳入扫描,只需扩展正则与提示语
- 性能优化:对超大型仓库(上万文件)可采用 stylelint 的
cache: true并结合eslint-nibble思路,增量扫描 - 低侵入方案:如果团队已使用 stylelint-config-standard,可把插件做成独立包
@company/stylelint-config-security,通过 extends 一键继承,避免每个项目重复配置 - 与 Secret-Scan 工具互补:样式里虽然极少出现密钥,但同一套思路可移植到
eslint-plugin-no-secret,实现前端代码全域安全扫描 - 法规落地:国内《网络安全法》《数据安全法》要求“上线前敏感信息清理”,把这条 Stylelint 规则纳入“代码质量门禁”,可直接作为审计证据,降低公司合规风险