Dependency & Supply Chain Security
依赖与供应链安全
Your application includes hundreds of npm packages. Each one is code written by someone else that runs in your application with full privileges.
你的应用包含数百个npm包,每个包都是第三方编写的代码,会以完全权限在你的应用中运行。
The Statistics Are Sobering
相关统计数据值得警惕
According to Sonatype's 2024 State of the Software Supply Chain Report:
- 245,000 malicious packages published to npm (2023)
- 700% increase in supply chain attacks (vs 2022)
- Average application has 200+ dependencies
- Each dependency averages 5 transitive dependencies (dependencies of dependencies)
根据Sonatype 2024年软件供应链现状报告:
- 2023年npm平台共发布24.5万个恶意包
- 供应链攻击数量较2022年增长700%
- 平均每个应用有200+个直接依赖
- 每个直接依赖平均有5个传递性依赖(即依赖的依赖)
Real-World Supply Chain Attacks
真实供应链攻击案例
event-stream Incident (2018):
A popular npm package (2 million downloads/week) was hijacked. The attacker added code that stole cryptocurrency wallet keys. Thousands of applications were affected before discovery.
ua-parser-js Incident (2021):
Package with 8 million weekly downloads was compromised. Attackers added cryptocurrency mining and password-stealing code.
colors.js / faker.js Incident (2022):
Maintainer intentionally corrupted packages in protest. Millions of applications broke. Demonstrated single-point-of-failure risk.
event-stream事件(2018年):
这款周下载量200万的热门npm包被劫持,攻击者添加了窃取加密货币钱包密钥的代码,在被发现前已有数千个应用受到影响。
ua-parser-js事件(2021年):
这款周下载量800万的包被入侵,攻击者添加了加密货币挖矿和密码窃取代码。
colors.js / faker.js事件(2022年):
维护者为抗议故意破坏包代码,导致数百万个应用崩溃,暴露了单点故障风险。
Our Dependency Security Architecture
我们的依赖安全架构
- ✅ All dependencies up-to-date
- ✅ Next.js 15.5.4 (latest stable)
- ✅ 0 known vulnerabilities (npm audit)
- ✅ Package-lock.json committed (reproducible builds)
- ✅ 所有依赖均为最新版本
- ✅ 使用Next.js 15.5.4(最新稳定版)
- ✅ 0已知漏洞(npm audit检测结果)
- ✅ 已提交Package-lock.json(支持可复现构建)
Why Next.js 15.5.4 Specifically
为何特意使用Next.js 15.5.4
We updated from 15.3.5 to 15.5.4 to fix three security vulnerabilities:
- Cache Key Confusion (moderate)
- Content Injection (moderate)
- SSRF via Middleware Redirects (moderate)
Keeping frameworks updated is critical. According to Snyk's research, 80% of vulnerabilities have patches available within days, but average time to patch is 148 days.
我们从15.3.5升级到15.5.4是为了修复3个安全漏洞:
- 缓存键混淆(中危)
- 内容注入(中危)
- 中间件重定向导致的SSRF(中危)
保持框架更新至关重要。 根据Snyk的研究,80%的漏洞会在几天内推出补丁,但企业平均修复时间长达148天。
scripts/security-check.sh
- Runs npm audit + shows outdated packages
- - Locks exact versions (supply chain consistency)
scripts/security-check.sh
- 运行npm audit并展示过期包
- - 锁定精确版本(保障供应链一致性)
Running Security Audits
运行安全审计
Check for vulnerabilities
检查漏洞
- Severity (critical, high, moderate, low)
- 严重等级(Critical、High、Moderate、Low)
- Vulnerability description
- 漏洞描述
- Affected package
- 受影响的包
- Recommended fix
- 推荐修复方案
Production-Only Audit
仅生产环境审计
Only check production dependencies (ignores devDependencies)
仅检查生产依赖(忽略devDependencies)
npm audit --production
**Use this before every production deploy.** Must show: **0 vulnerabilities**
npm audit --production
**每次生产环境部署前必须运行本命令,输出必须显示:0 vulnerabilities**
Automated Security Check Script
自动化安全检查脚本
Run our comprehensive security check
运行我们的综合安全检查
bash scripts/security-check.sh
**What it does:**
1. Runs `npm audit` (shows vulnerabilities)
2. Runs `npm outdated` (shows outdated packages)
3. Provides fix commands
**Expected output:**
=== Security Audit ===
found 0 vulnerabilities
=== Outdated Packages ===
Package Current Wanted Latest Location
next 15.5.4 15.5.4 15.5.4 node_modules/next
✓ All packages up to date!
bash scripts/security-check.sh
**脚本功能:**
1. 运行`npm audit`(展示漏洞)
2. 运行`npm outdated`(展示过期包)
3. 提供修复命令
**预期输出:**
=== Security Audit ===
found 0 vulnerabilities
=== Outdated Packages ===
Package Current Wanted Latest Location
next 15.5.4 15.5.4 15.5.4 node_modules/next
✓ All packages up to date!
Fixing Vulnerabilities
漏洞修复
Automatic Fixes (Safe)
自动修复(安全)
Fix vulnerabilities with patch/minor version updates
通过补丁/次版本更新修复漏洞
npm audit fix
**What it does:**
- Updates to latest patch version (e.g., 1.2.3 → 1.2.4)
- Updates to latest minor version (e.g., 1.2.3 → 1.3.0)
- **Safe:** No breaking changes
npm audit fix
**功能说明:**
- 更新到最新补丁版本(例如1.2.3 → 1.2.4)
- 更新到最新次版本(例如1.2.3 → 1.3.0)
- **安全:不会引入破坏性变更**
Force Fixes (Risky)
强制修复(高风险)
Fix vulnerabilities with major version updates
通过主版本更新修复漏洞
npm audit fix --force
⚠️ **WARNING:** This can introduce breaking changes!
**What it does:**
- Updates to latest major version (e.g., 1.2.3 → 2.0.0)
- **May break your code** if API changed
**After running --force:**
1. Check what changed: `git diff package.json package-lock.json`
2. Read migration guides for updated packages
3. Run tests: `npm test`
4. Test app manually
5. Commit only if everything works
npm audit fix --force
⚠️ **警告:这可能引入破坏性变更!**
**功能说明:**
- 更新到最新主版本(例如1.2.3 → 2.0.0)
- 如果API发生变化**可能导致代码崩溃**
**运行--force后必须:**
1. 检查变更:`git diff package.json package-lock.json`
2. 阅读更新包的迁移指南
3. 运行测试:`npm test`
4. 手动测试应用功能
5. 确认所有功能正常后再提交代码
Update specific package
更新指定包
Update to specific version
更新到指定版本
npm install package-name@1.2.3
npm install package-name@1.2.3
Update all packages to latest (respecting semver)
按语义化版本规则更新所有包到最新版本
Dependency Update Strategy
依赖更新策略
Monthly Routine (30 minutes)
月度例行更新(30分钟)
1. Check for outdated packages
1. 检查过期包
2. Review what's outdated and why
2. 审核过期包信息及更新原因
Check changelogs for major updates
查阅大版本更新的变更日志
3. Update safe packages (patch/minor)
3. 更新安全的包(补丁/次版本)
5. Fix vulnerabilities
5. 修复漏洞
6. Test everything
6. 测试所有功能
7. Commit if successful
7. 运行成功后提交代码
git add package.json package-lock.json
git commit -m "chore: update dependencies"
git add package.json package-lock.json
git commit -m "chore: update dependencies"
Before Every Production Deploy
每次生产部署前
Must show 0 vulnerabilities
必须输出0漏洞
npm audit --production
**If vulnerabilities found:**
1. Run `npm audit fix`
2. Test thoroughly
3. If fix causes issues, investigate package alternatives
4. **Never deploy with known vulnerabilities**
npm audit --production
**如果发现漏洞:**
1. 运行`npm audit fix`
2. 全面测试
3. 如果修复导致问题,调研替代包
4. **绝对不要带着已知漏洞部署**
Major Framework Updates (Quarterly)
框架大版本更新(季度)
When Next.js releases major update (e.g., 15.x → 16.x):
当Next.js发布大版本更新时(例如15.x → 16.x):
1. Read upgrade guide
1. 阅读升级指南
2. Create new branch
2. 创建新分支
git checkout -b upgrade-nextjs-16
git checkout -b upgrade-nextjs-16
3. Update Next.js
3. 更新Next.js
npm install next@latest react@latest react-dom@latest
npm install next@latest react@latest react-dom@latest
4. Follow migration guide
4. 遵循迁移指南操作
Update deprecated APIs
更新废弃API
5. Run full test suite
5. 运行完整测试套件
npm test
npm run build
npm run lint
npm test
npm run build
npm run lint
Click through all features
点击测试所有功能点
7. Deploy to staging first
7. 先部署到预发环境
Test in production-like environment
在类生产环境测试
8. If successful, deploy to production
8. 测试通过后部署到生产环境
Preventing Supply Chain Attacks
防范供应链攻击
1. Package-lock.json (Always Commit)
1. 始终提交Package-lock.json
Package-lock.json ensures:
Package-lock.json保障:
- Exact versions installed
- 安装精确版本的包
- Reproducible builds
- 可复现构建
- Detect tampering
- 可检测篡改
✅ **DO commit package-lock.json to git**
❌ **DON'T add package-lock.json to .gitignore**
✅ **必须将package-lock.json提交到git**
❌ **不要将package-lock.json加入.gitignore**
2. Verify Package Integrity
2. 验证包完整性
npm automatically verifies package integrity using
npm会自动使用package-lock.json中的校验和
checksums from package-lock.json
验证包的完整性
If integrity check fails:
如果完整性校验失败,会输出:
Error: integrity checksum failed
Error: integrity checksum failed
**This protects against:**
- Tampered packages on npm registry
- Man-in-the-middle attacks during download
- Corrupted packages
**可防范:**
- npm registry上被篡改的包
- 下载过程中的中间人攻击
- 损坏的包
3. Audit New Packages Before Installing
3. 安装新包前先审计
Before adding a new package:
-
- Weekly downloads (popular = more vetted)
- Last update date (recently maintained?)
- Number of dependents (widely used?)
- GitHub stars/issues
-
Check for typosquatting:
- ✅ (correct)
- ❌ (typo package - could be malicious)
- ❌ (typo package - could be malicious)
-
Check package maintainers:
- Look for verified maintainers
- Check GitHub profile
- Multiple maintainers = better
-
Check GitHub:
- Stars (popularity indicator)
- Open issues (maintained?)
- Recent commits
- Code quality
-
Run audit after installing:
bash
npm install new-package
npm audit
添加新包前必须:
-
- 周下载量(下载量越高说明经过更多验证)
- 最近更新日期(是否仍在维护?)
- 依赖方数量(是否被广泛使用?)
- GitHub星数/Issue情况
-
检查是否是抢注恶意包:
- ✅(正确)
- ❌(拼写错误的包,可能是恶意包)
- ❌(拼写错误的包,可能是恶意包)
-
检查包维护者:
- 优先选择经过验证的维护者
- 检查维护者的GitHub资料
- 多个维护者更安全
-
检查GitHub仓库:
- 星数(流行度指标)
- 开放Issue数量(是否仍在维护?)
- 最近提交记录
- 代码质量
-
安装后运行审计:
bash
npm install new-package
npm audit
4. Use npm ci for Clean Installs
4. 在CI/CD中使用npm ci进行干净安装
In CI/CD pipelines, use:
在CI/CD流水线中使用:
npm install
**Why `npm ci`:**
- Installs from package-lock.json exactly
- Fails if package.json and package-lock.json are out of sync
- Removes node_modules before installing
- Faster and more reliable for CI/CD
npm install
**使用`npm ci`的原因:**
- 完全按照package-lock.json的版本安装
- 如果package.json和package-lock.json不同步会直接失败
- 安装前会删除node_modules
- 对CI/CD来说更快更可靠
5. Avoid Dangerous Packages
5. 避免使用危险包
Never install packages that:
- Have very low download counts (< 100/week)
- Were just published (wait a few weeks)
- Have suspicious names (typosquatting)
- Request unusual permissions
- Have no source code visible
Examples of dangerous packages (real incidents):
- (typo of - was malicious)
- (typo of - was malicious)
- (typo of - was malicious)
绝对不要安装符合以下特征的包:
- 下载量极低(周下载量<100)
- 刚发布不久(建议等待几周再使用)
- 名称可疑(拼写抢注)
- 要求异常权限
- 没有公开源代码
危险包真实案例:
- (的拼写错误包,为恶意包)
- (的拼写错误包,为恶意包)
- (的拼写错误包,为恶意包)
Dependency Confusion Attacks
依赖混淆攻击
Attacker publishes malicious package with same name as your internal package. npm might install malicious one instead.
攻击者发布和你内部包同名的恶意包,npm可能会优先安装恶意版本。
Internal package (not on npm)
内部包(未发布到npm公共库)
"@mycompany/auth": "1.0.0"
"@mycompany/auth": "1.0.0"
Attacker publishes to npm
攻击者发布到npm公共库
"@mycompany/auth": "99.0.0"
"@mycompany/auth": "99.0.0"
npm might install attacker's version!
npm可能会安装攻击者的版本!
-
Use scoped packages for internal packages:
json
{
"name": "@mycompany/internal-package"
}
-
Configure npm to only use internal registry for your scope:
bash
# .npmrc
@mycompany:registry=https://npm.mycompany.com
-
Don't publish internal packages to public npm
-
内部包使用作用域命名:
json
{
"name": "@mycompany/internal-package"
}
-
配置npm仅从内部 registry 拉取你的作用域包:
bash
# .npmrc
@mycompany:registry=https://npm.mycompany.com
-
不要将内部包发布到公共npm库
Scripts/security-check.sh
Scripts/security-check.sh
bash
#!/bin/bash
echo "================================="
echo "Security & Dependency Check"
echo "================================="
echo ""
echo "=== Security Audit ==="
npm audit --production
echo ""
echo "=== Outdated Packages ==="
npm outdated
echo ""
echo "================================="
echo "To fix vulnerabilities:"
echo " npm audit fix (safe patch/minor updates)"
echo " npm audit fix --force (risky major updates)"
echo ""
echo "To update outdated packages:"
echo " npm update (respects semver)"
echo " npm update package-name (specific package)"
echo "================================="
bash
#!/bin/bash
echo "================================="
echo "Security & Dependency Check"
echo "================================="
echo ""
echo "=== Security Audit ==="
npm audit --production
echo ""
echo "=== Outdated Packages ==="
npm outdated
echo ""
echo "================================="
echo "To fix vulnerabilities:"
echo " npm audit fix (safe patch/minor updates)"
echo " npm audit fix --force (risky major updates)"
echo ""
echo "To update outdated packages:"
echo " npm update (respects semver)"
echo " npm update package-name (specific package)"
echo "================================="
Using Snyk for Enhanced Security
使用Snyk增强安全能力
Scan for Vulnerabilities
漏洞扫描
Monitor project (continuous monitoring)
监控项目(持续监控)
Test specific package before installing
安装前测试指定包
.github/workflows/security.yml
.github/workflows/security.yml
name: Security Audit
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
schedule:
# Run daily at 2am
- cron: '0 2 * * *'
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run npm audit
run: npm audit --production
- name: Check for outdated packages
run: npm outdated || true
- name: Run Snyk test
run: npx snyk test --severity-threshold=high
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
name: Security Audit
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
schedule:
# 每天凌晨2点运行
- cron: '0 2 * * *'
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run npm audit
run: npm audit --production
- name: Check for outdated packages
run: npm outdated || true
- name: Run Snyk test
run: npx snyk test --severity-threshold=high
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
Monitoring for New Vulnerabilities
新漏洞监控
GitHub Dependabot
GitHub Dependabot
Enable in GitHub:
- Go to repository Settings
- Security & analysis
- Enable "Dependabot alerts"
- Enable "Dependabot security updates"
What it does:
- Scans dependencies daily
- Creates PR when vulnerability found
- Automatically updates to fix version
- You review and merge
在GitHub中开启:
- 进入仓库设置页面
- 找到安全与分析板块
- 开启“Dependabot alerts”
- 开启“Dependabot security updates”
功能说明:
- 每日扫描依赖
- 发现漏洞时自动创建PR
- 自动更新到修复版本
- 你只需审核合并即可
npm Audit in CI/CD
CI/CD中集成npm Audit
Add to CI/CD pipeline
加入CI/CD流水线
npm audit --production --audit-level=moderate
**Fails build if:**
- Any moderate or higher vulnerabilities found
- Forces you to fix before deploy
npm audit --production --audit-level=moderate
**触发构建失败的条件:**
- 发现任何中危及以上漏洞
- 强制你在部署前修复
What Dependency Security Prevents
依赖安全的防护范围
✅ Known vulnerability exploitation - Regular audits catch CVEs
✅ Malicious package injection - Verification prevents tampering
✅ Supply chain attacks - Package-lock.json + verification
✅ Dependency confusion - Scoped packages + registry config
✅ Typosquatting attacks - Manual verification before install
✅ Outdated vulnerable code - Regular update routine
✅ Zero-day exploitation window - Fast patching reduces risk
✅ 已知漏洞利用 - 定期审计可捕获CVE漏洞
✅ 恶意包注入 - 完整性校验可防范篡改
✅ 供应链攻击 - Package-lock.json+完整性校验双重防护
✅ 依赖混淆 - 作用域包+registry配置防护
✅ 拼写抢注攻击 - 安装前人工校验防护
✅ 过期漏洞代码 - 定期更新机制防护
✅ 零日漏洞利用窗口 - 快速补丁降低风险
Common Mistakes to Avoid
要避免的常见错误
❌ DON'T ignore npm audit warnings
❌ DON'T use deprecated packages
❌ DON'T skip testing after dependency updates
❌ DON'T add package-lock.json to .gitignore
❌ DON'T install packages without checking them first
❌ DON'T run npm audit fix --force without testing
✅ DO run npm audit before every deploy
✅ DO commit package-lock.json
✅ DO verify new packages before installing
✅ DO update dependencies monthly
✅ DO enable Dependabot alerts
✅ DO use npm ci in CI/CD
❌ 不要忽略npm audit警告
❌ 不要使用已废弃的包
❌ 依赖更新后不要跳过测试
❌ 不要将package-lock.json加入.gitignore
❌ 不要未经检查就安装包
❌ 不要未经测试就运行npm audit fix --force
✅ 每次部署前必须运行npm audit
✅ 必须提交package-lock.json
✅ 安装新包前必须验证
✅ 每月必须更新依赖
✅ 必须开启Dependabot告警
✅ CI/CD中必须使用npm ci
Quick Reference Commands
快速参考命令
Check for vulnerabilities
检查漏洞
npm audit
npm audit --production
npm audit
npm audit --production
npm audit fix # Safe
npm audit fix --force # Risky, test thoroughly
npm audit fix # 安全
npm audit fix --force # 高风险,需全面测试
Check outdated packages
检查过期包
npm update # All packages
npm update package-name # Specific package
npm update # 所有包
npm update package-name # 指定包
Install from lock file (CI/CD)
从锁文件安装(CI/CD用)
Run security check script
运行安全检查脚本
bash scripts/security-check.sh
bash scripts/security-check.sh
- For pre-deployment checks: Use skill
- For CI/CD integration: Add npm audit to pipeline
- For monitoring: Enable GitHub Dependabot alerts
- For enhanced scanning: Install Snyk
- 部署前检查:使用技能
- CI/CD集成:将npm audit加入流水线
- 监控:开启GitHub Dependabot告警
- 增强扫描:安装Snyk