-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
550 lines (468 loc) · 18.3 KB
/
server.js
File metadata and controls
550 lines (468 loc) · 18.3 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
/**
* VinciUI Backend Server
* Simple Express server that handles all your API routes
*/
import express from 'express';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import dotenv from 'dotenv';
import jwt from 'jsonwebtoken';
// Strict DB-backed functions (no fallbacks)
const createUser = async (userData) => {
const { createUser: dbCreateUser } = await import('./api/utils/database.js');
return await dbCreateUser(userData);
};
const getUserByEmail = async (email) => {
const { getUserByEmail: dbGetUserByEmail } = await import('./api/utils/database.js');
return await dbGetUserByEmail(email);
};
const updateUserUsage = async (...args) => {
const { updateUserUsage: dbUpdateUserUsage } = await import('./api/utils/database.js');
return await dbUpdateUserUsage(...args);
};
const getUserUsage = async (userId) => {
const { getUserUsage: dbGetUserUsage } = await import('./api/utils/database.js');
return await dbGetUserUsage(userId);
};
import { authenticateToken } from './api/middleware/auth.js';
import { rateLimitMiddleware } from './api/middleware/rateLimit.js';
import { contentModerationMiddleware } from './api/middleware/contentModeration.js';
// Load environment variables
dotenv.config({ path: '.env.local' });
// Ensure DB schema is up to date on startup
try {
const db = await import('./api/utils/database.js');
await db.migrateDatabase();
} catch (e) {
console.log('⚠️ Skipping DB migration on startup:', e?.message || e);
const { resetPool } = await import('./api/utils/database.js');
resetPool();
}
const app = express();
const PORT = 3001;
// Middleware
app.use(cors({
origin: getFrontendOrigin(),
credentials: true
}));
app.use(express.json({ limit: '10mb' }));
app.use(cookieParser());
console.log('🚀 Starting VinciUI Backend Server...');
// Helpers to resolve URLs in any environment
function getApiBaseUrl(req) {
if (process.env.API_BASE_URL) {
return process.env.API_BASE_URL;
}
// Fallback: derive from request (only for development)
const protocol = req.get('x-forwarded-proto') || req.protocol || 'http';
const host = req.get('x-forwarded-host') || req.get('host') || 'localhost:3001';
return `${protocol}://${host}`;
}
function getFrontendOrigin() {
const raw = process.env.FRONTEND_ORIGIN || 'http://localhost:5173';
// Normalize to absolute URL. If no scheme provided, default to https in prod.
const hasScheme = /^https?:\/\//i.test(raw);
if (hasScheme) return raw;
const scheme = (process.env.NODE_ENV === 'production') ? 'https' : 'http';
return `${scheme}://${raw}`;
}
// Root endpoint
app.get('/', (req, res) => {
res.json({
status: 'ok',
message: 'VinciUI Backend API',
version: '1.0.0',
endpoints: {
health: '/api/health',
auth: '/api/auth/google',
debug: '/api/auth/debug'
}
});
});
// Health check with DB connectivity test (uses fresh connection, not cached pool)
app.get('/api/health', async (req, res) => {
try {
let dbStatus = 'unknown';
const databaseUrl = process.env.DATABASE_URL;
if (databaseUrl) {
try {
const { Pool } = await import('pg');
const testPool = new Pool({
connectionString: databaseUrl,
ssl: databaseUrl.includes('supabase') || databaseUrl.includes('pooler')
? { rejectUnauthorized: false }
: false,
});
await testPool.query('SELECT 1');
await testPool.end();
dbStatus = 'connected';
} catch (dbError) {
dbStatus = 'disconnected';
console.warn('[health] DB check failed:', dbError?.message || dbError);
}
}
res.json({
status: 'ok',
message: 'VinciUI Backend is running!',
timestamp: new Date().toISOString(),
database: dbStatus,
environment: process.env.NODE_ENV || 'development',
port: PORT
});
} catch (error) {
res.status(500).json({
status: 'error',
message: 'Health check failed',
error: error.message
});
}
});
// Auth diagnostics (non-sensitive) - helps verify session quickly
app.get('/api/auth/debug', async (req, res) => {
try {
const cookieToken = req.cookies?.auth_token ? 'present' : 'missing';
const authHeader = req.headers?.authorization || '';
const headerToken = authHeader.startsWith('Bearer ') ? 'present' : 'missing';
let decoded = null;
try {
const raw = req.cookies?.auth_token || (authHeader.startsWith('Bearer ') ? authHeader.substring(7) : undefined);
if (raw) {
decoded = jwt.verify(raw, process.env.JWT_SECRET);
}
} catch {}
let dbUser = null;
if (decoded?.email) {
try {
dbUser = await getUserByEmail(decoded.email);
} catch {}
}
res.json({
cookieToken,
headerToken,
decoded: decoded ? { userId: decoded.userId, email: decoded.email } : null,
dbUser: dbUser ? { id: dbUser.id, email: dbUser.email, tier: dbUser.tier } : null
});
} catch (e) {
res.status(500).json({ error: 'debug_failed' });
}
});
// ==========================================
// AUTH ROUTES
// ==========================================
// Google OAuth initiation
app.get('/api/auth/google', (req, res) => {
// Check if OAuth credentials are configured
if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) {
console.log('❌ OAuth not configured');
return res.status(500).json({ error: 'OAuth not configured' });
}
const redirectUri = `${getApiBaseUrl(req)}/api/auth/callback`;
console.log('🔐 OAuth redirect URI:', redirectUri);
console.log('🔐 API_BASE_URL env:', process.env.API_BASE_URL || 'NOT SET');
const googleAuthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({
client_id: process.env.GOOGLE_CLIENT_ID,
redirect_uri: redirectUri,
response_type: 'code',
scope: 'openid email profile',
access_type: 'offline',
prompt: 'consent'
})}`;
console.log('🔐 Redirecting to Google OAuth...');
res.redirect(googleAuthUrl);
});
// Google OAuth callback
app.get('/api/auth/callback', async (req, res) => {
const { code } = req.query;
if (!code) {
const frontend = getFrontendOrigin();
return res.redirect(`${frontend}#error=no_code`);
}
// No development bypass; require real OAuth
try {
console.log('🔄 Processing OAuth callback...');
const baseUrl = getApiBaseUrl(req);
const redirectUri = `${baseUrl.replace(/\/$/, '')}/api/auth/callback`;
console.log('🔐 OAuth callback redirect URI:', redirectUri);
console.log('🔐 API_BASE_URL env:', process.env.API_BASE_URL || 'NOT SET');
if (process.env.NODE_ENV === 'production' && !process.env.API_BASE_URL) {
console.warn('⚠️ API_BASE_URL not set in production; using request-derived URL. Set API_BASE_URL=https://api.vinci.scopophobic.xyz to avoid redirect_uri mismatch.');
}
// Exchange code for tokens
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
code,
grant_type: 'authorization_code',
redirect_uri: redirectUri
})
});
const tokens = await tokenResponse.json();
if (!tokens.access_token) {
console.error('❌ Token exchange failed:', tokens);
if (tokens.error === 'redirect_uri_mismatch') {
console.error('❌ REDIRECT URI MISMATCH!');
console.error(' Expected by Google:', tokens.error_description);
console.error(' Sent by us:', redirectUri);
console.error(' API_BASE_URL:', process.env.API_BASE_URL || 'NOT SET');
}
throw new Error(`Token exchange failed: ${tokens.error || 'Unknown error'}`);
}
// Get user info from Google
const userResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: { Authorization: `Bearer ${tokens.access_token}` }
});
const googleUser = await userResponse.json();
// Create or update user in database
const user = await createUser({
googleId: googleUser.id,
email: googleUser.email,
name: googleUser.name,
picture: googleUser.picture
});
// Generate JWT
const jwtToken = jwt.sign(
{ userId: user.id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '7d' }
);
// Set secure cookie
const isProd = (process.env.NODE_ENV === 'production');
res.cookie('auth_token', jwtToken, {
httpOnly: true,
secure: isProd,
sameSite: isProd ? 'none' : 'lax',
domain: isProd ? '.scopophobic.xyz' : undefined,
maxAge: 7 * 24 * 60 * 60 * 1000,
path: '/'
});
console.log('✅ User authenticated:', user.email);
console.log('🔗 Redirecting with token to frontend...');
// Use hash (#) so the token is not sent to the server and cannot be stripped by redirects.
const frontend = getFrontendOrigin();
const hash = `auth_success=true&token=${encodeURIComponent(jwtToken)}`;
res.redirect(`${frontend}#${hash}`);
} catch (error) {
console.error('❌ OAuth callback error:', error?.message || error);
if (error?.stack) console.error(error.stack);
const frontend = getFrontendOrigin();
res.redirect(`${frontend}#error=auth_failed`);
}
});
// Get current user
app.get('/api/auth/me', authenticateToken, async (req, res) => {
try {
console.log('🔍 /api/auth/me called for user:', req.user.email);
const user = await getUserByEmail(req.user.email);
if (!user) {
console.log('❌ User not found by email');
return res.status(404).json({ error: 'User not found' });
}
const usage = await getUserUsage(user.id);
// Map usage to frontend-friendly shape and limits
const tier = user.tier || 'free';
const dailyLimits = {
free: 2, // lifetime cap enforced separately
premium: 100,
tester: 50,
developer: 1000
};
res.json({
user: {
...user,
usage: {
imagesGenerated: usage?.images_generated ?? 0,
promptsEnhanced: usage?.prompts_enhanced ?? 0,
dailyLimit: dailyLimits[tier] ?? 2,
resetTime: usage?.reset_time ?? new Date(Date.now() + 24*60*60*1000)
}
}
});
} catch (error) {
console.error('Get user error:', error);
res.status(500).json({ error: 'Failed to get user data' });
}
});
// Logout
app.post('/api/auth/logout', (req, res) => {
res.clearCookie('auth_token');
res.json({ success: true });
});
// ==========================================
// IMAGE GENERATION ROUTES
// ==========================================
// Protected image generation (supports multi-image + seed)
app.post('/api/generate/image',
authenticateToken,
rateLimitMiddleware,
contentModerationMiddleware,
async (req, res) => {
const {
prompt,
images, // string[] of base64 images
imageBase64, // legacy single-image field (backwards compat)
model = 'gemini-2.5-flash-image-preview',
seed,
} = req.body;
try {
console.log('🎨 Generating image for user:', req.user.email);
const apiKey = process.env.GEMINI_API_KEY;
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
const promptParts = [{ text: prompt }];
// Multi-image support: prefer images[] array, fall back to legacy single image
const imageList = images && images.length > 0 ? images : (imageBase64 ? [imageBase64] : []);
// For legacy model that only supports single image, use first image only
const isLegacy = model === 'gemini-2.0-flash-preview-image-generation';
const imagesToSend = isLegacy ? imageList.slice(0, 1) : imageList;
for (const img of imagesToSend) {
promptParts.push({
inlineData: { mimeType: "image/png", data: img }
});
}
const generationConfig = {
temperature: 0.8,
candidateCount: 1,
responseModalities: ["TEXT", "IMAGE"],
};
if (seed != null) {
generationConfig.seed = seed;
}
const payload = {
contents: [{ parts: promptParts }],
generationConfig,
};
const apiResponse = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!apiResponse.ok) {
const errorData = await apiResponse.json();
throw new Error(`Gemini API error: ${apiResponse.status} - ${JSON.stringify(errorData)}`);
}
const result = await apiResponse.json();
let imageData = null;
if (result.candidates?.[0]?.content?.parts) {
for (const part of result.candidates[0].content.parts) {
if (part.inlineData) {
imageData = `data:image/png;base64,${part.inlineData.data}`;
break;
}
}
}
if (!imageData) {
throw new Error('No image generated in response');
}
await updateUserUsage(req.user.userId, 'image');
let latestUsage;
try {
latestUsage = await getUserUsage(req.user.userId);
} catch (e) {
latestUsage = null;
}
console.log('✅ Image generated successfully');
res.json({
image: imageData,
usage: latestUsage ? {
imagesGenerated: latestUsage.images_generated ?? 0,
promptsEnhanced: latestUsage.prompts_enhanced ?? 0,
resetTime: latestUsage.reset_time ?? new Date(Date.now() + 24*60*60*1000)
} : undefined
});
} catch (error) {
console.error('❌ Image generation error:', error);
res.status(500).json({ error: error.message });
}
}
);
// Prompt refinement (auto-refine, Q&A questions, apply answers)
app.post('/api/generate/refine',
authenticateToken,
rateLimitMiddleware,
async (req, res) => {
const { prompt, mode, referenceImages, answers } = req.body;
try {
console.log(`✨ Refine (${mode}) for user:`, req.user.email);
const apiKey = process.env.GEMINI_API_KEY;
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;
let systemPrompt;
if (mode === 'auto') {
systemPrompt = `You are a prompt optimizer for an AI image generator. The user wrote a basic prompt. Improve it by adding specific visual details about composition, lighting, colors, and style while preserving the user's core intent. Keep it under 150 words. Do NOT change what the user wants — only add quality-improving details. Output ONLY the improved prompt, nothing else.
User prompt: "${prompt}"`;
} else if (mode === 'questions') {
systemPrompt = `You are helping a user create a better image generation prompt. Given their prompt, generate exactly 3 short clarifying questions to understand what they want. Each question should have 3-5 concise preset answer options. Return ONLY a valid JSON array, no markdown, no explanation:
[{"question": "...", "options": ["...", "...", "..."]}]
User prompt: "${prompt}"`;
} else if (mode === 'apply') {
const answersText = (answers || []).map(a => `- ${a.question}: ${a.answer}`).join('\n');
systemPrompt = `Rewrite this image generation prompt incorporating the user's preferences below. Keep the core subject but enhance with the specified preferences. Output ONLY the rewritten prompt, nothing else. Keep under 200 words.
Original prompt: "${prompt}"
User preferences:
${answersText}`;
} else {
return res.status(400).json({ error: 'Invalid refine mode' });
}
const parts = [{ text: systemPrompt }];
if (referenceImages && referenceImages.length > 0) {
for (const img of referenceImages) {
parts.push({ inlineData: { mimeType: "image/png", data: img } });
}
}
const payload = {
contents: [{ parts }],
generationConfig: {
temperature: mode === 'questions' ? 0.3 : 0.7,
candidateCount: 1,
},
};
const apiResponse = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!apiResponse.ok) {
const errorData = await apiResponse.json();
throw new Error(`Gemini API error: ${apiResponse.status} - ${JSON.stringify(errorData)}`);
}
const result = await apiResponse.json();
const responseText = result.candidates?.[0]?.content?.parts?.[0]?.text || '';
if (mode === 'questions') {
try {
// Strip markdown code fences if present
const cleaned = responseText.replace(/```json\s*/g, '').replace(/```\s*/g, '').trim();
const questions = JSON.parse(cleaned);
// Initialize empty answers
const withAnswers = questions.map(q => ({ ...q, answer: '' }));
res.json({ questions: withAnswers });
} catch (parseError) {
console.error('Failed to parse questions JSON:', responseText);
res.json({
questions: [
{ question: 'What style do you prefer?', options: ['Photorealistic', 'Digital Art', 'Anime', 'Painterly', 'Minimalist'], answer: '' },
{ question: 'What mood should the image have?', options: ['Calm', 'Dramatic', 'Mysterious', 'Joyful', 'Epic'], answer: '' },
{ question: 'Any specific composition details?', options: ['Close-up', 'Wide shot', 'Bird\'s eye', 'Low angle', 'Centered'], answer: '' },
]
});
}
} else {
await updateUserUsage(req.user.userId, 'enhancement');
res.json({ refinedPrompt: responseText.trim() });
}
console.log(`✅ Refine (${mode}) completed successfully`);
} catch (error) {
console.error('❌ Refine error:', error);
res.status(500).json({ error: error.message });
}
}
);
// Start server
app.listen(PORT, () => {
console.log(`✅ Backend Server running on http://localhost:${PORT}`);
console.log(`🔗 Frontend: ${getFrontendOrigin()}`);
console.log(`🔧 Environment: ${process.env.NODE_ENV || 'development'}`);
console.log('');
console.log('🚀 Ready for OAuth and image generation!');
});
export default app;