-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcli-auth-client.js
More file actions
257 lines (224 loc) · 6.09 KB
/
cli-auth-client.js
File metadata and controls
257 lines (224 loc) · 6.09 KB
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
/**
* CLI Authentication Client
*
* This module provides a client for authenticating with the handit CLI system.
* It handles the device authorization flow and token management.
*/
import fetch from 'node-fetch';
import fs from 'fs';
import path from 'path';
import os from 'os';
class CLIAuthClient {
constructor(baseUrl = 'https://dashboard.handit.ai') {
this.baseUrl = baseUrl;
this.configDir = path.join(os.homedir(), '.handit');
this.configFile = path.join(this.configDir, 'config.json');
}
/**
* Ensure config directory exists
*/
ensureConfigDir() {
if (!fs.existsSync(this.configDir)) {
fs.mkdirSync(this.configDir, { recursive: true, mode: 0o700 });
}
}
/**
* Load configuration from file
*/
loadConfig() {
try {
if (fs.existsSync(this.configFile)) {
const data = fs.readFileSync(this.configFile, 'utf8');
return JSON.parse(data);
}
} catch (error) {
console.error('Error loading config:', error);
}
return null;
}
/**
* Save configuration to file
*/
saveConfig(config) {
try {
this.ensureConfigDir();
fs.writeFileSync(this.configFile, JSON.stringify(config, null, 2), { mode: 0o600 });
} catch (error) {
console.error('Error saving config:', error);
throw error;
}
}
/**
* Clear stored configuration
*/
logout() {
try {
if (fs.existsSync(this.configFile)) {
fs.unlinkSync(this.configFile);
}
} catch (error) {
console.error('Error during logout:', error);
}
}
/**
* Generate a new CLI authentication code
*/
async generateCode(userId, companyId) {
try {
const response = await fetch(`${this.baseUrl}/api/cli/auth/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ userId, companyId }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to generate code');
}
return await response.json();
} catch (error) {
console.error('Error generating code:', error);
throw error;
}
}
/**
* Check the status of a CLI authentication code
*/
async checkStatus(code) {
try {
const response = await fetch(`${this.baseUrl}/api/cli/auth/status`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to check status');
}
return await response.json();
} catch (error) {
console.error('Error checking status:', error);
throw error;
}
}
/**
* Complete authentication with code
*/
async completeAuthentication(code) {
try {
const result = await this.checkStatus(code);
if (result.status === 'success') {
return result;
}
throw new Error('Authentication failed');
} catch (error) {
console.error('❌ Authentication failed:', error.message);
throw error;
}
}
/**
* Complete the authentication flow
*/
async authenticate(userId, companyId) {
try {
// Generate authentication code
const { code, expiresAt } = await this.generateCode(userId, companyId);
// Complete authentication immediately
const result = await this.completeAuthentication(code);
// Save tokens
const config = {
authToken: result.authToken,
apiToken: result.apiToken,
stagingApiToken: result.stagingApiToken,
user: result.user,
company: result.company,
authenticatedAt: new Date().toISOString(),
};
this.saveConfig(config);
return config;
} catch (error) {
console.error('❌ Authentication failed:', error.message);
throw error;
}
}
/**
* Get current authentication status
*/
isAuthenticated() {
const config = this.loadConfig();
return config && config.authToken && config.apiToken;
}
/**
* Get stored tokens
*/
getTokens() {
const config = this.loadConfig();
if (!config) {
throw new Error('Not authenticated. Please run "handit login" first.');
}
return {
authToken: config.authToken,
apiToken: config.apiToken,
stagingApiToken: config.stagingApiToken,
};
}
/**
* Make an authenticated API request
*/
async makeRequest(endpoint, options = {}) {
const tokens = this.getTokens();
const defaultHeaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${tokens.authToken}`,
'X-Integration-Token': tokens.apiToken,
};
const response = await fetch(`${this.baseUrl}${endpoint}`, {
...options,
headers: {
...defaultHeaders,
...options.headers,
},
});
if (!response.ok) {
if (response.status === 401) {
console.error('❌ Authentication expired. Please run "handit login" again.');
this.logout();
process.exit(1);
}
const error = await response.json().catch(() => ({}));
throw new Error(error.error || `HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
}
/**
* Execute LLM call using system environment variables
*/
async executeLLM(messages, model, provider = 'OpenAI') {
try {
const response = await fetch(`${this.baseUrl}/api/cli/auth/llm`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages,
model,
provider,
}),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to execute LLM call');
}
const result = await response.json();
return result.result;
} catch (error) {
console.error('Error executing LLM:', error);
throw error;
}
}
}
export default CLIAuthClient;