User API Key Storage
Relevant source files
The following files were used as context for generating this wiki page:
User API Key Storage is a security-centric feature in OS Chat that allows users to "Bring Your Own Key" (BYOK) for various AI providers such as OpenAI, Anthropic, and Google Gemini. By providing their own keys, users can bypass platform-specific message limits and gain more control over their AI consumption. The system is built on the principle of Privacy-First and employs industry-standard encryption to ensure that sensitive credentials remain inaccessible to unauthorized parties, including the platform maintainers.
The system integrates directly with the Convex backend for real-time updates and secure server-side processing. It supports multiple providers simultaneously and offers a "Priority" vs "Fallback" mode, allowing users to choose whether their keys should be used immediately or only after their free credits are exhausted.
Sources: README.md:14-25, src/routes/settings/api-keys.tsx:325-345, src/routes/security.tsx:28-35
Security and Encryption Architecture
The core of the API key storage system is a robust encryption layer that ensures keys are never stored in plain text. The application uses the Web Crypto API for all cryptographic operations.
Encryption Mechanism
API keys are encrypted using AES-GCM 256-bit encryption. The process involves:
- Key Derivation: A unique master key is derived using PBKDF2 with 100,000 iterations and a SHA-256 hash.
- User Isolation: To ensure data isolation, the system generates a unique salt per user by hashing their
userIdwith SHA-256. This prevents "cross-user" decryption even if the globalAPI_KEY_SECRETwere compromised. - Payload Structure: The final stored string follows the format
ivHex:dataHex, whereivis a random 12-byte initialization vector.
Sources: convex/api_keys.ts:77-105, src/routes/security.tsx:28-35
Encryption Data Flow
The following diagram illustrates the secure path from the user input to the database storage:
Data Model and Schema
The user_api_keys table stores the encrypted credentials along with metadata required for management and usage tracking.
Table Schema: user_api_keys
| Field | Type | Description |
|---|---|---|
userId | Id<"users"> | Reference to the owner of the key. |
provider | string | The AI provider (e.g., "openai", "anthropic"). |
encryptedKey | string | The AES-GCM encrypted payload (iv:data). |
mode | "priority" | "fallback" | Determines usage logic (Priority: use first; Fallback: use after credits). |
messageCount | number | Incremental counter of messages sent using this specific key. |
createdAt | number | Timestamp of initial key registration. |
updatedAt | number | Timestamp of the last key update or mode change. |
Sources: convex/api_keys.ts:141-155, convex/api_keys.ts:258-270
Key Management Logic
The system provides several Convex functions (Queries and Mutations) to manage the lifecycle of user API keys.
Core Mutations
saveApiKey: Validates the user's session, encrypts the provided key, and either inserts a new record or patches an existing one for that provider. Defaults to "fallback" mode if not specified.deleteApiKey: Permanently removes the key record for a specific provider.updateApiKeyMode: Allows users to toggle between "priority" and "fallback" without re-entering the key.incrementUserApiKeyUsage: Atomically updates themessageCountfield whenever a key is successfully used in a chat completion.
Sources: convex/api_keys.ts:169-204, convex/api_keys.ts:232-254, convex/api_keys.ts:276-295
Usage Strategy in Chat API
The api.chat.ts route implements the logic for selecting whether to use a system key or a user key:
User Interface and Validation
The API Keys settings page provides a secure interface for key entry and status monitoring.
Key Validation Rules
The frontend employs specific validation patterns before sending keys to the backend to ensure format correctness:
| Provider | Validation Logic |
|---|---|
| OpenAI | Starts with sk- |
| Anthropic | Starts with sk-ant- |
| Mistral | Minimum length requirements |
| Gemini | Provider-specific alphanumeric patterns |
Sources: src/lib/config/api-keys.ts, src/routes/settings/api-keys.tsx:210-220
UI Components
ApiKeyInputForm: A masked password input field that prevents key exposure on screen.ProviderCard: Displays the configuration status of each provider, including supported models (e.g., GPT-4o, Claude 3.5 Sonnet) and a toggle for "Priority" mode.BadgeSystem: Visually distinguishes between "Priority" (using user key first) and "Fallback" (using user key when credits are exhausted).
Sources: src/routes/settings/api-keys.tsx:75-125, src/routes/settings/api-keys.tsx:145-180
Conclusion
The User API Key Storage system provides a secure, encrypted, and user-centric way to manage external AI credentials. By leveraging AES-GCM 256-bit encryption with user-specific salts, the platform ensures that keys are handled with the highest security standards. The integration into the chat pipeline allows for seamless switching between platform credits and personal keys, providing users with maximum flexibility and control over their AI costs and limits.