> ## 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.

# Gateway Service

> API Gateway service: proxy routing, JWT auth middleware, CORS, rate limiting, and plugin configuration.

## Overview

**Port:** 4000

The Gateway is the central entry point for all frontend requests. It routes to backend services via HTTP proxy and is completely stateless -- JWT signature is verified in middleware (verifyJwt) and context is passed via headers to downstream services.

## Proxy Routes

| Path Pattern                     | Target Service           | Port | Timeout |
| -------------------------------- | ------------------------ | ---- | ------- |
| `/api/auth/*`                    | auth                     | 4001 | 30s     |
| `/api/bots/*`, `/api/models*`    | bot                      | 4002 | 180s    |
| `/api/conversations/*`           | bot                      | 4002 | 180s    |
| `/api/bot/*`                     | bot                      | 4002 | 180s    |
| `/api/tools*`, `/api/templates*` | bot                      | 4002 | 30s     |
| `/api/knowledge/*`               | knowledge                | 4005 | 60s     |
| `/api/realtime-audio/*`          | realtime-audio           | 4003 | 60s     |
| `/api/hitl/*`                    | hitl                     | 4006 | 30s     |
| `/api/public/*`                  | bot (no auth)            | 4002 | 30s     |
| `/v1/*` (API-key auth)           | bot (agent-build / chat) | 4002 | varies  |
| `/health`                        | self                     | --   | --      |

<Note>
  The public API `/v1/*` routes (e.g. `POST /v1/agents:from-url`, `GET /v1/agents/builds/:buildId`, `POST /v1/chat`) use **API-key authentication** (Bearer API key, validated via the auth service) rather than JWT, and proxy to the bot service's agent-build and chat routes.
</Note>

<Warning>
  When adding new backend routes, you **must** add the corresponding proxy route in `services/gateway/src/routes/proxy.ts`. Without this, the frontend cannot reach your new endpoint.
</Warning>

## Auth Middleware

The gateway handles JWT authentication for all proxied requests:

<Steps>
  <Step title="Extract Token">
    JWT is extracted from the `Authorization: Bearer` header **or** the `access_token` cookie.
  </Step>

  <Step title="Verify Signature">
    The gateway verifies the JWT signature with the shared secret:

    ```typescript theme={null}
    const payload = verifyJwt(token, config.JWT_SECRET);
    ```
  </Step>

  <Step title="Validate Membership">
    Validates that the user has at least one organization membership.
  </Step>

  <Step title="Attach Auth Context">
    Sets `request.auth` with: `userId`, `organizationId`, `email`, `platformRole`, `orgRole`.
  </Step>

  <Step title="Forward Headers">
    Forwards auth context to downstream services as headers:

    * `user-id`
    * `organization-id`
    * `user-email`
    * `x-platform-role`
    * `x-org-role`
  </Step>
</Steps>

<Note>
  The gateway verifies the JWT signature; downstream services trust forwarded headers. The gateway is the trust boundary — it is the only public ingress, and downstream service ports (4001–4006) are not exposed to the internet.
</Note>

## Plugins

| Plugin                | Purpose                        |
| --------------------- | ------------------------------ |
| `@fastify/cors`       | Configurable CORS origins      |
| `@fastify/helmet`     | Security headers               |
| `@fastify/rate-limit` | 10,000 requests/min default    |
| Swagger               | API docs at `/docs` (dev only) |

## Configuration Variables

```bash theme={null}
# Service
API_GATEWAY_PORT=4000
CORS_ORIGIN=http://localhost:3000
JWT_SECRET=your-secret

# Downstream services
AUTH_SERVICE_HOST=localhost
AUTH_SERVICE_PORT=4001
BOT_SERVICE_HOST=localhost
BOT_SERVICE_PORT=4002
KNOWLEDGE_SERVICE_HOST=localhost
KNOWLEDGE_SERVICE_PORT=4005
REALTIME_AUDIO_SERVICE_HOST=localhost
REALTIME_AUDIO_SERVICE_PORT=4003

# Rate limiting
RATE_LIMIT_WINDOW_MS=60000
RATE_LIMIT_MAX_REQUESTS=10000
```

## Critical Patterns

<AccordionGroup>
  <Accordion title="JWT Verify">
    The gateway follows `AUTHENTICATION_PATTERN.md` -- the JWT signature is verified with the shared secret (`verifyJwt(token, config.JWT_SECRET)`). Downstream services trust requests that come through the gateway.
  </Accordion>

  <Accordion title="Auth Context via Headers">
    Auth context is passed via HTTP headers to downstream services, not via cookies. Services read `request.user` from their own JWT middleware that parses these headers.
  </Accordion>

  <Accordion title="Multipart Upload Handling">
    Custom parser passes raw buffer for multipart uploads. The realtime-audio service has a 50MB upload limit for voice samples.
  </Accordion>

  <Accordion title="Service Failure Handling">
    When a downstream service is unavailable, the gateway returns `503` with a descriptive error message.
  </Accordion>

  <Accordion title="Hop-by-Hop Header Filtering">
    Headers like `host`, `connection`, and `transfer-encoding` are filtered before forwarding to downstream services.
  </Accordion>
</AccordionGroup>
