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

# API Key Management

> Best practices for managing and protecting API keys

# API Key Management

Proper API key management is critical for security. This guide covers best practices for storing, rotating, and monitoring your API keys.

## API Key Types

| Key Type | Prefix     | Environment | Capabilities                      |
| -------- | ---------- | ----------- | --------------------------------- |
| Test     | `fb_test_` | Development | Test data only, no charges        |
| Live     | `fb_live_` | Production  | Real verifications, charges apply |

<Warning>
  Never use test keys in production or live keys in development. Each environment should have its own credentials.
</Warning>

## Secure Storage

### Environment Variables

The minimum viable approach for local development:

```bash theme={null}
# .env (never commit this file!)
FRAUD_BUSTER_API_KEY=fb_live_your_key_here
FRAUD_BUSTER_SECRET_KEY=your_secret_key_here
```

```typescript theme={null}
// Load from environment
import dotenv from 'dotenv';
dotenv.config();

const client = new TxnCheckClient({
  apiKey: process.env.FRAUD_BUSTER_API_KEY!,
  secretKey: process.env.FRAUD_BUSTER_SECRET_KEY,
});
```

### Secrets Manager (Recommended)

Use a dedicated secrets manager for production:

<Tabs>
  <Tab title="AWS Secrets Manager">
    ```typescript theme={null}
    import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';

    async function getApiKey(): Promise<string> {
      const client = new SecretsManagerClient({ region: 'ap-south-1' });
      
      const response = await client.send(
        new GetSecretValueCommand({
          SecretId: 'txncheck/api-keys',
        })
      );
      
      const secrets = JSON.parse(response.SecretString!);
      return secrets.FRAUD_BUSTER_API_KEY;
    }
    ```
  </Tab>

  <Tab title="HashiCorp Vault">
    ```typescript theme={null}
    import Vault from 'node-vault';

    async function getApiKey(): Promise<string> {
      const vault = Vault({
        endpoint: process.env.VAULT_ADDR,
        token: process.env.VAULT_TOKEN,
      });
      
      const result = await vault.read('secret/data/txncheck');
      return result.data.data.api_key;
    }
    ```
  </Tab>

  <Tab title="Google Secret Manager">
    ```typescript theme={null}
    import { SecretManagerServiceClient } from '@google-cloud/secret-manager';

    async function getApiKey(): Promise<string> {
      const client = new SecretManagerServiceClient();
      
      const [version] = await client.accessSecretVersion({
        name: 'projects/my-project/secrets/txncheck-api-key/versions/latest',
      });
      
      return version.payload!.data!.toString();
    }
    ```
  </Tab>

  <Tab title="Azure Key Vault">
    ```typescript theme={null}
    import { SecretClient } from '@azure/keyvault-secrets';
    import { DefaultAzureCredential } from '@azure/identity';

    async function getApiKey(): Promise<string> {
      const client = new SecretClient(
        'https://my-vault.vault.azure.net',
        new DefaultAzureCredential()
      );
      
      const secret = await client.getSecret('txncheck-api-key');
      return secret.value!;
    }
    ```
  </Tab>
</Tabs>

### Kubernetes Secrets

For containerized deployments:

```yaml theme={null}
# secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: txncheck-secrets
type: Opaque
stringData:
  api-key: fb_live_your_key_here
  secret-key: your_secret_key_here
---
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
        - name: app
          env:
            - name: FRAUD_BUSTER_API_KEY
              valueFrom:
                secretKeyRef:
                  name: txncheck-secrets
                  key: api-key
```

## Key Rotation

Rotate API keys regularly to limit exposure from potential leaks.

### Rotation Process

```mermaid theme={null}
flowchart TD
    A[Generate new key] --> B[Update secrets manager]
    B --> C[Deploy to staging]
    C --> D{Tests pass?}
    D -->|Yes| E[Deploy to production]
    D -->|No| F[Rollback]
    E --> G[Verify traffic on new key]
    G --> H[Revoke old key]
```

### Zero-Downtime Rotation

Support multiple valid keys during rotation:

```typescript theme={null}
// config/api-keys.ts
export interface APIKeyConfig {
  primary: string;
  secondary?: string; // Used during rotation
}

// During rotation, try primary first, fall back to secondary
class RotatingTxnCheckClient {
  private primaryClient: TxnCheckClient;
  private secondaryClient?: TxnCheckClient;

  constructor(config: APIKeyConfig) {
    this.primaryClient = new TxnCheckClient({ apiKey: config.primary });
    if (config.secondary) {
      this.secondaryClient = new TxnCheckClient({ apiKey: config.secondary });
    }
  }

  async upiByMobile(mobile: string, options: any) {
    try {
      return await this.primaryClient.upiByMobile(mobile, options);
    } catch (error) {
      if (this.isAuthError(error) && this.secondaryClient) {
        console.warn('Primary key failed, trying secondary');
        return await this.secondaryClient.upiByMobile(mobile, options);
      }
      throw error;
    }
  }

  private isAuthError(error: any): boolean {
    return error.statusCode === 401;
  }
}
```

