Skip to content
PermutationResearchPublic

About

Sentinel: security layer for AI APIs, and the private chat

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

37 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sentinel

The trust layer for AI APIs.

Find out if your LLM API blocks prompt injection — before your users find out it doesn't.

Pilot offer: one API, one day, observe mode, measurable p95 latency and blocked-risk report.

Success metric: abusive requests intercepted before upstream, with false positives and added latency shown beside it.

npx @sentinelapi/probe --url=https://your-api.example.com/v1/chat

No account needed. Results in under 60 seconds.

What sentinel-probe does

Fires 52 attack payloads across 7 categories — prompt injection, jailbreak, multilingual attacks, obfuscated input, role-override attempts, character-substitution bypasses, and data exfiltration — plus a 30-request burst to simulate crawler abuse. Results print live as they arrive: a pass/fail verdict, the worst payloads that got through verbatim, and an estimated monthly cost if left unfiltered.

# Quick demo — 10 payloads, ~8 seconds
npx @sentinelapi/probe --url=https://your-api.example.com/v1/chat --quick

# Full scan with auth header
npx @sentinelapi/probe \
  --url=https://your-api.example.com/v1/chat \
  --field=prompt \
  --header="Authorization: Bearer sk-..."

Options

Flag Default Description
--url (required) Your API endpoint
--quick — 10-payload demo mode (~8s) — one per category
--field prompt JSON body field that holds the prompt
--header="K: V" — Extra request header, repeatable
--method POST HTTP method
--delay 80 ms between request batches
--concurrency 4 Parallel requests per batch (max 10)
--blocked-field — JSON response field to check for a block signal
--blocked-value true Value that means "blocked"
--format text text or json
--output — Save full JSON report to a file
--dry-run — Print what would be sent without making requests

Interpreting the report

  • CRITICAL / HIGH — attacks reach your model; exit code 1
  • MEDIUM — partial protection; review missed categories
  • LOW — good coverage; check false-positive rate
  • Cost exposure — estimated monthly spend from unfiltered abuse (GPT-4o pricing, 10k DAU, 5% malicious traffic ratio)
  • Data exfiltration — if any data-exfiltration payloads pass, customer PII is accessible via your chatbot
# Save a JSON report for CI
npx @sentinelapi/probe \
  --url=https://staging.example.com/chat \
  --format=json \
  --output=probe-report.json

# Dry-run to preview all 52 payloads without sending requests
npx @sentinelapi/probe --url=https://example.com/chat --dry-run

# If you cloned the repo you can also use:
npm run probe -- --url=https://example.com/chat --quick

Quick start (2 minutes)

cp .env.example .env   # defaults work out of the box for local dev
npm start

The server starts on http://localhost:8000 in DEV_MODE=true — no blockchain or Stripe keys needed to try it.

By default, the API runs as a plain trust-layer gateway for normal SaaS/API companies:

  • no wallet required
  • no on-chain registry required
  • no crypto branding exposed to your customers

Advanced on-chain reputation and HTTP 402 payment rails are available when a customer asks for them, but they are not part of the default product story. If you want the on-chain variant later, set REPUTATION_BACKEND=evm and provide the chain credentials.


Get an API key

curl -s -X POST http://localhost:8000/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"you@example.com"}' | jq .apiKey

Save the key — you'll use it as x-api-key on every request.


Core endpoints

1. Scan a prompt for injection

curl -s -X POST http://localhost:8000/inspect \
  -H "x-api-key: YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"prompt":"Summarize this ticket in 3 bullet points."}'
{ "blocked": false, "confidence": 0.01, "agentId": 3842901234 }

If an injection is detected, blocked: true and the agent's reputation is automatically docked −50.


2. Check reputation of one agent

curl -s http://localhost:8000/agents/42/reputation \
  -H "x-api-key: YOUR_KEY"

For callers that have a stable provider/customer identity instead of a numeric agent id, the convenience form hashes query into the same reputation space:

curl -s "http://localhost:8000/api/sentinel/reputation?query=customer-123" \
  -H "x-api-key: YOUR_KEY"
{
  "agentId": 42,
  "combinedScore": 75,
  "directScore": 80,
  "networkScore": 65,
  "feedbackCount": 12
}

