-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-handler.ts
More file actions
421 lines (374 loc) · 13.1 KB
/
auth-handler.ts
File metadata and controls
421 lines (374 loc) · 13.1 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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/**
* Electron Authentication Handler
* Manages OAuth flow in Electron main process
*/
import { shell, BrowserWindow } from 'electron';
import * as http from 'http';
import { URL } from 'url';
import { GoogleAuthProvider, SessionManager, UserSession, AuthError } from '@polynote/security';
import type { Database } from 'better-sqlite3';
import type { IEncryptionService } from '@polynote/security';
/**
* OAuth configuration from environment variables
*/
interface AuthConfig {
googleClientId: string;
googleClientSecret: string;
redirectUri: string;
callbackPort: number;
}
/**
* Electron auth handler for managing OAuth flows
*/
export class ElectronAuthHandler {
private googleAuthProvider: GoogleAuthProvider;
private sessionManager: SessionManager;
private authConfig: AuthConfig;
private callbackServer: http.Server | null = null;
private currentSession: UserSession | null = null;
constructor(
db: Database,
encryptionService: IEncryptionService,
config?: Partial<AuthConfig>
) {
// Default configuration
this.authConfig = {
googleClientId: process.env.GOOGLE_CLIENT_ID || '',
googleClientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
redirectUri: config?.redirectUri || 'http://localhost:3000/auth/google/callback',
callbackPort: config?.callbackPort || 3000,
};
// Initialize providers
this.googleAuthProvider = new GoogleAuthProvider({
clientId: this.authConfig.googleClientId,
clientSecret: this.authConfig.googleClientSecret,
redirectUri: this.authConfig.redirectUri,
});
this.sessionManager = new SessionManager(db, encryptionService);
}
/**
* Initialize auth handler and restore session if valid
* Should be called on app startup
*/
async initialize(): Promise<void> {
try {
// Load session from persistent storage
const storedSession = await this.sessionManager.getCurrentSession();
if (!storedSession) {
console.log('No stored session found');
return;
}
// Check if access token is expired
if (this.isTokenExpired(storedSession.accessToken)) {
console.log('Stored session token is expired, attempting refresh...');
// Attempt token refresh if refresh token is available
if (storedSession.refreshToken) {
try {
await this.refreshToken(storedSession.userId);
// After successful refresh, reload the session
this.currentSession = await this.sessionManager.getCurrentSession();
console.log('Session restored successfully after token refresh');
} catch (error) {
console.error('Token refresh failed, clearing session:', error);
await this.sessionManager.deleteSession(storedSession.userId);
this.currentSession = null;
}
} else {
console.log('No refresh token available, clearing expired session');
await this.sessionManager.deleteSession(storedSession.userId);
this.currentSession = null;
}
} else {
// Token is still valid, restore session
this.currentSession = storedSession;
console.log('Session restored successfully');
}
} catch (error) {
console.error('Failed to initialize auth handler:', error);
this.currentSession = null;
}
}
/**
* Check if a JWT token is expired
* @param token - The JWT token to check
* @returns true if token is expired or invalid, false otherwise
*/
private isTokenExpired(token: string): boolean {
try {
// JWT tokens have 3 parts: header.payload.signature
const parts = token.split('.');
if (parts.length !== 3) return true;
const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());
const exp = payload.exp;
if (!exp) return false; // No expiration
const now = Math.floor(Date.now() / 1000);
const bufferTime = 300; // 5 minutes buffer
return exp < (now + bufferTime);
} catch {
return true; // If parsing fails, consider expired
}
}
/**
* Initiate Google OAuth login flow
*/
async initiateGoogleLogin(): Promise<UserSession> {
try {
// Validate configuration
if (!this.authConfig.googleClientId || !this.authConfig.googleClientSecret) {
throw new Error(
'Google OAuth credentials not configured. Please set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET environment variables.'
);
}
// Get authorization URL
const authUrl = await this.googleAuthProvider.getAuthUrl();
// Open browser for OAuth
await shell.openExternal(authUrl);
// Start local server to receive callback
const session = await this.startCallbackServer();
// Save session to persistent storage
await this.sessionManager.saveSession(session);
// Update current session
this.currentSession = session;
return session;
} catch (error) {
if (error instanceof AuthError) {
throw error;
}
throw new AuthError(
'Failed to initiate Google login',
'OAUTH_FAILED' as any,
error as Error
);
}
}
/**
* Start local HTTP server to handle OAuth callback
*/
private startCallbackServer(): Promise<UserSession> {
return new Promise((resolve, reject) => {
// Create callback server
this.callbackServer = http.createServer(async (req, res) => {
try {
if (!req.url) {
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end('<h1>Bad Request</h1>');
return;
}
const url = new URL(req.url, `http://localhost:${this.authConfig.callbackPort}`);
// Check for OAuth callback path
if (url.pathname === '/auth/google/callback') {
const code = url.searchParams.get('code');
const error = url.searchParams.get('error');
if (error) {
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end(`<h1>Authentication Failed</h1><p>Error: ${error}</p>`);
this.stopCallbackServer();
reject(new Error(`OAuth error: ${error}`));
return;
}
if (code) {
try {
// Exchange code for tokens
const session = await this.googleAuthProvider.handleCallback(code);
// Send success response
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<!DOCTYPE html>
<html>
<head>
<title>Authentication Successful</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.container {
text-align: center;
background: white;
padding: 3rem;
border-radius: 10px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}
h1 {
color: #667eea;
margin: 0 0 1rem 0;
}
p {
color: #555;
margin: 0;
}
.checkmark {
font-size: 4rem;
color: #4caf50;
}
</style>
</head>
<body>
<div class="container">
<div class="checkmark">✓</div>
<h1>Login Successful!</h1>
<p>You can now close this window and return to PolyNote.</p>
</div>
<script>
setTimeout(() => {
window.close();
}, 3000);
</script>
</body>
</html>
`);
// Stop server and resolve
this.stopCallbackServer();
resolve(session);
} catch (error) {
res.writeHead(500, { 'Content-Type': 'text/html' });
res.end(`<h1>Authentication Error</h1><p>${(error as Error).message}</p>`);
this.stopCallbackServer();
reject(error);
}
} else {
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end('<h1>Bad Request</h1><p>No authorization code received</p>');
}
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>Not Found</h1>');
}
} catch (error) {
console.error('Callback server error:', error);
res.writeHead(500, { 'Content-Type': 'text/html' });
res.end('<h1>Internal Server Error</h1>');
this.stopCallbackServer();
reject(error);
}
});
// Start listening
this.callbackServer.listen(this.authConfig.callbackPort, () => {
console.log(`OAuth callback server listening on port ${this.authConfig.callbackPort}`);
});
// Handle server errors
this.callbackServer.on('error', (error) => {
console.error('Callback server error:', error);
this.stopCallbackServer();
reject(error);
});
// Set timeout (5 minutes)
setTimeout(() => {
if (this.callbackServer) {
this.stopCallbackServer();
reject(new Error('OAuth callback timeout - please try again'));
}
}, 5 * 60 * 1000);
});
}
/**
* Stop callback server
*/
private stopCallbackServer(): void {
if (this.callbackServer) {
this.callbackServer.close();
this.callbackServer = null;
}
}
/**
* Get current session
*/
async getCurrentSession(): Promise<UserSession | null> {
return this.sessionManager.getCurrentSession();
}
/**
* Refresh access token
*/
async refreshToken(userId: string): Promise<void> {
try {
const session = await this.sessionManager.getSession(userId);
if (!session || !session.refreshToken) {
throw new Error('No refresh token available');
}
const newAccessToken = await this.googleAuthProvider.refreshAccessToken(
session.refreshToken
);
// Update session with new token in persistent storage
await this.sessionManager.updateSession(userId, {
accessToken: newAccessToken,
expiresAt: new Date(Date.now() + 3600 * 1000), // 1 hour from now
});
// Update current session if this is the current user
if (this.currentSession && this.currentSession.userId === userId) {
this.currentSession = await this.sessionManager.getSession(userId);
}
} catch (error) {
throw new AuthError(
'Failed to refresh access token',
'TOKEN_REFRESH_FAILED' as any,
error as Error
);
}
}
/**
* Logout user
*/
async logout(userId: string): Promise<void> {
try {
const session = await this.sessionManager.getSession(userId);
if (session) {
// Revoke access token
try {
await this.googleAuthProvider.revokeAccess(session.accessToken);
} catch (error) {
console.error('Failed to revoke access token:', error);
// Continue with logout even if revocation fails
}
// Delete local session from persistent storage
await this.sessionManager.deleteSession(userId);
// Clear current session if this is the current user
if (this.currentSession && this.currentSession.userId === userId) {
this.currentSession = null;
}
}
} catch (error) {
throw new AuthError('Failed to logout', 'OAUTH_FAILED' as any, error as Error);
}
}
/**
* Validate if user is authenticated
*/
async isAuthenticated(): Promise<boolean> {
const session = await this.sessionManager.getCurrentSession();
if (!session) {
return false;
}
// Check if session is expired
if (session.expiresAt < new Date()) {
// Try to refresh token
if (session.refreshToken) {
try {
await this.refreshToken(session.userId);
return true;
} catch (error) {
return false;
}
}
return false;
}
return true;
}
/**
* Get session manager for direct access
*/
getSessionManager(): SessionManager {
return this.sessionManager;
}
/**
* Cleanup
*/
cleanup(): void {
this.stopCallbackServer();
this.sessionManager.cleanupExpiredSessions();
}
}