Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | 2x 2x 2x 2x 2x | /** * API Client Service * Handles communication with Vaultace backend API */ const axios = require('axios') const https = require('https') const ConfigManager = require('../utils/config-manager') const logger = require('../utils/logger') class APIClient { constructor(config = null) { this.config = config || ConfigManager.getConfig() this.baseURL = this.config.apiUrl || 'https://api.vaultace.co' // Create axios instance this.client = axios.create({ baseURL: this.baseURL, timeout: 30000, headers: { 'Content-Type': 'application/json', 'User-Agent': `vaultace-cli/${this.getPackageVersion()}` } }) // Add auth and timing interceptors this.client.interceptors.request.use( (config) => { config.requestStartTime = Date.now(); if (this.config.auth?.accessToken) { config.headers.Authorization = `Bearer ${this.config.auth.accessToken}` } return config }, (error) => Promise.reject(error) ) // Add response interceptor for token refresh and logging this.client.interceptors.response.use( (response) => { const duration = Date.now() - response.config.requestStartTime; logger.apiRequest( response.config.method.toUpperCase(), response.config.url, response.status, duration ); return response; }, async (error) => { if (error.config) { const duration = Date.now() - (error.config.requestStartTime || Date.now()); logger.apiRequest( error.config.method?.toUpperCase() || 'UNKNOWN', error.config.url || 'unknown', error.response?.status || 0, duration ); } if (error.response?.status === 401 && this.config.auth?.refreshToken) { try { await this.refreshAccessToken() // Retry original request return this.client.request(error.config) } catch (refreshError) { // Refresh failed, clear tokens ConfigManager.clearAuth() throw new Error('Authentication expired. Please login again.') } } return Promise.reject(error) } ) } getPackageVersion() { try { const pkg = require('../../package.json') return pkg.version } catch { return '1.0.0' } } // Authentication async login(email, password, rememberMe = false) { try { const response = await this.client.post('/auth/login', { email, password, remember_me: rememberMe }) const { access_token, refresh_token, expires_in } = response.data // Store tokens ConfigManager.setAuth({ accessToken: access_token, refreshToken: refresh_token, expiresAt: Date.now() + (expires_in * 1000) }) return response.data } catch (error) { throw this.handleAPIError(error, 'Login failed') } } async register(organizationName, organizationSlug, email, password, firstName, lastName) { try { const response = await this.client.post('/auth/register', { organization_name: organizationName, organization_slug: organizationSlug, email, password, first_name: firstName, last_name: lastName }) return response.data } catch (error) { throw this.handleAPIError(error, 'Registration failed') } } async logout() { try { await this.client.post('/auth/logout') ConfigManager.clearAuth() } catch (error) { // Clear local auth even if API call fails ConfigManager.clearAuth() throw this.handleAPIError(error, 'Logout failed') } } async refreshAccessToken() { if (!this.config.auth?.refreshToken) { throw new Error('No refresh token available') } try { const response = await this.client.post('/auth/refresh', { refresh_token: this.config.auth.refreshToken }) const { access_token, expires_in } = response.data // Update stored token ConfigManager.setAuth({ ...this.config.auth, accessToken: access_token, expiresAt: Date.now() + (expires_in * 1000) }) return response.data } catch (error) { throw this.handleAPIError(error, 'Token refresh failed') } } async getCurrentUser() { try { const response = await this.client.get('/auth/me') return response.data } catch (error) { throw this.handleAPIError(error, 'Failed to get user info') } } // Repository Management async getRepositories() { try { const response = await this.client.get('/repositories') return response.data } catch (error) { throw this.handleAPIError(error, 'Failed to get repositories') } } async addRepository(name, url, provider = 'github', branch = 'main') { try { const response = await this.client.post('/repositories', { name, url, provider, branch, scan_enabled: true }) return response.data } catch (error) { throw this.handleAPIError(error, 'Failed to add repository') } } async removeRepository(repositoryId) { try { await this.client.delete(`/repositories/${repositoryId}`) } catch (error) { throw this.handleAPIError(error, 'Failed to remove repository') } } // Vulnerability Management async uploadScanResults(results) { try { const response = await this.client.post('/scans', { scan_id: results.scanId, vulnerabilities: results.vulnerabilities, stats: results.stats, scan_type: 'local_cli', timestamp: results.timestamp }) return response.data } catch (error) { throw this.handleAPIError(error, 'Failed to upload scan results') } } async getVulnerabilities(repositoryId = null, severity = null) { try { const params = {} if (repositoryId) params.repository_id = repositoryId if (severity) params.severity = severity const response = await this.client.get('/vulnerabilities', { params }) return response.data } catch (error) { throw this.handleAPIError(error, 'Failed to get vulnerabilities') } } async markVulnerabilityResolved(vulnerabilityId, resolution) { try { const response = await this.client.patch(`/vulnerabilities/${vulnerabilityId}`, { status: 'resolved', resolution_notes: resolution }) return response.data } catch (error) { throw this.handleAPIError(error, 'Failed to resolve vulnerability') } } // Organization Management async getOrganizationInfo() { try { const response = await this.client.get('/organizations/current') return response.data } catch (error) { throw this.handleAPIError(error, 'Failed to get organization info') } } // Health Check async healthCheck() { try { const response = await this.client.get('/health') return response.data } catch (error) { return { status: 'unhealthy', error: error.message } } } // Generic HTTP methods for new commands async get(url, options = {}) { try { const response = await this.client.get(url, options); return response; } catch (error) { throw this.handleAPIError(error, `GET ${url} failed`); } } async post(url, data = {}, options = {}) { try { const response = await this.client.post(url, data, options); return response; } catch (error) { throw this.handleAPIError(error, `POST ${url} failed`); } } async put(url, data = {}, options = {}) { try { const response = await this.client.put(url, data, options); return response; } catch (error) { throw this.handleAPIError(error, `PUT ${url} failed`); } } async patch(url, data = {}, options = {}) { try { const response = await this.client.patch(url, data, options); return response; } catch (error) { throw this.handleAPIError(error, `PATCH ${url} failed`); } } async delete(url, options = {}) { try { const response = await this.client.delete(url, options); return response; } catch (error) { throw this.handleAPIError(error, `DELETE ${url} failed`); } } // Error handling handleAPIError(error, defaultMessage) { logger.error('API Error', { message: error.message, status: error.response?.status, url: error.config?.url, method: error.config?.method }); if (error.response?.data?.detail) { return new Error(error.response.data.detail) } if (error.response?.status === 401) { return new Error('Authentication required. Please login first.') } if (error.response?.status === 403) { return new Error('Permission denied') } if (error.response?.status === 429) { return new Error('Rate limit exceeded. Please try again later.') } if (error.response?.status >= 500) { return new Error('Vaultace service temporarily unavailable') } if (error.code === 'ECONNREFUSED') { return new Error('Cannot connect to Vaultace API') } return new Error(defaultMessage + ': ' + (error.message || 'Unknown error')) } } module.exports = APIClient |