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

# Backend architecture

> NestJS bootstrap, middleware, filters, and request processing

## Bootstrap sequence

The application starts in `main.ts`:

```mermaid theme={null}
flowchart TD
    A[NestFactory.create AppModule] --> B[app.use express.json limit 20mb]
    B --> C[app.use compression]
    C --> D[app.use helmet]
    D --> E[parseAllowedOrigins from FRONTEND_ORIGIN]
    E --> F[app.use cookieParser]
    F --> G[app.enableCors credentials true]
    G --> H[app.setGlobalPrefix 'api/v1']
    H --> I[app.useGlobalPipes ValidationPipe]
    I --> J[app.useGlobalFilters PrismaExceptionFilter, HttpExceptionFilter]
    J --> K[Mount better-auth handler at /api/auth]
    K --> L[app.listen port 3001]
```

## Global middleware stack

Applied in order in `main.ts`:

| Order | Middleware                        | Purpose                                                             |
| ----- | --------------------------------- | ------------------------------------------------------------------- |
| 1     | `express.json({ limit: '20mb' })` | Parse JSON bodies, up to 20MB for large imports                     |
| 2     | `compression()`                   | gzip all responses; reduces report payloads by roughly 90%          |
| 3     | `helmet()`                        | HTTP security headers (CSP disabled for SPA compatibility)          |
| 4     | `cookie-parser`                   | Parse cookies for better-auth session tokens                        |
| 5     | `cors()`                          | Allow cross-origin requests from `FRONTEND_ORIGIN` with credentials |
| 6     | `ValidationPipe`                  | Validate and strip all DTOs                                         |

## Global exception filters

Two filters are registered globally in `main.ts`.

### PrismaExceptionFilter

Catches `Prisma.PrismaClientKnownRequestError` and maps Prisma error codes to semantic HTTP responses:

| Prisma code | HTTP status     | Meaning                                      |
| ----------- | --------------- | -------------------------------------------- |
| `P2002`     | 409 Conflict    | Unique constraint violation                  |
| `P2003`     | 400 Bad Request | Foreign key constraint failure               |
| `P2025`     | 404 Not Found   | Record not found for update/delete           |
| `P2034`     | 409 Conflict    | Transaction conflict / serialization failure |
| Other       | 400 Bad Request | Generic database error                       |

The filter humanizes constraint names (for example `Order_submittedById_fkey` becomes "order") for user-facing messages.

### HttpExceptionFilter

Catch-all filter. Passes NestJS `HttpException` subclasses through with their original status codes. Any unknown error is logged and returned as a sanitized 500:

```json theme={null}
{
  "statusCode": 500,
  "message": "An internal server error occurred.",
  "error": "Internal Server Error"
}
```

No stack traces or internal details reach the client.

## Authorization stack

Every request passes through three guards registered by the global `AuthModule`:

```mermaid theme={null}
flowchart LR
    A[Request arrives] --> B[SessionGuard]
    B -->|"No session"| X[401 Unauthorized]
    B -->|"Valid session"| C[PermissionsGuard]
    C -->|"No matching permission"| Y[403 Forbidden]
    C -->|"Permission granted"| D[ScopeGuard]
    D -->|"Out of scope"| Z[403 Forbidden]
    D -->|"In scope"| E[Controller method]
```

The guards' configuration and internals are documented in [Authorization](/security/authorization).

## Rate limiting

Configured via `@nestjs/throttler`:

```typescript theme={null}
ThrottlerModule.forRoot([{
  ttl: 60_000,      // 60 seconds
  limit: 100,       // 100 requests per ttl window
}])
```

Applied globally with no per-route overrides. Bulk operations use single batched requests instead of N individual calls precisely so large selections stay under this limit.

## Request timeout

Set to 15 minutes in `main.ts`:

```typescript theme={null}
httpServer.requestTimeout = 15 * 60_000;
```

This accommodates large report generation and CSV imports.
