The security module manages access control, usage quotas, and request validation. It ensures fair usage and protects against abuse.
| File | Purpose |
|---|---|
quota-service.ts |
Token-based quota management with optimistic holds |
allowed-users.ts |
Email allowlist and invite system |
internal-token.ts |
Internal API token validation |
user-profile.ts |
User profile and preferences management |
graph LR
Request --> InternalToken{Internal Token?}
InternalToken -->|Yes| InternalAPI[Internal API]
InternalToken -->|No| AllowList{On Allowlist?}
AllowList -->|Yes| QuotaCheck{Quota Available?}
AllowList -->|No| Reject[403 Forbidden]
QuotaCheck -->|Yes| Process[Process Request]
QuotaCheck -->|No| RateLimit[429 Rate Limited]
The quota system uses optimistic holds to prevent race conditions:
- Place Hold: Reserve tokens before generation starts
- Consume Hold: Convert hold to usage on success
- Release Hold: Return tokens on failure
import { quotaService } from '@/lib/security/quota-service';
const holdKey = await quotaService.placeHold(userId, 1);
try {
await generateDocument();
await quotaService.consumeHold(userId, holdKey);
} catch (error) {
await quotaService.releaseHold(userId, holdKey);
throw error;
}Users must be on the allowlist to access the application:
- Admin email gets automatic access (
ADMIN_EMAILenv var) - Other users must be added to Firestore
allowedEmailsarray
API routes like /api/log require the internal token:
- Header:
x-internal-token - Must match
ACCESS_CONTROL_INTERNAL_TOKENenv var
| Env Variable | Purpose |
|---|---|
ADMIN_EMAIL |
Email with automatic admin access |
ACCESS_CONTROL_INTERNAL_TOKEN |
Token for internal API access |
DEFAULT_QUOTA_TOKENS |
Default tokens for new users (usually 10) |
ADMIN_QUOTA_TOKENS |
Tokens for admin user (usually 1000) |