Skip to content

Latest commit

 

History

History
79 lines (57 loc) · 2.09 KB

File metadata and controls

79 lines (57 loc) · 2.09 KB

Security Module

Overview

The security module manages access control, usage quotas, and request validation. It ensures fair usage and protects against abuse.


Files

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

Architecture

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]
Loading

Key Concepts

Quota Holds

The quota system uses optimistic holds to prevent race conditions:

  1. Place Hold: Reserve tokens before generation starts
  2. Consume Hold: Convert hold to usage on success
  3. 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;
}

Allowlist Service

Users must be on the allowlist to access the application:

  • Admin email gets automatic access (ADMIN_EMAIL env var)
  • Other users must be added to Firestore allowedEmails array

Internal Token

API routes like /api/log require the internal token:

  • Header: x-internal-token
  • Must match ACCESS_CONTROL_INTERNAL_TOKEN env var

Configuration

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)