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

# Security

> API token security, best practices, and threat mitigation strategies

Security is your responsibility. The Melonly API provides secure infrastructure, but proper token management and implementation practices are critical for maintaining system security.

<Warning>
  **No Security Support:** Security vulnerabilities, breaches, or compromised tokens are not supported. Implement proper security measures from the start.
</Warning>

***

## Token Security

API tokens provide full access to your server data and operations. Treat them as sensitive credentials.

### Storage Requirements

<Tabs>
  <Tab title="Environment Variables">
    **Recommended Approach**

    ```bash theme={null}
    # .env file
    MELONLY_API_TOKEN=your_token_here

    # Access in application
    const token = process.env.MELONLY_API_TOKEN;
    ```

    Never commit `.env` files to version control.
  </Tab>

  <Tab title="Secrets Management">
    **Production Systems**

    ```yaml theme={null}
    # Kubernetes Secret
    apiVersion: v1
    kind: Secret
    metadata:
      name: melonly-api-token
    type: Opaque
    data:
      token: base64_encoded_token_here
    ```

    Use dedicated secrets management systems (HashiCorp Vault, AWS Secrets Manager, etc.).
  </Tab>

  <Tab title="Configuration Services">
    **Cloud Platforms**

    ```javascript theme={null}
    // AWS Parameter Store
    const token = await ssm.getParameter({
      Name: '/app/melonly/api-token',
      WithDecryption: true
    }).promise();

    // Azure Key Vault
    const credential = new DefaultAzureCredential();
    const client = new SecretClient(vaultUrl, credential);
    const secret = await client.getSecret('melonly-api-token');
    ```
  </Tab>
</Tabs>

### Security Violations

**Never:**

* Commit tokens to version control (Git, SVN, etc.)
* Include tokens in client-side code or JavaScript bundles
* Share tokens in chat messages, emails, or documentation
* Log tokens in application logs or error messages
* Store tokens in browser local storage or cookies

***

## Token Lifecycle Management

<AccordionGroup>
  <Accordion title="Token Rotation">
    **Recommended Schedule:** Every 90 days minimum

    ```javascript theme={null}
    // Implementation example
    const rotateToken = async () => {
      // 1. Generate new token via dashboard (please note that this is not an API endpoint, you will need to use Melonlys tRPC endpoint)
      const newToken = await generateNewToken();
      
      // 2. Update application configuration
      await updateSecretStore('MELONLY_API_TOKEN', newToken);
      
      // 3. Deploy updated configuration
      await deployApplication();
      
      // 4. Revoke old token after verification
      await revokeToken(oldToken);
    };
    ```
  </Accordion>

  <Accordion title="Emergency Revocation">
    **Immediate Actions for Compromised Tokens:**

    1. **Revoke token immediately** via Melonly dashboard
    2. **Generate replacement token** with new name/identifier
    3. **Update all applications** using the compromised token
    4. **Review audit logs** for unauthorized activity
    5. **Investigate breach source** and remediate vulnerability
  </Accordion>
</AccordionGroup>

***

## Network Security

### HTTPS Requirements

All API communication must use HTTPS. HTTP connections are rejected.

```javascript theme={null}
// Correct - HTTPS enforced
const response = await fetch('https://api.melonly.xyz/api/v1/server/info', {
  headers: { 'Authorization': 'Bearer ' + token }
});

// Incorrect - Will fail
const response = await fetch('http://api.melonly.xyz/api/v1/server/info', {
  headers: { 'Authorization': 'Bearer ' + token }
});
```

### IP Restrictions

Consider implementing IP allowlisting at your application level:

<CodeGroup>
  ```javascript Node.js Middleware theme={null}
  const allowedIPs = ['192.168.1.100', '10.0.0.50'];

  app.use('/api/*', (req, res, next) => {
    const clientIP = req.ip || req.connection.remoteAddress;
    
    if (!allowedIPs.includes(clientIP)) {
      return res.status(403).json({ error: 'IP not allowed' });
    }
    
    next();
  });
  ```

  ```python Flask theme={null}
  from flask import request, abort

  ALLOWED_IPS = ['192.168.1.100', '10.0.0.50']

  @app.before_request
  def limit_remote_addr():
      if request.remote_addr not in ALLOWED_IPS:
          abort(403)
  ```
</CodeGroup>

***

## Application Security

### Input Validation

Always validate data before sending to the API:

```javascript theme={null}
const validateInput = (data) => {
  // Sanitize user input
  const sanitized = {
    username: data.username?.replace(/[<>]/g, ''),
    reason: data.reason?.substring(0, 500),
    // ... other fields
  };
  
  // Validate required fields
  if (!sanitized.username || !sanitized.reason) {
    throw new Error('Missing required fields');
  }
  
  return sanitized;
};

// Use validated data in API calls
const validData = validateInput(userInput);
const response = await melonlyAPI.createLog(validData);
```

### Error Handling

Implement secure error handling that doesn't expose sensitive information:

<CodeGroup>
  ```javascript Secure Error Handling theme={null}
  const handleAPIError = (error, res) => {
    // Log full error internally
    console.error('API Error:', error);
    
    // Return sanitized error to client
    if (error.status === 401) {
      return res.status(401).json({ error: 'Authentication failed' });
    }
    
    if (error.status === 403) {
      return res.status(403).json({ error: 'Access denied' });
    }
    
    // Generic error for everything else
    return res.status(500).json({ error: 'Internal server error' });
  };
  ```

  ```python Python Error Handling theme={null}
  import logging

  def handle_api_error(error):
      # Log full error details
      logging.error(f"API Error: {error}")
      
      # Return sanitized response
      if error.status_code == 401:
          return {"error": "Authentication failed"}, 401
      elif error.status_code == 403:
          return {"error": "Access denied"}, 403
      else:
          return {"error": "Internal server error"}, 500
  ```
</CodeGroup>

***

## Audit and Compliance

### Request Logging

Log API requests for security monitoring (without exposing tokens):

```javascript theme={null}
const logAPIRequest = (method, url, statusCode, duration) => {
  console.log(JSON.stringify({
    timestamp: new Date().toISOString(),
    method,
    url: url.replace(/Bearer\s+[^\s]+/, 'Bearer [REDACTED]'),
    statusCode,
    duration,
    userAgent: req.headers['user-agent']
  }));
};
```

***

## Incident Response

### Suspected Token Compromise

1. **Immediate containment** - Revoke token via dashboard
2. **Damage assessment** - Review audit logs for unauthorized actions
3. **System remediation** - Update affected applications with new tokens
4. **Root cause analysis** - Identify and fix the compromise vector
5. **Prevention measures** - Implement additional security controls

### Security Contact

For security vulnerabilities in the Melonly API itself (not implementation issues), contact: `admin@melonly.xyz`

<Note>
  **Scope Limitation:** Security support is limited to API infrastructure vulnerabilities only. Implementation security, token management, and application-level security issues are not supported.
</Note>
