Skill: sihan2017/business-api-recorder (version 1.0.0)

# Business API Recorder 通过Chrome扩展控制浏览器，打开目标系统网址，分析业务场景并完整记录API调用，为AI重构生成完整实现文档。 --- **作者**: 周坚 **邮箱**: [REDACTED_SECRET] **版本**: 1.0.0 **许可证**: MIT --- ## 适用场景 - 分析内部办公系统的业务流程 - 记录业务表单的完整API调用链 - 为AI重构业务功能获取真实接口数据 - 生成API接口文档和数据字典 - 探索系统的安全边界和运行机制 ## 效果预览 完成一次业务分析后，将输出： 1. **API调用日志** - 完整的请求/响应记录（JSON格式） 2. **完整实现文档** - 按模板生成，包含： - 业务流程（主流程 + 分支场景） - API接口清单（请求/响应参数） - 数据字典（枚举值、树形结构） - 业务规则（验证约束） - 前端实现要点 - 错误处理 - 参考示例 - 抓包日志样本 这些文档可以直接用于AI重构该业务功能。

path: DOCUMENT_TEMPLATE.md
content: # Business API Recorder - 文档生成模板

API分析完成后，按照此模板生成完整实现文档，供AI重构使用。

---

# [标题] - 完整实现文档

[前言/背景介绍]

---

## 1. 业务流程

### 1.1 主流程

[Mermaid流程图或步骤描述]

```
[主要业务流程步骤]
  ↓
[关键决策点1]
  ├─ → 分支A
  └─ → 分支B
  ↓
[关键决策点2]
  └─ → [后续流程]
```

### 1.2 分支场景

#### 分支1: [分支名称]
- **条件**: [触发条件]
- **影响**:
  - 字段变化1
  - 字段变化2
- **API验证**: [涉及的API调用]

#### 分支2: [分支名称]
- **条件**: [触发条件]
- **影响**:
  - 字段变化1
- **审批影响**: [对审批流程的影响]

(更多分支...)

---

## 2. API接口清单

### 2.[序号] [API名称]
**接口**: `[METHOD] /api/path`

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `param1` | string | 是 | 参数说明 |
| `param2` | number | 否 | 参数说明 |

#### 请求字段

```typescript
interface RequestType {
  field1: string;        // 字段1说明
  field2?: number;       // 字段2说明（可选）
  nested: {
    subField: string;   // 嵌套字段
  };
}
```

#### 响应字段

```json
{
  "code": "0",
  "msg": "操作成功",
  "data": [
    {
      "id": "xxx",
      "name": "xxx"
    }
  ]
}
```

(更多API...)

---

## 3. 数据字典

### 3.1 枚举值

#### 枚举1名称

```typescript
enum EnumName {
  VALUE1 = "key1",  // 说明
  VALUE2 = "key2"   // 说明
};
```

### 3.2 树形结构

```
顶层分类
├── 一级分类1
│   ├── 二级分类1
│   └── 二级分类2
├── 一级分类2
└── ...
```

---

## 4. 业务规则

### 4.1 必填验证规则

| 字段 | 必填 | 验证规则 |
|------|------|----------|
| field1 | ✅ | 规则1 |
| field2 | ⚠️ | 规则2（某些条件下可选） |

### 4.2 业务约束

1. **约束1**: [说明]

2. **约束2**: [说明]

---

## 5. 状态流转

### 5.1 [实体名称] 状态

| 状态 | 说明 |
|------|------|
| STATE1 | 说明1 |
| STATE2 | 说明2 |

### 5.2 [实体名称] 状态

(同上格式)

---

## 6. 常量配置

### 6.1 系统配置项

| 配置Key | 说明 | 典型值 |
|---------|------|--------|
| CONFIG_KEY_1 | 配置1说明 | "value1" |
| CONFIG_KEY_2 | 配置2说明 | "value2" |

### 6.2 响应状态码

| Code | 说明 |
|------|------|
| "0" | 操作成功 |
| "ERROR_CODE" | 错误说明 |

---

## 7. 前端实现要点

### 7.1 级联联动规则

| 触发字段 | 影响 | API调用 |
|---------|------|---------|
| field1 | 自动填充field2 | api-call-1 |
| field2 | 自动填充field3 | api-call-2 |

### 7.2 表单数据格式

**金额字段**:
- 显示：元，2位小数
- 提交：分，整数

**日期字段**:
- 显示：YYYY-MM-DD
- 提交：字符串

**比例字段**:
- 显示/提交：0-100整数

---

## 8. 错误处理

### 8.1 常见错误场景

| 错误场景 | API | 处理方式 |
|---------|-----|---------|
| 场景1 | api-name | 提示用户xxx |
| 场景2 | api-name | 提示用户xxx |

