-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
381 lines (329 loc) · 11.5 KB
/
Copy pathserver.js
File metadata and controls
381 lines (329 loc) · 11.5 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
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const rateLimit = require('express-rate-limit');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3001;
const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:3000';
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3001';
// Configure CORS with specific origins
const allowedOrigins = process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(',').map(origin => origin.trim())
: [FRONTEND_URL];
app.use(cors({
origin: allowedOrigins,
credentials: true
}));
app.use(express.json({ limit: '10mb' })); // Add size limit to prevent abuse
// Rate limiting for authentication endpoints
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // 10 requests per window
message: { error: 'Too many authentication attempts, please try again later' },
standardHeaders: true,
legacyHeaders: false,
});
// General API rate limiter
const apiLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 100, // 100 requests per minute
message: { error: 'Too many requests, please try again later' },
standardHeaders: true,
legacyHeaders: false,
});
// Apply general rate limit to all API routes
app.use('/api/', apiLimiter);
// Security headers
app.use((req, res, next) => {
// Content Security Policy
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://accounts.spotify.com https://api.spotify.com https://accounts.google.com https://oauth2.googleapis.com https://www.googleapis.com"
);
// Prevent clickjacking
res.setHeader('X-Frame-Options', 'DENY');
// Prevent MIME type sniffing
res.setHeader('X-Content-Type-Options', 'nosniff');
// Enable XSS protection
res.setHeader('X-XSS-Protection', '1; mode=block');
// Referrer policy
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
next();
});
let youtubeToken = null;
let youtubeCredentials = null;
// Load YouTube credentials
try {
const credentialsPath = path.join(__dirname, 'credentials.json');
if (fs.existsSync(credentialsPath)) {
const credentialsData = fs.readFileSync(credentialsPath, 'utf8');
youtubeCredentials = JSON.parse(credentialsData);
}
} catch (error) {
console.warn('Could not load credentials.json:', error.message);
}
// Function to check if token is valid (not expired)
const isTokenValid = (token) => {
if (!token || !token.expiry) return false;
const expiryTime = new Date(token.expiry);
const now = new Date();
// Add 5 minute buffer before expiry
return expiryTime.getTime() > (now.getTime() + 5 * 60 * 1000);
};
// Function to refresh YouTube token
const refreshYouTubeToken = async (token) => {
if (!youtubeCredentials || !token.refresh_token) {
throw new Error('No credentials or refresh token available');
}
const credentials = youtubeCredentials.installed;
try {
const response = await axios.post('https://oauth2.googleapis.com/token',
new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: token.refresh_token,
client_id: credentials.client_id,
client_secret: credentials.client_secret,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
// Update token with new access token and expiry
const updatedToken = {
...token,
token: response.data.access_token,
expiry: new Date(Date.now() + response.data.expires_in * 1000).toISOString()
};
// Save updated token to root directory only
const tokenPath = path.join(__dirname, 'token.json');
fs.writeFileSync(tokenPath, JSON.stringify(updatedToken, null, 2));
return updatedToken;
} catch (error) {
console.error('Failed to refresh YouTube token:', error.response?.data || error.message);
throw error;
}
};
// Function to load and validate YouTube token
const loadYouTubeToken = async () => {
try {
const tokenPath = path.join(__dirname, 'token.json');
if (fs.existsSync(tokenPath)) {
const tokenData = fs.readFileSync(tokenPath, 'utf8');
youtubeToken = JSON.parse(tokenData);
// Check if token is valid
if (!isTokenValid(youtubeToken)) {
console.log('YouTube token is expired, attempting to refresh...');
try {
youtubeToken = await refreshYouTubeToken(youtubeToken);
console.log('YouTube token refreshed successfully');
} catch (error) {
console.warn('Failed to refresh YouTube token:', error.message);
youtubeToken = null;
}
} else {
console.log('YouTube token is valid');
}
}
} catch (error) {
console.warn('Could not load token.json:', error.message);
}
};
// Load token on startup
loadYouTubeToken();
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
youtube: {
configured: youtubeCredentials !== null,
authenticated: youtubeToken !== null && isTokenValid(youtubeToken)
}
});
});
app.post('/api/spotify/token', authLimiter, async (req, res) => {
const { code, codeVerifier, redirectUri, clientId } = req.body;
// Input validation
if (!code || typeof code !== 'string' || code.length > 1000) {
return res.status(400).json({ error: 'Invalid code parameter' });
}
if (!codeVerifier || typeof codeVerifier !== 'string' || codeVerifier.length > 200) {
return res.status(400).json({ error: 'Invalid codeVerifier parameter' });
}
if (!redirectUri || typeof redirectUri !== 'string' || !redirectUri.startsWith('http')) {
return res.status(400).json({ error: 'Invalid redirectUri parameter' });
}
if (!clientId || typeof clientId !== 'string' || clientId.length > 200) {
return res.status(400).json({ error: 'Invalid clientId parameter' });
}
try {
const response = await axios.post('https://accounts.spotify.com/api/token',
new URLSearchParams({
grant_type: 'authorization_code',
code: code,
redirect_uri: redirectUri,
client_id: clientId,
client_secret: process.env.SPOTIFY_CLIENT_SECRET,
code_verifier: codeVerifier,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
res.json(response.data);
} catch (error) {
console.error('Token exchange error:', error.response?.data || error.message);
res.status(400).json({
error: 'Failed to exchange code for token',
details: error.response?.data || error.message
});
}
});
// YouTube OAuth authorization URL
app.get('/api/youtube/auth-url', (req, res) => {
if (!youtubeCredentials) {
return res.status(400).json({
error: 'YouTube credentials not available',
details: 'credentials.json file not found'
});
}
const credentials = youtubeCredentials.installed;
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?` +
`client_id=${credentials.client_id}&` +
`redirect_uri=${encodeURIComponent(`${BACKEND_URL}/api/youtube/callback`)}&` +
`scope=${encodeURIComponent('https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.force-ssl')}&` +
`response_type=code&` +
`access_type=offline&` +
`prompt=consent`;
res.json({ authUrl });
});
// YouTube OAuth callback
app.get('/api/youtube/callback', authLimiter, async (req, res) => {
const { code } = req.query;
// Input validation
if (!code || typeof code !== 'string' || code.length > 1000) {
return res.status(400).send('Invalid authorization code');
}
if (!youtubeCredentials) {
return res.status(400).send('YouTube credentials not available');
}
try {
const credentials = youtubeCredentials.installed;
const response = await axios.post('https://oauth2.googleapis.com/token',
new URLSearchParams({
code: code,
client_id: credentials.client_id,
client_secret: credentials.client_secret,
redirect_uri: `${BACKEND_URL}/api/youtube/callback`,
grant_type: 'authorization_code'
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
// Create token object
const tokenData = {
token: response.data.access_token,
refresh_token: response.data.refresh_token,
token_uri: 'https://oauth2.googleapis.com/token',
client_id: credentials.client_id,
client_secret: credentials.client_secret,
scopes: [
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl'
],
universe_domain: 'googleapis.com',
account: '',
expiry: new Date(Date.now() + response.data.expires_in * 1000).toISOString()
};
// Save token to root directory only
const tokenPath = path.join(__dirname, 'token.json');
fs.writeFileSync(tokenPath, JSON.stringify(tokenData, null, 2));
// Update in-memory token
youtubeToken = tokenData;
console.log('YouTube OAuth successful, token saved');
// Redirect back to frontend
res.redirect(`${FRONTEND_URL}?youtube_auth=success`);
} catch (error) {
console.error('YouTube OAuth error:', error.response?.data || error.message);
res.redirect(`${FRONTEND_URL}?youtube_auth=error`);
}
});
app.post('/api/youtube/refresh', authLimiter, async (req, res) => {
if (!youtubeToken) {
return res.status(400).json({
error: 'YouTube token not available',
details: 'token.json file not found or invalid'
});
}
try {
youtubeToken = await refreshYouTubeToken(youtubeToken);
res.json({
success: true,
access_token: youtubeToken.token,
expires_in: Math.floor((new Date(youtubeToken.expiry) - new Date()) / 1000)
});
} catch (error) {
console.error('YouTube token refresh error:', error.message);
res.status(400).json({
error: 'Failed to refresh token',
details: error.message
});
}
});
// Add an endpoint to check token validity
app.get('/api/youtube/token/status', (req, res) => {
if (!youtubeToken) {
return res.json({ valid: false, reason: 'No token available' });
}
const valid = isTokenValid(youtubeToken);
res.json({
valid,
expiry: youtubeToken.expiry,
reason: valid ? 'Token is valid' : 'Token is expired'
});
});
// YouTube configuration status endpoint
app.get('/api/youtube/config/status', (req, res) => {
const configured = youtubeCredentials !== null;
res.json({
configured,
reason: configured ? 'credentials.json loaded successfully' : 'credentials.json not found or invalid'
});
});
// Add an endpoint to get current access token (for authenticated requests)
app.get('/api/youtube/token', (req, res) => {
if (!youtubeToken) {
return res.status(400).json({
error: 'No YouTube token available',
details: 'Authentication required'
});
}
if (!isTokenValid(youtubeToken)) {
return res.status(401).json({
error: 'Token expired',
details: 'Token refresh needed'
});
}
res.json({
access_token: youtubeToken.token,
expires_in: Math.floor((new Date(youtubeToken.expiry) - new Date()) / 1000)
});
});
// Only start server if this file is run directly (not imported for testing)
if (require.main === module) {
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
}
module.exports = app;