-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccountManager.js
More file actions
253 lines (221 loc) · 7.51 KB
/
accountManager.js
File metadata and controls
253 lines (221 loc) · 7.51 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
/**
* 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');
const APP_ORIGIN = 'https://graysoft.dev';
const API_BASE = `${APP_ORIGIN}/api`;
/** OAuth return URL — graysoft callbacks append ?guide_token=JWT (trusted hostname). */
const OAUTH_RETURN_URL = `${APP_ORIGIN}/auth/callback`;
class AccountManager extends EventEmitter {
/**
* @param {import('./settingsManager').SettingsManager} settingsManager
*/
constructor(settingsManager) {
super();
this._settingsManager = settingsManager;
this._machineId = this._generateMachineId();
this._sessionToken = settingsManager.get('sessionToken') || null;
this._user = settingsManager.get('accountUser') || null;
this._isAuthenticated = !!this._sessionToken;
}
get isAuthenticated() { return this._isAuthenticated; }
get user() { return this._user; }
get machineId() { return this._machineId; }
getSessionToken() {
return this._sessionToken;
}
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 }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || data.success === false) {
return { success: false, error: data.error || `HTTP ${res.status}` };
}
if (!data.token) {
return { success: false, error: data.error || 'Login failed — no session token' };
}
await this._hydrateSessionFromToken(data.token, { email });
return { success: true, user: this._user, licenseKey: data.licenseKey, plan: data.plan };
} catch (e) {
return { success: false, error: `Cannot reach authentication server: ${e.message}` };
}
}
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,
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || data.success === false) {
return { success: false, error: data.error || `HTTP ${res.status}` };
}
return this.loginWithEmail(email, password);
} catch (e) {
return { success: false, error: `Cannot reach authentication server: ${e.message}` };
}
}
/**
* OAuth start URL — uses graysoft.dev /api/auth/google|github (not legacy /auth/oauth/*).
*/
getOAuthURL(provider) {
const path = provider === 'github' ? '/api/auth/github' : '/api/auth/google';
const params = new URLSearchParams({
return: OAUTH_RETURN_URL,
});
return {
url: `${APP_ORIGIN}${path}?${params}`,
state: null,
};
}
/**
* Complete OAuth using guide_token from the redirect URL (graysoft.dev desktop flow).
*/
async completeOAuthWithToken(guideToken) {
if (!guideToken) {
return { success: false, error: 'Missing session token from sign-in' };
}
try {
await this._hydrateSessionFromToken(guideToken);
return { success: true, user: this._user };
} catch (e) {
return { success: false, error: e.message || 'Failed to validate sign-in token' };
}
}
async refreshSession() {
if (!this._sessionToken) return { success: false };
try {
const profile = await this._fetchProfile(this._sessionToken);
if (!profile) {
this.logout();
return { success: false };
}
this._applyProfile(this._sessionToken, profile);
return { success: true };
} catch {
return { success: false };
}
}
logout() {
this._sessionToken = null;
this._user = null;
this._isAuthenticated = false;
this._settingsManager.set('sessionToken', null);
this._settingsManager.set('accountUser', null);
this.emit('logout');
}
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 || {};
res.json(await this.loginWithEmail(email, password));
});
app.post('/api/account/register', async (req, res) => {
const { email, password, name } = req.body || {};
res.json(await this.register(email, password, name));
});
app.post('/api/account/oauth/start', async (req, res) => {
const { provider } = req.body || {};
if (!provider || !['google', 'github'].includes(provider)) {
return res.json({ success: false, error: 'Invalid OAuth provider' });
}
const { url } = this.getOAuthURL(provider);
res.json({ success: true, url });
});
app.post('/api/account/logout', (req, res) => {
this.logout();
res.json({ success: true });
});
app.post('/api/account/refresh', async (req, res) => {
res.json(await this.refreshSession());
});
}
async _hydrateSessionFromToken(token, hints = {}) {
const profile = await this._fetchProfile(token);
if (profile?.user) {
this._applyProfile(token, profile);
return;
}
const email = hints.email || profile?.email || 'user@graysoft.dev';
this._setSession(token, {
id: hints.id,
email,
name: hints.name || email.split('@')[0],
avatar: null,
plan: hints.plan || 'free',
});
}
async _fetchProfile(token) {
const res = await fetch(`${API_BASE}/auth/me`, {
headers: { Authorization: `Bearer ${token}` },
});
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.success) return null;
return data;
}
_applyProfile(token, profile) {
const u = profile.user;
this._setSession(token, {
id: u.id,
email: u.email,
name: u.name || u.email?.split('@')[0],
avatar: u.avatar || null,
plan: u.license?.plan || 'free',
});
}
_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, API_BASE, OAUTH_RETURN_URL, APP_ORIGIN };