{"id":51702338,"url":"https://github.com/reaatech/agent-auth-proxy","last_synced_at":"2026-07-16T12:30:46.049Z","repository":{"id":354491425,"uuid":"1223078496","full_name":"reaatech/agent-auth-proxy","owner":"reaatech","description":"Identity-aware proxy for agent-to-service communication. OAuth2 token management, per-user credential isolation, scope enforcement, and audit logging. Agents act on behalf of users safely.","archived":false,"fork":false,"pushed_at":"2026-06-29T13:16:18.000Z","size":483,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-29T15:14:05.027Z","etag":null,"topics":["agent-auth","agent-proxy","agentic-ai","ai","ai-agents","developer-tools","mcp","oauth2","security","typescript"],"latest_commit_sha":null,"homepage":"https://reaatech.com/products/testing-security/agent-auth-proxy","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/reaatech.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2026-04-28T01:46:18.000Z","updated_at":"2026-06-29T13:18:20.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/reaatech/agent-auth-proxy","commit_stats":null,"previous_names":["reaatech/agent-auth-proxy"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/reaatech/agent-auth-proxy","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reaatech%2Fagent-auth-proxy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reaatech%2Fagent-auth-proxy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reaatech%2Fagent-auth-proxy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reaatech%2Fagent-auth-proxy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/reaatech","download_url":"https://codeload.github.com/reaatech/agent-auth-proxy/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reaatech%2Fagent-auth-proxy/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35544514,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-16T02:00:06.687Z","response_time":83,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent-auth","agent-proxy","agentic-ai","ai","ai-agents","developer-tools","mcp","oauth2","security","typescript"],"created_at":"2026-07-16T12:30:45.309Z","updated_at":"2026-07-16T12:30:46.037Z","avatar_url":"https://github.com/reaatech.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Agent Auth Proxy\n\nIdentity-aware reverse proxy for secure agent-to-service communication.\n\nA stateful proxy layer that sits between AI agents and downstream APIs (Google, GitHub, etc.), managing OAuth2 tokens, API keys, and scope enforcement on behalf of users. Built with a zero-trust security model — every request is authenticated, authorized, and audited.\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)\n[![Node.js](https://img.shields.io/badge/node-%3E%3D22.0.0-green)](package.json)\n[![pnpm](https://img.shields.io/badge/pnpm-%3E%3D10.0.0-orange)](package.json)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.8%2B-blue)](tsconfig.json)\n\n---\n\n## Table of Contents\n\n- [Features](#features)\n- [Architecture](#architecture)\n- [Tech Stack](#tech-stack)\n- [Prerequisites](#prerequisites)\n- [Quick Start](#quick-start)\n- [Configuration](#configuration)\n- [API Overview](#api-overview)\n- [Development](#development)\n- [Deployment](#deployment)\n- [Project Structure](#project-structure)\n- [Security](#security)\n- [Contributing](#contributing)\n- [License](#license)\n\n---\n\n## Features\n\n### Core\n\n- **OAuth2 Proxy** — Full authorization code flow with PKCE, automatic token refresh, and transparent credential injection into proxied requests\n- **API Key Vault** — AES-256-GCM encrypted storage for service credentials with per-user encryption keys derived via scrypt (N=16384)\n- **Scope Enforcement** — Fine-grained permission control per user-agent grant with escalation detection and risk-level ceilings\n- **Agent Authentication** — JWT-based agent identity with short-lived tokens and API key exchange\n\n### Security\n\n- **Zero-Trust Model** — Every request authenticated, authorized, and audited; no implicit trust between components\n- **Defense in Depth** — Multiple validation layers: authentication → authorization → scope validation → credential selection\n- **Rate Limiting** — Per-IP, per-user, and per-agent rate limiting with configurable windows\n- **Header Sanitization** — Security-sensitive response headers stripped from downstream API responses\n- **Constant-Time Comparison** — Admin API key validation resists timing attacks\n\n### Operations\n\n- **Structured Audit Logging** — Comprehensive audit trail with SIEM forwarding support (JSON, structured pino logs)\n- **Health \u0026 Readiness** — `/health` and `/ready` endpoints for orchestration probes\n- **Prometheus Metrics** — Request duration, auth success/failure, token refreshes, rate limit hits, scope violations\n- **Circuit Breaker** — Proxy-to-upstream circuit breaker with configurable failure thresholds\n\n---\n\n## Architecture\n\n```\n┌─────────────┐      ┌──────────────────────┐      ┌─────────────────┐\n│   AI Agent  │─────▶│   Agent Auth Proxy   │─────▶│  Downstream API │\n│  (Client)   │      │   (Identity Layer)   │      │  (Google, etc)  │\n└─────────────┘      └──────────────────────┘      └─────────────────┘\n                            │\n                            ▼\n                    ┌──────────────┐\n                    │  PostgreSQL  │\n                    └──────────────┘\n```\n\n**Request Pipeline:**\n1. Authenticate agent (JWT validation)\n2. Extract user context and requested scopes\n3. Validate granted scopes (scope enforcement)\n4. Retrieve and decrypt user credentials\n5. Attach credentials to downstream request\n6. Forward and stream response back to agent\n\nSee [ARCHITECTURE.md](ARCHITECTURE.md) for detailed component design, security model, scaling strategy, and monitoring setup.\n\n---\n\n## Tech Stack\n\n| Layer | Technology |\n|---|---|\n| **Runtime** | Node.js 22+ |\n| **Framework** | Fastify 5 |\n| **Language** | TypeScript 5.8+ (strict mode) |\n| **Database** | PostgreSQL 15+ |\n| **ORM** | Drizzle ORM |\n| **Auth** | `@fastify/jwt`, PKCE OAuth2 |\n| **Validation** | Zod |\n| **Logging** | Pino (structured JSON) |\n| **Metrics** | prom-client |\n| **Package Manager** | pnpm 10+ (workspaces) |\n| **Build orchestration** | Turborepo |\n| **Build** | tsup |\n| **Lint/format** | Biome |\n| **Test** | Vitest, Supertest |\n| **Versioning** | Changesets |\n| **Container** | Docker, Docker Compose |\n| **Orchestration** | Kubernetes (manifests provided) |\n\n---\n\n## Prerequisites\n\n- **Node.js** \u003e= 22.0.0\n- **pnpm** \u003e= 10.0.0\n- **PostgreSQL** 15+ (or Docker for local development)\n- **Docker \u0026 Docker Compose** (optional, for containerized setup)\n\n---\n\n## Quick Start\n\n### Option 1: Docker Compose\n\n```bash\n# Clone the repository\ngit clone https://github.com/reaatech/agent-auth-proxy.git\ncd agent-auth-proxy\n\n# Configure environment\ncp .env.example .env\n# Edit .env with your secrets (see Configuration section)\n\n# Start services\ndocker compose up -d\n\n# Run database migrations\ndocker compose --profile setup run --rm migrate\n\n# Verify\ncurl http://localhost:3000/health\n```\n\n### Option 2: Local Development\n\n```bash\n# Install dependencies\npnpm install\n\n# Configure environment\ncp .env.example .env\n# Edit .env — set DATABASE_URL and generate MASTER_KEY\n\n# Start PostgreSQL (Docker convenience)\ndocker compose up -d db\n\n# Run migrations\npnpm db:migrate\n\n# Start development server with hot reload\npnpm dev\n```\n\n---\n\n## Configuration\n\n### Required Environment Variables\n\n| Variable | Description |\n|---|---|\n| `DATABASE_URL` | PostgreSQL connection string |\n| `MASTER_KEY` | Base64-encoded 32-byte encryption key for credential vault |\n| `AGENT_JWT_SECRET` | Secret key for signing agent JWTs (32+ chars recommended) |\n| `ADMIN_API_KEY` | Pre-shared key for management API endpoints |\n\n### OAuth Providers\n\n| Variable | Required For |\n|---|---|\n| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | Google API proxy |\n| `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` | GitHub API proxy |\n| `OAUTH_REDIRECT_URI` | OAuth2 callback URL (e.g., `https://proxy.example.com`) |\n\n### Optional\n\n| Variable | Default | Description |\n|---|---|---|\n| `PORT` | `3000` | Server listen port |\n| `HOST` | `0.0.0.0` | Server bind address |\n| `NODE_ENV` | `development` | Environment (`development`, `production`, `test`) |\n| `AGENT_JWT_EXPIRY` | `3600` | Agent JWT lifetime in seconds |\n| `RATE_LIMIT_GLOBAL_MAX` | `1000` | Max requests per IP per 15-minute window |\n| `PROXY_STREAM_TIMEOUT_MS` | `60000` | Upstream response timeout (ms) |\n| `PROXY_BODY_LIMIT_BYTES` | `10485760` | Max request body size (10 MB) |\n| `AUDIT_RETENTION_DAYS` | `90` | Days to retain audit logs |\n| `AUDIT_BATCH_SIZE` | `100` | Audit log batch size for DB writes |\n| `AUDIT_FLUSH_INTERVAL_MS` | `5000` | Audit log flush interval (ms) |\n| `SIEM_ENDPOINT` | — | SIEM forwarding URL |\n| `SIEM_API_KEY` | — | SIEM authentication key |\n\n### Generating Secrets\n\n```bash\n# Generate MASTER_KEY (base64-encoded 32-byte key)\nnode -e \"console.log(require('crypto').randomBytes(32).toString('base64'))\"\n\n# Generate ADMIN_API_KEY (base64url-encoded 32-byte key)\nnode -e \"console.log(require('crypto').randomBytes(32).toString('base64url'))\"\n\n# Generate AGENT_JWT_SECRET\nnode -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"\n```\n\n---\n\n## API Overview\n\n### Agent Authentication\n\n```\nPOST /auth/agent\nAuthorization: Bearer \u003cagent_api_key\u003e\n\nResponse: { \"token\": \"\u003cjwt\u003e\", \"agent\": { \"id\": \"\u003cuuid\u003e\", \"name\": \"\u003cstring\u003e\" } }\n```\n\nAgents exchange their long-lived API key (prefix `aap_`) for a short-lived JWT (default 1 hour). The JWT is then used as a Bearer token for all proxied requests. Agent API keys are returned by `POST /api/v1/agents` at registration time — they are shown only once.\n\n### Proxy Requests\n\nProxied requests forward method, path, headers, and body to the target downstream API with the user's credentials attached.\n\n```\nMETHOD /proxy/:provider/\u003cpath...\u003e\nAuthorization: Bearer \u003cagent_jwt\u003e\nX-User-ID: \u003cuser_id\u003e\n?_scope=\u003ccomma,separated,scopes\u003e      # Optional: enforce scopes\n\n# Example: Read Google Calendar\ncurl -X GET \"http://localhost:3000/proxy/google/calendar/v3/calendars/primary?_scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly\" \\\n  -H \"Authorization: Bearer \u003cagent_jwt\u003e\" \\\n  -H \"X-User-ID: \u003cuser_id\u003e\"\n```\n\nThe proxy forwards status codes, headers, and body directly from the downstream API. No response envelope — compatible with standard HTTP clients and SDKs.\n\n**Supported providers:** `google`, `github`\n\n### Management API\n\nAll management endpoints are mounted under `/api/v1` and require the admin API key passed via the `X-Admin-API-Key` header.\n\n**Users:**\n| Method | Path | Description |\n|---|---|---|\n| `POST` | `/api/v1/users` | Create a user |\n| `GET` | `/api/v1/users/:id` | Get user details |\n| `DELETE` | `/api/v1/users/:id` | Delete a user |\n| `GET` | `/api/v1/users/:id/grants` | List user's agent grants |\n\n**Agents:**\n| Method | Path | Description |\n|---|---|---|\n| `POST` | `/api/v1/agents` | Register a new agent (response includes the one-time `api_key`) |\n| `GET` | `/api/v1/agents/:id` | Get agent details |\n| `DELETE` | `/api/v1/agents/:id` | Delete an agent |\n\n**Grants:**\n| Method | Path | Description |\n|---|---|---|\n| `POST` | `/api/v1/grants` | Create user-agent grant with scopes |\n| `GET` | `/api/v1/grants` | List all grants |\n| `DELETE` | `/api/v1/grants/:id` | Revoke a grant |\n\n**Tokens:**\n| Method | Path | Description |\n|---|---|---|\n| `GET` | `/api/v1/tokens` | List OAuth token metadata (no secrets) |\n| `DELETE` | `/api/v1/tokens/:id` | Revoke a token |\n\n**OAuth:**\n| Method | Path | Description |\n|---|---|---|\n| `GET` | `/oauth/authorize?user_id\u0026provider\u0026scopes` | Initiate OAuth2 authorization flow (redirects to provider) |\n| `GET` | `/oauth/:provider/callback` | OAuth2 callback (handled by provider redirect) |\n\n### Client SDK\n\nA typed TypeScript SDK is published as `@reaatech/agent-auth-proxy-client`. It wraps these endpoints with `AgentClient` (auth + proxy) and `AdminClient` (management). See [`packages/client/README.md`](packages/client/README.md).\n\n---\n\n## Development\n\n```bash\n# Install dependencies\npnpm install\n\n# Start development server (hot reload)\npnpm dev\n\n# Build for production\npnpm build\n\n# Run all tests\npnpm test\n\n# Run tests with coverage\npnpm test:coverage\n\n# Run tests in watch mode\npnpm test:watch\n\n# Run security-focused tests\npnpm test:security\n\n# Type-check the project\npnpm typecheck\n\n# Lint and format\npnpm lint\npnpm format\n\n# Database operations\npnpm db:generate          # Generate migration files from schema\npnpm db:migrate           # Run pending migrations\npnpm db:seed              # Seed database with test data\npnpm db:studio            # Open Drizzle Studio (GUI)\n\n# Security audit\npnpm audit\n```\n\n### Code Quality\n\nCI enforces:\n- Biome lint + format (`pnpm lint`, `pnpm format:check`)\n- TypeScript strict mode (`pnpm typecheck`)\n- Test coverage thresholds (85% lines, 85% functions, 78% branches)\n- `pnpm audit` at moderate level and above\n\n---\n\n## Deployment\n\n### Docker\n\n```bash\n# Build the image\npnpm docker:build\n\n# Run with Docker Compose\npnpm docker:up\n\n# Tear down\npnpm docker:down\n```\n\nThe Dockerfile uses multi-stage builds: a `builder` stage compiles TypeScript, and a slim `runtime` stage runs the application as a non-root `nodejs` user.\n\n### Kubernetes\n\nKubernetes manifests are provided in `k8s/`:\n\n| Manifest | Purpose |\n|---|---|\n| `deployment.yaml` | 3-replica deployment with resource limits and health probes |\n| `service.yaml` | ClusterIP service on port 3000 |\n| `ingress.yaml` | Ingress configuration for external access |\n| `hpa.yaml` | HorizontalPodAutoscaler (3–20 replicas, CPU 70% / memory 80%) |\n| `secrets.yaml` | Secret template for `DATABASE_URL`, `MASTER_KEY`, etc. |\n\n```bash\nkubectl apply -f k8s/\n```\n\n### Production Considerations\n\n- Front the service with a reverse proxy (nginx, AWS ALB) for TLS termination\n- Store secrets in a secrets manager (AWS Secrets Manager, HashiCorp Vault, Kubernetes Secrets)\n- Set `NODE_ENV=production`\n- Enable audit log SIEM forwarding for centralized monitoring\n- Rotate `MASTER_KEY`, `AGENT_JWT_SECRET`, and `ADMIN_API_KEY` regularly\n\n---\n\n## Project Structure\n\nThis is a pnpm + Turborepo monorepo with three publishable packages.\n\n```\nagent-auth-proxy/\n├── packages/\n│   ├── core/                          # @reaatech/agent-auth-proxy-core\n│   │   └── src/                       # zod schemas, OAuth/scope types, error classes\n│   ├── client/                        # @reaatech/agent-auth-proxy-client\n│   │   └── src/                       # AgentClient + AdminClient SDKs (fetch-based)\n│   └── server/                        # @reaatech/agent-auth-proxy-server\n│       ├── src/\n│       │   ├── api/                   # Fastify routes and middleware\n│       │   ├── auth/                  # OAuth2 manager, key vault, scope enforcer\n│       │   ├── config/                # Environment and app configuration\n│       │   ├── db/\n│       │   │   ├── schema/            # Drizzle ORM table definitions\n│       │   │   └── migrations/        # SQL migration files\n│       │   ├── proxy/                 # Proxy engine\n│       │   ├── services/              # Audit logging, cleanup tasks\n│       │   ├── utils/                 # Crypto, logger\n│       │   ├── app.ts                 # buildApp() / start() — library entry\n│       │   └── bin.ts                 # CLI entry (#!/usr/bin/env node)\n│       ├── tests/                     # Vitest suites (unit + integration + security)\n│       ├── scripts/                   # migrate.ts, seed.ts\n│       ├── drizzle.config.ts\n│       └── vitest.config.ts\n├── docs/                              # Extended documentation\n├── skills/                            # AI agent development skill definitions\n├── k8s/                               # Kubernetes manifests\n├── docker/                            # Docker assets\n├── .github/workflows/                 # CI/CD pipeline definitions\n├── .changeset/                        # Changesets for versioning + publishing\n├── Dockerfile                         # Builds and runs packages/server\n├── docker-compose.yml                 # Local development stack\n├── pnpm-workspace.yaml\n├── turbo.json\n├── biome.json\n├── tsconfig.json                      # Shared base config\n└── package.json                       # Workspace root (private)\n```\n\n### Package responsibilities\n\n| Package | Purpose | Depends on |\n|---|---|---|\n| `@reaatech/agent-auth-proxy-core` | Shared zod schemas, OAuth/scope types, error classes. No framework deps. | `zod` |\n| `@reaatech/agent-auth-proxy-client` | Typed HTTP SDK (`AgentClient`, `AdminClient`) for talking to the proxy. | `core` |\n| `@reaatech/agent-auth-proxy-server` | Fastify-based proxy server. Embeddable via `buildApp()`/`start()`, runnable via the `agent-auth-proxy-server` bin. | `core` |\n\n---\n\n## Security\n\n- **Credential Encryption:** OAuth tokens and API keys are encrypted at rest with AES-256-GCM, with per-user encryption keys derived via scrypt (N=16384) from the `MASTER_KEY`\n- **Agent Auth:** Short-lived JWTs (default 1 hour) with unique token IDs for revocation\n- **Admin API:** Protected by a pre-shared key validated with constant-time comparison\n- **No Credential Exposure:** Decrypted credentials are never returned to agents — they are attached by the proxy internally\n- **Header Stripping:** Downstream security headers (`set-cookie`, `x-powered-by`, etc.) are removed from proxy responses\n\nFor reporting vulnerabilities, see [SECURITY.md](SECURITY.md). Do not open public issues for security concerns.\n\n---\n\n## Contributing\n\nContributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on:\n\n- Development setup\n- Code style (Biome, Conventional Commits)\n- Testing requirements\n- Pull request process (Changesets for versioning)\n- Security best practices\n\n---\n\n## License\n\nMIT © 2026 Rick Somers. See [LICENSE](LICENSE) for full terms.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freaatech%2Fagent-auth-proxy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Freaatech%2Fagent-auth-proxy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freaatech%2Fagent-auth-proxy/lists"}