jwt-config.js•2.85 kB
#!/usr/bin/env node
/**
* Centralized JWT Configuration Module
* @version 1.0.0
* @description Single source of truth for JWT token location and loading
*/
import { readFileSync } from 'fs';
import { join } from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Project root detection
const PROJECT_ROOT = join(__dirname, '..', '..');
/**
* JWT Configuration - Single Source of Truth
*/
export class JWTConfig {
constructor() {
this.token = null;
this.primaryPath = join(PROJECT_ROOT, 'config', 'jwt-token.txt');
this.fallbackPaths = [
join(PROJECT_ROOT, 'archive', 'authentication', 'correct-jwt-new.txt'),
join(PROJECT_ROOT, 'correct-jwt-new.txt'),
join(PROJECT_ROOT, 'tools', 'servers', 'correct-jwt-new.txt')
];
}
/**
* Load JWT token from configured location
* @returns {string} JWT token
* @throws {Error} If token cannot be loaded
*/
loadToken() {
if (this.token) {
return this.token;
}
// Try primary path first
try {
this.token = readFileSync(this.primaryPath, 'utf-8').trim();
console.log(`[JWT] ✅ Token loaded from primary path: ${this.primaryPath}`);
return this.token;
} catch (error) {
console.log(`[JWT] ⚠️ Primary path not found: ${this.primaryPath}`);
}
// Try fallback paths
for (const fallbackPath of this.fallbackPaths) {
try {
this.token = readFileSync(fallbackPath, 'utf-8').trim();
console.log(`[JWT] ✅ Token loaded from fallback: ${fallbackPath}`);
return this.token;
} catch (error) {
console.log(`[JWT] ❌ Fallback failed: ${fallbackPath}`);
}
}
throw new Error(`
❌ JWT Token not found in any configured location:
Primary: ${this.primaryPath}
Fallbacks: ${this.fallbackPaths.join(', ')}
Please ensure the JWT token file exists in one of these locations.
`);
}
/**
* Get the currently configured primary token path
* @returns {string} Primary token path
*/
getPrimaryPath() {
return this.primaryPath;
}
/**
* Get all configured fallback paths
* @returns {string[]} Fallback paths
*/
getFallbackPaths() {
return [...this.fallbackPaths];
}
/**
* Reset cached token (force reload on next access)
*/
resetToken() {
this.token = null;
}
}
/**
* Singleton instance for global use
*/
export const jwtConfig = new JWTConfig();
/**
* Convenience function to get JWT token
* @returns {string} JWT token
*/
export function getJWTToken() {
return jwtConfig.loadToken();
}
/**
* Convenience function to get primary JWT path
* @returns {string} Primary JWT token path
*/
export function getJWTPrimaryPath() {
return jwtConfig.getPrimaryPath();
}