# 最佳实践
基于 Lighthouse 最佳实践审计的现代 Web 开发标准。涵盖安全性、浏览器兼容性和代码质量模式。
## 安全性
### 全站 HTTPS
**强制 HTTPS:**
html

**HSTS 响应头:**
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
### 内容安全策略 (CSP)
html
**CSP 响应头 (推荐):**
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-abc123' https://trusted.com;
style-src 'self' 'nonce-abc123';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
frame-ancestors 'self';
base-uri 'self';
form-action 'self';
**为内联脚本使用 nonce:**
html
// 此内联脚本被允许
### 安全响应头
# 防止点击劫持
X-Frame-Options: DENY
# 防止 MIME 类型嗅探
X-Content-Type-Options: nosniff
# 启用 XSS 过滤器 (旧版浏览器)
X-XSS-Protection: 1; mode=block
# 控制 Referrer 信息
Referrer-Policy: strict-origin-when-cross-origin
# 权限策略 (原 Feature-Policy)
Permissions-Policy: geolocation=(), microphone=(), camera=()
### 避免使用有漏洞的库
bash
# 检查漏洞
npm audit
yarn audit
# 尽可能自动修复
npm audit fix
# 检查特定包
npm ls lodash
**保持依赖更新:**
// package.json
{
"scripts": {
"audit": "npm audit --audit-level=moderate",
"update": "npm update && npm audit fix"
}
}
**应避免的已知漏洞模式:**
javascript
// ❌ 原型污染漏洞模式
Object.assign(target, userInput);
_.merge(target, userInput);
// ✅ 更安全的替代方案
const safeData = JSON.parse(JSON.stringify(userInput));