UNPKG

@theoptimalpartner/jwt-auth-validator

Version:

JWT token validation package with offline JWKS validation and Redis-based token revocation support

103 lines 3.38 kB
import Redis from 'ioredis'; export class RedisService { client = null; config = null; constructor(config) { if (config) { this.config = config; } } async initialize(config) { if (config) { this.config = config; } if (!this.config) { throw new Error('Redis configuration is required'); } if (this.client && this.client.status === 'ready') { return; } try { const redisOptions = { host: this.config.host, port: this.config.port || 6380, family: this.config.family || 4, connectTimeout: this.config.connectTimeout || 60000, commandTimeout: this.config.commandTimeout || 30000, lazyConnect: this.config.lazyConnect !== false, maxRetriesPerRequest: this.config.maxRetriesPerRequest || 3, reconnectOnError: this.config.reconnectOnError || ((err) => { const reconnectErrors = [ 'READONLY', 'ECONNRESET', 'EPIPE', 'ETIMEDOUT', 'ENOTFOUND', 'ENETUNREACH', 'ECONNREFUSED', 'EHOSTUNREACH' ]; return reconnectErrors.some(target => err.message.includes(target)); }), retryStrategy: this.config.retryStrategy || ((times) => { if (times > 10) return null; return Math.min(times * 200, 5000); }), }; if (this.config.password) { redisOptions.password = this.config.password; } if (this.config.tls) { redisOptions.tls = this.config.tls; } this.client = new Redis(redisOptions); await this.client.connect(); } catch (error) { console.error('Failed to connect to Redis:', error); throw error; } } async ping() { if (!this.client) { throw new Error('Redis client not initialized'); } return this.client.ping(); } async disconnect() { if (this.client) { await this.client.quit(); this.client = null; } } async set(key, value, ttl) { if (!this.client) { throw new Error('Redis client not initialized'); } await this.client.set(key, value, 'EX', ttl); } async get(key) { if (!this.client) { throw new Error('Redis client not initialized'); } return this.client.get(key); } async exists(key) { if (!this.client) { throw new Error('Redis client not initialized'); } return this.client.exists(key); } async del(key) { if (!this.client) { throw new Error('Redis client not initialized'); } return this.client.del(key); } async saveRevokedToken(token, ttl) { await this.set(`revoked:${token}`, '1', ttl); } async isTokenRevoked(token) { const result = await this.exists(`revoked:${token}`); return result === 1; } get isConnected() { return this.client?.status === 'ready'; } } //# sourceMappingURL=redis-service.js.map