npm package: @flightdev/auth
Description: Auth adapters for Flight Framework - BetterAuth, JWT, OAuth, Clerk providers
Latest version: 0.4.2

# @flightdev/auth

Authentication adapters for Flight Framework. Integrate with any auth provider using a unified interface.

## Installation

```bash
npm install @flightdev/auth
```

## Quick Start

```typescript
import { createAuth } from '@flightdev/auth';
import { betterAuth } from '@flightdev/auth/better-auth';
import { createDb } from '@flightdev/db';
import { postgres } from '@flightdev/db/postgres';

const db = createDb(postgres({
  connectionString: process.env.DATABASE_URL,
}));

const auth = createAuth(betterAuth({ db }));

// Get current user from request
const user = await auth.getUser(request);

// Verify a session token
const session = await auth.verifySession(token);
```

## Adapters

### Better Auth

Full-featured authentication with email/password and social providers.

```typescript
import { betterAuth } from '@flightdev/auth/better-auth';

const adapter = betterAuth({
  db,
  emailAndPassword: true,
  socialProviders: {
    github: {
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    },
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    },
  },
  session: {
    expiresIn: 60 * 60 * 24 * 7,  // 7 days
    cookieName: 'auth_session',
  },
});
```

This adapter handles the following API routes:

| Route | Method | Description |
|-------|--------|-------------|
| `/api/auth/signup` | POST | Create a new user account |
| `/api/auth/signin` | POST | Sign in with email/password |
| `/api/auth/signout` | POST | Sign out and clear session |
| `/api/auth/session` | GET | Get current session |

### Lucia

Lightweight session management for custom authentication flows.

```typescript
import { lucia } from '@flightdev/auth/lucia';

const adapter = lucia({
  db,
  sessionCookie: 'auth_session',
  sessionExpiry: 60 * 60 * 24 * 30,  // 30 days
  csrfProtection: true,
});
```

### Supabase Auth

Integration with Supabase's built-in authentication.

```typescript
import { supabaseAuth } from '@flightdev/auth/supabase';

const adapter = supabaseAuth({
  url: process.env.SUPABASE_URL,
  key: process.env.SUPABASE_ANON_KEY,
  cookieName: 'sb-auth-token',
});
```

### Clerk

Integration with Clerk authentication service.

```typescript
import { clerkAuth } from '@flightdev/auth/clerk';

const adapter = clerkAuth({
  secretKey: process.env.CLERK_SECRET_KEY,
  publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
  authorizedParties: ['https://myapp.com'],
});
```

Clerk adapter uses `@clerk/backend` which works with standard Web Requests - no middleware required.

## JWT Authentication

For stateless authentication using JSON Web Tokens.

```typescript
import { createJWTAuth, createToken, verifyToken } from '@flightdev/auth/jwt';

const auth = createJWTAuth({
  secret: process.env.JWT_SECRET,
  issuer: 'my-app',
  audience: 'my-app-users',
  expiresIn: 60 * 60 * 24,  // 24 hours
});

// Create a token for a user
const token = await auth.createToken({
  id: user.id,
  email: user.email,
});

// Verify a token from a request
const session = await auth.verifySession(token);
```

## OAuth Providers

Support for OAuth 2.0 authentication flows.

```typescript
import { createOAuthProvider } from '@flightdev/auth/oauth';

const github = createOAuthProvider({
  provider: 'github',
  clientId: process.env.GITHUB_CLIENT_ID,
  clientSecret: process.env.GITHUB_CLIENT_SECRET,
  redirectUri: 'https://myapp.com/auth/callback',
  scopes: ['user:email'],
});

// Get authorization URL
const authUrl = await github.getAuthorizationUrl();

// Exchange code for tokens
const tokens = await github.exchangeCode(code);

// Get user info
const user = await github.getUserInfo(tokens.accessToken);
```

## API Reference

### AuthAdapter Interface

```typescript
interface AuthAdapter {
  name: string;

  // Get user from request
  getUser(request: Request): Promise<AuthUser | null>;

  // Verify a session token
  verifySession(token: string): Promise<AuthSession | null>;

  // Optional middleware for auth routes
  middleware?: (req: Request) => Promise<Response | null>;
}
```

### AuthUser

```typescript
interface AuthUser {
  id: string;
  email?: string;
  name?: string;
  avatar?: string;
  metadata?: Record<string, unknown>;
}
```

### AuthSession

```typescript
interface AuthSession {
  user: AuthUser;
  expiresAt: Date;
  token: string;
}
```

## Database Schema

The Better Auth and Lucia adapters expect the following tables:

```sql
CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email VARCHAR(255) UNIQUE NOT NULL,
  password_hash VARCHAR(255),
  name VARCHAR(255),
  avatar VARCHAR(255),
  created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE sessions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  expires_at TIMESTAMP NOT NULL,
  created_at TIMESTAMP DEFAULT NOW()
);
```

## Integration with Flight

```typescript
// flight.config.ts
import { defineConfig } from '@flightdev/core';
import { betterAuth } from '@flightdev/auth/better-auth';

export default defineConfig({
  auth: betterAuth({ db }),
});

// In your routes
export async function loader({ request, auth }) {
  const user = await auth.getUser(request);

  if (!user) {
    return redirect('/login');
  }

  return { user };
}
```

## Creating Custom Adapters

Implement the `AuthAdapter` interface for custom providers.

```typescript
import type { AuthAdapter, AuthUser, AuthSession } from '@flightdev/core/adapters';

export function customAuth(config: CustomConfig): AuthAdapter {
  return {
    name: 'custom-auth',

    async getUser(request: Request): Promise<AuthUser | null> {
      // Your authentication logic
      return null;
    },

    async verifySession(token: string): Promise<AuthSession | null> {
      // Your session verification logic
      return null;
    },
  };
}
```

## License

MIT