# @meistrari/auth-sdk

A Nuxt module that provides authentication and organization management capabilities using Better Auth.

## Installation

```bash
npm install @meistrari/auth-sdk
```

## Setup

Add the module to your `nuxt.config.ts`:

```typescript
export default defineNuxtConfig({
  modules: ['@meistrari/auth-sdk'],
  authSdk: {
    apiUrl: 'https://your-auth-api.com',
    useJwt: true, // Enable JWT token refresh cycle 
    jwtCookieName: 'auth-jwt', // Custom JWT cookie name
    skipServerMiddleware: false, // Skip automatic server middleware
    isDevelopment: false, // Development mode settings
  }
})
```

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiUrl` | `string` | **Required** | Base URL of your authentication API |
| `useJwt` | `boolean` | `false` | Enable JWT cookie management and token refresh |
| `jwtCookieName` | `string` | `'auth-jwt'` | Name of the JWT cookie |
| `skipServerMiddleware` | `boolean` | `false` | Skip automatic server-side auth context setup |
| `isDevelopment` | `boolean` | `false` | Enable development-specific features |

## Usage

### Client-side Authentication

The SDK provides the `useMeistrariAuth` composable for managing authentication state:

```vue
<script setup>
const { user, session, signOut } = useMeistrariAuth()

// Access current user
console.log(user.value) // User object or null

// Access current session
console.log(session.value) // Session object or null

// Sign out
await signOut(() => {
  // Optional callback after sign out
  console.log('User signed out')
})
</script>

<template>
  <div v-if="user">
    Welcome, {{ user.name }}!
    <button @click="signOut">Sign Out</button>
  </div>
  <div v-else>
    Please sign in
  </div>
</template>
```

### Authentication Client

Access the underlying Better Auth client through the Nuxt app:

```typescript
// In a plugin, middleware, or component
const { $auth } = useNuxtApp()

// Get current session
const sessionData = await $auth.client.getSession()

// Organization operations
await $auth.client.organization.create({
  name: 'My Organization',
  slug: 'my-org'
})

// Access custom endpoints
await $auth.client.customEndpoints.session.token()
```

### Server-side Usage

The SDK automatically sets up server-side authentication context for API routes:

```typescript
// server/api/protected.ts
export default defineEventHandler(async (event) => {
  // Authentication context is automatically available
  const { user, session } = event.context.auth

  if (!user) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized'
    })
  }

  return {
    message: `Hello, ${user.name}!`,
    userId: user.id
  }
})
```

### Custom Middleware

You can create custom server middleware using the provided helper:

```typescript
// server/middleware/custom.ts
import { meistrariAuthMiddleware } from '@meistrari/auth-sdk/server/middleware/auth'

export default meistrariAuthMiddleware(async (event) => {
  // Your custom logic here
  // event.context.auth contains user and session
})
```

### JWT Token Management

When `useJwt` is enabled, the SDK automatically:

- Manages JWT tokens in cookies
- Refreshes tokens before expiration (every 60 seconds)
- Validates token expiry client-side
- Provides `getToken()` method for accessing valid tokens

```typescript
const { $auth } = useNuxtApp()

// Get a valid JWT token (refreshes if needed)
const token = await $auth.getToken()
```

## Types

The SDK exports comprehensive TypeScript types:

```typescript
import type {
  User,
  Session,
  Organization,
  Workspace,
  Member,
  Invitation,
  Team,
  TeamMember
} from '@meistrari/auth-sdk/utils'
```

### Key Types

- **User**: User account information including email, name, and verification status
- **Session**: Active session data with expiration and device info
- **Organization**: Organization entity with basic metadata
- **Workspace**: Extended organization with settings and statistics
- **Member**: Organization member with role and team assignments
- **Team**: Team entity within an organization
- **Invitation**: Pending organization invitations

## Organization & Team Management

The SDK includes full organization and team management capabilities:

```typescript
const { $auth } = useNuxtApp()

// Create organization
await $auth.client.organization.create({
  name: 'Acme Corp',
  slug: 'acme-corp'
})

// Invite members
await $auth.client.organization.inviteMember({
  email: 'user@example.com',
  role: 'org:member',
  organizationId: 'org-id'
})

// Create teams
await $auth.client.organization.createTeam({
  name: 'Development Team',
  organizationId: 'org-id'
})

// Manage member roles
await $auth.client.organization.updateMemberRole({
  membershipId: 'member-id',
  role: 'org:admin'
})
```

### Role-based Access Control

The SDK implements role-based access control with three built-in roles:

- **org:admin**: Full organization management permissions
- **org:reviewer**: Review-only access
- **org:member**: Basic member access

```typescript
// Access control is automatically enforced in API calls
// Roles are validated server-side based on user permissions
```

## Utilities

### Token Validation

```typescript
import { isTokenExpired, validateToken } from '@meistrari/auth-sdk/utils'

// Check if token is expired
if (isTokenExpired(jwtToken)) {
  // Token needs refresh
}

// Validate token against JWKS endpoint
const isValid = await validateToken(jwtToken, 'https://your-api.com')
```

## Error Handling

The SDK handles common authentication errors automatically:

- Expired tokens are refreshed automatically
- Invalid sessions redirect to sign-in
- Network errors are gracefully handled
- CSRF protection is built-in

```typescript
try {
  await $auth.client.getSession()
} catch (error) {
  console.error('Authentication failed:', error.message)
}
```

## Development

Set `isDevelopment: true` in your config to enable:

- Additional debugging logs
- Development-specific cookie handling
- Relaxed security policies for local development

## Security Features

- **CSRF Protection**: Built into all API calls
- **JWT Validation**: Cryptographic validation using JWKS
- **Secure Cookies**: HTTP-only, secure cookies in production
- **Token Refresh**: Automatic token rotation
- **Session Management**: Secure session handling

## Migration

If upgrading from a previous version, ensure your configuration includes the required `apiUrl` parameter and update any deprecated options.