3. Filter a batch of agents (cheapest per-check)

curl -s -X POST http://localhost:8000/agents/filter \
  -H "x-api-key: YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agentIds": [1, 2, 3, 42, 99],
    "minScore": 0
  }'
{
  "summary": { "checked": 5, "allowed": 4, "blocked": 1 },
  "allowed": [1, 2, 42, 99],
  "blocked": [3]
}

Combine with a prompt scan in one call — add "prompt": "..." to the body.


4. Submit feedback

curl -s -X POST http://localhost:8000/feedback \
  -H "x-api-key: YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"agentId": 42, "value": 10, "tag1": "helpful"}'

value range: −100 (terrible) to +100 (excellent).


5. Proxy any API (zero code changes)

Register your upstream API once:

curl -s -X POST http://localhost:8000/proxy/register \
  -H "x-api-key: YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "clientId":      "openai",
    "name":          "OpenAI",
    "adapter":       "openai",
    "targetBaseUrl": "https://api.openai.com",
    "authHeader":    "Authorization",
    "authValue":     "Bearer sk-YOUR-OPENAI-KEY"
  }'

Then point callers to /proxy/openai/... instead of api.openai.com/... — every request is automatically scanned and tracked. Supported adapter presets are generic-json, openai, anthropic, and graphql; omit adapter for generic-json.

You can also add automated report contacts at registration:

"contacts": [
  { "type": "email", "target": "security@client.com", "label": "Security Lead" },
  { "type": "webhook", "target": "https://hooks.slack.com/services/...", "label": "Slack Channel" }
]

Agent credit decision support

Sentinel keeps financial reputation separate from its security reputation. A credit score is calculated only from verified repayment, settlement, default, chargeback, and collateral events; self-reported events remain pending and have no score impact.

# An authorized verifier records an evidence-backed repayment
curl -s -X POST http://localhost:8000/credit/events \
  -H "x-api-key: ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agentId": 42,
    "idempotencyKey": "servicer:repayment:123",
    "type": "repayment-on-time",
    "facilityId": "facility-123",
    "amountCents": 50000,
    "verified": true,
    "verificationSource": "servicer",
    "evidenceHash": "sha256:..."
  }'

# The subject retrieves its private financial profile
curl -s http://localhost:8000/agents/42/credit/profile \
  -H "x-api-key: SUBJECT_KEY"

# Generate an explainable, advisory short-duration credit decision
curl -s -X POST http://localhost:8000/credit/decisions \
  -H "x-api-key: SUBJECT_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "requestedPrincipalCents": 25000,
    "durationDays": 30,
    "collateralValueCents": 40000
  }'

Decisions return approve, review, or decline, reason codes, confidence, and recommended exposure/duration/collateral boundaries. They are decision support only: Sentinel does not originate loans, custody collateral, perform KYC/AML, or replace affordability and legal checks. See docs/agent-credit.md and the phased custody-first credit program.


All endpoints

