npm package: @getjai/auth-sdk
Description: Shared OAuth 2.1 authentication SDK for JAI Platform (RagAgent, JAI-Pay, JDocFlow, Admin-App, Ontology-Merger)
Author: JAI Platform
Latest version: 1.1.1

# JAI Platform Auth SDK

Shared OAuth 2.1 authentication SDK for all JAI Platform applications. Validates tokens against RagAgent (Central Identity Hub).

## Supported Platforms

- **TypeScript/JavaScript**: Express, Next.js, Hono
- **Python**: FastAPI, Flask

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    RagAgent (Central Auth)                  │
│              yauykuzuqmgzpbjswmoo.supabase.co              │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────────┐   │
│  │ Tenants │  │ Agents  │  │  Users  │  │ Credentials │   │
│  └─────────┘  └─────────┘  └─────────┘  └─────────────┘   │
│                         │                                   │
│                    JWKS Endpoint                           │
│               /auth/v1/jwks                                │
└─────────────────────────────────────────────────────────────┘
                          │
          ┌───────────────┼───────────────┐
          │               │               │
          ▼               ▼               ▼
    ┌──────────┐   ┌──────────┐   ┌──────────┐
    │ JAI-Pay  │   │ JDocFlow │   │ Mycelia  │
    │ (Stripe) │   │(Workflow)│   │(Ontology)│
    └──────────┘   └──────────┘   └──────────┘
```

## Installation

### TypeScript

```bash
npm install @jai-platform/auth-sdk
# or
pnpm add @jai-platform/auth-sdk
```

### Python

```bash
pip install jai-auth-sdk
# With FastAPI support
pip install jai-auth-sdk[fastapi]
# With Flask support
pip install jai-auth-sdk[flask]
```

## Usage

### TypeScript - Core

```typescript
import { validateToken, TokenValidator } from '@jai-platform/auth-sdk';

// Quick validation (uses default RagAgent)
const result = await validateToken(bearerToken);
if (result.valid) {
  console.log(result.context); // AuthContext
}

// Custom validator
const validator = new TokenValidator({
  supabaseUrl: 'https://your-project.supabase.co',
  debug: true,
});
```

### TypeScript - Express

```typescript
import express from 'express';
import { createAuthMiddleware, requirePermissions } from '@jai-platform/auth-sdk/express';

const app = express();

// Protect all routes
app.use(createAuthMiddleware());

// Access auth context
app.get('/profile', (req, res) => {
  res.json({ user: req.auth });
});

// Require specific permissions
app.post('/payments', requirePermissions('payments:create'), (req, res) => {
  // Only users with payments:create permission
});
```

### TypeScript - Next.js

```typescript
// middleware.ts
import { createNextAuthMiddleware } from '@jai-platform/auth-sdk/nextjs';

export default createNextAuthMiddleware({
  protectedPaths: ['/api/*', '/dashboard/*'],
  publicPaths: ['/api/health', '/api/public/*'],
});

// API route
import { getAuthContext, requireAuth } from '@jai-platform/auth-sdk/nextjs';

export async function GET(request: Request) {
  const auth = requireAuth(request); // Throws if not authenticated
  return Response.json({ user: auth });
}
```

### TypeScript - Hono

```typescript
import { Hono } from 'hono';
import { honoAuth, requirePermissions } from '@jai-platform/auth-sdk/hono';

const app = new Hono();

// Protect routes
app.use('/api/*', honoAuth());

// Access auth context
app.get('/profile', (c) => {
  const auth = c.get('auth');
  return c.json({ user: auth });
});

// Require permissions
app.post('/payments', requirePermissions('payments:create'), (c) => {
  return c.json({ success: true });
});
```

### Python - FastAPI

```python
from fastapi import FastAPI, Depends
from jai_auth_sdk.fastapi import get_auth, require_permissions, AuthDependency
from jai_auth_sdk import AuthContext

app = FastAPI()

# Basic authentication
@app.get("/profile")
async def profile(auth: AuthContext = Depends(get_auth)):
    return {"user_id": auth.user_id, "email": auth.email}

# Require specific permissions
@app.post("/payments")
async def create_payment(auth: AuthContext = Depends(require_permissions("payments:create"))):
    return {"success": True}
```

### Python - Flask

```python
from flask import Flask, g
from jai_auth_sdk.flask import auth_required, require_permissions, get_current_auth

app = Flask(__name__)

@app.route("/profile")
@auth_required
def profile():
    auth = get_current_auth()
    return {"user_id": auth.user_id, "email": auth.email}

@app.route("/payments", methods=["POST"])
@require_permissions("payments:create")
def create_payment():
    return {"success": True}
```

## Token Claims

The SDK expects JWT tokens with these claims:

```typescript
interface TokenClaims {
  // Standard JWT
  sub: string;           // Subject (user/agent/service ID)
  aud: string | string[]; // Audience
  iss: string;           // Issuer
  exp: number;           // Expiration
  iat: number;           // Issued at

  // JAI Platform
  type: 'user' | 'agent' | 'service';
  tenant_id: string;
  roles: string[];
  permissions: string[];
  scopes?: string[];     // For agents/services

  // User-specific
  email?: string;
  name?: string;
  is_super_admin?: boolean;
}
```

## Standard Permissions

```typescript
import { PERMISSIONS, ROLES } from '@jai-platform/auth-sdk';

// Permissions
PERMISSIONS.PAYMENTS_CREATE  // 'payments:create'
PERMISSIONS.WORKFLOWS_EXECUTE // 'workflows:execute'
PERMISSIONS.MCP_ADMIN        // 'mcp:admin'

// Roles
ROLES.ORG_ADMIN    // 'org:admin'
ROLES.SUPER_ADMIN  // 'super:admin'
ROLES.DEVELOPER    // 'developer'
```

## Configuration

```typescript
const validator = new TokenValidator({
  // RagAgent Supabase URL (default: production RagAgent)
  supabaseUrl: 'https://yauykuzuqmgzpbjswmoo.supabase.co',

  // JWKS endpoint (default: supabaseUrl + /auth/v1/jwks)
  jwksUrl: 'https://...',

  // Token issuer (default: supabaseUrl + /auth/v1)
  issuer: 'https://...',

  // Default audience
  defaultAudience: 'authenticated',

  // JWKS cache TTL in ms (default: 1 hour)
  jwksCacheTtl: 3600000,

  // Enable debug logging
  debug: false,
});
```

## License

MIT