import { Repository } from 'typeorm'; import { StorageAdapter, LoggerService, BaseRateLimit, BaseStorageLock } from '@nauth-toolkit/core'; /** * Database Storage Adapter * * Implements StorageAdapter interface using TypeORM repositories for persistent storage. * Stores transient state (rate limits, locks, token reuse tracking) in database tables. * * **Key Features:** * - Multi-server compatible (all servers share same database) * - Atomic operations via database-level increment/decrement * - TTL support via expiresAt column with scheduled cleanup * - Hash and list operations stored as JSON * - Seamlessly integrates with existing TypeORM DataSource * * **Database Tables:** * - `nauth_rate_limits`: Key-value pairs with expiration * - `nauth_storage_locks`: Distributed locks with expiration * * **Usage:** * ```typescript * import { DatabaseStorageAdapter } from '@nauth-toolkit/storage-database'; * * AuthModule.forRoot({ * storageAdapter: new DatabaseStorageAdapter(), // Uses injected repositories * }); * ``` * * @example * ```typescript * const adapter = new DatabaseStorageAdapter(); * await adapter.initialize(); * await adapter.set('key', 'value', 60); // Set with 60 second TTL * const value = await adapter.get('key'); * ``` */ export declare class DatabaseStorageAdapter implements StorageAdapter { private rateLimitRepo; private storageLockRepo; private logger?; /** * Creates a new DatabaseStorageAdapter instance * * @param rateLimitRepo - TypeORM repository for rate limit storage (injected) * @param storageLockRepo - TypeORM repository for distributed locks (injected) * @param logger - Logger service for error and debug logging * @throws {NAuthException} If repositories are not provided (entities not registered in TypeORM) */ constructor(rateLimitRepo: Repository | null, storageLockRepo: Repository | null, logger?: LoggerService | undefined); /** * Set repositories after construction (for factory-created adapters) * This method is called by the auth module when repositories become available * * @param rateLimitRepo - TypeORM repository for rate limit storage * @param storageLockRepo - TypeORM repository for distributed locks */ setRepositories(rateLimitRepo: Repository, storageLockRepo: Repository): void; /** * Determine which repository to use based on key prefix * Locks and token reuse tracking go to storageLockRepo * Rate limits and other data go to rateLimitRepo * * @param key - The storage key * @returns The appropriate repository */ private getRepositoryForKey; /** * Initialize the storage adapter * Performs health check to ensure repositories are accessible * * @throws {Error} If repositories are not available */ initialize(): Promise; /** * Check if the storage adapter is healthy and operational * @returns True if repositories are available, false otherwise */ isHealthy(): Promise; /** * Get a value by key * @param key - The key to retrieve * @returns The stored value or null if not found/expired */ get(key: string): Promise; /** * Set a key-value pair with optional TTL (time to live) * * @param key - The key to store * @param value - The value to store * @param ttlSeconds - Time to live in seconds (optional) * @param options - Additional options like nx (set if not exists) */ set(key: string, value: string, ttlSeconds?: number, options?: { nx?: boolean; }): Promise; /** * Delete a key from storage * @param key - The key to delete */ del(key: string): Promise; /** * Check if a key exists * @param key - The key to check * @returns True if the key exists and is not expired, false otherwise */ exists(key: string): Promise; /** * Increment a counter stored at key * Uses TypeORM transaction with pessimistic locking for thread-safety * Automatically resets to 1 if the record is expired (treats as new window) * * @param key - The key to increment * @param ttlSeconds - Optional TTL in seconds to set when creating a new record (defaults to 24 hours) * @returns The new value after incrementing */ incr(key: string, ttlSeconds?: number): Promise; /** * Decrement a counter stored at key * Uses TypeORM transaction with pessimistic locking for thread-safety * * @param key - The key to decrement * @returns The new value after decrementing (minimum 0) */ decr(key: string): Promise; /** * Set expiration time for a key * @param key - The key to set expiration for * @param ttlSeconds - Time to live in seconds * @throws {Error} If expiration cannot be set (key doesn't exist or update fails) */ expire(key: string, ttlSeconds: number): Promise; /** * Build a DB-specific expression for NOW() + seconds * Ensures createdAt and expiresAt are in the same time base (database-side). */ private getDbNowPlusSecondsExpression; /** * Get the time-to-live for a key in seconds * @param key - The key to check * @returns TTL in seconds, or -1 if key doesn't exist, or -2 if no expiration */ ttl(key: string): Promise; /** * Set a field in a hash stored at key * @param key - The hash key * @param field - The field name * @param value - The field value */ hset(key: string, field: string, value: string): Promise; /** * Get a field from a hash stored at key * @param key - The hash key * @param field - The field name * @returns The field value or null if not found */ hget(key: string, field: string): Promise; /** * Get all fields and values from a hash stored at key * @param key - The hash key * @returns Object with all field-value pairs */ hgetall(key: string): Promise>; /** * Delete fields from a hash stored at key * @param key - The hash key * @param fields - The field names to delete * @returns The number of fields that were removed */ hdel(key: string, ...fields: string[]): Promise; /** * Push a value to the left (beginning) of a list stored at key * @param key - The list key * @param value - The value to push */ lpush(key: string, value: string): Promise; /** * Get a range of elements from a list stored at key * @param key - The list key * @param start - Start index (0-based) * @param stop - End index (inclusive, -1 for end) * @returns Array of elements in the specified range */ lrange(key: string, start: number, stop: number): Promise; /** * Get the length of a list stored at key * @param key - The list key * @returns The length of the list */ llen(key: string): Promise; /** * Find keys matching a pattern * @param pattern - Glob pattern to match keys against * @returns Array of matching keys */ keys(pattern: string): Promise; /** * Scan for keys matching a pattern (simplified version) * @param cursor - Cursor for pagination (unused in this implementation) * @param pattern - Pattern to match * @param count - Maximum number of keys to return * @returns [nextCursor, keys] tuple */ scan(cursor: number, pattern: string, count: number): Promise<[number, string[]]>; /** * Clean up expired keys (called periodically by background task) * Cleans both rate limit and storage lock tables */ cleanup(): Promise; /** * Disconnect from storage (no-op for database adapter) */ disconnect(): Promise; } //# sourceMappingURL=database-storage.adapter.d.ts.map