# AI Guard v0.2.0

Dual-plane AI security — **static analysis CLI** + **runtime enforcement SDK** — detecting and blocking prompt injection, API key leaks, unsafe output, RAG poisoning, agent hijacking, and more.

For the complete tutorial, open the dashboard at `/tutorial` or see `docs/user-guide.md`.

---

## What it detects

| Category | Severity | Description |
|---|---|---|
| prompt-injection | Critical | Classic, jailbreak, multilingual, evasion, taint flow, zero-width chars |
| api-key-leak | Critical | OpenAI, Anthropic, AWS, Stripe, GitHub, Cohere, Mistral + 6 more |
| sensitive-data | High | PII, passwords, tokens, private keys in source or payloads |
| unsafe-output | High | innerHTML, eval(), Function(), shell commands from model output |
| ai-runtime-abuse | Critical | Tool argument injection, privilege escalation, RAG context poisoning |
| rag-poisoning | Critical | Embedding injection, chunk splitting, metadata injection |
| multimodal | High | Image alt-text, base64 data URIs, audio transcript injection |
| supply-chain | Medium | Unpinned AI packages, Dockerfile :latest tags |
| excessive-agency | High | Agent tool permissions, missing human approval gates |
| model-theft | High | Model weight exposure, unauthenticated logits |
| overreliance | Medium | Direct LLM output execution without validation |
| training-data-poisoning | High | Untrusted dataset sources, unvalidated HTTP ingestion |
| model-dos | Medium | Missing max_tokens, recursive agent loops, no input validation |
| config-exposure | Medium | Hardcoded API keys, system prompts, model base URLs in config |

---

## Install

```bash
npm install -g @scan5/ai-guard      # CLI (global)
npm install @scan5/ai-guard          # SDK (project dependency)
```

## CLI Quickstart

```bash
ai-guard scan ./src                                    # Scan a directory
ai-guard scan https://github.com/owner/repo           # Scan a GitHub repo
ai-guard scan ./src --sarif report.sarif --json report.json  # CI outputs
ai-guard scan ./src --baseline baseline.json --ci-delta     # Delta mode
ai-guard scan ./src --siem-json siem-findings.ndjson        # Splunk/Datadog
```

## SDK Quickstart

```typescript
import { getSDK, wrapOpenAIClient } from "@scan5/ai-guard/sdk";

// Initialize with hard-block enforcement (default)
const sdk = getSDK({ enforcementMode: "hard-block" });

// Wrap your provider — scanning is automatic
const openai = wrapOpenAIClient(new OpenAI());

// Non-streaming: block before response if critical finding
const response = await openai.chat.completions.create({
  model: "gpt-4",
  messages: [{ role: "user", content: userInput }],
});
// If blocked: { object: "ai_guard.block", choices: [{ finish_reason: "ai_guard_blocked" }] }

// Streaming: interceptor scans chunks before delivery
const stream = await openai.chat.completions.create({
  stream: true,
  messages: [{ role: "user", content: userInput }],
});
// If critical finding mid-stream: terminates with [BLOCKED by AI Guard]
```

## Provider Wrappers

```typescript
import {
  wrapOpenAIClient, wrapAnthropicClient, wrapGeminiClient,
  wrapBedrockClient, wrapAzureOpenAIClient, wrapCohereClient,
  wrapMistralClient, wrapOllamaClient, wrapGenericOpenAICompatibleClient,
  wrapLangChainLLM, aiGuardMiddleware,
} from "@scan5/ai-guard/sdk";
```

## Enforcement Modes

| Mode | Behavior |
|---|---|
| `hard-block` | **Default.** Blocks requests with critical findings. Non-streaming returns error object, streaming terminates with `[BLOCKED]`. |
| `shadow-block` | Observes + logs warnings via `X-AI-Guard-Warning` headers. Marks `wouldHaveBlocked`. Never blocks. |
| `observe` | Scans and logs only. No warnings, no blocks. |

```typescript
const sdk = getSDK({ enforcementMode: "shadow-block" }); // validate before enabling
```

## Observability

```typescript
import { prometheusMetricsText, healthCheck } from "@scan5/ai-guard/sdk";

app.get("/metrics", (_, res) => res.type("text").send(prometheusMetricsText()));
app.get("/healthz", (_, res) => res.json(healthCheck()));
```

10 Prometheus metrics exposed: `ai_guard_scans_total`, `ai_guard_findings_total`, `ai_guard_runtime_requests_total`, `ai_guard_runtime_requests_blocked_total`, `ai_guard_runtime_errors_total`, and more.

## Enterprise Features

- **JWT auth** — workspace-scoped HS256 tokens with refresh
- **RBAC** — 4-tier role hierarchy (owner > admin > member > viewer) on all endpoints
- **Rate limiting** — Redis-backed sliding window with in-memory fallback
- **SSO** — SAML 2.0 + OIDC infrastructure (config via `AI_GUARD_SSO_MODE`)
- **Audit logging** — batched writes to Supabase `audit_logs` table
- **Alerting** — Slack, Discord, email, webhook, SIEM with dedup + retry + escalation
- **Docker** — `docker compose up` for full stack (API + Web + Redis)
- **Kubernetes** — Helm chart with autoscaling, PDB, health probes

## Docs

- **Tutorial**: 30-section guide at `/tutorial` in the dashboard
- **SDK**: `SDK_README.md`
- **Integration**: `docs/user-guide/integration-express.md`
- **Operations**: `docs/operations/production-deployment-guide.md`, `docs/operations/incident-response.md`

## Test

```bash
npm test                    # All tests
npm run test:unit           # 320 unit tests
npm run test:integration    # Integration tests
```

## Exit Codes

- `0`: Scan completed successfully
- `1`: Runtime failure
- `2`: Validation/config/input error

## License

MIT

## Version History

- **0.2.0** — Enforcement (hard-block/shadow-block/observe), 4 new providers (Cohere/Mistral/Ollama/Generic), streaming interceptor, RBAC, JWT auth, rate limiting, RAG/multimodal/multilingual rules, Prometheus metrics, web dashboard with findings triage + compliance posture, SSO infrastructure, Redis state layer, Helm chart, audit logging, penetration test suite
- **0.1.1** — GitHub device login, repo scan auth flow
- **0.1.0** — Initial release: CLI scanner + SDK
