npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@snhp/risk-analysis

v1.0.0

Published

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

Readme

@risk-control/risk-analysis

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

特性

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

安装

bun add @risk-control/risk-analysis

快速开始

基础使用

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)

高级配置

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)

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

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)

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

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)

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

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)

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

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)

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

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: [...]
// }

类型定义

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

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 集成

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