> ## Documentation Index
> Fetch the complete documentation index at: https://docs.brainstormer.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Auth Service

> Authentication service: JWT auth, user/org management, RBAC, platform configuration, email verification, and prompt registry.

## Overview

**Port:** 4001

The Auth Service handles authentication, user and organization management, RBAC enforcement, platform configuration (encrypted key-value store), email verification, and the prompt type registry.

## Endpoints

### Authentication

| Route            | Method | Purpose                               |
| ---------------- | ------ | ------------------------------------- |
| `/auth/register` | POST   | Register user + auto-create workspace |
| `/auth/login`    | POST   | Email/password login, returns JWT     |
| `/auth/refresh`  | POST   | Refresh access token                  |
| `/auth/logout`   | POST   | Invalidate session                    |
| `/auth/me`       | GET    | Get current user                      |

### Email Verification and Password

| Route                   | Method | Purpose                 |
| ----------------------- | ------ | ----------------------- |
| `/auth/verify-email`    | POST   | Verify email with token |
| `/auth/send-otp`        | POST   | Request OTP code        |
| `/auth/verify-otp`      | POST   | Verify OTP              |
| `/auth/forgot-password` | POST   | Request password reset  |
| `/auth/reset-password`  | POST   | Complete reset          |

### Organization Management

| Route                             | Method   | Purpose             |
| --------------------------------- | -------- | ------------------- |
| `/auth/invite-member`             | POST     | Invite org member   |
| `/auth/accept-invitation`         | POST     | Accept invite       |
| `/auth/organizations/:id/members` | GET      | List org members    |
| `/auth/organizations/:id`         | PATCH    | Update org settings |
| `/auth/api-keys`                  | GET/POST | Manage API keys     |

### Platform Config (Superadmin)

| Route                             | Method | Purpose                         |
| --------------------------------- | ------ | ------------------------------- |
| `/auth/admin/config`              | GET    | Platform config values          |
| `/auth/admin/config`              | POST   | Set config value (encrypted)    |
| `/auth/admin/config/health`       | GET    | Config health + bootstrap check |
| `/auth/admin/config/setup-status` | GET    | Platform setup status           |

### Prompt Type Registry (Superadmin)

| Route                                | Method | Purpose                                        |
| ------------------------------------ | ------ | ---------------------------------------------- |
| `/admin/prompt-types`                | GET    | List prompt type registry                      |
| `/admin/prompt-types`                | POST   | Register new prompt type                       |
| `/admin/prompt-types/:key`           | PUT    | Update prompt type metadata (key is immutable) |
| `/admin/prompt-types/:key/deprecate` | POST   | Soft-deprecate a prompt type                   |

### System Prompt Defaults (Superadmin)

| Route                                   | Method | Purpose                                           |
| --------------------------------------- | ------ | ------------------------------------------------- |
| `/admin/prompt-defaults`                | GET    | List all system-wide prompt defaults              |
| `/admin/prompt-defaults/:type`          | GET    | Get system default for a prompt type              |
| `/admin/prompt-defaults/:type`          | PUT    | Create or update system default (with versioning) |
| `/admin/prompt-defaults/:type/versions` | GET    | Version history for a system default              |
| `/admin/prompt-defaults/:type/rollback` | POST   | Rollback system default to a specific version     |

## JWT Pattern

<Warning>
  This is a critical pattern. All services must follow it exactly.
</Warning>

* The auth service **issues and signs** JWTs (`signJwt`); the **gateway verifies** them on every request (`verifyJwt(token, JWT_SECRET)`); downstream services trust the auth context the gateway forwards as headers:
  ```typescript theme={null}
  // Auth service signs:
  const token = signJwt(payload, JWT_SECRET);
  // Gateway verifies:
  const payload = verifyJwt(token, JWT_SECRET);
  ```
* **Payload structure:**
  ```json theme={null}
  {
    "userId": "uuid",
    "email": "user@example.com",
    "platformRole": "user",
    "organizations": [
      { "id": "uuid", "name": "My Org", "slug": "my-org", "role": "owner" }
    ]
  }
  ```
* Access token: 24h, Refresh token: 7d (configurable)
* First registered user is auto-promoted to superadmin

## Platform Config System

The platform configuration system provides an encrypted key-value store:

* **Repository:** `ConfigRepository` manages the `platform_config` table
* **Encryption:** AES-256-GCM using JWT\_SECRET as key (via `@brainstormer/shared` encrypt/decrypt)
* **Precedence:** DB values take precedence over env vars (`getConfigValue()` checks DB first, falls back to `process.env`)
* **Categories:** `ai`, `voice`, `knowledge`, `feature_flags`
* **Admin UI:** Manages all API keys (OPENROUTER, OPENAI, ELEVENLABS, LIVEKIT, PINECONE, etc.)

## Prompt Registry and Defaults

<AccordionGroup>
  <Accordion title="Superadmin Only">
    All `/admin/prompt-types/*` and `/admin/prompt-defaults/*` endpoints require `x-platform-role: superadmin` (checked via gateway-forwarded header).
  </Accordion>

  <Accordion title="Key Immutability">
    `prompt_type_registry.key` cannot be changed after creation. Update only label, description, and category.
  </Accordion>

  <Accordion title="Deprecation Before Deletion">
    Set `deprecated_at` via the deprecate endpoint. Cannot delete a type with existing configs or defaults.
  </Accordion>

  <Accordion title="Versioning on PUT">
    Every update to a system default auto-increments the version (minor unless mode changes, which triggers major) and snapshots to `system_prompt_default_versions`.
  </Accordion>

  <Accordion title="Rollback">
    Creates a new version entry (does not rewrite history). Changelog notes "Rolled back to vX.Y".
  </Accordion>
</AccordionGroup>

## Database Tables

| Table                            | Purpose                                                     |
| -------------------------------- | ----------------------------------------------------------- |
| `users`                          | Email, displayName, accountType, platformRole, isSuperAdmin |
| `organizations`                  | Name, slug, settings                                        |
| `user_organization_roles`        | Multi-org membership (owner/admin/editor/viewer)            |
| `platform_config`                | Encrypted config key-value store                            |
| `platform_setup_status`          | First-time setup tracking                                   |
| `email_verification_tokens`      | Email verification                                          |
| `password_reset_tokens`          | Password reset flow                                         |
| `api_keys`, `api_applications`   | API key management                                          |
| `prompt_type_registry`           | Valid prompt types (key, label, category, supported\_modes) |
| `system_prompt_defaults`         | Platform-wide default prompts per type                      |
| `system_prompt_default_versions` | Version history for system defaults                         |

## Email (Resend)

The auth service sends emails via Resend:

* **Email types:** verification, OTP, password reset, invitation, welcome
* **Fallback:** Console logging if `RESEND_API_KEY` not set
* **Config:** `RESEND_API_KEY`, `EMAIL_FROM`, `WEB_APP_URL`

## Configuration Variables

```bash theme={null}
JWT_SECRET=your-secret
JWT_EXPIRES_IN=24h
JWT_REFRESH_EXPIRES_IN=7d
DATABASE_URL=postgresql://brainstormer:<password set by POSTGRES_PASSWORD>@localhost:5432/brainstormer
RESEND_API_KEY=re_...
EMAIL_FROM=noreply@brainstormer.ai
WEB_APP_URL=https://bsio2.brainstormer.io
BCRYPT_ROUNDS=12
REDIS_HOST=localhost
```