### 8.2 错误响应格式

```json
{
  "code": "ERROR_CODE",
  "msg": "错误描述",
  "data": null
}
```

---

## 9. 实现检查清单

- [ ] 功能点1
- [ ] 功能点2
- [ ] 功能点3
- [ ] ...

---

## 10. 参考示例

### 10.1 场景1: [场景名称]

```
输入：
- 参数1: 值1
- 参数2: 值2

提交数据：
{
  "field1": "value1",
  "field2": "value2"
}
```

### 10.2 场景2: [场景名称]

(同上格式)

(更多场景...)

---

## 11. 附录

### 11.1 抓包日志样本

完整的网络请求样本位置：`output/[任务名]-api-log.json`

### 11.2 其他参考资料

[相关文档链接或说明]

---

## 12. 补充说明

[其他需要补充的重要信息]

path: README.md
content: # Business API Recorder

> 通过Chrome扩展自动拦截浏览器API，分析业务流程并生成完整的AI重构文档。

---

## 📦 Meta Information

| Field | Value |
|-------|-------|
| **Name** | `business-api-recorder` |
| **Version** | `1.0.0` |
| **Description** | 通过Chrome扩展控制浏览器，自动拦截并分析 Web 应用的 API 调用，生成完整的业务文档和接口清单 |
| **Author** | 周坚 `[REDACTED_SECRET]` |
| **License** | MIT |
| **Homepage** | https://github.com/[your-repo]/business-api-recorder |
| **Keywords** | `api-recorder`, `browser-automation`, `api-documentation`, `business-analysis`, `chrome-extension`, `network-monitoring` |
| **Category** | Developer Tools / API Documentation |

---

## ⚙️ Dependencies

### Required Dependencies

| Dependency | Version | Description |
|------------|---------|-------------|
| OpenClaw CLI | Latest | AI agent orchestration platform - https://docs.openclaw.ai |
| Chrome Extension | Latest | Browser extension for Chrome DevTools Protocol control - https://docs.openclaw.ai/tools/chrome-extension |

### OpenClaw Capabilities

This skill requires the following OpenClaw capabilities:
- `browser` - Control Chrome browser via extension
- `write` - Save analysis results
- `exec` - Run shell commands

---

## 🎯 Use Cases

- ✅ 实时拦截浏览器的 fetch/XMLHttpRequest
- ✅ 记录完整的请求/响应日志
- ✅ 分析业务流程和分支场景
- ✅ 生成 12-chapter implementation document for AI
- ✅ 创建 API inventory and data dictionary
- ✅ Capture data relationships and validation rules

---

## 🚀 Quick Start

### 1. Install OpenClaw

```bash
# Install via official installer
curl -sSL https://install.openclaw.ai | sh

# Or visit https://docs.openclaw.ai for detailed instructions
```

### 2. Install Chrome Extension

```bash
# Install to local machine
openclaw browser extension install

# View extension path
openclaw browser extension path

# Expected output:
# ~/.openclaw/browser-extensions/openclaw-relay/
```

Then in Chrome:
1. Open `chrome://extensions`
2. Enable "Developer mode"
3. Click "Load unpacked" and select the extension directory
4. Configure: Port=`18792`, Gateway Token=`<your-OPENCLAW_GATEWAY_TOKEN>`

### 3. Start Recording

Login to your target system in Chrome, click the OpenClaw extension icon (Badge `ON`), then in your OpenClaw agent:

```python
# 1. Check browser connection
browser(action="tabs", profile="chrome")

# 2. Inject monitoring script
browser(action="act", kind="evaluate", profile="chrome", fn="<从 get-monitor.sh 获取的脚本>")

# 3. Execute business operations...

# 4. Export API logs
browser(action="act", kind="evaluate", profile="chrome", fn="JSON.stringify(window.__OPENCLAW_NETWORK_LOG__, null, 2)")

# 5. Generate implementation document (参考 DOCUMENT_TEMPLATE.md)
```

---

## 📁 File Structure

```
business-api-recorder/
├── SKILL.md                    # 使用文档
├── README.md                   # 本文件
├── DOCUMENT_TEMPLATE.md         # AI重构文档模板 (12章节)
├── LICENSE                     # MIT 许可证
└── scripts/
    ├── network-monitor.js      # 网络监控脚本 (核心)
    └── get-monitor.sh          # 获取脚本工具
```

---

## 📄 Preview Output

After completing one business analysis, the following files will be generated:

```
output/
├── [业务功能]-完整实现文档.md      # 主要交付物
├── [业务功能]-api-log.json          # 完整日志
└── [业务功能]-api-report.md         # 简要报告
```