### Rotation Schedule

| Environment    | Rotation Frequency | Process                  |
| -------------- | ------------------ | ------------------------ |
| Development    | On demand          | Regenerate in dashboard  |
| Staging        | Monthly            | Automated rotation       |
| Production     | Quarterly          | Manual with verification |
| After incident | Immediate          | Emergency rotation       |

## Scoped API Keys

Request API keys with minimum necessary permissions:

```typescript theme={null}
// Key with limited scope
const limitedClient = new TxnCheckClient({
  apiKey: process.env.FRAUD_BUSTER_BLOCKLIST_ONLY_KEY!,
  // This key only has access to vpa-chargeback-check
});

// Full access key for admin operations
const adminClient = new TxnCheckClient({
  apiKey: process.env.FRAUD_BUSTER_ADMIN_KEY!,
});
```

<Note>
  Contact TxnCheck support to request scoped API keys with limited method access.
</Note>

## Monitoring API Key Usage

### Track Key Usage

```typescript theme={null}
// middleware/api-tracking.ts
export function trackApiUsage(keyName: string) {
  return async (req: Request, res: Response, next: NextFunction) => {
    const startTime = Date.now();
    
    res.on('finish', () => {
      const duration = Date.now() - startTime;
      
      // Send to your monitoring system
      metrics.increment('fraud_buster.api_calls', {
        key: keyName,
        endpoint: req.path,
        status: res.statusCode,
        duration,
      });
    });
    
    next();
  };
}
```

### Alert on Anomalies

Set up alerts for:

* Unusual spike in API calls
* High error rates (especially 401/403)
* Calls from unexpected IP addresses
* Usage outside business hours

```typescript theme={null}
// Example alert rule (pseudo-code)
const alertRules = [
  {
    name: 'High Error Rate',
    condition: 'error_rate > 10% over 5 minutes',
    action: 'page_oncall',
  },
  {
    name: 'Unusual Volume',
    condition: 'request_count > 3x baseline over 1 hour',
    action: 'slack_alert',
  },
  {
    name: 'Auth Failures',
    condition: 'status_401_count > 10 in 1 minute',
    action: 'page_security',
  },
];
```

## Preventing Key Exposure

### Git Pre-commit Hooks

Prevent accidental commits:

```bash theme={null}
# .git/hooks/pre-commit
#!/bin/bash

# Check for API keys
if git diff --cached | grep -E 'fb_(test|live)_[a-zA-Z0-9]+'; then
  echo "ERROR: Possible API key detected in commit"
  echo "Remove sensitive data before committing"
  exit 1
fi
```

### .gitignore

Always ignore sensitive files:

```gitignore theme={null}
# .gitignore
.env
.env.local
.env.*.local
*.key
secrets/
```

### Secret Scanning

Enable GitHub secret scanning or use tools like:

* [GitLeaks](https://github.com/gitleaks/gitleaks)
* [TruffleHog](https://github.com/trufflesecurity/trufflehog)
* [detect-secrets](https://github.com/Yelp/detect-secrets)

```bash theme={null}
# Run GitLeaks before pushing
gitleaks detect --source . --verbose
```

## Emergency Key Revocation

If a key is compromised:

### Immediate Steps

1. **Revoke the compromised key** in your TxnCheck dashboard
2. **Generate a new key** with same permissions
3. **Update all services** using the compromised key
4. **Review logs** for unauthorized usage

### Automation Script

```bash theme={null}
#!/bin/bash
# emergency-rotate.sh

set -e

echo "🚨 Emergency API Key Rotation"

# Generate new key via API (if available) or manually in dashboard
NEW_KEY="fb_live_new_key_here"

# Update secrets manager
aws secretsmanager update-secret \
  --secret-id txncheck/api-keys \
  --secret-string "{\"FRAUD_BUSTER_API_KEY\":\"$NEW_KEY\"}"

# Force redeploy services
kubectl rollout restart deployment/my-service

# Revoke old key (via dashboard or API)
echo "⚠️ Remember to revoke the old key in the dashboard!"

echo "✅ Rotation complete"
```

## Best Practices Summary

<AccordionGroup>
  <Accordion title="Storage">
    * Use secrets manager in production
    * Never hardcode keys
    * Different keys per environment
  </Accordion>

  <Accordion title="Rotation">
    * Rotate quarterly minimum
    * Immediate rotation after suspected breach
    * Zero-downtime rotation process
  </Accordion>

  <Accordion title="Monitoring">
    * Track all API key usage
    * Alert on anomalies
    * Regular access reviews
  </Accordion>

  <Accordion title="Prevention">
    * Pre-commit hooks
    * Secret scanning in CI/CD
    * Code review for key exposure
  </Accordion>
</AccordionGroup>

## Related Guides

<CardGroup cols={2}>
  <Card title="Security Overview" icon="shield" href="/security/overview">
    Complete security guide
  </Card>

  <Card title="Authentication" icon="lock" href="/authentication">
    API authentication details
  </Card>
</CardGroup>