Method Path What it does
GET /health Server status
GET /openapi.json OpenAPI discovery document for the integration surface
GET /.well-known/api-security.json API/agent security discovery manifest
GET /.well-known/agent-security.json Alias discovery manifest for agents
GET /pricing Plans and rates
GET /identity Your resolved agentId (free)
POST /auth/register Get an API key by email
POST /auth/privy Optional: link a wallet (10% discount, only when enabled)
GET /billing/usage Quota and credit balance
POST /billing/checkout/subscription Upgrade plan
POST /billing/checkout/credits Top up credits
GET /agents/:id/reputation Single agent score
GET /api/sentinel/reputation?query=... Convenience score lookup by agent id or stable identity
POST /inspect Prompt injection scan
GET /trust/:clientId/agent-security.json Client-specific security/trust integration manifest
POST /agents/filter Batch score + optional scan
POST /feedback Write reputation feedback
GET /agents/recommend UCB-ranked agent list
POST /credit/events Record an idempotent pending or verifier-approved credit event
POST /credit/events/:eventId/verification Admin/verifier: finalize a pending event
GET /agents/:id/credit/events List the subject's private financial history
GET /agents/:id/credit/profile Financial score, confidence, metrics, and reason codes
POST /credit/decisions Explainable advisory credit eligibility and terms
POST /proxy/register Register an upstream API
GET /proxy/clients List your proxies
POST /proxy/:clientId/tokens Issue scoped, short-lived proxy token
GET /proxy/:clientId/tokens List active proxy tokens (metadata only)
POST /proxy/:clientId/tokens/revoke Revoke a proxy token
GET /proxy/:clientId/reputation-feed Anonymized suspicious-traffic feed for provider sharing
ANY /proxy/:clientId/* Scan + forward + track
GET /admin/metrics Admin: global and per-tenant trust metrics
GET /admin/slo Admin: pass/fail SLO status snapshot
GET /admin/compliance/iso42001 Admin: ISO 42001 readiness checks and failed controls
POST /admin/incidents/ai Admin: log AI incidents as audit evidence
GET /admin/incidents/ai Admin: list AI incident evidence log
POST /admin/proxy/:clientId/policy Admin: update/rollback tenant policy
POST /admin/reports/send Admin: force-send daily/weekly reports (`{"kind":"daily

Plans

Plan Price Reads Writes
Free $0 200 5
Builder $15/mo 5,000 300
Scale $49/mo 100,000 2,000
Business $149/mo 1,000,000 15,000
Enterprise Contact us Unlimited Unlimited

Or pay as you go: $0.005 per read · $0.08 per write · $0.002 per agent filtered.


Production checklist

  • Set DEV_MODE=false
  • Set BASE_URL to your public HTTPS URL
  • Set DATABASE_URL; production fails closed without PostgreSQL user, billing, audit, and outbox authority
  • Use a dedicated PostgreSQL application role with NOSUPERUSER NOBYPASSRLS; production refuses unsafe roles
  • Set REDIS_URL; production requires distributed rate limits, lockouts, idempotency, and cache state
  • Run npm run verify:user-postgres against an isolated staging database
  • Run npm run verify:organization-postgres against an isolated database owned by the production-shaped application role
  • Run npm run verify:receipts-postgres and npm run verify:compliance-postgres under that same role
  • Run npm run verify:security-outbox-postgres and prove signed, idempotent acceptance against the configured security-event receiver
  • Run npm run verify:proxy-postgres under the production-shaped role
  • Run the proxy migration dry-run, resolve every ambiguous organization mapping, apply in the approved cutover window, and prove an idempotent rerun
  • Put API behind trusted ingress/proxy and set TRUST_PROXY=true
  • Choose REPUTATION_BACKEND=offchain or evm
  • If using evm, set real RPC_URL, REPUTATION_REGISTRY, SERVICE_PRIVATE_KEY
  • Set real Stripe keys
  • Optional: enable Privy only after its client login, recovery, revocation, MFA, and organization-role flows pass end-to-end testing
  • Set a strong ADMIN_API_KEY
  • Restrict admin HTTP surface: set ADMIN_IP_ALLOWLIST (comma-separated IPs or IPv4 CIDRs) and/or ADMIN_HTTP_DISABLED=true on public ingress; optional REQUIRE_ADMIN_IP_ALLOWLIST=true to fail boot if the allowlist is empty
  • Tune auth brute-force backoff if needed: AUTH_FAILURE_MAX, AUTH_FAILURE_WINDOW_MS, AUTH_LOCKOUT_MS, AUTH_LOCKOUT_ENABLED
  • Key rotation: see docs/KEY-ROTATION.md
  • Set compliance controls (SHADOW_RECEIPTS_ENABLED=true, SLO thresholds, COMPLIANCE_AUDIT_FILE)
  • Configure global abuse limits:
    • GLOBAL_RATE_LIMIT_WINDOW_MS=60000
    • GLOBAL_RATE_LIMIT_IP_MAX=120
    • GLOBAL_RATE_LIMIT_AUTH_MAX=600
  • Run python3 src/inspector.py (dual-model scan; falls back to heuristic if down)
  • Verify hardening headers are present (CSP, HSTS, X-Frame-Options, Referrer-Policy)
  • Configure automated reporting:
    • REPORTS_ENABLED=true
    • REPORT_DAILY_UTC_HOUR=14
    • REPORT_WEEKLY_UTC_DAY=1 (Mon)
    • REPORT_WEEKLY_UTC_HOUR=15
    • REPORTING_DB_FILE=./data/reporting-metrics.json
  • Configure delivery channels:
    • Webhooks only: no extra env needed
    • Email via Resend: RESEND_API_KEY, REPORTS_FROM_EMAIL


Client onboarding — proxy setup (end-to-end)

This is the exact sequence to give a client access to the proxy layer.

Step 1 — Create an account and get an API key

curl -s -X POST https://YOUR_DOMAIN/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"client@example.com"}' | jq .apiKey
# → "sk_live_..."

In production, the client receives a verification email before the key is active.

Step 2 — Register their upstream API as a proxy target

curl -s -X POST https://YOUR_DOMAIN/proxy/register \
  -H "x-api-key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "clientId":      "acme-openai-prod",
    "name":          "Acme — OpenAI Production",
    "adapter":       "openai",
    "targetBaseUrl": "https://api.openai.com",
    "authHeader":    "Authorization",
    "authValue":     "Bearer sk-proj-...",
    "blockOnFlag":   true,
    "contacts": [
      { "type": "webhook", "target": "https://acme.example.com/hooks/reputation", "label": "Security alerts" }
    ],
    "policy": {
      "reputationBlockThreshold": -30,
      "blockOnInjection": true
    }
  }'

The authValue is encrypted at rest immediately. Any webhook URLs are live-tested during registration — if unreachable, the call returns 400 before persisting anything. Adapter presets choose sensible prompt extraction defaults; set promptFields only when a tenant has a custom request shape.

Step 3 — Issue scoped client token (never expose real provider key)

curl -s -X POST https://YOUR_DOMAIN/proxy/acme-openai-prod/tokens \
  -H "x-api-key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "environment": "prod",
    "ttlSeconds": 86400,
    "scopes": ["proxy:forward","flags:read:public","config:eval:safe-only","no-full-dump"],
    "label": "web-client-prod"
  }'

Return includes the raw token once. Use that token in x-proxy-token from browser/mobile/server clients.

Step 4 — Secure mode for browser/mobile SDKs

Enable on registration via:

"secureMode": {
  "enabled": true,
  "secret": "long-random-secret",
  "requiredForClient": true
}

Client-side calls must send:

  • x-secure-user-id
  • x-secure-user-hash where hash = HMAC_SHA256(userId, secureMode.secret)

When secure mode is enforced, the proxy returns only a minimal flags payload and strips extra config fields.

Response:

{
  "status": "registered",
  "clientId": "acme-openai-prod",
  "proxyUrl": "https://YOUR_DOMAIN/proxy/acme-openai-prod",
  "webhooksTested": 1
}

Step 3 — Point the client's app at the proxy URL

The client replaces their OpenAI base URL:

- baseURL: "https://api.openai.com"
+ baseURL: "https://YOUR_DOMAIN/proxy/acme-openai-prod"

All other code stays the same. Their Authorization header is forwarded to OpenAI; the proxy layer adds reputation scoring and injection detection transparently.

Step 4 — Verify a test request flows through

curl -s -X POST https://YOUR_DOMAIN/proxy/acme-openai-prod/v1/chat/completions \
  -H "x-api-key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Hello"}]}'

You should see a normal OpenAI response plus x-reputation-score and x-reputation-tier headers. Check the dashboard for the decision event.

Dashboard

https://YOUR_DOMAIN/dashboard?key=ADMIN_API_KEY

Live view of request volume, injection blocks, reputation blocks, inspector status, and the most recent 50 decision events. Auto-refreshes every 10 s.


Run tests

npm run typecheck
npm test

CI (.github/workflows/ci.yml) runs typecheck, tests, required high-severity dependency audit, manual security controls automation, and the API security checklist script. See docs/dependency-vulnerability-policy.md for the dependency gate policy.

TypeScript 7 dual-compiler setup

npm run typecheck and npm run build invoke the Go-native TypeScript 7 compiler directly (node_modules/typescript-7/bin/tsc, ~7× faster checks). The typescript package name is aliased to @typescript/typescript6 because tools that consume the compiler's JS API (typescript-eslint) don't support TS 7 until its stable programmatic API lands in 7.1 — once typescript-eslint declares TS 7 support, collapse the alias back to a single typescript@^7 dependency and restore the plain tsc script invocations. TS 7's checker is semantically identical to 6.0, so both compilers agree on the code.

Observability

JSON error responses usually include requestId (and related trace headers). Forward structured logs and GET /admin/events / GET /admin/metrics data to your SIEM or metrics stack for anomaly detection and alerting.

Smoke checks

curl -s http://localhost:8000/ | jq .
curl -s http://localhost:8000/health | jq .
curl -s http://localhost:8000/robots.txt
curl -s http://localhost:8000/onboarding/checklist -H "x-api-key: YOUR_KEY" | jq .

Docker

docker compose up --build

Persistence

Production user, organization, proxy-client and policy authority lives in PostgreSQL. JSON stores are development fixtures or explicit migration inputs:

  • USER_DB_FILE — default ./data/users.json
  • PROXY_DB_FILE — legacy/development proxy-client input; migrate with npm run migrate:proxy-clients:dry-run then npm run migrate:proxy-clients:apply
  • CREDIT_EVENTS_FILE — default ./data/credit-events.json
  • ASSET_PASSPORT_FILE — default ./data/asset-passports.json (custody-first pilot only)

Production must not use shared JSON files as an authority.


Execution playbooks

  • docs/plan-30-60-90.md — ICP, KPI proof motion, and 90-day execution plan
  • docs/slo-and-rollout-spec.md — latency/false-positive SLOs and rollout ladder
  • docs/one-day-quickstart.md — one-day integration path for API providers
  • docs/drop-in-proxy-patterns.md — code patterns for drop-in proxy adoption
  • docs/integration-recipes.md — stack-specific recipes for OpenAI, Anthropic, Vercel AI SDK, Next.js, FastAPI, Express/Hono, and GraphQL
  • docs/protected-api-contract.md — the technical contract for a protected AI API
  • docs/compliance-enabling-controls.md — compliance-support control mapping and claim guidance
  • docs/iso-42001-readiness.md — ISO 42001 readiness controls, evidence, and audit checklist
  • docs/compliance/iso42001/risk-register.md — AI risk register template
  • docs/compliance/iso42001/ai-incident-response-runbook.md — AI incident response procedure
  • docs/compliance/iso42001/model-and-dependency-register.md — model and supplier dependency inventory
  • docs/standards/reason-codes-v1.md — interoperable trust reason-code taxonomy
  • docs/standards/trust-decision-receipts-v1.md — signed trust decision receipt spec
  • docs/standards/agent-api-security-manifest-v1.md — .well-known discovery manifest for protected AI APIs
  • docs/custody-passport-api.md — custody-first asset passport pilot API and funding gates
  • docs/custody-first-credit-program.md — legal, operating and external-audit requirements before a live custody-first credit pilot
  • docs/custody-credit-workspace.md — unified lender workspace, governance, reporting and agent-security funding controls

Local dual-model inspector

The local inspector can be started with bash scripts/start-inspector.sh. The launcher uses .venv, the configured models/ directory, one CPU thread per model, and opt-in eager weight loading (INSPECTOR_DISABLE_MMAP=true) to avoid stalls on external storage. The verified local setup uses Transformers 5.23.0 and model weights on the LaCie volume; that volume must be mounted.

For a local development API, set DEV_MODE=true and INSPECT_TIMEOUT_MS=3000 when starting the API; its default inspector timeout is 350 ms. Inspect responses report whether they fell back to the heuristic. This local setup is not production qualification.

About

Sentinel: security layer for AI APIs, and the private chat

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages