AST-Grep 代码安全与结构分析助手
---
name: ast-code-analysis-superpower
description: AST-based code pattern analysis using ast-grep for security, performance, and structural issues. Use when (1) reviewing code for security vulnerabilities, (2) analyzing React hook dependencies or performance patterns, (3) detecting structural anti-patterns across large codebases, (4) needing systematic pattern matching beyond manual inspection.
---
# AST-Grep 代码分析
AST 模式匹配通过结构识别而非逐行阅读来发现代码问题。代码结构能揭示表面检查遗漏的隐藏关系、漏洞和反模式。
## 配置
- **目标语言**:
- **分析重点**:
- **严重级别**:
- **框架**:
- **最大嵌套深度**:
## 前提条件
```bash
# Install ast-grep (if not available)
npm install -g @ast-grep/cli
# Or: mise install -g ast-grep
```
## 决策树:何时使用 AST 分析
```
Code review needed?
|
+-- Simple code (< lines, obvious structure) --> Manual review
|
+-- Complex code (nested, multi-file, abstraction layers)
|
+-- Security review required? --> Use security patterns
+-- Performance analysis? --> Use performance patterns
+-- Structural quality? --> Use structure patterns
+-- Cross-file patterns? --> Run with --include glob
```
## 模式类别
| 类别 | 重点 | 常见发现 |
|----------|-------|-----------------|
| 安全 | 加密函数、认证流程 | 硬编码密钥、弱令牌 |
| 性能 | Hook、循环、异步 | 无限重新渲染、内存泄漏 |
| 结构 | 嵌套、复杂度 | 深层条件判断、可维护性差 |
## 常用模式
### 安全:硬编码密钥
```yaml
# sg-rules/security/hardcoded-secrets.yml
id: hardcoded-secrets
language:
rule:
pattern: |
const $VAR = '$LITERAL';
$FUNC($VAR, ...)
meta:
severity:
message: "Potential hardcoded secret detected"
```
### 安全:不安全的令牌生成
```yaml
# sg-rules/security/insecure-tokens.yml
id: insecure-token-generation
language:
rule:
pattern: |
btoa(JSON.stringify($OBJ) + '.' + $SECRET)
meta:
severity:
message: "Insecure token generation using base64"
```
### 性能: Hook 依赖项
```yaml
# sg-rules/performance/react-hook-deps.yml
id: react-hook-dependency-array
language: typescript
rule:
pattern: |
useEffect(() => {
$BODY
}, [$FUNC])
meta:
severity: WARNING
message: "Function dependency may cause infinite re-renders"
```
### 结构:深层嵌套
```yaml
# sg-rules/structure/deep-nesting.yml
id: deep-nesting
language:
rule:
any:
- pattern: |
if ($COND1) {
if ($COND2) {
if ($COND3) {
$BODY
}
}
}
- pattern: |
for ($INIT) {
for ($INIT2) {
for ($INIT3) {
$BODY
}
}
}
meta:
severity: WARNING
message: "Deep nesting (> levels) - consider refactoring"
```
## 运行分析
```bash
# Security scan
ast-grep run -r sg-rules/security/
# Performance scan on files
ast-grep run -r sg-rules/performance/ --include="*.tsx,*.jsx"
# Full scan with JSON output
ast-grep run -r sg-rules/ --format=json > analysis-report.json
# Interactive mode for investigation
ast-grep run -r sg-rules/ --interactive
```
## 模式编写清单
- [ ] 模式匹配具体的反模式,而非一般代码
- [ ] 使用 `inside` 或 `has` 设置上下文约束
- [ ] 包含 `not` 约束以减少误报
- [ ] 按语言分别编写规则(JS 与 TS)
- [ ] 适当的严重级别(/WARNING/INFO)
## 常见错误
| 错误 | 症状 | 修复 |
|---------|---------|-----|
| 模式过于宽泛 | 误报很多 | 添加上下文约束 |
| 缺少 `inside` | 匹配到错误位置 | 用父级上下文限定范围 |
| 没有 `not` 子句 | 匹配到有效模式 | 排除已知的正确情况 |
| 在 TS 上使用 JS 模式 | 类型注解导致匹配失败 | 创建针对语言的规则 |
## 验证步骤
1. **测试模式准确性**:在已知存在漏洞的代码样本上运行
2. **检查误报率**:人工审查前 个匹配结果
3. **验证严重级别**:确认 级别的发现可以执行
4. **跨文件覆盖**:确认模式在预期范围内全部运行
## 输出示例
```
$ ast-grep run -r sg-rules/
src/components/UserProfile.jsx:15: [insecure-tokens] Insecure token generation
src/hooks/useAuth.js:8: [hardcoded-secrets] Potential hardcoded secret
src/components/Dashboard.tsx:23: WARNING [react-hook-deps] Function dependency
src/utils/processData.js:45: WARNING [deep-nesting] Deep nesting detected
Found 4 issues (2 errors, 2 warnings)
```
## 项目设置
```bash
# Initialize ast-grep in project
ast-grep init
# Create rule directories
mkdir -p sg-rules/{security,performance,structure}
# Add to CI pipeline
# .github/workflows/lint.yml
# - run: ast-grep run -r sg-rules/ --format=json
```
## 自定义模式模板
### 专用模式
```yaml
# Missing key in list rendering
id: missing-list-key
language: typescript
rule:
pattern: |
$ARRAY.map(($ITEM) => <$COMPONENT $$$PROPS />)
constraints:
$PROPS:
not:
has:
pattern: 'key={$_}'
meta:
severity: WARNING
message: "Missing key prop in list rendering"
```
### 异步/Await 模式
```yaml
# Missing error handling in async
id: unhandled-async
language:
rule:
pattern: |
async function $NAME($$$) {
$$$BODY
}
constraints:
$BODY:
not:
has:
pattern: 'try { $$$ } catch'
meta:
severity: WARNING
message: "Async function without try-catch error handling"
```
## 与 CI/CD 集成
```yaml
# GitHub Actions example
name: AST Analysis
on: [push, pull_request]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install ast-grep
run: npm install -g @ast-grep/cli
- name: Run analysis
run: |
ast-grep run -r sg-rules/ --format=json > report.json
if grep -q '"severity": ""' report.json; then
echo "Critical issues found!"
exit 1
fi
```