robertovargasdev/threat-intelligence-api
GitHub: robertovargasdev/threat-intelligence-api
一款基于 NestJS 的模块化威胁情报 API,通过并发编排多个外部情报源对 HTTP 请求来源进行实时风险评估与风险评分。
Stars: 0 | Forks: 0
# 🛡️ 威胁情报 API
一款高性能的无状态 RESTful API,旨在实时分析 IP 地址,检测恶意流量(Proxies、VPNs、TOR 节点)并计算标准化的风险评分。
该项目作为一个编排器,并发查询多个情报源,通过内存缓存优化延迟,并使用请求限流保护自身资源。
## 技术








## 学习与架构
本项目作为软件架构实验室开发,巩固了以下技术概念:
* **异步编排:** 使用 `Promise.all` 和 `RxJS Observables` 同时解析对外部提供商的多个 HTTP 请求,大幅降低响应延迟。
* **Cache-Aside 模式:** 实现内存(RAM)缓存以避免对外部 API 的冗余请求,防止失败响应导致的缓存污染,并节省使用配额。
* **边界防御:** 配置全局 `ThrottlerGuard` 以缓解 DDoS 攻击和资源滥用。
* **隔离测试:** 通过依赖注入和 `Mocks` 介绍白盒单元测试的使用,在不依赖互联网连接的情况下模拟网络和缓存的行为。
* **无状态容器:** 优化多阶段构建(Multi-stage build)的 `Dockerfile`,排除开发依赖以创建超轻量的生产镜像。
## ⚙️ 核心功能
### 1. 情报集成 (OSINT)
API 作为一个 *Facade*,查询三个情报源:
* **AbuseIPDB:** 用于获取垃圾邮件和网络攻击的历史报告。
* **IP-API:** 用于精确定位和检测数据中心/托管服务。
* **ProxyCheck:** 用于识别混淆连接(VPN、Proxy、TOR)。
### 2. 风险评估引擎 (Risk Score)
原始响应由确定性算法处理,基于以下条件返回可供前端操作的风险级别(`Low`、`Medium`、`High`、`Critical`):
* 对使用 VPNs 的中等惩罚(+20 pts)。
* 对使用 TOR 网络节点的严重惩罚(+50 pts)。
* 检测来自云服务器而非住宅网络的流量(+15 pts)。
### 3. 请求限流
限制 API 的使用以防止 DDoS 攻击和资源滥用。
### 4. 内存缓存
利用内存缓存避免对外部 API 的冗余请求,防止失败响应导致的缓存污染,并节省使用配额。
## 🛡️ 可重用性:通过 Guards 实现持续集成
本项目纯粹的模块化架构允许提取 `src/modules/threat` 文件夹,并直接将其作为内部库集成到任何其他单体 NestJS 项目中(例如,电子商务平台或银行系统)。
无需在每个 endpoint 手动验证 IP,此模块的真正威力在于将 `ThreatService` 封装在 **Guard** 中。这会创建一个网络防护盾,在请求生命周期的早期评估流量,直接阻断攻击者,而不会“污染”控制器的业务逻辑。
### 实现示例
```
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { ThreatService } from './threat/threat.service';
@Injectable()
export class ThreatGuard implements CanActivate {
constructor(private readonly threatService: ThreatService) {}
async canActivate(context: ExecutionContext): Promise {
const request = context.switchToHttp().getRequest();
// Extracción estándar de IP (ajustable según tu proxy reverso/Nginx)
const clientIp = request.headers['x-forwarded-for'] || request.socket.remoteAddress;
const report = await this.threatService.analyzeIp(clientIp);
// ⛔ Bloqueo automático si se detecta un nodo TOR o servidor comprometido
if (report.riskLevel === 'Critical') {
throw new ForbiddenException('Security Policy: Acceso denegado por tráfico anómalo o red maliciosa.');
}
return true; // ✅ El tráfico es seguro, la petición continúa
}
}
```
### 在关键路由中的精准应用
通过将逻辑隔离在 Guard 中,你可以仅在实际需要此高成本 OSINT 分析的 endpoint(如支付网关或登录)上应用它,从而节省 API 配额并保持用户常规浏览的快速响应。
```
import { Controller, Post, Body, UseGuards } from '@nestjs/common';
import { ThreatGuard } from '../threat/threat.guard';
@Controller('checkout')
export class CheckoutController {
@Post('pay')
@UseGuards(ThreatGuard) // Escudo de inteligencia activado
async processPayment(@Body() paymentData: PaymentDto) {
// Si la petición llega aquí, la IP está matemáticamente comprobada como "Segura"
return this.paymentService.process(paymentData);
}
}
```
## 💻 本地安装与运行
### 前置条件
* 已安装 [Docker](https://www.docker.com/) 和 Docker Compose。
* 一个免费的 [AbuseIPDB](https://www.abuseipdb.com/) API Key。
### 第一步:克隆仓库
```
git clone https://github.com/robertovargasdev/threat-intelligence-api.git
cd threat-intelligence-api
```
### 第二步:配置环境变量
通过复制基础模板在项目根目录创建一个名为 .env 的文件:
```
cp .env.example .env
```
打开 .env 文件并输入你的私钥,请在此 [AbuseIPDB](https://www.abuseipdb.com/) 服务中创建。
```
ABUSEIPDB_API_KEY="tu_clave_secreta_aqui"
```
### 第三步:启动容器
运行以下命令构建镜像并启动 API:
```
docker compose up -d --build
```
### 第四步:测试 API
容器显示为绿色后,你可以使用浏览器、Postman 或 cURL 测试 IP 分析:
```
# 分析 Google 的 DNS
curl http://localhost:3000/threat/8.8.8.8
```
预期输出:
```
{
"statusCode": 200,
"message": "Operación ejecutada con éxito",
"data": {
"ip": "8.8.8.8",
"riskScore": 0,
"riskLevel": "Low",
"isProxyOrVPN": false,
"raw_data": {
"abuse": {
"data": {
"ipAddress": "8.8.8.8",
"isPublic": true,
"ipVersion": 4,
"isWhitelisted": true,
"abuseConfidenceScore": 0,
"countryCode": "US",
"usageType": "Content Delivery Network",
"isp": "Google LLC",
"domain": "google.com",
"hostnames": [
"dns.google"
],
"isTor": false,
"totalReports": 60,
"numDistinctUsers": 37,
"lastReportedAt": "2026-06-07T14:00:05+00:00"
}
},
"geolocation": {
"status": "success",
"country": "United States",
"countryCode": "US",
"region": "VA",
"regionName": "Virginia",
"city": "Ashburn",
"zip": "20149",
"lat": 39.03,
"lon": -77.5,
"timezone": "America/New_York",
"isp": "Google LLC",
"org": "Google Public DNS",
"as": "AS15169 Google LLC",
"query": "8.8.8.8"
},
"proxy": {
"status": "ok",
"8.8.8.8": {
"asn": "AS15169",
"range": "8.8.8.0/24",
"hostname": "dns.google",
"provider": "Google LLC",
"organisation": "Level 3",
"continent": "North America",
"continentcode": "NA",
"country": "United States",
"isocode": "US",
"region": "California",
"regioncode": "CA",
"timezone": "America/Los_Angeles",
"city": "Mountain View",
"postcode": "94043",
"latitude": 37.422,
"longitude": -122.085,
"currency": {
"code": "USD",
"name": "Dollar",
"symbol": "$"
},
"devices": {
"address": 0,
"subnet": 6
},
"proxy": "no",
"type": "Business"
}
}
},
"source": "network",
"executionTimeMs": 370
},
"timestamp": "2026-06-08T02:03:42.457Z",
"path": "/api/threat/8.8.8.8"
}
```
## 文档
要查看自动生成的完整文档,请访问 endpoint:http://localhost:3000/api/docs
标签:IP分析, MITM代理, NestJS, RESTful API, Syscall, TypeScript, Web开发, 威胁情报, 安全插件, 开发者工具, 提示词优化, 自动化攻击, 请求拦截