npm package: @siran/auth-nestjs
Description: NestJS integration for Siran Auth - controllers, guards, and module setup
Latest version: 0.1.0

# @siran/auth-nestjs

NestJS integration for Siran Auth - provides controllers, services, and module setup for easy authentication integration.

## Features

- **AuthModule**: Dynamic NestJS module with dependency injection
- **AuthController**: Pre-built HTTP endpoints for login, register, logout
- **AuthService**: Service wrapper for authentication logic
- **Type-safe configuration**: TypeScript interfaces for all configuration
- **Framework-agnostic core**: Uses @siran/auth-http under the hood
- **Extensible**: Support for custom TokenProvider and SessionStore implementations

## Installation

```bash
npm install @siran/auth-nestjs @siran/auth-http @siran/auth-core
```

## Quick Start

### 1. Create an AuthEngine

Using Supabase adapter:

```typescript
import { AuthEngine } from '@siran/auth-supabase';

const authEngine = new AuthEngine({
  supabaseUrl: process.env.SUPABASE_URL,
  supabaseKey: process.env.SUPABASE_KEY,
});
```

### 2. Create a TokenProvider (Optional)

Using JWT implementation:

```typescript
import { JwtTokenProvider } from '@siran/auth-http-jwt';

const tokenProvider = new JwtTokenProvider({
  secret: process.env.JWT_SECRET,
  algorithm: 'HS256',
});
```

### 3. Setup the NestJS Module

```typescript
import { Module } from '@nestjs/common';
import { AuthModule } from '@siran/auth-nestjs';
import { AuthEngine } from '@siran/auth-supabase';
import { JwtTokenProvider } from '@siran/auth-http-jwt';

@Module({
  imports: [
    AuthModule.register({
      authEngine: new AuthEngine({ ... }),
      tokenProvider: new JwtTokenProvider({ ... }),
      sessionExpiresIn: 24 * 60 * 60, // 24 hours
    }),
  ],
})
export class AppModule {}
```

### 4. Use in Your Controllers

The module automatically provides:
- **POST /auth/login** - Login endpoint
- **POST /auth/register** - Registration endpoint
- **POST /auth/logout** - Logout endpoint

Or inject `AuthService` into your own controllers:

```typescript
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from '@siran/auth-nestjs';
import type { LoginRequestBody } from '@siran/auth-nestjs';

@Controller('my-auth')
export class MyAuthController {
  constructor(private authService: AuthService) {}

  @Post('login')
  async login(@Body() body: LoginRequestBody) {
    const result = await this.authService.login(body);
    return result;
  }
}
```

## Async Configuration

For complex setups, use `registerAsync`:

```typescript
@Module({
  imports: [
    AuthModule.registerAsync({
      useFactory: async (configService: ConfigService) => ({
        authEngine: configService.get('authEngine'),
        tokenProvider: configService.get('tokenProvider'),
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}
```

## Request Bodies

### Login/Register

```json
{
  "type": "password",
  "identifier": "user@example.com",
  "password": "password123"
}
```

Supported types:
- `password` - Email/username with password
- `otp` - One-time password
- `magic_link` - Magic link token
- `oauth` - OAuth provider code

## Response Format

### Success Response

```json
{
  "ok": true,
  "user": {
    "id": "user_123",
    "email": "user@example.com",
    "displayName": "John Doe"
  },
  "token": "eyJhbGc...",
  "session": {
    "id": "session_123",
    "expiresAt": "2024-01-27T14:30:00Z"
  }
}
```

### Error Response

```json
{
  "ok": false,
  "error": "INVALID_CREDENTIALS",
  "message": "Invalid email or password",
  "violatedPolicies": []
}
```

## Configuration

### AuthModuleConfig

```typescript
interface AuthModuleConfig {
  /**
   * The AuthEngine instance (required)
   */
  authEngine: AuthEngine;

  /**
   * Token provider for JWT/token generation (optional)
   */
  tokenProvider?: TokenProvider;

  /**
   * Session store for session management (optional)
   */
  sessionStore?: SessionStore;

  /**
   * Session expiration in seconds (default: 86400)
   */
  sessionExpiresIn?: number;
}
```

## API Endpoints

### POST /auth/login

Login with various authentication methods.

**Request:**
```json
{
  "type": "password",
  "identifier": "user@example.com",
  "password": "password123"
}
```

**Response:** 200 OK with AuthResponse

### POST /auth/register

Register a new user.

**Request:**
```json
{
  "type": "password",
  "identifier": "user@example.com",
  "password": "password123"
}
```

**Response:** 201 Created with AuthResponse

### POST /auth/logout

Logout current user.

**Response:** 200 OK with success response

## Error Handling

The module automatically maps authentication errors to HTTP status codes:

- `INVALID_CREDENTIALS` → 401 Unauthorized
- `INVALID_FIELD` → 400 Bad Request
- `PASSWORD_RESET_REQUIRED` → 403 Forbidden
- `RATE_LIMIT_EXCEEDED` → 429 Too Many Requests
- etc.

See @siran/auth-http for complete error mapping.

## Dependencies

### Peer Dependencies

- `@nestjs/common` ^10.0.0
- `@nestjs/core` ^10.0.0

### Required Dependencies

- `@siran/auth-core` ^0.14.0
- `@siran/auth-http` ^0.1.0

### Optional Dependencies

- `@siran/auth-http-jwt` - For JWT token provider
- `@siran/auth-supabase` - For Supabase AuthEngine

## License

MIT