> ## Documentation Index
> Fetch the complete documentation index at: https://acm-aa28ebf6.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Learn how to authenticate with the SuperBox API

## Overview

SuperBox uses **Firebase Authentication** with **JWT (JSON Web Tokens)** for secure API access. All authenticated endpoints require a valid Bearer token in the Authorization header.

<Card title="Authentication Method" icon="shield">
  Firebase JWT Bearer Token Authentication
</Card>

## Getting Your API Token

<Steps>
  <Step title="Create an Account">
    Sign up at [SuperBox](https://superbox.1mindlabs.org) using one of our supported providers:

    <CardGroup cols={3}>
      <Card title="Google" icon="google">
        Sign in with Google
      </Card>

      <Card title="GitHub" icon="github">
        Sign in with GitHub
      </Card>

      <Card title="Email" icon="envelope">
        Email/Password
      </Card>
    </CardGroup>
  </Step>

  <Step title="Navigate to Settings">
    Go to your [Profile Settings](https://superbox.1mindlabs.org/settings) page.
  </Step>

  <Step title="Generate API Token">
    Click **"Generate API Token"** to create a new authentication token.

    <Warning>
      This token will only be shown once. Store it securely!
    </Warning>
  </Step>

  <Step title="Copy and Store">
    Copy your token and store it in a secure location like:

    * Environment variables
    * Secure password manager
    * Encrypted configuration file

    <Note>
      Never commit tokens to version control or share them publicly.
    </Note>
  </Step>
</Steps>

## Using Your Token

### Environment Variable (Recommended)

Store your token in an environment variable:

```bash theme={null}
export SUPERBOX_API_TOKEN="your_firebase_jwt_token_here"
```

Then reference it in your code:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://api.superbox.ai/api/v1/servers" \
    -H "Authorization: Bearer $SUPERBOX_API_TOKEN"
  ```

  ```javascript JavaScript theme={null}
  const token = process.env.SUPERBOX_API_TOKEN;

  const response = await fetch("https://api.superbox.ai/api/v1/servers", {
    headers: {
   Authorization: `Bearer ${token}`,
   "Content-Type": "application/json",
    },
  });
  ```

  ```python Python theme={null}
  import os
  import requests

  token = os.getenv('SUPERBOX_API_TOKEN')
  headers = {
   'Authorization': f'Bearer {token}',
   'Content-Type': 'application/json'
  }

  response = requests.get(
   'https://api.superbox.ai/api/v1/servers',
   headers=headers
  )
  ```
</CodeGroup>

### Direct Usage

For testing or development, you can use the token directly:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://api.superbox.ai/api/v1/servers" \
    -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjE5..."
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api.superbox.ai/api/v1/servers", {
    headers: {
   Authorization: "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjE5...",
   "Content-Type": "application/json",
    },
  });
  ```

  ```python Python theme={null}
  headers = {
   'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjE5...',
   'Content-Type': 'application/json'
  }

  response = requests.get(
   'https://api.superbox.ai/api/v1/servers',
   headers=headers
  )
  ```
</CodeGroup>

## Authentication Flow

```mermaid theme={null}
sequenceDiagram
 participant User
 participant Frontend
 participant Firebase
 participant API
 participant Resource

 User->>Frontend: Login Request
 Frontend->>Firebase: Authenticate
 Firebase-->>Frontend: JWT Token
 Frontend->>Frontend: Store Token
 Frontend->>API: Request + Bearer Token
 API->>Firebase: Validate Token
 Firebase-->>API: Token Valid
 API->>Resource: Access Granted
 Resource-->>API: Data
 API-->>Frontend: Response
 Frontend-->>User: Display Data
```

## Token Validation

When you make an authenticated request, the API validates your token:

<Steps>
  <Step title="Extract Token">
    API extracts the Bearer token from the Authorization header
  </Step>

  <Step title="Verify Signature">
    Token signature is verified using Firebase public keys
  </Step>

  <Step title="Check Expiration">Token expiration time is checked</Step>

  <Step title="Extract Claims">
    User ID and other claims are extracted from the token
  </Step>

  <Step title="Authorize Request">
    User permissions are checked for the requested resource
  </Step>
</Steps>

## Token Structure

Firebase JWT tokens contain three parts separated by dots:

```
eyJhbGciOiJSUzI1NiIsImtpZCI6IjE5...  (Header)
.
eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20v...  (Payload)
.
Signature_Hash_Value...  (Signature)
```

### Token Payload Example

```json theme={null}
{
  "iss": "https://securetoken.google.com/superbox-project",
  "aud": "superbox-project",
  "auth_time": 1702123456,
  "user_id": "abc123def456",
  "sub": "abc123def456",
  "iat": 1702123456,
  "exp": 1702127056,
  "email": "user@example.com",
  "email_verified": true,
  "firebase": {
 "identities": {
"google.com": ["123456789"],
"email": ["user@example.com"]
 },
 "sign_in_provider": "google.com"
  }
}
```

<ParamField body="user_id" type="string">
  Unique user identifier
</ParamField>

<ParamField body="email" type="string">
  User's email address
</ParamField>

<ParamField body="exp" type="integer">
  Token expiration timestamp (Unix time)
</ParamField>

<ParamField body="iat" type="integer">
  Token issued at timestamp (Unix time)
</ParamField>

## Token Expiration

<Card title="Token Lifetime" icon="clock">
  Firebase tokens expire after **1 hour** (3600 seconds)
</Card>

When a token expires, you'll receive a `401 Unauthorized` response:

```json theme={null}
{
  "success": false,
  "error": {
 "code": "INVALID_TOKEN",
 "message": "Authentication token has expired",
 "details": {
"expiredAt": "2025-12-09T11:30:00Z"
 }
  }
}
```

### Automatic Token Refresh

The SuperBox frontend automatically refreshes tokens before they expire. For API clients, implement token refresh logic:

<CodeGroup>
  ```javascript JavaScript theme={null}
  let token = await getFirebaseToken();
  let tokenExpiry = getTokenExpiry(token);

  async function makeRequest(url, options = {}) {
  // Refresh if token expires in < 5 minutes
  if (Date.now() > tokenExpiry - 5 * 60 * 1000) {
  token = await refreshFirebaseToken();
  tokenExpiry = getTokenExpiry(token);
  }

  return fetch(url, {
  ...options,
  headers: {
  ...options.headers,
  'Authorization': `Bearer ${token}`
  }
  });
  }

  ```

  ```python Python theme={null}
  import time
  import jwt
  from datetime import datetime, timedelta

  class SuperBoxClient:
   def __init__(self, token):
    self.token = token
    self.token_expiry = self._get_token_expiry()

   def _get_token_expiry(self):
    decoded = jwt.decode(self.token, options={"verify_signature": False})
    return datetime.fromtimestamp(decoded['exp'])

   def _should_refresh(self):
    # Refresh if token expires in < 5 minutes
    return datetime.now() > self.token_expiry - timedelta(minutes=5)

   def make_request(self, url, **kwargs):
    if self._should_refresh():
  self.token = self._refresh_token()
  self.token_expiry = self._get_token_expiry()

    headers = kwargs.get('headers', {})
    headers['Authorization'] = f'Bearer {self.token}'
    kwargs['headers'] = headers

    return requests.request(**kwargs)
  ```
</CodeGroup>

## Public vs Authenticated Endpoints

<Tabs>
  <Tab title="Public Endpoints">
    These endpoints don't require authentication:

    <ResponseField name="GET /servers" type="public">
      List all servers (read-only)
    </ResponseField>

    <ResponseField name="GET /servers/:name" type="public">
      Get server details (read-only)
    </ResponseField>

    <Note>Public endpoints have stricter rate limits (100 req/hour)</Note>
  </Tab>

  <Tab title="Authenticated Endpoints">
    These endpoints require a valid Bearer token:

    <ResponseField name="POST /servers" type="authenticated" required>
      Create a new server
    </ResponseField>

    <ResponseField name="PUT /servers/:name" type="authenticated" required>
      Update server metadata
    </ResponseField>

    <ResponseField name="DELETE /servers/:name" type="authenticated" required>
      Delete a server
    </ResponseField>

    <Note>MCP execution happens via WebSocket API (not HTTP endpoints). Use `superbox pull` to configure AI clients.</Note>
    <Info>Authenticated endpoints have higher rate limits (1000 req/hour)</Info>
  </Tab>
</Tabs>

## Permission Levels

SuperBox implements resource-level permissions:

<AccordionGroup>
  <Accordion icon="eye" title="Read Permission">
    All authenticated users can read any server's information
  </Accordion>

  <Accordion icon="pen" title="Write Permission">
    Only the server owner can update their server's metadata
  </Accordion>

  <Accordion icon="trash" title="Delete Permission">
    Only the server owner can delete their server
  </Accordion>

  <Accordion icon="crown" title="Admin Permission">
    SuperBox admins can modify or delete any server
  </Accordion>
</AccordionGroup>

## Error Responses

### Missing Token

```json theme={null}
{
  "success": false,
  "error": {
 "code": "MISSING_TOKEN",
 "message": "Authentication token is required",
 "details": {
"hint": "Include 'Authorization: Bearer <token>' header"
 }
  }
}
```

### Invalid Token

```json theme={null}
{
  "success": false,
  "error": {
 "code": "INVALID_TOKEN",
 "message": "Authentication token is invalid or malformed",
 "details": {
"reason": "Invalid signature"
 }
  }
}
```

### Expired Token

```json theme={null}
{
  "success": false,
  "error": {
 "code": "EXPIRED_TOKEN",
 "message": "Authentication token has expired",
 "details": {
"expiredAt": "2025-12-09T10:30:00Z",
"hint": "Refresh your token and try again"
 }
  }
}
```

### Insufficient Permissions

```json theme={null}
{
  "success": false,
  "error": {
 "code": "FORBIDDEN",
 "message": "You don't have permission to perform this action",
 "details": {
"required": "owner",
"current": "user"
 }
  }
}
```

## Best Practices

<AccordionGroup>
  <Accordion icon="lock" title="Store Tokens Securely">
    * Use environment variables - Never hardcode tokens in source code - Don't
      commit tokens to version control - Use secret management services (AWS
      Secrets Manager, HashiCorp Vault)
  </Accordion>

  <Accordion icon="rotate" title="Implement Token Refresh">
    * Check token expiry before requests - Refresh tokens proactively (5 min
      before expiry) - Handle 401 responses gracefully - Retry failed requests after
      refresh
  </Accordion>

  <Accordion icon="shield-check" title="Use HTTPS Only">
    * Always use HTTPS for API requests - Never send tokens over unencrypted
      connections - Validate SSL certificates
  </Accordion>

  <Accordion icon="clock-rotate-left" title="Rotate Tokens Regularly">
    * Generate new tokens periodically - Revoke old tokens after rotation -
      Monitor token usage for anomalies
  </Accordion>

  <Accordion icon="bell" title="Monitor for Breaches">
    * Set up alerts for unusual activity - Review access logs regularly - Revoke
      compromised tokens immediately
  </Accordion>
</AccordionGroup>

## SDK Authentication

Using our official SDKs simplifies authentication:

<CodeGroup>
  ```python Python SDK theme={null}
  from superbox import SuperBoxClient

  # Initialize with token

  client = SuperBoxClient(token=os.getenv('SUPERBOX_API_TOKEN'))

  # Token refresh is handled automatically

  servers = client.servers.list()

  ```

  ```javascript Node.js SDK theme={null}
  import { SuperBoxClient } from '@superbox/sdk';

  // Initialize with token
  const client = new SuperBoxClient({
    token: process.env.SUPERBOX_API_TOKEN
  });

  // Token refresh is handled automatically
  const servers = await client.servers.list();
  ```

  ```go Go SDK theme={null}
  package main

  import (
   "os"
   "github.com/superbox/sdk-go"
  )

  func main() {
   // Initialize with token
   client := superbox.NewClient(os.Getenv("SUPERBOX_API_TOKEN"))

   // Token refresh is handled automatically
   servers, err := client.Servers.List()
  }
  ```
</CodeGroup>

## Testing Authentication

Test your authentication setup:

```bash theme={null}
# Test with valid token
curl -X GET "https://api.superbox.ai/api/v1/auth/me" \
  -H "Authorization: Bearer $SUPERBOX_API_TOKEN"

# Expected: 200 OK with user profile

# Test with invalid token
curl -X GET "https://api.superbox.ai/api/v1/auth/me" \
  -H "Authorization: Bearer invalid_token"

# Expected: 401 Unauthorized

# Test without token
curl -X GET "https://api.superbox.ai/api/v1/auth/me"

# Expected: 401 Unauthorized (missing token)
```

<Check>
  **You're all set!** You now know how to authenticate with the SuperBox API.
</Check>

## Next Steps

<CardGroup cols={2}>
  <Card title="Create Your First Server" icon="rocket" href="/api/servers/create">
    Deploy an MCP server using authenticated endpoints
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/api/errors">
    Learn how to handle authentication errors
  </Card>
</CardGroup>
