Token Storage & Caching
Relevant source files
The following files were used as context for generating this wiki page:
The Token Storage and Caching system in MoodTune is a critical core component designed to securely manage authentication credentials and optimize network performance. The system is responsible for the persistent storage of Supabase session tokens, handling large token sizes through chunking, and providing a high-performance in-memory cache to minimize redundant disk I/O.
This module works in tandem with the Authentication System Implementation Plan to ensure that users remain authenticated across app restarts while maintaining high security standards through encryption. It also integrates with the network layer via interceptors to handle automatic token injection and reactive session refreshing.
Sources: authplan.md:65-67, CLAUDE.md:61-63
Architecture and Core Components
The storage architecture is built on a layered approach, utilizing the flutter_secure_storage package as the underlying persistent engine. This ensures that sensitive tokens are encrypted using platform-specific secure storage (Keychain for iOS and Keystore for Android).
TokenStorage Class
Located at lib/core/network/token_storage.dart, the TokenStorage class serves as the primary interface for all token-related operations. It abstracts the complexities of secure storage and adds optimization logic.
| Feature | Description |
|---|---|
| Secure Persistence | Uses FlutterSecureStorage for encrypted on-disk storage. |
| Size Optimization | Implements chunking for tokens exceeding 3500 characters. |
| Performance Cache | Maintains an in-memory variable to provide synchronous-like access speeds. |
| Metadata Management | Tracks token_storage_type to determine if a token is direct or chunked. |
Sources: authplan.md:73-81, pubspec.yaml:26
Data Flow Diagram
The following diagram illustrates the flow of a token from the SupabaseAuthService into persistent storage, including the chunking logic.
Sources: authplan.md:85-92
Storage Logic and Chunking
A significant technical requirement of the system is handling large authentication tokens. Because some storage providers have character limits, the TokenStorage implements a specific chunking strategy.
Storage Thresholds
The system evaluates the token string length to decide the storage method:
- Direct Storage: Tokens under 3500 characters are stored as a single entry.
- Compression/Chunking: Tokens between 3500 and 7000 characters trigger an attempt at compression, falling back to chunking if necessary.
- Chunked Storage: Tokens exceeding 7000 characters are broken into 3000-character segments.
Sources: authplan.md:88-91
Key Methods
The implementation includes the following asynchronous methods to manage the lifecycle of a token:
class TokenStorage {
// Encrypts and persists the token, updating the local cache.
Future<void> storeToken(String token);
// Retrieves the token, reconstructing chunks if metadata indicates chunked storage.
Future<String?> getToken();
// Removes all token data and metadata from secure storage and memory.
Future<void> clearToken();
}
Sources: authplan.md:82-84
Network Integration and Caching Strategy
Token storage is not a passive component; it is actively used by the network layer to authorize outgoing requests. The AuthInterceptor is the primary consumer of cached tokens.
AuthInterceptor Flow
The AuthInterceptor (located in lib/core/network/interceptors/auth_interceptor.dart) interacts with TokenStorage during the request lifecycle.
Sources: authplan.md:104-114, CLAUDE.md:61-63
Dependency Injection
The system uses the GetIt service locator to manage the lifecycle of these components. The tokenProvider lambda captures the Supabase session token at call time and passes it to the data sources, ensuring that the cache is always fresh.
Sources: CLAUDE.md:88-90, authplan.md:270-280
Implementation and Configuration
Environment Setup
Token storage behaviors may vary based on environment variables defined in .env or dev.env files, specifically for the SUPABASE_URL and SUPABASE_ANON_KEY which are required to initialize the auth services that feed the storage.
| Variable | Usage in Token Storage |
|---|---|
SUPABASE_URL | Used to validate and refresh sessions. |
SUPABASE_ANON_KEY | Required for initial guest-to-auth transitions. |
Sources: CLAUDE.md:126-130, README.md:83-85
Platform-Specific Persistence
The implementation relies on the following platform-specific secure features:
- iOS: Data is stored in the Keychain with
remove_alpha_iosconsiderations for icons, though the token data itself is standard encrypted strings. - Android: Data is stored in the Keystore. The
AndroidManifest.xmlmust be configured for OAuth flows that generate the tokens.
Sources: authplan.md:330-340, pubspec.yaml:57, android/app/src/main/AndroidManifest.xml
Summary
The Token Storage & Caching system provides a production-ready solution for managing sensitive credentials. By combining FlutterSecureStorage with a custom chunking algorithm and an in-memory cache, the system balances security and performance. Its tight integration with the AuthInterceptor ensures that token lifecycle events—such as expiry and 401 refresh cycles—are handled transparently for the rest of the application.
Sources: authplan.md:377-385, CLAUDE.md:107-112