# auth

Adopt this skill: https://proskills.md/skills/other/benja-pauls-serpentstack-skills-auth

Page: https://proskills.md/skills/other/benja-pauls-serpentstack-skills-auth
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: .skills/auth/SKILL.md
size: 6414
sha: a93db09c318654584710ecf543deaa2fc3b09a03
upstream: https://github.com/benja-pauls/serpentstack/blob/main/.skills/auth/SKILL.md

````text
---
name: auth
description: "Understand and customize authentication in this project. Use when: adding auth to routes, swapping auth providers (Clerk, Auth0, custom SSO), debugging auth issues, or understanding the UserInfo contract and get_current_user dependency."
---

# Auth

SerpentStack ships with working local JWT authentication (register, login, token validation). This skill explains the auth architecture and how to swap providers.

## How Auth Works (Built-in)

### Architecture

```
POST /api/v1/auth/register  →  UserService.register()  →  bcrypt hash  →  DB  →  JWT
POST /api/v1/auth/login     →  UserService.authenticate()  →  verify hash  →  JWT
GET  /api/v1/auth/me        →  get_current_user dependency  →  decode JWT  →  UserResponse

Any protected route:
    @router.delete("/{id}")
    async def delete(user: UserInfo = Depends(get_current_user)):
        # user.user_id, user.email available here
```

### Key Files

| File | Role |
|---|---|
| `backend/app/routes/auth.py` | Auth routes + `get_current_user` dependency |
| `backend/app/services/user.py` | Registration, authentication, password hashing |
| `backend/app/models/user.py` | User SQLAlchemy model (email, hashed_password) |
| `backend/app/schemas/user.py` | Request/response schemas (register, login, token) |
| `backend/app/middleware/auth.py` | Optional global auth middleware (not enabled by default) |

### The `UserInfo` Contract

All protected routes receive a `UserInfo` object via dependency injection:

```python
class UserInfo(BaseModel):
    user_id: str
    email: str | None = None
    name: str | None = None
    raw_claims: dict[str, Any] = {}
```

**This is the interface between auth and the rest of the app.** When swapping providers, keep this shape — every route that uses `Depends(get_current_user)` depends on it.

## Protecting a Route

Add `Depends(get_current_user)` to any route that requires authentication:

```python
from app.routes.auth import UserInfo, get_current_user

@router.post("")
async def create_thing(
    payload: ThingCreate,
    user: UserInfo = Depends(get_current_user),  # ← requires valid JWT
    db: AsyncSession = Depends(get_db),
    service: ThingService = Depends(get_thing_service),
) -> ThingResponse:
    thing = await service.create(payload, owner_id=user.user_id)
    await db.commit()
    return ThingResponse.model_validate(thing)
```

For optional auth (authenticated if token present, anonymous otherwise):

```python
from app.routes.auth import get_optional_user

@router.get("")
async def list_things(
    user: UserInfo | None = Depends(get_optional_user),
) -> list[ThingResponse]:
    # user is None if no token, UserInfo if authenticated
    ...
```

## Swapping to an External Provider

To replace the built-in JWT auth with Clerk, Auth0, or another provider:

### Step 1: Replace `get_current_user` in `routes/auth.py`

The **only function you need to change** is `get_current_user`. Replace JWT decode with your provider's token validation:

