agentguard-ai/tealtiger-typescript-prod

GitHub: agentguard-ai/tealtiger-typescript-prod

面向 AI 智能体应用的安全 SDK,提供护栏检测、策略引擎、熔断保护、审计追踪与多厂商编排能力。

Stars: 0 | Forks: 0

TealTiger Logo # TealTiger SDK [![npm version](https://badge.fury.io/js/tealtiger.svg)](https://www.npmjs.com/package/tealtiger) [![npm downloads](https://img.shields.io/npm/dm/tealtiger.svg)](https://www.npmjs.com/package/tealtiger) [![Tests](https://github.com/agentguard-ai/tealtiger-sdk/actions/workflows/test.yml/badge.svg)](https://github.com/agentguard-ai/tealtiger-sdk/actions/workflows/test.yml) [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/) [![v1.1.1](https://img.shields.io/badge/version-v1.1.1-teal.svg)](https://www.npmjs.com/package/tealtiger)
## 🚀 快速开始 ``` npm install tealtiger ``` ``` import { TealOpenAI, GuardrailEngine, PIIDetectionGuardrail, PromptInjectionGuardrail } from 'tealtiger'; // Set up guardrails const engine = new GuardrailEngine(); engine.registerGuardrail(new PIIDetectionGuardrail()); engine.registerGuardrail(new PromptInjectionGuardrail()); // Create guarded client — drop-in replacement for OpenAI const client = new TealOpenAI({ apiKey: process.env.OPENAI_API_KEY, agentId: 'my-agent', guardrailEngine: engine }); const response = await client.chat.completions.create({ model: 'gpt-4', messages: [{ role: 'user', content: 'Hello!' }] }); console.log(response.choices[0].message.content); console.log('Guardrails passed:', response.security?.guardrailResult?.passed); ``` ## 🌐 支持的提供商 覆盖 95% 以上市场,支持 7 家 LLM 提供商: | Provider | Client | Models | Features | |----------|--------|--------|----------| | **OpenAI** | `TealOpenAI` | GPT-4, GPT-3.5 Turbo | Chat, Completions, Embeddings | | **Anthropic** | `TealAnthropic` | Claude 3, Claude 2 | Chat, Streaming | | **Google** | `TealGemini` | Gemini Pro, Ultra | Multimodal, Safety Settings | | **AWS** | `TealBedrock` | Claude, Titan, Jurassic, Command, Llama | Multi-model, Regional | | **Azure** | `TealAzureOpenAI` | GPT-4, GPT-3.5 | Deployment-based, Azure AD | | **Mistral** | `TealMistral` | Large, Medium, Small, Mixtral | EU Data Residency, GDPR | | **Cohere** | `TealCohere` | Command, Embed | RAG, Citations, Connectors | ### 多提供商编排 ``` import { TealMultiProvider, TealOpenAI, TealAnthropic } from 'tealtiger'; const multiProvider = new TealMultiProvider({ strategy: 'priority', // or 'round-robin', 'cost', 'use-case' enableFailover: true, maxFailoverAttempts: 3 }); multiProvider.registerProvider({ type: 'openai', name: 'openai-primary', client: new TealOpenAI({ apiKey: 'key' }), priority: 1 }); multiProvider.registerProvider({ type: 'anthropic', name: 'anthropic-backup', client: new TealAnthropic({ apiKey: 'key' }), priority: 2 }); // Automatic failover if primary fails const response = await multiProvider.chat({ messages: [{ role: 'user', content: 'Hello' }] }); ``` ## 🛡️ 核心功能 ### TealEngine — 策略评估 确定性策略评估,支持多模式执行: ``` import { TealEngine, PolicyMode, DecisionAction, ReasonCode } from 'tealtiger'; const engine = new TealEngine({ policies: myPolicies, mode: { defaultMode: PolicyMode.ENFORCE, // or MONITOR, REPORT_ONLY policyModes: { 'tools.file_delete': PolicyMode.ENFORCE, 'identity.admin_access': PolicyMode.ENFORCE } } }); const decision = engine.evaluate({ agentId: 'agent-001', action: 'tool.execute', tool: 'file_delete', correlation_id: 'req-12345' }); switch (decision.action) { case DecisionAction.ALLOW: await executeTool(); break; case DecisionAction.DENY: if (decision.reason_codes.includes(ReasonCode.TOOL_NOT_ALLOWED)) { throw new ToolNotAllowedError(decision.reason); } break; case DecisionAction.REQUIRE_APPROVAL: await requestApproval(decision); break; } // Risk-based routing if (decision.risk_score > 80) { await escalateToHuman(decision); } ``` **决策字段:** `action` (ALLOW, DENY, REDACT, TRANSFORM, REQUIRE_APPROVAL, DEGRADE), `reason_codes` (标准化枚举), `risk_score` (0-100), `correlation_id`, `metadata` ### TealGuard — 安全护栏 客户端护栏,毫秒级运行,无需依赖服务器: ``` import { GuardrailEngine, PIIDetectionGuardrail, PromptInjectionGuardrail, ContentModerationGuardrail } from 'tealtiger'; const engine = new GuardrailEngine({ mode: 'parallel', timeout: 5000 }); engine.registerGuardrail(new PIIDetectionGuardrail({ action: 'redact' })); engine.registerGuardrail(new PromptInjectionGuardrail({ sensitivity: 'high' })); engine.registerGuardrail(new ContentModerationGuardrail({ threshold: 0.7 })); const result = await engine.execute(userInput); console.log('Passed:', result.passed); console.log('Risk Score:', result.riskScore); ``` **检测内容:** PII(电子邮件、电话、SSN、信用卡)、Prompt 注入、越狱、有害内容、自定义模式。 ### TealCircuit — 熔断器 级联故障预防与自动故障转移: ``` import { TealCircuit } from 'tealtiger'; const circuit = new TealCircuit({ failureThreshold: 5, resetTimeout: 30000, monitorInterval: 10000 }); // Wraps provider calls with circuit breaker protection const response = await circuit.execute(() => client.chat.completions.create({ model: 'gpt-4', messages }) ); ``` ### TealAudit — 审计日志与脱敏 带有默认安全 PII 脱敏的版本化审计事件: ``` import { TealAudit, RedactionLevel } from 'tealtiger'; const audit = new TealAudit({ outputs: [new FileOutput('./audit.log')], config: { input_redaction: RedactionLevel.HASH, // SHA-256 hash + size (default) output_redaction: RedactionLevel.HASH, detect_pii: true, debug_mode: false } }); ``` **脱敏级别:** HASH(默认,生产环境安全),SIZE_ONLY,CATEGORY_ONLY,FULL,NONE(仅限调试)。 ### 关联 ID 与可追溯性 跨所有组件的端到端请求追踪: ``` import { ContextManager } from 'tealtiger'; const context = ContextManager.createContext({ tenant_id: 'acme-corp', app: 'customer-support', env: 'production' }); // Context propagates through TealEngine, TealAudit, and all providers const response = await client.chat.create({ model: 'gpt-4', messages: [{ role: 'user', content: 'Hello' }], context: context }); // Query audit logs by correlation_id const events = audit.query({ correlation_id: context.correlation_id }); ``` **功能:** 自动生成 UUID v4 关联 ID、OpenTelemetry 兼容的 Trace ID、HTTP Header 传播、多租户支持。 ### 策略测试工具 在生产部署前验证策略行为: ``` import { PolicyTester, TestCorpora } from 'tealtiger'; const tester = new PolicyTester(engine); const report = tester.runSuite({ name: 'Customer Support Policy Tests', tests: [ { name: 'Block file deletion', context: { agentId: 'support-001', action: 'tool.execute', tool: 'file_delete' }, expected: { action: DecisionAction.DENY, reason_codes: [ReasonCode.TOOL_NOT_ALLOWED] } }, ...TestCorpora.promptInjection(), ...TestCorpora.piiDetection() ] }); console.log(`Tests: ${report.passed}/${report.total} passed`); // Export for CI/CD const junitXml = tester.exportReport(report, 'junit'); ``` ``` # CLI 用法 npx tealtiger test ./policies/*.test.json --coverage --format=junit --output=./results.xml ``` ### 成本追踪与预算管理 追踪 50 多个模型的成本并强制执行支出限制: ``` import { CostTracker, BudgetManager, InMemoryCostStorage } from 'tealtiger'; const storage = new InMemoryCostStorage(); const tracker = new CostTracker({ enabled: true }); const budgetManager = new BudgetManager(storage); budgetManager.createBudget({ name: 'Daily GPT-4 Budget', limit: 10.0, period: 'daily', alertThresholds: [50, 75, 90, 100], action: 'block', enabled: true }); // Estimate before request const estimate = tracker.estimateCost('gpt-4', { inputTokens: 1000, outputTokens: 500 }, 'openai'); // Check budget const check = await budgetManager.checkBudget('agent-123', estimate); if (!check.allowed) { console.log(`Blocked by: ${check.blockedBy?.name}`); } ``` ## 🛡️ OWASP 智能体应用 Top 10 覆盖范围 TealTiger v1.1.0 通过其纯 SDK 架构覆盖了 **10 项中的 7 项** OWASP ASI: | ASI | Vulnerability | Coverage | Components | |-----|--------------|----------|------------| | ASI01 | Goal Hijacking & Prompt Injection | 🟡 Partial | TealGuard, TealEngine | | ASI02 | Tool Misuse & Unauthorized Actions | 🟢 Full | TealEngine | | ASI03 | Identity & Access Control Failures | 🟢 Full | TealEngine | | ASI04 | Supply Chain Vulnerabilities | 🔧 Support | TealAudit | | ASI05 | Unsafe Code Execution | 🟢 Full | TealEngine | | ASI06 | Memory & Context Corruption | 🟢 Full | TealEngine, TealGuard | | ASI07 | Inter-Agent Communication Security | ❌ Platform | N/A | | ASI08 | Cascading Failures & Resource Exhaustion | 🟢 Full | TealCircuit | | ASI09 | Harmful Content Generation | 🔧 Support | TealGuard | | ASI10 | Rogue Agent Behavior | 🟢 Full | TealAudit | 📖 [完整的 OWASP ASI 映射](../../OWASP-AGENTIC-TOP10-TEALTIGER-MAPPING.md) | [OWASP 智能体应用 Top 10](https://owasp.org/www-project-top-10-for-agentic-applications/) ## 🎯 应用场景 - **客户支持机器人** — 保护客户 PII - **医疗 AI** — HIPAA 合规 - **金融服务** — 防止数据泄露 - **电子商务** — 保护支付信息安全 - **企业 AI** — 策略执行与审计追踪 - **教育平台** — 内容安全 ## 📚 文档 - [完整文档](https://docs.tealtiger.ai) - [API 参考](https://docs.tealtiger.ai/api) - [示例](https://github.com/agentguard-ai/tealtiger-typescript/tree/main/examples) - [更新日志](https://github.com/agentguard-ai/tealtiger-typescript/blob/main/CHANGELOG.md) ## 🤝 参与贡献 欢迎参与贡献!请参阅我们的[贡献指南](https://github.com/agentguard-ai/tealtiger-typescript/blob/main/CONTRIBUTING.md)。 ## 📄 许可证 Apache 2.0 — 详见 [LICENSE](https://github.com/agentguard-ai/tealtiger-typescript/blob/main/LICENSE) ## 🔗 链接 - **npm**: https://www.npmjs.com/package/tealtiger - **GitHub**: https://github.com/agentguard-ai/tealtiger-typescript - **Python SDK**: https://pypi.org/project/tealtiger/ - **Documentation**: https://docs.tealtiger.ai - **Contact**: reachout@tealtiger.ai - **Issues**: https://github.com/agentguard-ai/tealtiger-typescript/issues **由 TealTiger 团队用 ❤️ 制作**
标签:AI安全, API安全, AppSec, AutoGPT, Chat Copilot, CMS安全, CrewAI, DLL 劫持, DNS 反向解析, GPT-4, Guardrails, JavaScript, JSON输出, LangChain, MITM代理, NPM包, OpenAI, OSV-Scalibr, Petitpotam, PII检测, ProjectDiscovery, TypeScript, 人工智能安全, 内存规避, 合规性, 大语言模型, 安全插件, 对抗攻击, 开发工具包, 护栏, 敏感信息检测, 数据保护, 数据可视化, 智能体安全, 渗透测试框架, 网络安全, 自动化攻击, 轻量级, 防御, 隐私保护, 隐私合规