-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccountManager.js
More file actions
307 lines (261 loc) · 9.47 KB
/
accountManager.js
File metadata and controls
307 lines (261 loc) · 9.47 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
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
/**
* guIDE 2.0 — Account Manager
*
* Manages user authentication state, OAuth flows, and account sessions.
* Supports:
* - Email/password login via the guIDE cloud API
* - Google OAuth (redirect flow)
* - GitHub OAuth (redirect flow)
* - Session persistence via settingsManager
* - Machine ID generation for license binding
*
* Local-first: the app works 100% without an account.
* Authentication is only needed for cloud AI proxy and license features.
*/
'use strict';
const crypto = require('crypto');
const os = require('os');
const EventEmitter = require('events');
// ─── Constants ───────────────────────────────────────────
const API_BASE = 'https://api.graysoft.dev';
const OAUTH_REDIRECT_BASE = 'https://graysoft.dev/auth/callback';
class AccountManager extends EventEmitter {
/**
* @param {import('./settingsManager').SettingsManager} settingsManager
*/
constructor(settingsManager) {
super();
this._settingsManager = settingsManager;
this._machineId = this._generateMachineId();
// Restore persisted session
this._sessionToken = settingsManager.get('sessionToken') || null;
this._user = settingsManager.get('accountUser') || null;
this._isAuthenticated = !!this._sessionToken;
}
// ─── Public getters ──────────────────────────────────
get isAuthenticated() { return this._isAuthenticated; }
get user() { return this._user; }
get machineId() { return this._machineId; }
getSessionToken() {
return this._sessionToken;
}
// ─── Login methods ───────────────────────────────────
/**
* Login with email and password.
* @param {string} email
* @param {string} password
* @returns {Promise<{ success: boolean, error?: string, user?: object }>}
*/
async loginWithEmail(email, password) {
if (!email || !password) {
return { success: false, error: 'Email and password are required' };
}
try {
const res = await fetch(`${API_BASE}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, machineId: this._machineId }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
return { success: false, error: err.error || `HTTP ${res.status}` };
}
const data = await res.json();
if (data.token && data.user) {
this._setSession(data.token, data.user);
return { success: true, user: this._user };
}
return { success: false, error: data.error || 'Login failed' };
} catch (e) {
return { success: false, error: `Cannot reach authentication server: ${e.message}` };
}
}
/**
* Register a new account with email and password.
* @param {string} email
* @param {string} password
* @param {string} [name]
* @returns {Promise<{ success: boolean, error?: string, user?: object }>}
*/
async register(email, password, name) {
if (!email || !password) {
return { success: false, error: 'Email and password are required' };
}
try {
const res = await fetch(`${API_BASE}/auth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, name: name || email.split('@')[0], machineId: this._machineId }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
return { success: false, error: err.error || `HTTP ${res.status}` };
}
const data = await res.json();
if (data.token && data.user) {
this._setSession(data.token, data.user);
return { success: true, user: this._user };
}
return { success: false, error: data.error || 'Registration failed' };
} catch (e) {
return { success: false, error: `Cannot reach authentication server: ${e.message}` };
}
}
/**
* Get the OAuth redirect URL for the given provider.
* @param {'google' | 'github'} provider
* @returns {{ url: string, state: string }}
*/
getOAuthURL(provider) {
const state = crypto.randomBytes(16).toString('hex');
this._oauthState = state;
const params = new URLSearchParams({
provider,
state,
machineId: this._machineId,
redirect: OAUTH_REDIRECT_BASE,
});
return {
url: `${API_BASE}/auth/oauth/${provider}?${params}`,
state,
};
}
/**
* Complete OAuth flow with the callback code/state.
* @param {string} code
* @param {string} state
* @returns {Promise<{ success: boolean, error?: string, user?: object }>}
*/
async completeOAuth(code, state) {
if (!code || !state) {
return { success: false, error: 'Missing OAuth callback parameters' };
}
if (this._oauthState && state !== this._oauthState) {
return { success: false, error: 'OAuth state mismatch — possible CSRF attack' };
}
try {
const res = await fetch(`${API_BASE}/auth/oauth/callback`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state, machineId: this._machineId }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
return { success: false, error: err.error || `HTTP ${res.status}` };
}
const data = await res.json();
if (data.token && data.user) {
this._setSession(data.token, data.user);
return { success: true, user: this._user };
}
return { success: false, error: data.error || 'OAuth failed' };
} catch (e) {
return { success: false, error: `Cannot reach authentication server: ${e.message}` };
}
}
/**
* Refresh the session token.
* @returns {Promise<{ success: boolean }>}
*/
async refreshSession() {
if (!this._sessionToken) return { success: false };
try {
const res = await fetch(`${API_BASE}/auth/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this._sessionToken}`,
},
body: JSON.stringify({ machineId: this._machineId }),
});
if (!res.ok) {
// Token expired or invalid — clear session
if (res.status === 401) this.logout();
return { success: false };
}
const data = await res.json();
if (data.token) {
this._sessionToken = data.token;
this._settingsManager.set('sessionToken', data.token);
return { success: true };
}
return { success: false };
} catch {
return { success: false };
}
}
/** Logout — clear session. */
logout() {
this._sessionToken = null;
this._user = null;
this._isAuthenticated = false;
this._settingsManager.set('sessionToken', null);
this._settingsManager.set('accountUser', null);
this.emit('logout');
}
// ─── API routes ──────────────────────────────────────
/**
* Register Express API routes.
* @param {import('express').Application} app
*/
registerRoutes(app) {
app.get('/api/account/status', (req, res) => {
res.json({
isAuthenticated: this._isAuthenticated,
user: this._user,
machineId: this._machineId,
});
});
app.post('/api/account/login', async (req, res) => {
const { email, password } = req.body || {};
const result = await this.loginWithEmail(email, password);
res.json(result);
});
app.post('/api/account/register', async (req, res) => {
const { email, password, name } = req.body || {};
const result = await this.register(email, password, name);
res.json(result);
});
app.post('/api/account/oauth/start', (req, res) => {
const { provider } = req.body || {};
if (!provider || !['google', 'github'].includes(provider)) {
return res.json({ success: false, error: 'Invalid OAuth provider' });
}
const { url, state } = this.getOAuthURL(provider);
res.json({ success: true, url, state });
});
app.post('/api/account/oauth/callback', async (req, res) => {
const { code, state } = req.body || {};
const result = await this.completeOAuth(code, state);
res.json(result);
});
app.post('/api/account/logout', (req, res) => {
this.logout();
res.json({ success: true });
});
app.post('/api/account/refresh', async (req, res) => {
const result = await this.refreshSession();
res.json(result);
});
}
// ─── Internal ────────────────────────────────────────
_setSession(token, user) {
this._sessionToken = token;
this._user = {
id: user.id,
email: user.email,
name: user.name || user.email?.split('@')[0],
avatar: user.avatar || null,
plan: user.plan || 'free',
};
this._isAuthenticated = true;
this._settingsManager.set('sessionToken', token);
this._settingsManager.set('accountUser', this._user);
this.emit('login', this._user);
}
_generateMachineId() {
const data = `${os.hostname()}:${os.userInfo().username}:${os.platform()}:${os.arch()}`;
return crypto.createHash('sha256').update(data).digest('hex').substring(0, 32);
}
}
module.exports = { AccountManager };