**For Clerk** — see [Clerk FastAPI guide](https://clerk.com/docs/references/fastapi/overview):
```python
from jwt import PyJWKClient

jwks_client = PyJWKClient("https://your-clerk-domain/.well-known/jwks.json")

async def get_current_user(
    credentials: HTTPAuthorizationCredentials | None = Security(bearer_scheme),
) -> UserInfo:
    if credentials is None:
        raise HTTPException(status_code=401, detail="Not authenticated")

    token = credentials.credentials
    signing_key = jwks_client.get_signing_key_from_jwt(token)
    payload = jwt.decode(token, signing_key.key, algorithms=["RS256"])

    return UserInfo(
        user_id=payload["sub"],
        email=payload.get("email"),
        name=payload.get("name"),
        raw_claims=payload,
    )
```

**For Auth0** — see [Auth0 FastAPI guide](https://auth0.com/docs/quickstart/backend/python/01-authorization):
```python
jwks_client = PyJWKClient("https://your-tenant.auth0.com/.well-known/jwks.json")

async def get_current_user(...) -> UserInfo:
    # Same pattern, add audience validation:
    payload = jwt.decode(
        token, signing_key.key, algorithms=["RS256"],
        audience="your-api-audience",
        issuer="https://your-tenant.auth0.com/",
    )
    return UserInfo(user_id=payload["sub"], email=payload.get("email"), ...)
```

### Step 2: Remove unused files (optional)

If you no longer need local registration/login:
- Remove `backend/app/services/user.py`
- Remove `backend/app/models/user.py` (and its import in `models/__init__.py`)
- Remove `backend/app/schemas/user.py`
- Remove the `/register` and `/login` routes from `routes/auth.py`
- Remove `passlib[bcrypt]` from `pyproject.toml`

### Step 3: Update environment variables

Add your provider's config to `.env`:
```bash
# For Clerk:
CLERK_JWKS_URL=https://your-clerk-domain/.well-known/jwks.json

# For Auth0:
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=your-api-audience
```

### What stays the same

- `UserInfo` shape — all routes keep working
- `Depends(get_current_user)` pattern — no route changes needed
- `get_optional_user` — works with any provider
- Frontend token storage pattern — still sends `Authorization: Bearer <token>`

## Testing Auth

```bash
# Register a user
curl -X POST http://localhost:8000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com", "password": "testpass123"}'

# Login
curl -X POST http://localhost:8000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com", "password": "testpass123"}'

# Use the token
TOKEN="<access_token from login response>"
curl http://localhost:8000/api/v1/auth/me \
  -H "Authorization: Bearer $TOKEN"

# Protected route (delete item)
curl -X DELETE http://localhost:8000/api/v1/items/<item-id> \
  -H "Authorization: Bearer $TOKEN"
```

## Troubleshooting

| Problem | Cause | Fix |
|---|---|---|
| 401 on every request | Missing or malformed `Authorization: Bearer <token>` header | Check header format, ensure token isn't expired |
| 422 on register | Password too short or invalid email | Password must be ≥8 chars, email must be valid |
| 409 on register | Email already taken | Use a different email or login instead |
| `jwt.InvalidTokenError` in logs | Token signed with wrong key or expired | Check `SECRET_KEY` matches between token creation and validation |
````

## File: README.md
upstream: https://github.com/benja-pauls/serpentstack/blob/main/README.md

````text
# SerpentStack

<p align="center"><img src="assets/serpentstack-logo.png" alt="SerpentStack" width="400" /></p>

<p align="center">
  <a href="https://www.npmjs.com/package/serpentstack"><img src="https://img.shields.io/npm/v/serpentstack?color=blue" alt="npm" /></a>
  <a href="https://github.com/Benja-Pauls/SerpentStack/releases/latest"><img src="https://img.shields.io/github/v/release/Benja-Pauls/SerpentStack?label=release&color=blue" alt="Release" /></a>
  <a href="https://github.com/Benja-Pauls/SerpentStack/actions/workflows/ci.yml"><img src="https://github.com/Benja-Pauls/SerpentStack/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT License" /></a>
</p>

<p align="center"><strong>Find any AI agent skill or MCP server. Search every registry, install in seconds.</strong></p>

<p align="center"><img src="assets/serpentstack_demo.gif" alt="serpentstack search demo" width="720" /></p>

<p align="center">
  <a href="#quick-start">Quick Start</a> &middot;
  <a href="#search">Search</a> &middot;
  <a href="#install">Install</a> &middot;
  <a href="#discover">Discover</a> &middot;
  <a href="#base-skills">Base Skills</a> &middot;
  <a href="#persistent-agents">Persistent Agents</a>
</p>

---

[Agent skills](https://agentskills.io/home) are how [Stripe merges 1,300+ agent-generated PRs per week](https://stripe.dev/blog/how-we-build-software-at-stripe-in-2025) and [Shopify operates with agents as a core part of engineering](https://www.businessinsider.com/shopify-ceo-tells-employees-to-use-ai-before-asking-for-more-staff-2025-4). But skills are scattered across registries with no unified way to find or install them.

SerpentStack searches **every major skill registry and MCP server directory at once** — [Anthropic](https://github.com/anthropics/skills), [skills.sh](https://skills.sh/), [awesome-agent-skills](https://github.com/VoltAgent/awesome-agent-skills), public GitHub, and the [MCP Registry](https://registry.modelcontextprotocol.io/) — with a single command. One CLI to search, install, and manage skills and discover MCP servers for any AI coding agent.

```bash
npm install -g serpentstack
```

Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, Windsurf, and any tool that reads the [Agent Skills open standard](https://agentskills.io/home). Zero dependencies. Requires Node 22+.

---

## Why SerpentStack?

Skills and MCP servers are scattered across isolated registries. There's no unified way to find what exists.

| | [skills.sh](https://skills.sh/) | [Anthropic](https://github.com/anthropics/skills) | [awesome-agent-skills](https://github.com/VoltAgent/awesome-agent-skills) | [Glama](https://glama.ai/mcp) | [mcp.so](https://mcp.so) | **SerpentStack** |
|---|---|---|---|---|---|---|
| Skills | :white_check_mark: | :white_check_mark: | :white_check_mark: | | | :white_check_mark: **all** |
| MCP servers | | | | :white_check_mark: | :white_check_mark: | :white_check_mark: **all** |
| Single CLI search | | | | | | :white_check_mark: |
| Install from any source | | | | | | :white_check_mark: |
| Project-aware recommendations | | | | | | :white_check_mark: |
| Auto-generate missing skills | | | | | | :white_check_mark: |

One search, every source. Skills and MCP servers together, clearly labeled.

---

## Quick Start

```bash
serpentstack search "react testing"        # search every registry
serpentstack add clerk                     # install by name
serpentstack add stripe/agent-toolkit      # install from a GitHub repo
serpentstack discover                      # get recommendations for your project
```

That's it. Skills are installed to `.skills/<name>/SKILL.md` and your agents pick them up automatically.

---

## Search

Search across all major skill registries and MCP server directories with one command. Results are ranked by relevance, clearly split into **Skills** and **MCP Servers** so you always know what you're looking at.

```bash
serpentstack search "auth oauth"
serpentstack search "stripe payments"
serpentstack search "postgres database"
serpentstack search "docker deploy"
```

```
  ── Skills (3) ──────────────────────────────────────

   1. clerk  anthropic
      Authentication and user management with Clerk
      $ serpentstack add anthropics/skills/clerk

   2. better-auth  skills.sh
      Type-safe authentication framework for TypeScript
      $ serpentstack add better-auth/best-practices

   3. oauth-patterns  awesome
      OAuth 2.0 and OpenID Connect integration patterns
      $ serpentstack add nichochar/oauth-patterns

  ── MCP Servers (2) ─────────────────────────────────

   1. supabase  mcp
      Manage Supabase projects, databases, edge functions, and auth
      Claude Code: claude mcp add supabase -- npx -y supabase-mcp-server
      Docs:        github.com/supabase-community/supabase-mcp

   2. neon  mcp
      Serverless Postgres with branching, schema migrations, and database management
      Claude Code: claude mcp add --transport http neon https://mcp.neon.tech/sse
      Docs:        github.com/neondatabase/mcp-server-neon
```

Skills and MCP servers are clearly labeled: `anthropic` `skills.sh` `awesome` `github` for skills, `mcp` for MCP servers. Skills teach agents *how* to build; MCP servers give agents *tools* to use — you often want both.

---

## Install

Install skills from any source — a registry name, a GitHub repo, or a URL. SerpentStack resolves the source, fetches the `SKILL.md`, and drops it into your `.skills/` directory.

```bash
serpentstack add clerk                           # resolve via registries
serpentstack add anthropics/skills/clerk          # specific GitHub path
serpentstack add stripe/agent-toolkit             # GitHub repo
serpentstack add --force clerk                    # overwrite existing
```

**If no community skill exists**, SerpentStack auto-generates a context-rich stub by pulling the project's README, package metadata, install commands, and docs URL from GitHub. You get a useful starting point instead of nothing.

```bash
serpentstack add fastify
# → Generated fastify → .skills/fastify/SKILL.md
#   Source: github.com/fastify/fastify
#   Docs:   fastify.dev
```

---

## Discover

Analyze your project and get skill and MCP server recommendations tailored to your actual stack. SerpentStack reads your dependency files, detects frameworks/services/tools, and searches registries for matching skills and MCP servers — skipping skills you already have installed.

```bash
cd your-project
serpentstack discover
```

```
  Your stack
  Languages:    javascript, typescript
  Frameworks:   react, nextjs
  Services:     clerk, stripe, prisma
  Tools:        vitest, tailwindcss, eslint

  ── Services ────────────────────────────────────────
  clerk  anthropic
  $ serpentstack add anthropics/skills/clerk

  stripe-best-practices  skills.sh
  $ serpentstack add stripe/agent-toolkit
  ...

  ── MCP Servers (3) ─────────────────────────────────
  stripe  mcp
  $ claude mcp add stripe -- npx -y @stripe/mcp

  neon  mcp
  $ claude mcp add --transport http neon https://mcp.neon.tech/sse
  ...

  12 skill recommendations, 3 MCP servers based on your stack.
  3 skills already installed.
```

Detects: JavaScript/TypeScript, Python, Go, Rust, Ruby — and 50+ frameworks, services, and tools within each.

---

## Base Skills

SerpentStack ships 10 production-quality skills you can install into any project. These aren't descriptions — they contain complete, copy-paste templates with real imports and type signatures. Every skill ends with a verification step so agents can confirm their own work.

```bash
serpentstack skills                     # install all 10 base skills
serpentstack skills update              # update to latest versions
```

| Skill | What it teaches agents |
|---|---|
| `scaffold` | End-to-end resource generation: model, schema, service, route, migration, tests, frontend types |
| `auth` | JWT, owners
````
