npm package: @snhp/risk-analysis
Description: 一个强类型、模块化的风险分析系统包，用于检测和分析 HTTP 请求的潜在风险。
Latest version: 1.0.0

# @risk-control/risk-analysis

一个强类型、模块化的风险分析系统包，用于检测和分析 HTTP 请求的潜在风险。

## 特性

- ✅ **100% 类型安全** - 完全的 TypeScript 支持，无 any 类型
- ✅ **模块化设计** - 每个功能模块独立且内聚
- ✅ **工厂函数配置** - 通过强类型工厂函数构建分析系统
- ✅ **可扩展架构** - 易于添加新的分析模块
- ✅ **零依赖** - 不依赖任何外部包

## 安装

```bash
bun add @risk-control/risk-analysis
```

## 快速开始

### 基础使用

```typescript
import { createRiskAnalysisSystem } from '@risk-control/risk-analysis'

// 创建风险分析系统
const riskAnalyzer = createRiskAnalysisSystem()

// 分析请求
const result = riskAnalyzer.analyze({
  method: 'GET',
  url: 'https://example.com/api/data',
  headers: {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'accept': 'application/json',
    'accept-language': 'en-US,en;q=0.9',
  }
})

console.log('风险评分:', result.riskScore.score)
console.log('建议操作:', result.riskScore.recommendation)
```

### 高级配置

```typescript
import { createRiskAnalysisSystem } from '@risk-control/risk-analysis'

const riskAnalyzer = createRiskAnalysisSystem({
  riskAnalysis: {
    botDetection: {
      enabled: true,
      priority: 1,
      userAgentPatterns: [
        /bot/i,
        /crawl/i,
        /spider/i,
      ],
      requiredHeaders: ['accept', 'accept-language'],
    },
    riskScoring: {
      weights: {
        botDetection: 0.5,
        suspiciousPatterns: 0.3,
        cloudflareThreats: 0.2,
      },
      thresholds: {
        veryLow: 0,
        low: 20,
        medium: 50,
        high: 80,
        veryHigh: 95,
      }
    },
    logging: {
      enabled: true,
      level: 'info',
      includeHeaders: true,
    }
  }
})
```

## 核心模块

### 1. 请求信息提取器 (Request Extractor)

负责从原始请求中提取和解析基础信息：

```typescript
import { createHeaderExtractor } from '@risk-control/risk-analysis'

const extractor = createHeaderExtractor({
  headerNameNormalization: 'lowercase',
  maxUserAgentLength: 500,
  includeUnknownHeaders: false,
})

const requestInfo = extractor.extractRequestInfo(context)
const headersInfo = extractor.extractHeadersInfo(context)
const cloudflareInfo = extractor.extractCloudflareInfo(context)
```

### 2. 用户代理分析器 (User Agent Analyzer)

分析用户代理字符串，检测设备类型、浏览器和操作系统：

```typescript
import { createUserAgentAnalyzer } from '@risk-control/risk-analysis'

const analyzer = createUserAgentAnalyzer({
  enableMobileDetection: true,
  enableBrowserDetection: true,
  enableOSDetection: true,
})

const analysis = analyzer.analyze(userAgent)
// {
//   isMobile: false,
//   isDesktop: true,
//   browser: { isChrome: true, isFirefox: false, ... },
//   os: { isWindows: true, isMac: false, ... }
// }
```

### 3. 机器人检测分析器 (Bot Detection Analyzer)

检测和分析可能的机器人/爬虫行为：

```typescript
import { createBotDetectionAnalyzer } from '@risk-control/risk-analysis'

const detector = createBotDetectionAnalyzer({
  enabled: true,
  userAgentPatterns: [/bot/i, /crawl/i],
  requiredHeaders: ['accept', 'accept-language'],
  suspiciousHeaders: { 'x-requested-with': 'XMLHttpRequest' },
})

const result = detector.detect(context)
// {
//   isBot: true,
//   confidence: 0.85,
//   reasons: ['用户代理匹配已知机器人模式'],
//   detectionMethods: ['user-agent-pattern']
// }
```

### 4. 可疑模式检测分析器 (Suspicious Pattern Analyzer)

检测各种可疑的请求模式：

```typescript
import { createSuspiciousPatternAnalyzer } from '@risk-control/risk-analysis'

const analyzer = createSuspiciousPatternAnalyzer({
  enabled: true,
  urlPatterns: [/\.(php|asp)$/i],
  userAgentRules: [/^$/], // 空用户代理
})

const result = analyzer.analyze(context)
// {
//   patterns: ['用户代理字符串过短'],
//   severity: 'medium',
//   details: [...]
// }
```

### 5. 风险评分分析器 (Risk Scoring Analyzer)

综合各种分析结果计算最终风险评分：

```typescript
import { createRiskScoringAnalyzer } from '@risk-control/risk-analysis'

const scorer = createRiskScoringAnalyzer({
  enabled: true,
  weights: {
    botDetection: 0.4,
    suspiciousPatterns: 0.3,
    cloudflareThreats: 0.2,
  },
  thresholds: {
    low: 20,
    medium: 50,
    high: 80,
    veryHigh: 95,
  }
})

const result = scorer.calculate({
  botDetection,
  suspiciousPatterns,
  cloudflareInfo,
})
// {
//   score: 75,
//   level: 'high',
//   recommendation: 'challenge',
//   factors: [...]
// }
```

## 类型定义

所有的类型都是完全类型安全的：

```typescript
interface RiskAnalysisResult {
  readonly requestInfo: RequestInfo
  readonly headersInfo: HeadersInfo
  readonly cloudflareInfo: CloudflareInfo
  readonly userAgentAnalysis: UserAgentAnalysis
  readonly botDetection: BotDetectionResult
  readonly suspiciousPatterns: SuspiciousPatternResult
  readonly riskScore: RiskScoreResult
}

type RecommendationAction = 
  | 'allow'      // 允许访问
  | 'monitor'    // 监控
  | 'challenge'  // 人机验证
  | 'rate-limit' // 速率限制
  | 'block'      // 阻止访问
```

## 与 TanStack Start 集成

```typescript
import { createServerFn } from '@tanstack/react-start'
import { getWebRequest, getHeaders } from '@tanstack/react-start/server'
import { createRiskAnalysisSystem } from '@risk-control/risk-analysis'

const riskAnalyzer = createRiskAnalysisSystem()

export const analyzeRequest = createServerFn({
  method: 'GET',
}).handler(async () => {
  const request = getWebRequest()
  const headers = getHeaders()

  const analysis = riskAnalyzer.analyze({
    method: request.method,
    url: request.url,
    headers: headers as Record<string, string>,
  })

  // 根据风险评分决定后续操作
  if (analysis.riskScore.recommendation === 'block') {
    throw new Error('请求被阻止')
  }

  return analysis
})
```

## 许可证

MIT