# Authentication

> API key management and access control for the Nyx API

This guide covers authentication methods, API key management, and access control
for the Nyx Astronomy API.

## Table of Contents

1. [Overview](#overview)
2. [API Keys](#api-keys)
3. [Authentication Methods](#authentication-methods)
4. [Access Tiers](#access-tiers)
5. [Rate Limiting](#rate-limiting)
6. [Security Best Practices](#security-best-practices)
7. [Troubleshooting](#troubleshooting)

---

## Overview

The Nyx API uses API key authentication to:

- Identify your application
- Determine your access tier and rate limits
- Track usage for billing and analytics
- Protect against abuse

### Do I Need an API Key?

| Use Case                     | API Key Required  |
| ---------------------------- | ----------------- |
| Basic object searches        | No (rate limited) |
| Ephemeris calculations       | Recommended       |
| Real-time satellite tracking | Yes               |
| WebSocket connections        | Yes               |
| Widget embedding             | Recommended       |
| Production applications      | Yes               |

---

## API Keys

### Getting an API Key

1. Create an account at
   [nyx.oshun.io/developers](https://nyx.oshun.io/developers)
2. Navigate to "API Keys" in your dashboard
3. Click "Create New Key"
4. Name your key and select permissions
5. Copy and securely store your key

### API Key Format

Nyx API keys follow this format:

```
nyx_{tier}_{random_string}
```

**Examples:**

- `nyx_free_demo123456` (Free tier)
- `nyx_pro_abc123xyz789` (Pro tier)
- `nyx_enterprise_corp456def` (Enterprise tier)

### Test API Keys

For development and testing, you can use these demo keys:

| Key                      | Tier       | Rate Limit    |
| ------------------------ | ---------- | ------------- |
| `nyx_free_demo123456`    | Free       | 300 req/min   |
| `nyx_pro_testkey789`     | Pro        | 1,000 req/min |
| `nyx_enterprise_corp456` | Enterprise | 5,000 req/min |

> **Note**: Demo keys are for testing only. Do not use in production.

### Key Management

#### Listing Keys

View all your API keys in the dashboard or via API:

```bash
curl -H "Authorization: Bearer YOUR_ACCOUNT_TOKEN" \
  "https://api.nyx.oshun.io/v1/account/keys"
```

#### Revoking Keys

Revoke a compromised key immediately:

```bash
curl -X DELETE \
  -H "Authorization: Bearer YOUR_ACCOUNT_TOKEN" \
  "https://api.nyx.oshun.io/v1/account/keys/KEY_ID"
```

#### Rotating Keys

Best practice is to rotate keys periodically:

1. Create a new key
2. Update your application to use the new key
3. Monitor for any failed requests with the old key
4. Revoke the old key

---

## Authentication Methods

### Method 1: X-API-Key Header (Recommended)

```bash
curl -H "X-API-Key: nyx_pro_abc123xyz789" \
  "https://api.nyx.oshun.io/api/v1/objects/M42"
```

### Method 2: Authorization Header

```bash
curl -H "Authorization: Bearer nyx_pro_abc123xyz789" \
  "https://api.nyx.oshun.io/api/v1/objects/M42"
```

### Method 3: Query Parameter

> **Note**: Less secure; avoid in production.

```bash
curl "https://api.nyx.oshun.io/api/v1/objects/M42?api_key=nyx_pro_abc123xyz789"
```

### WebSocket Authentication

Authenticate after connecting:

```javascript
const ws = new WebSocket('wss://api.nyx.oshun.io/ws');

ws.onopen = () => {
  ws.send(
    JSON.stringify({
      type: 'auth',
      payload: {
        apiKey: 'nyx_pro_abc123xyz789',
      },
    })
  );
};
```

---

## Access Tiers

### Tier Comparison

| Feature                | Anonymous | Free    | Pro       | Enterprise |
| ---------------------- | --------- | ------- | --------- | ---------- |
| **Rate Limit**         | 60/min    | 300/min | 1,000/min | 5,000/min  |
| **Burst Limit**        | 10        | 30      | 100       | 500        |
| **Object Search**      | ✓         | ✓       | ✓         | ✓          |
| **Ephemeris**          | Limited   | ✓       | ✓         | ✓          |
| **Events**             | ✗         | ✓       | ✓         | ✓          |
| **Satellite Tracking** | ✗         | Limited | ✓         | ✓          |
| **WebSocket**          | ✗         | 5 subs  | 100 subs  | 1,000 subs |
| **Batch Requests**     | ✗         | ✗       | ✓         | ✓          |
| **Webhooks**           | ✗         | ✗       | ✗         | ✓          |
| **SLA**                | None      | None    | 99.5%     | 99.9%      |
| **Support**            | Community | Email   | Priority  | Dedicated  |

### Feature Access

Certain endpoints require specific tiers:

| Endpoint Category           | Minimum Tier |
| --------------------------- | ------------ |
| `/api/v1/objects`           | Anonymous    |
| `/api/v1/objects/search`    | Anonymous    |
| `/api/v1/ephemeris`         | Free         |
| `/api/v1/events`            | Free         |
| `/api/v1/satellites`        | Free         |
| `/api/v1/satellites/passes` | Pro          |
| `/api/v1/batch/*`           | Pro          |
| `/api/v1/webhooks/*`        | Enterprise   |

### Insufficient Tier Response

If you access an endpoint above your tier:

```json
{
  "type": "https://api.nyx.io/problems/forbidden",
  "title": "Forbidden",
  "status": 403,
  "detail": "This endpoint requires one of the following tiers: pro, enterprise. Your current tier: free",
  "code": "INSUFFICIENT_TIER",
  "requiredTiers": ["pro", "enterprise"],
  "currentTier": "free"
}
```

---

## Rate Limiting

### Rate Limit by Tier

| Tier       | Requests/Minute | Burst | WebSocket Updates |
| ---------- | --------------- | ----- | ----------------- |
| Anonymous  | 60              | 10    | N/A               |
| Free       | 300             | 30    | 1/second          |
| Pro        | 1,000           | 100   | 10/second         |
| Enterprise | 5,000           | 500   | 100/second        |

### Rate Limit Headers

Every response includes rate limit information:

```
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 287
X-RateLimit-Reset: 1705334445
X-RateLimit-Tier: free
```

| Header                  | Description                       |
| ----------------------- | --------------------------------- |
| `X-RateLimit-Limit`     | Maximum requests per minute       |
| `X-RateLimit-Remaining` | Requests remaining in window      |
| `X-RateLimit-Reset`     | Unix timestamp when window resets |
| `X-RateLimit-Tier`      | Your current tier                 |

### Rate Limit Exceeded

When rate limited, you'll receive a 429 response:

```json
{
  "type": "https://api.nyx.io/problems/rate-limit-exceeded",
  "title": "Rate Limit Exceeded",
  "status": 429,
  "detail": "You have exceeded the rate limit of 300 requests per minute. Please wait 45 seconds.",
  "code": "RATE_LIMIT_EXCEEDED",
  "limit": 300,
  "remaining": 0,
  "resetAt": 1705334445,
  "tier": "free"
}
```

The response also includes a `Retry-After` header:

```
Retry-After: 45
```

### Handling Rate Limits

```javascript
async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const response = await fetch(url, options);

    if (response.status === 429) {
      const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
      console.log(`Rate limited. Retrying in ${retryAfter}s...`);
      await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
      continue;
    }

    return response;
  }

  throw new Error('Max retries exceeded');
}
```

### Rate Limit Best Practices

1. **Cache responses** - Astronomical data changes slowly
2. **Use WebSocket** - For real-time data instead of polling
3. **Batch requests** - Combine multiple queries (Pro tier)
4. **Implement backoff** - Exponential backoff on rate limits
5. **Monitor usage** - Track your API usage in the dashboard

---

## Security Best Practices

### Protect Your API Key

**Do:**

- Store keys in environment variables
- Use server-side API calls when possible
- Rotate keys periodically
- Use separate keys for development and production
- Monitor for unusual activity

**Don't:**

- Commit keys to version control
- Expose keys in client-side JavaScript
- Share keys between applications
- Log API keys in plain text

### Environment Variables

```bash
# .env file (never commit this!)
NYX_API_KEY=nyx_pro_abc123xyz789
```

```javascript
// Node.js
const apiKey = process.env.NYX_API_KEY;

// Browser (proxied through your server)
// Never expose keys in frontend code
```

### Server-Side Proxy

For web applications, proxy API requests through your server:

```javascript
// Your backend (Express example)
app.get('/api/astronomy/:endpoint', async (req, res) => {
  const response = await fetch(
    `https://api.nyx.oshun.io/api/v1/${req.params.endpoint}`,
    {
      headers: {
        'X-API-Key': process.env.NYX_API_KEY,
      },
    }
  );

  const data = await response.json();
  res.json(data);
});

// Your frontend
const data = await fetch('/api/astronomy/objects/M42');
```

### IP Allowlisting

For Enterprise tier, restrict API key usage to specific IPs:

1. Go to API Keys in your dashboard
2. Select a key
3. Add allowed IP addresses or CIDR ranges
4. Save changes

### Key Permissions

Create keys with minimal required permissions:

| Permission           | Allows                     |
| -------------------- | -------------------------- |
| `read:objects`       | Read celestial object data |
| `read:ephemeris`     | Calculate positions        |
| `read:events`        | Read event data            |
| `read:satellites`    | Read satellite data        |
| `write:observations` | Log observations           |
| `admin:account`      | Manage account settings    |

---

## Troubleshooting

### Invalid API Key

```json
{
  "type": "https://api.nyx.io/problems/invalid-api-key",
  "title": "Invalid API Key",
  "status": 401,
  "detail": "The provided API key is invalid or has been revoked.",
  "code": "INVALID_API_KEY"
}
```

**Solutions:**

1. Verify the key is correct (no extra spaces)
2. Check if the key was revoked
3. Ensure you're using the right header format

### Expired API Key

```json
{
  "type": "https://api.nyx.io/problems/api-key-expired",
  "title": "API Key Expired",
  "status": 401,
  "detail": "The provided API key has expired. Please renew your subscription.",
  "code": "API_KEY_EXPIRED"
}
```

**Solutions:**

1. Renew your subscription
2. Create a new API key
3. Contact support if unexpected

### Missing API Key

```json
{
  "type": "https://api.nyx.io/problems/unauthorized",
  "title": "Unauthorized",
  "status": 401,
  "detail": "This endpoint requires authentication. Please provide a valid API key.",
  "code": "MISSING_API_KEY"
}
```

**Solutions:**

1. Add the `X-API-Key` header
2. Verify header name is correct
3. Check for typos in header name

### Forbidden (Insufficient Tier)

```json
{
  "type": "https://api.nyx.io/problems/forbidden",
  "title": "Forbidden",
  "status": 403,
  "detail": "This endpoint requires one of the following tiers: pro, enterprise",
  "code": "INSUFFICIENT_TIER"
}
```

**Solutions:**

1. Upgrade your subscription
2. Use a different endpoint
3. Contact sales for enterprise features

### Common Issues

| Issue                        | Solution                               |
| ---------------------------- | -------------------------------------- |
| Key works locally, not prod  | Check environment variables            |
| Intermittent 401 errors      | Check for clock skew                   |
| Key suddenly stopped working | Check for revocation in dashboard      |
| Rate limited unexpectedly    | Check for multiple apps using same key |

---

## API Key Endpoints

### Check Authentication Status

```bash
curl -H "X-API-Key: YOUR_KEY" \
  "https://api.nyx.oshun.io/api/v1/auth/status"
```

**Response:**

```json
{
  "success": true,
  "data": {
    "authenticated": true,
    "tier": "pro",
    "userId": "user_abc123",
    "keyId": "key_xyz789",
    "permissions": ["read:objects", "read:ephemeris", "read:events"],
    "rateLimit": {
      "limit": 1000,
      "remaining": 987,
      "resetAt": 1705334445
    }
  }
}
```

### Get Usage Statistics

```bash
curl -H "Authorization: Bearer YOUR_ACCOUNT_TOKEN" \
  "https://api.nyx.oshun.io/api/v1/account/usage?period=month"
```

**Response:**

```json
{
  "success": true,
  "data": {
    "period": "2026-01",
    "totalRequests": 45230,
    "breakdown": {
      "objects": 12500,
      "ephemeris": 18200,
      "events": 5800,
      "satellites": 8730
    },
    "websocket": {
      "connections": 1250,
      "messages": 892000
    },
    "averageLatency": 45,
    "errorRate": 0.02
  }
}
```

---

## Contact

For authentication issues or questions:

- **Documentation**: You're here!
- **Support**: api-support@nyx.oshun.io
- **Enterprise Sales**: sales@nyx.oshun.io

---

## Back to [API Documentation](./README.md)
