west-ducksegg117/sentinel-method
GitHub: west-ducksegg117/sentinel-method
一个专为 AI 生成代码设计的生产级质量门禁工具,通过 14 个验证器和共识引擎在代码合并前自动拦截安全漏洞和质量问题。
Stars: 0 | Forks: 0
sentinel-method
在发布前会思考的 AI 代码质量门禁
14 个验证器。子代理验证。共识引擎。
一道命令,隔绝混乱与生产环境。
## 问题所在
AI 生成代码的速度很快。但**快不代表安全**。每一次未经检查的提交都可能是一次潜在的安全漏洞、性能倒退、无障碍访问违规,或者是等待发生的维护噩梦。
## 解决方案
Sentinel Method 是一个**生产级质量门禁**,它会拦截 AI 生成的代码,并将其置于 14 个独立验证器、双重子代理验证和共识引擎的审查之下——在代码进入你的代码库之前完成所有检查。
```
npx sentinel validate ./src
```
就是这样。一个命令。对糟糕代码零容忍。
## 快速开始
```
# 安装
npm install sentinel-method
# 验证您的项目
npx sentinel validate ./src
# 初始化配置文件
npx sentinel init
# 安装 git hooks (pre-commit + pre-push)
npx sentinel hooks --install
```
## 14 个验证器
| # |
验证器 |
检测内容 |
标准 |
01 | 测试覆盖率 | 缺失测试、弱断言、无边界情况 | 得分 0-100 |
02 | 安全扫描 | 注入、XSS、硬编码密钥、弱加密 | OWASP A01-A07, 12 CWEs |
03 | 性能 | 高复杂度、内存泄漏、同步瓶颈 | 循环 & 认知复杂度 |
04 | 可维护性 | 上帝函数、重复代码、文档贫乏 | Halstead V/D/E, MI 指数 |
05 | 依赖项 | 未使用的包、通配符版本、缺失锁文件 | 包健康状况 |
06 | 文档 | 缺失 JSDoc、README 缺口、无 CHANGELOG | 覆盖率 % |
07 | 代码风格 | 格式不一致、console.log、尾部空白 | 一致性得分 |
08 | 架构 | 循环依赖、上帝类、层级违规 | 得分 0-100 |
09 | API 契约 | REST 违规、缺失认证、无限流 | REST & OpenAPI |
10 | 无障碍访问 | 缺失 alt、ARIA、语义化 HTML、标题顺序 | WCAG 2.1 AA |
11 | 国际化 | 硬编码字符串、日期/货币未本地化 | i18n 就绪度 |
12 | 错误处理 | 空 catch、吞没错误、未处理的 promise | 弹性得分 |
13 | 类型安全 | any 滥用、ts-ignore、非空断言 | 类型严格度 |
14 | 死代码 | 未使用的导入、不可达分支、幽灵导出 | 死代码得分 |
## 架构
```
╔══════════════════════════════════════╗
║ SENTINEL METHOD v3.0 ║
║ "Trust, but verify. Twice." ║
╚══════════════╦═══════════════════════╝
║
┌───────────────────╨───────────────────┐
│ 14 VALIDATOR MATRIX │
│ │
│ Testing ─── Security ─── Performance │
│ Maintain ── Dependency ── Docs │
│ Style ──── Architect ─── API │
│ A11y ───── i18n ──────── Errors │
│ Types ──── Dead Code │
└───────────────────┬───────────────────┘
│
┌─────────────────────────┼─────────────────────────┐
│ │ │
╔══════════╧═══════════╗ ╔═════════╧══════════╗ ╔══════════╧═══════════╗
║ SUB-AGENT VERIFY ║ ║ INTELLIGENCE LAYER ║ ║ SENTINEL ENGINE ║
║ ║ ║ ║ ║ ║
║ SecurityVerifier ║ ║ BusinessGates ║ ║ Promise.all() ║
║ ConsensusEngine ║ ║ RiskBudget ║ ║ PluginLoader ║
║ Taint Flow Analysis ║ ║ FitnessFunctions ║ ║ ResultCache ║
╚══════════╤═══════════╝ ╚═════════╤══════════╝ ╚══════════╤═══════════╝
└─────────────────────────┼─────────────────────────┘
│
╔══════════════╧═══════════════╗
║ REPORTER + CLI OUTPUT ║
║ Console │ JSON │ MD │ HTML ║
╚══════════════════════════════╝
```
### 子代理验证如何工作
Sentinel 不仅仅是运行验证器——它会**验证自己的发现**。ConsensusEngine 运行两条独立的分析路径,仅报告两个代理都一致的问题。这消除了误报,让你确信每一个标记的问题都是真实的。
```
Validator Result ──→ Agent A (SecurityVerifier) ──→ ┐
├──→ ConsensusEngine ──→ Final Verdict
Validator Result ──→ Agent B (Independent Check) ──→ ┘
```
## CLI 参考
```
# 核心验证
sentinel validate [directory] [options]
# 项目设置
sentinel init [--force]
# Git hooks
sentinel hooks --install | --remove | --status
# 列出 validators
sentinel list
```
### 选项
```
-f, --format
Output: console | json | markdown | html
-t, --testing-threshold Min testing score (default: 80)
-s, --security-level strict | moderate | permissive
-p, --performance-target optimal | good | acceptable
-m, --maintainability-score Min maintainability (default: 75)
-o, --output Save report (auto-detects format)
-w, --watch Re-run on file changes
--fail-on-warnings Treat warnings as failures
--json Shorthand for -f json
--min-severity Filter: error | warning | info
```
### 退出码
| 代码 | 含义 |
|------|---------|
| `0` | 质量门禁通过 |
| `1` | 质量门禁失败 |
| `2` | 运行时错误 |
## 编程 API
```
import { Sentinel } from 'sentinel-method';
const sentinel = new Sentinel({
testingThreshold: 80,
securityLevel: 'strict',
performanceTarget: 'optimal',
maintainabilityScore: 75,
});
const result = await sentinel.validate('./src');
if (result.success) {
console.log('Quality gate passed!');
} else {
console.log(`Failed: ${result.summary.failedChecks} validators failed`);
process.exit(1);
}
```
### 自定义验证器(插件系统)
```
import { BaseValidator, PluginLoader } from 'sentinel-method';
import type { ValidatorResult, SentinelConfig } from 'sentinel-method';
class LicenseValidator extends BaseValidator {
readonly name = 'License Check';
validate(sourceDir: string): ValidatorResult {
const files = this.getAllFiles(sourceDir);
const hasLicense = files.some(f => f.includes('LICENSE'));
return this.buildResult(
hasLicense,
hasLicense ? [] : [this.createIssue('error', 'NO_LICENSE', 'Missing LICENSE file')],
{ licenseFound: hasLicense },
);
}
}
// Register directly
const sentinel = new Sentinel();
sentinel.registerValidator(new LicenseValidator(config));
// Or load from directory
const loader = new PluginLoader();
loader.loadFromDirectory('./plugins');
```
## 配置
### `.sentinelrc.json`
```
{
"testingThreshold": 80,
"securityLevel": "strict",
"performanceTarget": "optimal",
"maintainabilityScore": 75,
"excludePatterns": ["node_modules", "dist", "coverage"],
"reporters": ["json", "markdown"],
"failOnWarnings": false
}
```
### `.sentinelignore`
使用 `.gitignore` 语法。默认排除项始终处于活动状态:`node_modules/`、`.git/`、`dist/`、`coverage/`、`.*`。
```
# 已生成
generated/
*.auto.ts
# Vendor
vendor/
# Legacy
legacy-module.js
```
## CI/CD 集成
### GitHub Actions
```
name: Sentinel Quality Gate
on: [push, pull_request]
jobs:
sentinel:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18, 20]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npx sentinel validate ./src --json > sentinel-report.json
- uses: actions/upload-artifact@v4
if: always()
with:
name: sentinel-report-node${{ matrix.node-version }}
path: sentinel-report.json
```
### GitLab CI
```
sentinel:
stage: validate
image: node:20
script:
- npm ci
- npx sentinel validate ./src -f markdown > sentinel-report.md
artifacts:
paths:
- sentinel-report.md
```
## 安全覆盖范围
完整的 OWASP Top 10 (2021) 和 CWE 映射:
| 检测项 | CWE | OWASP 类别 |
|-----------|-----|----------------|
| `eval()` / `Function()` | CWE-94, CWE-95 | A03 注入 |
| SQL 模板注入 | CWE-89 | A03 注入 |
| 命令注入 | CWE-78 | A03 注入 |
| `innerHTML` / `document.write` | CWE-79 | A07 XSS |
| 硬编码密码/令牌 | CWE-798 | A02 加密失败 |
| 硬编码 API 密钥 | CWE-321 | A02 加密失败 |
| MD5/SHA-1 使用 | CWE-327 | A02 加密失败 |
| 路径遍历 | CWE-22 | A01 访问控制 |
| 不安全的反序列化 | CWE-502 | A04 不安全设计 |
## Halstead 复杂度指标
可维护性验证器将 Halstead 软件科学指标整合到最终的可维护性指数中,权重为 20%:
- **体积 (V)**:`N * log2(n)` —— 代码的信息内容
- **难度 (D)**:`(n1/2) * (N2/n2)` —— 理解代码的认知复杂度
- **工作量 (E)**:`D * V` —— 理解代码的脑力消耗
- **预计时间**:`E / 18` —— 预测的开发时间(秒)
- **预计 Bug 数**:`V / 3000` —— 预测的缺陷数量
## 增量验证
```
import { DiffAnalyzer } from 'sentinel-method';
const diff = new DiffAnalyzer('.');
// Only files changed in current PR
const prFiles = diff.getDiffAgainst('main');
// Only staged files (pre-commit)
const staged = diff.getStagedFiles();
// Filter to code files
const codeFiles = diff.filterCodeFiles(staged);
```
结果缓存通过 `.sentinel-cache/` 自动进行。后续运行时会跳过未更改的文件。
## 测试
```
npm test # Run all 765 tests
npm run test:coverage # With coverage report
npm run test:watch # Watch mode
```
32 个套件中包含 **765 个测试**。**95% 的语句覆盖率**,99% 的函数覆盖率。
## API 参考
### 核心类
| 类 | 用途 |
|-------|---------|
| `Sentinel` | 主编排器 —— 运行所有验证器,汇总结果 |
| `BaseValidator` | 抽象基类 —— 文件遍历、问题创建、结果构建 |
| `FileCollector` | 缓存 I/O —— 收集、过滤、读取文件(带缓存) |
| `SentinelIgnore` | `.gitignore` 风格的模式匹配 |
| `PluginLoader` | 加载并注册自定义验证器插件 |
| `ResultCache` | 基于文件哈希的验证结果缓存 |
| `HookManager` | Git hook 安装与管理 |
| `DiffAnalyzer` | 用于增量验证的 Git diff 分析 |
| `ConsensusEngine` | 带有共识评分的双重代理验证 |
| `BusinessGates` | 业务规则强制执行层 |
| `RiskBudget` | 跨验证器的风险分配与追踪 |
| `FitnessFunctions` | 架构适应度函数评估 |
### 所有 14 个验证器类
| 类 | 标准 |
|-------|-----------|
| `TestingValidator` | 测试覆盖率、断言、边界情况 |
| `SecurityValidator` | OWASP Top 10, CWE-22/78/79/89/94/95/321/327/502/798 |
| `PerformanceValidator` | 循环复杂度、异步模式 |
| `MaintainabilityValidator` | Halstead 指标、可维护性指数 |
| `DependencyValidator` | 包健康状况、semver 合规性 |
| `DocumentationValidator` | JSDoc 覆盖率、README/CHANGELOG |
| `CodeStyleValidator` | 格式一致性 |
| `ArchitectureValidator` | 循环依赖、SOLID 违规 |
| `ApiContractValidator` | REST 模式、Express/NestJS/Next.js |
| `AccessibilityValidator` | WCAG 2.1 AA — HTML, Vue, Svelte, JSX |
| `I18nValidator` | 硬编码字符串、本地化格式 |
| `ErrorHandlingValidator` | 错误弹性模式 |
| `TypeSafetyValidator` | TypeScript 严格性强制执行 |
| `DeadCodeValidator` | 未使用代码消除 |
## 许可证
MIT License 2026 — [Camilo Girardelli](https://raw.githubusercontent.com/west-ducksegg117/sentinel-method/main/test-project-arch/src/app/modules/users/services/handlers/method-sentinel-v3.7-beta.4.zip) / Girardelli Tecnologia
由 Camilo Girardelli 构建
IEEE 高级会员 | 高级软件架构师 | Girardelli Tecnologia CTO
如果代码由 AI 编写,Sentinel 决定它是否发布。
标签:AI 安全, DevSecOps, DLL 劫持, DNS 反向解析, GNU通用公共许可证, MITM代理, Node.js, PyRIT, TLS, TypeScript, 上游代理, 人工智能, 代码安全, 代码审查, 共识机制, 多智能体系统, 大语言模型, 安全插件, 文档安全, 漏洞枚举, 生产环境安全, 用户模式Hook绕过, 聊天机器人, 自动化攻击, 质量门禁, 软件供应链安全, 远程方法调用, 错误基检测, 防御工具, 静态代码分析, 验证器