๐ Supernal TTS Security Documentation
Overviewโ
This document outlines the security measures implemented in the Supernal TTS API to ensure safe, reliable, and compliant operation in production environments.
Table of Contentsโ
- Authentication & Authorization
- Rate Limiting
- Input Validation
- Security Headers
- Data Protection
- Deployment Security
- Security Checklist
Authentication & Authorizationโ
API Key Authenticationโ
The API uses Bearer token authentication with API keys prefixed with sk-tts-:
curl -X POST https://api.supernal-tts.com/v1/generate \
-H "Authorization: Bearer sk-tts-xxxxx" \
-H "Content-Type: application/json" \
-d '{"text": "Hello world"}'
API Key Features:โ
- Bcrypt hashing: Keys are hashed with bcrypt (10 rounds) before storage
- Scopes: Each key has configurable scopes (read, write, admin)
- Rate limits: Per-key rate limiting
- Expiration: Optional expiration dates
- Usage tracking: Last used timestamp
Creating API Keys (Development):โ
// Set CREATE_TEST_KEYS=true in development
// Keys will be printed to console on startup
JWT Authenticationโ
Alternative authentication using JWT tokens:
curl -X POST https://api.supernal-tts.com/v1/generate \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
-H "Content-Type: application/json" \
-d '{"text": "Hello world"}'
JWT Features:โ
- Standard JWT with HS256 signing
- Contains user ID, email, and roles
- Configurable expiration
- Role-based access control
Development Modeโ
For development, authentication can be disabled:
REQUIRE_AUTH=false npm start
Rate Limitingโ
Tiered Rate Limitingโ
Different rate limits for different scenarios:
| Tier | Limit | Window | Use Case |
|---|---|---|---|
| Global | 100 req/min | 60s | Per IP address |
| Authenticated | 1000 req/min | 60s | Per API key |
| Generation | 10 req/min | 60s | TTS generation |
| Strict | 10 req/min | 60s | Unauthenticated |
Rate Limit Headersโ
All responses include rate limit information:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 2024-01-01T00:01:00Z
Retry-After: 60
Redis Supportโ
For distributed rate limiting across multiple instances:
REDIS_URL=redis://localhost:6379 npm start
Bypassing Rate Limitsโ
Admin users automatically bypass rate limits. Custom rate limits can be set per API key.
Input Validationโ
Text Validationโ
All text inputs are validated with Zod schemas:
- Min length: 1 character
- Max length: 100,000 characters
- Sanitization: Removes control characters
- Whitespace: Normalized to single spaces
Request Validationโ
{
text: string, // Required, 1-100k chars
options: {
provider: string, // openai|cartesia|azure|mock
voice: string, // Provider-specific
speed: number, // 0.25-4.0
format: string, // mp3|opus|aac|flac|wav
quality: string, // standard|high
language: string, // ISO 639-1 code
cache: boolean // Default: true
}
}
Error Responsesโ
Validation errors return detailed information:
{
"error": "Validation failed",
"details": [
{
"path": "options.voice",
"message": "Invalid voice for selected provider"
}
]
}
Security Headersโ
Helmet Configurationโ
The API uses Helmet.js with the following configuration:
{
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
mediaSrc: ["'self'"], // Allow audio playback
// ... other directives
}
},
hsts: {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true
}
}
Custom Headersโ
Additional security headers:
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: microphone=(), camera=(), geolocation=()
CORS Configurationโ
CORS is configured per environment:
# Development
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
# Production
ALLOWED_ORIGINS=https://app.example.com,https://www.example.com
Data Protectionโ
Request Sanitizationโ
- Text sanitization: Removes zero-width characters and control codes
- Size limits: 1MB default request size
- Content-Type validation: Only accepts application/json
Sensitive Data Handlingโ
- No PII storage: Audio is cached by content hash, not user data
- API keys: Never logged or returned in responses
- Error messages: Sanitized to prevent information leakage
Caching Securityโ
- Files cached with SHA-256 hashes
- No user-identifiable information in cache
- Cache directory permissions: 0755
Deployment Securityโ
Environment Variablesโ
Required security environment variables:
# Production Required
NODE_ENV=production
JWT_SECRET=<strong-random-secret>
REQUIRE_AUTH=true
# Optional Security
TRUST_PROXY=true # Behind reverse proxy
WHITELISTED_IPS=1.2.3.4,5.6.7.8
MAX_REQUEST_SIZE=1mb
HTTPS/TLSโ
Always deploy behind HTTPS:
- Use reverse proxy (nginx, caddy)
- Enable HSTS headers
- Use TLS 1.2 minimum
- Strong cipher suites only
Container Securityโ
When using Docker:
# Run as non-root user
USER node
# Read-only root filesystem
# Mount cache directory as volume
# No sensitive data in image
# Use secrets management
Infrastructure Securityโ
- Network isolation: API in private subnet
- Firewall rules: Only allow required ports
- Monitoring: Log all authentication failures
- Secrets management: Use AWS Secrets Manager, Vault, etc.
Security Checklistโ
Pre-Deploymentโ
- All environment variables set correctly
- Authentication enabled (
REQUIRE_AUTH=true) - Strong JWT secret (min 32 chars)
- HTTPS/TLS configured
- Rate limiting tested
- Input validation working
- Security headers verified
Monitoringโ
- Authentication failures logged
- Rate limit violations tracked
- Error rates monitored
- Response times tracked
- Suspicious patterns alerted
Regular Auditsโ
- Dependency updates (
npm audit) - Security scanning (Snyk, etc.)
- Penetration testing
- Access log review
- API key rotation
Testing Securityโ
Run the security test suite:
# Basic security tests
./scripts/test-security.sh
# With verbose output
VERBOSE=true ./scripts/test-security.sh
# Against production
API_URL=https://api.example.com/v1 ./scripts/test-security.sh
Reporting Security Issuesโ
If you discover a security vulnerability:
- DO NOT open a public issue
- Email security@supernal.com
- Include:
- Description of the issue
- Steps to reproduce
- Potential impact
- Suggested fix (if any)
We aim to respond within 48 hours and provide fixes within 7 days for critical issues.
Complianceโ
The API is designed to support:
- GDPR: No PII storage, data minimization
- SOC 2: Audit logging, access controls
- HIPAA: Encryption, access controls (with proper BAA)
- PCI DSS: No payment data handling
Note: Compliance requires proper deployment and configuration.
Security Roadmapโ
Completed (Phase 1) โ โ
- API key authentication
- JWT support
- Rate limiting
- Input validation
- Security headers
- CORS protection
Planned (Phase 2)โ
- OAuth 2.0 support
- Webhook signatures
- Audit logging
- IP allowlisting UI
Future (Phase 3)โ
- mTLS support
- Hardware security module (HSM)
- Zero-trust architecture
- Advanced threat detection