| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| const crypto = require('crypto'); |
| const jwt = require('jsonwebtoken'); |
|
|
| class KeySystem { |
| constructor() { |
| |
| this.jwtSecret = process.env.JWT_SECRET || 'chahuadev-framework-super-secret-key-for-development-2025-v1.0.0-thailand'; |
| this.algorithm = 'HS256'; |
| this.defaultExpiry = '1h'; |
| |
| console.log(' Key System initialized'); |
| |
| if (!process.env.JWT_SECRET) { |
| console.warn(' Warning: Using fallback JWT secret. Set JWT_SECRET environment variable for production!'); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| generateToken(payload = {}, expiresIn = this.defaultExpiry) { |
| try { |
| const tokenPayload = { |
| ...payload, |
| iat: Math.floor(Date.now() / 1000), |
| iss: 'chahuadev-framework' |
| }; |
|
|
| const token = jwt.sign(tokenPayload, this.jwtSecret, { |
| algorithm: this.algorithm, |
| expiresIn: expiresIn |
| }); |
|
|
| console.log(' JWT token generated successfully'); |
| return token; |
| |
| } catch (error) { |
| console.error(' JWT generation failed:', error.message); |
| throw new Error('Failed to generate JWT token'); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| verifyToken(token) { |
| try { |
| if (!token) { |
| throw new Error('Token is required'); |
| } |
|
|
| const decoded = jwt.verify(token, this.jwtSecret, { |
| algorithms: [this.algorithm] |
| }); |
|
|
| console.log(' JWT token verified successfully'); |
| return decoded; |
| |
| } catch (error) { |
| console.error(' JWT verification failed:', error.message); |
| throw new Error(`Invalid token: ${error.message}`); |
| } |
| } |
|
|
| |
| |
| |
| |
| generateApiKey() { |
| const apiKey = crypto.randomBytes(32).toString('hex'); |
| console.log(' API key generated'); |
| return apiKey; |
| } |
|
|
| |
| |
| |
| |
| |
| hashData(data) { |
| if (!data) { |
| throw new Error('Data is required for hashing'); |
| } |
|
|
| const hash = crypto.createHash('sha256') |
| .update(data) |
| .digest('hex'); |
| |
| return hash; |
| } |
|
|
| |
| |
| |
| |
| |
| generateSecureRandom(length = 16) { |
| return crypto.randomBytes(Math.ceil(length / 2)) |
| .toString('hex') |
| .slice(0, length); |
| } |
|
|
|
|
|
|
| |
| |
| |
| |
| |
| isTokenExpired(token) { |
| try { |
| this.verifyToken(token); |
| return false; |
| } catch (error) { |
| return error.message.includes('expired'); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| decodeTokenUnsafe(token) { |
| try { |
| return jwt.decode(token); |
| } catch (error) { |
| return null; |
| } |
| } |
|
|
| |
| |
| |
| |
| getStatus() { |
| return { |
| algorithm: this.algorithm, |
| hasJwtSecret: !!process.env.JWT_SECRET, |
| defaultExpiry: this.defaultExpiry, |
| ready: true |
| }; |
| } |
| } |
|
|
| |
| module.exports = KeySystem; |