NPM audit fix陷入循环求助:react-scripts相关漏洞困境
React-Scripts 5.0.1 依赖漏洞修复疑难
我的package.json(已移除隐私数据)如下:
{ "dependencies": { "@fluentui/react": "^8.49.6", "@testing-library/react": "^12.1.2", "@testing-library/user-event": "^13.5.0", "@types/node": "^17.0.8", "@types/react": "^17.0.38", "@types/react-dom": "^17.0.11", "axios": "^0.24.0", "http-proxy-middleware": "^2.0.1", "prettier": "^2.5.1", "react": "^17.0.2", "react-scripts": "^5.0.1", "typescript": "^4.5.5", "web-vitals": "^2.1.3" }, "scripts": { "start": "HTTPS=true react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "lint": "eslint . --ext .tsx --ext .js" }, "devDependencies": { "@types/content-disposition": "^0.5.4", "@typescript-eslint/eslint-plugin": "^4.0.0", "@typescript-eslint/parser": "^4.33.0", "eslint": "^7.32.0", "eslint-config-standard": "^16.0.3", "eslint-plugin-import": "^2.25.4", "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^5.2.0", "eslint-plugin-react": "^7.28.0" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
之前用react-scripts 2.x.x版本时存在28个漏洞,升级到5.0.1后多数问题已修复,但现在遇到麻烦:运行npm audit fix --force会自动安装react-scripts@2.1.3(属于破坏性降级),反而产生69个新漏洞,且搞不清依赖层级关系,不知道该怎么正确修复。
相关审计信息:
fix available via `npm audit fix --force` Will install react-scripts@2.1.3, which is a breaking change node_modules/svgo/node_modules/nth-check css-select <=3.1.0 Depends on vulnerable versions of nth-check node_modules/svgo/node_modules/css-select svgo 1.0.0 - 1.3.2 Depends on vulnerable versions of css-select node_modules/svgo @svgr/plugin-svgo <=5.5.0 Depends on vulnerable versions of svgo node_modules/@svgr/plugin-svgo @svgr/webpack 4.0.0 - 5.5.0 Depends on vulnerable versions of @svgr/plugin-svgo node_modules/@svgr/webpack react-scripts >=2.1.4 Depends on vulnerable versions of @svgr/webpack node_modules/react-scripts
问题根源
漏洞并非来自react-scripts 5.0.1本身,而是其嵌套依赖链里的老旧包:
- react-scripts依赖
@svgr/webpack(版本范围4.0.0-5.5.0) @svgr/webpack依赖@svgr/plugin-svgo(<=5.5.0)@svgr/plugin-svgo依赖svgo(1.0.0-1.3.2)svgo依赖css-select(<=3.1.0)css-select依赖存在漏洞的nth-check版本
npm audit fix --force的逻辑是降级react-scripts到2.1.3来规避嵌套依赖,完全是舍本逐末,反而引入更多漏洞。
修复方案
1. 禁止使用npm audit fix --force
这个命令会强制执行破坏性变更,直接弃用。
2. 用npm overrides强制升级嵌套依赖
npm 8.3及以上版本支持overrides字段,可强制替换整个依赖树里的指定包版本,无需降级主依赖。
在package.json中添加以下内容:
"overrides": { "nth-check": "^2.0.1", "css-select": "^4.1.3", "svgo": "^2.8.0", "@svgr/plugin-svgo": "^6.5.1", "@svgr/webpack": "^6.5.1" }
添加后运行npm install,npm会自动将所有嵌套依赖中的对应包升级到指定安全版本。
3. 验证修复效果
运行npm audit检查漏洞是否修复,或用npm ls nth-check查看该包实际版本是否为2.0.1及以上。
4. 备选方案:用yarn resolutions(若切换到yarn)
如果使用yarn包管理器,可在package.json中添加resolutions字段实现同样效果:
"resolutions": { "nth-check": "^2.0.1", "css-select": "^4.1.3", "svgo": "^2.8.0", "@svgr/plugin-svgo": "^6.5.1", "@svgr/webpack": "^6.5.1" }
然后运行yarn install即可。
内容的提问来源于stack exchange,提问作者alphadmon
相关产品推荐
相关产品推荐

