JWT-ARCHITECTURE-v5.2.0.mdā¢8.13 kB
# JWT Architecture Consolidation - v5.2.0
**Document**: Centralized JWT Configuration Architecture
**Version**: v5.2.0 FULLY OPERATIONAL
**Date**: January 12, 2025
**Status**: š§ ARCHITECTURE IMPROVEMENT - JWT Consolidation
**Sync**: EuConquisto Composer MCP v5.2.0
## Problem Analysis
### Before: Fragmented JWT References (Poor Practice)
The system had **6+ different hardcoded paths** for the same JWT token file:
```javascript
// Pattern 1: Archive path
const tokenPath = join(PROJECT_ROOT, 'archive/authentication/correct-jwt-new.txt');
// Pattern 2: Project root
const tokenPath = join(PROJECT_ROOT, 'correct-jwt-new.txt');
// Pattern 3: Server directory
this.jwtFilePath = path.join(__dirname, 'correct-jwt-new.txt');
// Pattern 4: Relative paths
const tokenPath = resolve(currentDir, '..', 'correct-jwt-new.txt');
// Pattern 5: Hardcoded absolute paths
const jwtToken = fs.readFileSync('/Users/.../correct-jwt-new.txt', 'utf8');
// Pattern 6: Various __dirname combinations
const jwtPath = join(__dirname, 'archive/authentication/correct-jwt-new.txt');
```
### Issues Identified
1. **Maintenance Nightmare**: Changes require updating 20+ files
2. **Fragility**: Moving/renaming token file breaks multiple components
3. **Inconsistency**: Different files look in different locations
4. **No Single Source of Truth**: No centralized configuration
5. **Error Prone**: Easy to miss references during updates
6. **Poor Debugging**: Hard to track down JWT loading issues
## Solution: Centralized JWT Configuration
### After: Single Source of Truth (Best Practice)
```javascript
// All files now use:
import { getJWTToken, getJWTPrimaryPath } from '../src/config/jwt-config.js';
// Simple token loading
const token = getJWTToken();
// Path access if needed
const tokenPath = getJWTPrimaryPath();
```
### Architecture Components
#### 1. Centralized Configuration Module
**File**: `/src/config/jwt-config.js`
```javascript
export class JWTConfig {
constructor() {
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')
];
}
loadToken() {
// Intelligent loading with fallbacks
}
}
```
#### 2. Standardized Location
**Primary Path**: `/config/jwt-token.txt`
- Clean, semantic naming
- Dedicated configuration directory
- Clear separation from source code
#### 3. Intelligent Fallback System
- Automatic fallback to legacy locations
- Graceful migration path
- Clear logging for debugging
## Migration Strategy
### Phase 1: Infrastructure (Complete ā
)
- ā
Created centralized JWT configuration module
- ā
Established primary JWT location (`/config/jwt-token.txt`)
- ā
Implemented intelligent fallback system
- ā
Created migration tooling
### Phase 2: Critical Files Migration (In Progress š§)
**Target Files**:
- `dist/browser-automation-api-jit-v5.1.0.js` (Main production entry)
- `tools/servers/jwt-redirect-server-v1.0.2.js` (JWT server)
**Migration Tool**: `/utils/migrate-jwt-references.js`
### Phase 3: Gradual Migration (Future)
- Update remaining source files progressively
- Remove duplicate token files
- Clean up legacy path references
## Implementation Details
### New Usage Pattern
```javascript
// Before (Fragmented)
try {
const tokenPath = join(PROJECT_ROOT, 'archive/authentication/correct-jwt-new.txt');
this.jwtToken = readFileSync(tokenPath, 'utf-8').trim();
} catch (error) {
try {
const fallbackPath = join(PROJECT_ROOT, 'correct-jwt-new.txt');
this.jwtToken = readFileSync(fallbackPath, 'utf-8').trim();
} catch (fallbackError) {
// Handle error
}
}
// After (Centralized)
import { getJWTToken } from '../src/config/jwt-config.js';
this.jwtToken = getJWTToken(); // Handles all fallbacks automatically
```
### Error Handling
```javascript
// Centralized error handling with clear messaging
try {
const token = getJWTToken();
} catch (error) {
console.error(`
ā JWT Token not found in any configured location:
Primary: /config/jwt-token.txt
Fallbacks: /archive/authentication/correct-jwt-new.txt, ...
Please ensure the JWT token file exists in one of these locations.
`);
}
```
### Configuration Access
```javascript
import { jwtConfig, getJWTToken, getJWTPrimaryPath } from '../src/config/jwt-config.js';
// Simple token access
const token = getJWTToken();
// Path information
const primaryPath = getJWTPrimaryPath();
const fallbacks = jwtConfig.getFallbackPaths();
// Force reload (if token changes)
jwtConfig.resetToken();
```
## Benefits
### 1. Maintainability ā
- **Single point of change** for JWT configuration
- **Easy token file relocation** without breaking system
- **Centralized fallback logic** instead of scattered implementations
### 2. Reliability ā
- **Consistent token loading** across all components
- **Automatic fallback system** prevents failures
- **Better error messages** for debugging
### 3. Security ā
- **Clear token file location** management
- **Consistent access patterns** reduce security mistakes
- **Centralized validation** and error handling
### 4. Developer Experience ā
- **Simple API** (`getJWTToken()` vs complex path logic)
- **Clear documentation** of JWT architecture
- **Migration tooling** for safe updates
## File Structure
### Current JWT Locations
```
/config/
āāā jwt-token.txt # ā
PRIMARY - New centralized location
/archive/authentication/
āāā correct-jwt-new.txt # š FALLBACK - Legacy location
/tools/servers/
āāā correct-jwt-new.txt # š FALLBACK - Server location
/correct-jwt-new.txt # š FALLBACK - Root location
```
### Recommended Cleanup (Post-Migration)
```
/config/
āāā jwt-token.txt # ā
ONLY LOCATION
# Remove duplicates after migration complete
```
## Migration Commands
### Run Migration Tool
```bash
cd /path/to/project
node utils/migrate-jwt-references.js
```
### Manual Migration Pattern
```javascript
// Replace this pattern:
const tokenPath = join(PROJECT_ROOT, 'any/path/to/correct-jwt-new.txt');
const token = readFileSync(tokenPath, 'utf-8').trim();
// With this pattern:
import { getJWTToken } from '../src/config/jwt-config.js';
const token = getJWTToken();
```
## Testing
### Verify Centralized Loading
```javascript
import { getJWTToken } from './src/config/jwt-config.js';
try {
const token = getJWTToken();
console.log('ā
JWT loaded successfully:', token.length, 'characters');
} catch (error) {
console.error('ā JWT loading failed:', error.message);
}
```
### Test Fallback System
```bash
# Move primary token temporarily
mv config/jwt-token.txt config/jwt-token.txt.backup
# Verify fallback works
node -e "import('./src/config/jwt-config.js').then(m => console.log('Token length:', m.getJWTToken().length))"
# Restore primary token
mv config/jwt-token.txt.backup config/jwt-token.txt
```
## Success Criteria
### ā
Phase 1 Complete
- [x] Centralized JWT configuration module created
- [x] Primary JWT location established
- [x] Intelligent fallback system implemented
- [x] Migration tooling created
### š§ Phase 2 In Progress
- [ ] Critical production files migrated
- [ ] JWT redirect server updated
- [ ] Production testing completed
### ā³ Phase 3 Future
- [ ] All source files migrated
- [ ] Legacy token files removed
- [ ] Documentation updated
## Conclusion
This JWT architecture consolidation transforms a fragmented, error-prone system into a maintainable, reliable configuration architecture. The centralized approach eliminates the **6+ different hardcoded paths** problem and provides a foundation for robust JWT token management.
**Impact**:
- **Before**: 20+ files with hardcoded JWT paths
- **After**: Single import statement: `getJWTToken()`
This change significantly improves system integrity and maintenance efficiency.