UNPKG

@aerocorp/cli

Version:

AeroCorp CLI 5.1.0 - Future-Proofed Enterprise Infrastructure with Live Preview, Tunneling & Advanced DevOps

191 lines (163 loc) 6.65 kB
import axios from 'axios'; import chalk from 'chalk'; import inquirer from 'inquirer'; import ora from 'ora'; import { ConfigService } from './config'; export class AuthService { private configService = new ConfigService(); async login(options: any = {}) { console.log(chalk.cyan('╔══════════════════╗')); console.log(chalk.cyan('║ AeroCorp Login ║')); console.log(chalk.cyan('╚══════════════════╝')); // Check for root API token in environment const rootToken = process.env.AEROCORP_CLI_ROOT_API_TOKEN; if (rootToken) { console.log(chalk.yellow('🔑 Root API token detected in environment')); return await this.authenticateWithRootToken(rootToken); } // Get URL and token from options or prompt let coolifyUrl = options.url || this.configService.get('coolify_url'); let apiToken = options.token; if (!coolifyUrl) { const urlAnswer = await inquirer.prompt([ { type: 'input', name: 'url', message: 'Enter your Coolify instance URL:', default: 'https://coolify.aerocorpindustries.org', validate: (input) => { if (!input.startsWith('http')) { return 'Please enter a valid URL starting with http:// or https://'; } return true; } } ]); coolifyUrl = urlAnswer.url; } if (!apiToken) { const tokenAnswer = await inquirer.prompt([ { type: 'password', name: 'token', message: 'Enter your API token:', mask: '*' } ]); apiToken = tokenAnswer.token; } const spinner = ora('Authenticating...').start(); try { // Test the API token const response = await axios.get(`${coolifyUrl}/api/v1/projects`, { headers: { 'Authorization': `Bearer ${apiToken}`, 'Accept': 'application/json', 'Content-Type': 'application/json' }, timeout: 10000 }); if (response.status === 200) { spinner.succeed('Authentication successful'); // Save configuration this.configService.set('coolify_url', coolifyUrl); this.configService.set('api_token', apiToken); this.configService.set('authenticated', true); this.configService.set('server_ip', '128.140.35.238'); this.configService.set('environment', 'production'); console.log(chalk.green('✓ Logged in successfully')); console.log(chalk.blue(`📡 Connected to: ${coolifyUrl}`)); console.log(chalk.blue(`🏠 Server IP: 128.140.35.238`)); // Show available projects if (response.data && Array.isArray(response.data)) { console.log(chalk.green(`\n📋 Available projects: ${response.data.length}`)); response.data.forEach((project: any, index: number) => { console.log(chalk.gray(` ${index + 1}. ${project.name} (${project.uuid})`)); }); } return true; } } catch (error) { spinner.fail('Authentication failed'); if (error.response) { const status = error.response.status; const message = error.response.data?.message || error.response.statusText; switch (status) { case 401: throw new Error('Invalid API token. Please check your token and try again.'); case 403: throw new Error('Access forbidden. Your token may not have sufficient permissions.'); case 404: throw new Error('API endpoint not found. Please check your Coolify URL.'); case 500: throw new Error('Server error. Please try again later.'); default: throw new Error(`API Error: ${message} (Status: ${status})`); } } else if (error.code === 'ECONNREFUSED') { throw new Error('Connection refused. Please check your Coolify URL and network connection.'); } else if (error.code === 'ENOTFOUND') { throw new Error('Host not found. Please check your Coolify URL.'); } else if (error.code === 'ETIMEDOUT') { throw new Error('Connection timeout. Please check your network connection.'); } else { throw new Error(`Network error: ${error.message}`); } } } private async authenticateWithRootToken(rootToken: string) { const spinner = ora('Authenticating with root token...').start(); try { const coolifyUrl = 'https://coolify.aerocorpindustries.org'; const response = await axios.get(`${coolifyUrl}/api/v1/projects`, { headers: { 'Authorization': `Bearer ${rootToken}`, 'Accept': 'application/json', 'Content-Type': 'application/json' }, timeout: 10000 }); if (response.status === 200) { spinner.succeed('Root authentication successful'); // Save configuration this.configService.set('coolify_url', coolifyUrl); this.configService.set('api_token', rootToken); this.configService.set('authenticated', true); this.configService.set('server_ip', '128.140.35.238'); this.configService.set('environment', 'production'); this.configService.set('root_access', true); console.log(chalk.green('✓ Root access granted')); console.log(chalk.blue(`📡 Connected to: ${coolifyUrl}`)); console.log(chalk.blue(`🏠 Server IP: 128.140.35.238`)); console.log(chalk.red('🔑 ROOT ACCESS ENABLED')); return true; } } catch (error) { spinner.fail('Root authentication failed'); throw error; } } isAuthenticated(): boolean { const token = this.configService.get('api_token') || process.env.AEROCORP_CLI_ROOT_API_TOKEN; const authenticated = this.configService.get('authenticated'); return !!(token && authenticated); } getAuthHeaders(): Record<string, string> { const token = this.configService.get('api_token') || process.env.AEROCORP_CLI_ROOT_API_TOKEN; if (!token) { throw new Error('Not authenticated. Run "aerocorp login" first.'); } return { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json', 'Content-Type': 'application/json' }; } getCoolifyUrl(): string { return this.configService.get('coolify_url') || 'https://coolify.aerocorpindustries.org'; } logout() { this.configService.clear(); console.log(chalk.green('✓ Logged out successfully')); } }