---

## 🔑 Key API Functions

Once the monitoring script is injected, the following functions are available in browser console:

| Function | Description |
|----------|-------------|
| `__openclaw_getNetworkLog()` | 获取完整日志 |
| `__openclaw_getStats()` | 获取统计信息 |
| `__openclaw_clearNetworkLog()` | 清空日志 |

---

## ⚡ Workflow

```
1. 连接浏览器 2. 打开URL 3. 注入监控 4. 分析页面 5. 执行操作 6. 提取日志 7. 生成文档
```

---

## 📚 Documentation

- **详细使用**: `SKILL.md`
- **文档模板**: `DOCUMENT_TEMPLATE.md`
- **OpenClaw文档**: https://docs.openclaw.ai
- **Chrome扩展**: https://docs.openclaw.ai/tools/chrome-extension

---

## 🐛 Troubleshooting

### Badge shows `!`

```bash
# Check Gateway status
openclaw gateway status

# Verify Token matches OPENCLAW_API_TOKEN
openclaw config show
```

### No requests captured

- Confirm monitoring script is injected (console shows "✅ 网络监控已启动")
- Check if requests are made after injection
- Some cross-origin requests may not be fully interceptable

---

## 🤝 Contributing

Contributions are welcome! Please:
1. Follow existing code style
2. Add tests for new features
3. Update documentation
4. Submit pull requests

---

## 📄 License

MIT License - see [LICENSE](./LICENSE) file.

---

## 👏 Acknowledgments

- OpenClaw team for the excellent AI orchestration platform
- Chrome DevTools Protocol for browser control capabilities

---

**Author**: 周坚  
**Email**: [REDACTED_SECRET]

path: package.json
content: {
  "name": "business-api-recorder",
  "version": "1.0.0",
  "description": "通过Chrome扩展自动拦截浏览器API，分析业务流程并生成完整的AI重构文档",
  "author": "周坚",
  "email": "[REDACTED_SECRET]",
  "license": "MIT",
  "homepage": "https://github.com/zhoujian/business-api-recorder",
  "repository": "https://github.com/zhoujian/business-api-recorder.git",
  "keywords": [
    "api-recorder",
    "browser-automation",
    "api-documentation",
    "business-analysis",
    "chrome-extension",
    "network-monitoring"
  ],
  "category": "Developer Tools",
  "dependencies": {
    "openclaw": ">=1.0.0",
    "chrome-extension": ">=1.0.0"
  },
  "requires": [
    "browser",
    "write",
    "exec"
  ]
}

path: scripts/get-monitor.sh
content: #!/bin/bash
# Business API Recorder - 网络监控脚本

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MONITOR_SCRIPT="$SCRIPT_DIR/scripts/network-monitor.js"

# 检查脚本是否存在
if [ ! -f "$MONITOR_SCRIPT" ]; then
    echo "Error: network-monitor.js not found"
    exit 1
fi

# 输出脚本内容（供注入使用）
cat "$MONITOR_SCRIPT"


path: scripts/network-monitor.js
content: /**
 * 网络请求监控脚本
 * 注入到页面中，拦截所有fetch/XMLHttpRequest请求
 * 并存储到全局变量中供后续提取
 */

(function() {
    // 存储所有请求记录
    window.__OPENCLAW_NETWORK_LOG__ = {
        requests: [],
        startTime: new Date().toISOString(),
        pageUrl: window.location.href
    };

    // 生成唯一ID
    function generateId() {
        return 'req_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    // 记录请求
    function logRequest(type, data) {
        const record = {
            id: generateId(),
            timestamp: new Date().toISOString(),
            type: type,
            ...data
        };
        window.__OPENCLAW_NETWORK_LOG__.requests.push(record);
        console.log('[OpenClaw Network]', type, data.url || data.method, record);
        return record;
    }

    // ========== 拦截 Fetch ==========
    const originalFetch = window.fetch;
    window.fetch = async function(url, options = {}) {
        const requestId = generateId();
        const startTime = Date.now();
        
        // 记录请求
        const requestRecord = logRequest('fetch_request', {
            requestId: requestId,
            method: options.method || 'GET',
            url: url instanceof Request ? url.url : url.toString(),
            headers: options.headers || {},
            body: options.body || null,
            bodyType: typeof options.body
        });

        try {
            const response = await originalFetch.apply(this, arguments);
            const endTime = Date.now();
            
            // 尝试读取响应体
            let responseBody = null;
            let responseText = null;
            
            try {
                // 克隆响应以便读取
                const clonedResponse = response.clone();
                responseText = await clonedResponse.text();
                
                // 尝试解析为JSON
                try {
                    responseBody = JSON.parse(responseText);
                } catch (e) {
                    responseBody = responseText.substring(0, 5000); // 限制长度
                }
            } catch (e) {
                responseBody = '[无法读取响应体]';
            }

            // 记录响应
            logRequest('fetch_response', {
                requestId: requestId,
                url: requestRecord.url,
                status: response.status,
                statusText: response.statusText,
                headers: Object.fromEntries(response.headers.entries()),
                body: responseBody,
                duration: endTime - startTime
            });

            return response;
        } catch (error) {
            // 记录错误
            logRequest('fetch_error', {
                requestId: requestId,
                url: requestRecord.url,
                error: error.message,
                duration: Date.now() - startTime
            });
            throw error;
        }
    };

    // ========== 拦截 XMLHttpRequest ==========
    const originalXHROpen = XMLHttpRequest.prototype.open;
    const originalXHRSend = XMLHttpRequest.prototype.send;
    const originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;

    XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
        this.__openclaw = {
            id: generateId(),
            method: method,
            url: url,
            async: async,
            headers: {},
            startTime: null
        };
        return originalXHROpen.apply(this, arguments);
    };

    XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
        if (this.__openclaw) {
            this.__openclaw.headers[header] = value;
        }
        return originalXHRSetRequestHeader.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function(body) {
        const xhr = this;
        const xhrData = xhr.__openclaw;
        
        if (xhrData) {
            xhrData.startTime = Date.now();
            xhrData.body = body;

            // 记录请求
            logRequest('xhr_request', {
                requestId: xhrData.id,
                method: xhrData.method,
                url: xhrData.url,
                headers: xhrData.headers,
                body: body,
                bodyType: typeof body
            });

            // 监听响应
            xhr.addEventListener('load', function() {
                const endTime = Date.now();
                let responseBody = null;

                try {
                    responseBody = xhr.responseText;
                    try {
                        responseBody = JSON.parse(responseBody);
                    } catch (e) {
                        // 保持文本格式
                    }
                } catch (e) {
                    responseBody = '[无法读取响应]';
                }

                logRequest('xhr_response', {
                    requestId: xhrData.id,
                    url: xhrData.url,
                    status: xhr.status,
                    statusText: xhr.statusText,
                    headers: {}, // XHR不直接暴露响应头
                    body: responseBody,
                    duration: endTime - xhrData.startTime
                });
            });

            xhr.addEventListener('error', function() {
                logRequest('xhr_error', {
                    requestId: xhrData.id,
                    url: xhrData.url,
                    error: 'XHR error',
                    duration: Date.now() - xhrData.startTime
                });
            });
        }

        return originalXHRSend.apply(this, arguments);
    };

    // ========== 辅助函数 ==========
    
    // 获取所有请求记录
    window.__openclaw_getNetworkLog = function() {
        return window.__OPENCLAW_NETWORK_LOG__;
    };

    // 清空记录
    window.__openclaw_clearNetworkLog = function() {
        window.__OPENCLAW_NETWORK_LOG__ = {
            requests: [],
            startTime: new Date().toISOString(),
            pageUrl: window.location.href
        };
    };

    // 导出为JSON
    window.__openclaw_exportNetworkLog = function() {
        return JSON.stringify(window.__OPENCLAW_NETWORK_LOG__, null, 2);
    };

    // 按类型筛选
    window.__openclaw_filterRequests = function(type) {
        return window.__OPENCLAW_NETWORK_LOG__.requests.filter(r => r.type === type);
    };

    // 按URL筛选
    window.__openclaw_filterByUrl = function(pattern) {
        const regex = new RegExp(pattern, 'i');
        return window.__OPENCLAW_NETWORK_LOG__.requests.filter(r => 
            r.url && regex.test(r.url)
        );
    };

    // 统计信息
    window.__openclaw_getStats = function() {
        const logs = window.__OPENCLAW_NETWORK_LOG__;
        const requests = logs.requests;
        
        return {
            totalRequests: requests.filter(r => r.type.includes('request') && !r.type.includes('response')).length,
            fetchRequests: requests.filter(r => r.type === 'fetch_request').length,
            xhrRequests: requests.filter(r => r.type === 'xhr_request').length,
            errors: requests.filter(r => r.type.includes('error')).length,
            uniqueUrls: [...new Set(requests.filter(r => r.url).map(r => r.url))].length,
            pageUrl: logs.pageUrl,
            startTime: logs.startTime
        };
    };

    console.log('[OpenClaw] 网络监控已启动');
    console.log('[OpenClaw] 使用 __openclaw_getNetworkLog() 获取所有记录');
    console.log('[OpenClaw] 使用 __openclaw_getStats() 获取统计信息');
})();


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)