Hritam-Ai commited on
Commit
3100d8d
·
1 Parent(s): ad936df

Delete proxy-server.js

Browse files
Files changed (1) hide show
  1. proxy-server.js +0 -715
proxy-server.js DELETED
@@ -1,715 +0,0 @@
1
- // proxy-server.js - Complete PDF Converter with S3 and Authentication
2
- const express = require('express');
3
- const cors = require('cors');
4
- const fetch = require('node-fetch');
5
- const path = require('path');
6
- const AWS = require('aws-sdk');
7
- const { v4: uuidv4 } = require('uuid');
8
- const bcrypt = require('bcryptjs');
9
- const jwt = require('jsonwebtoken');
10
- const multer = require('multer');
11
- const rateLimit = require('express-rate-limit');
12
-
13
- const app = express();
14
- const port = 3001;
15
-
16
- // ========================================
17
- // CONFIGURATION - REPLACE WITH YOUR CREDENTIALS
18
- // ========================================
19
-
20
- // Anthropic API Key (Get from: https://console.anthropic.com/)
21
- const ANTHROPIC_API_KEY = 'YOUR_ANTHROPIC_API_KEY';
22
-
23
- // AWS Configuration (Get from AWS IAM Console)
24
- const AWS_CONFIG = {
25
- accessKeyId: 'YOUR_AWS_ACCESS_KEY_ID',
26
- secretAccessKey: 'YOUR_AWS_SECRET_ACCESS_KEY',
27
- region: 'us-east-1' // Change to your preferred region
28
- };
29
-
30
- // JWT Secret for authentication (Generate with: node -e "console.log(require('crypto').randomBytes(64).toString('hex'))")
31
- const JWT_SECRET = 'YOUR_JWT_SECRET';
32
-
33
- // ========================================
34
- // AWS S3 SETUP
35
- // ========================================
36
-
37
- AWS.config.update(AWS_CONFIG);
38
- const s3 = new AWS.S3();
39
-
40
- // ========================================
41
- // MIDDLEWARE
42
- // ========================================
43
-
44
- app.use(cors({
45
- origin: true,
46
- credentials: true
47
- }));
48
-
49
- app.use(express.json({ limit: '50mb' }));
50
- app.use(express.urlencoded({ extended: true, limit: '50mb' }));
51
- app.use(express.static('.'));
52
-
53
- // Rate limiting
54
- const limiter = rateLimit({
55
- windowMs: 15 * 60 * 1000, // 15 minutes
56
- max: 100, // limit each IP to 100 requests per windowMs
57
- message: {
58
- error: 'Too many requests from this IP, please try again later.'
59
- }
60
- });
61
- app.use(limiter);
62
-
63
- // Multer for file uploads
64
- const upload = multer({
65
- storage: multer.memoryStorage(),
66
- limits: {
67
- fileSize: 50 * 1024 * 1024 // 50MB limit
68
- },
69
- fileFilter: (req, file, cb) => {
70
- if (file.mimetype === 'application/pdf') {
71
- cb(null, true);
72
- } else {
73
- cb(new Error('Only PDF files are allowed'));
74
- }
75
- }
76
- });
77
-
78
- // ========================================
79
- // IN-MEMORY USER STORAGE (Replace with database in production)
80
- // ========================================
81
-
82
- const users = new Map(); // userId -> { username, email, hashedPassword, bucketName, createdAt }
83
- const sessions = new Map(); // token -> { userId, expiresAt }
84
-
85
- // ========================================
86
- // UTILITY FUNCTIONS
87
- // ========================================
88
-
89
- // Generate unique bucket name
90
- function generateBucketName(userId) {
91
- return `pdf-converter-${userId.toLowerCase().replace(/[^a-z0-9]/g, '')}`;
92
- }
93
-
94
- // Create S3 bucket for user
95
- async function createUserBucket(bucketName) {
96
- try {
97
- // Check if bucket already exists
98
- try {
99
- await s3.headBucket({ Bucket: bucketName }).promise();
100
- console.log(`✅ Bucket already exists: ${bucketName}`);
101
- return true;
102
- } catch (error) {
103
- if (error.statusCode !== 404) {
104
- throw error;
105
- }
106
- }
107
-
108
- // Create bucket
109
- const params = {
110
- Bucket: bucketName
111
- };
112
-
113
- // Only add CreateBucketConfiguration if not in us-east-1
114
- if (AWS_CONFIG.region !== 'us-east-1') {
115
- params.CreateBucketConfiguration = {
116
- LocationConstraint: AWS_CONFIG.region
117
- };
118
- }
119
-
120
- await s3.createBucket(params).promise();
121
-
122
- // Set bucket versioning
123
- await s3.putBucketVersioning({
124
- Bucket: bucketName,
125
- VersioningConfiguration: {
126
- Status: 'Enabled'
127
- }
128
- }).promise();
129
-
130
- // Set bucket encryption
131
- await s3.putBucketEncryption({
132
- Bucket: bucketName,
133
- ServerSideEncryptionConfiguration: {
134
- Rules: [
135
- {
136
- ApplyServerSideEncryptionByDefault: {
137
- SSEAlgorithm: 'AES256'
138
- }
139
- }
140
- ]
141
- }
142
- }).promise();
143
-
144
- console.log(`✅ Created bucket: ${bucketName}`);
145
- return true;
146
-
147
- } catch (error) {
148
- console.error(`❌ Error creating bucket ${bucketName}:`, error.message);
149
- throw new Error(`Failed to create S3 bucket: ${error.message}`);
150
- }
151
- }
152
-
153
- // Upload file to S3
154
- async function uploadToS3(bucketName, key, buffer, contentType) {
155
- try {
156
- const result = await s3.upload({
157
- Bucket: bucketName,
158
- Key: key,
159
- Body: buffer,
160
- ContentType: contentType,
161
- ServerSideEncryption: 'AES256',
162
- Metadata: {
163
- 'uploaded-by': 'pdf-converter',
164
- 'upload-time': new Date().toISOString()
165
- }
166
- }).promise();
167
-
168
- console.log(`✅ Uploaded to S3: ${key}`);
169
- return result;
170
- } catch (error) {
171
- console.error(`❌ Error uploading to S3:`, error.message);
172
- throw new Error(`Failed to upload to S3: ${error.message}`);
173
- }
174
- }
175
-
176
- // Authentication middleware
177
- function authenticateToken(req, res, next) {
178
- const authHeader = req.headers['authorization'];
179
- const token = authHeader && authHeader.split(' ')[1];
180
-
181
- if (!token) {
182
- return res.status(401).json({ error: 'Access token required' });
183
- }
184
-
185
- const session = sessions.get(token);
186
- if (!session || session.expiresAt < Date.now()) {
187
- sessions.delete(token);
188
- return res.status(403).json({ error: 'Token expired or invalid' });
189
- }
190
-
191
- const user = users.get(session.userId);
192
- if (!user) {
193
- sessions.delete(token);
194
- return res.status(403).json({ error: 'User not found' });
195
- }
196
-
197
- req.userId = session.userId;
198
- req.user = user;
199
- next();
200
- }
201
-
202
- // ========================================
203
- // ROUTES
204
- // ========================================
205
-
206
- // Health check
207
- app.get('/health', (req, res) => {
208
- res.json({
209
- status: 'OK',
210
- message: 'PDF Converter with S3 integration is running',
211
- timestamp: new Date().toISOString(),
212
- version: '2.0.0'
213
- });
214
- });
215
-
216
- // Serve the main page
217
- app.get('/', (req, res) => {
218
- res.sendFile(path.join(__dirname, 'index.html'));
219
- });
220
-
221
- // ========================================
222
- // AUTHENTICATION ROUTES
223
- // ========================================
224
-
225
- // Register new user
226
- app.post('/auth/register', async (req, res) => {
227
- try {
228
- const { username, email, password } = req.body;
229
-
230
- // Validation
231
- if (!username || !email || !password) {
232
- return res.status(400).json({ error: 'Username, email, and password are required' });
233
- }
234
-
235
- if (!/^[a-zA-Z0-9_]+$/.test(username)) {
236
- return res.status(400).json({ error: 'Username can only contain letters, numbers, and underscores' });
237
- }
238
-
239
- if (password.length < 6) {
240
- return res.status(400).json({ error: 'Password must be at least 6 characters long' });
241
- }
242
-
243
- if (!/\S+@\S+\.\S+/.test(email)) {
244
- return res.status(400).json({ error: 'Please enter a valid email address' });
245
- }
246
-
247
- // Check if user already exists
248
- for (const [userId, user] of users) {
249
- if (user.username.toLowerCase() === username.toLowerCase() || user.email.toLowerCase() === email.toLowerCase()) {
250
- return res.status(409).json({ error: 'Username or email already exists' });
251
- }
252
- }
253
-
254
- // Generate user ID and hash password
255
- const userId = uuidv4();
256
- const hashedPassword = await bcrypt.hash(password, 12);
257
- const bucketName = generateBucketName(userId);
258
-
259
- // Create user record
260
- const newUser = {
261
- username,
262
- email: email.toLowerCase(),
263
- hashedPassword,
264
- bucketName,
265
- createdAt: new Date().toISOString()
266
- };
267
-
268
- // Create S3 bucket for user
269
- await createUserBucket(bucketName);
270
-
271
- // Store user
272
- users.set(userId, newUser);
273
-
274
- // Generate JWT token
275
- const token = jwt.sign({ userId, username }, JWT_SECRET, { expiresIn: '24h' });
276
- const expiresAt = Date.now() + (24 * 60 * 60 * 1000); // 24 hours
277
-
278
- sessions.set(token, { userId, expiresAt });
279
-
280
- console.log(`✅ New user registered: ${username} (${userId})`);
281
-
282
- res.json({
283
- success: true,
284
- message: 'User registered successfully',
285
- token,
286
- user: {
287
- userId,
288
- username,
289
- email: newUser.email,
290
- bucketName,
291
- createdAt: newUser.createdAt
292
- }
293
- });
294
-
295
- } catch (error) {
296
- console.error('❌ Registration error:', error);
297
- res.status(500).json({ error: 'Registration failed', details: error.message });
298
- }
299
- });
300
-
301
- // Login user
302
- app.post('/auth/login', async (req, res) => {
303
- try {
304
- const { username, password } = req.body;
305
-
306
- if (!username || !password) {
307
- return res.status(400).json({ error: 'Username and password are required' });
308
- }
309
-
310
- // Find user
311
- let userId = null;
312
- let user = null;
313
-
314
- for (const [id, userData] of users) {
315
- if (userData.username.toLowerCase() === username.toLowerCase() ||
316
- userData.email.toLowerCase() === username.toLowerCase()) {
317
- userId = id;
318
- user = userData;
319
- break;
320
- }
321
- }
322
-
323
- if (!user) {
324
- return res.status(401).json({ error: 'Invalid credentials' });
325
- }
326
-
327
- // Verify password
328
- const isValid = await bcrypt.compare(password, user.hashedPassword);
329
- if (!isValid) {
330
- return res.status(401).json({ error: 'Invalid credentials' });
331
- }
332
-
333
- // Generate JWT token
334
- const token = jwt.sign({ userId, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
335
- const expiresAt = Date.now() + (24 * 60 * 60 * 1000); // 24 hours
336
-
337
- sessions.set(token, { userId, expiresAt });
338
-
339
- console.log(`✅ User logged in: ${user.username} (${userId})`);
340
-
341
- res.json({
342
- success: true,
343
- message: 'Login successful',
344
- token,
345
- user: {
346
- userId,
347
- username: user.username,
348
- email: user.email,
349
- bucketName: user.bucketName,
350
- createdAt: user.createdAt
351
- }
352
- });
353
-
354
- } catch (error) {
355
- console.error('❌ Login error:', error);
356
- res.status(500).json({ error: 'Login failed', details: error.message });
357
- }
358
- });
359
-
360
- // Logout user
361
- app.post('/auth/logout', authenticateToken, (req, res) => {
362
- const authHeader = req.headers['authorization'];
363
- const token = authHeader && authHeader.split(' ')[1];
364
-
365
- if (token) {
366
- sessions.delete(token);
367
- }
368
-
369
- console.log(`✅ User logged out: ${req.user.username}`);
370
- res.json({ success: true, message: 'Logged out successfully' });
371
- });
372
-
373
- // Get user profile
374
- app.get('/auth/profile', authenticateToken, (req, res) => {
375
- const user = req.user;
376
- res.json({
377
- success: true,
378
- user: {
379
- userId: req.userId,
380
- username: user.username,
381
- email: user.email,
382
- bucketName: user.bucketName,
383
- createdAt: user.createdAt
384
- }
385
- });
386
- });
387
-
388
- // ========================================
389
- // PDF PROCESSING ROUTES
390
- // ========================================
391
-
392
- // Upload and process PDF
393
- app.post('/upload-pdf', authenticateToken, upload.single('pdf'), async (req, res) => {
394
- try {
395
- if (!req.file) {
396
- return res.status(400).json({ error: 'No PDF file uploaded' });
397
- }
398
-
399
- const user = req.user;
400
- const file = req.file;
401
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
402
- const baseFileName = file.originalname.replace(/\.pdf$/i, '').replace(/[^a-zA-Z0-9._-]/g, '_');
403
-
404
- // Generate file keys for S3
405
- const pdfKey = `pdfs/${timestamp}_${baseFileName}.pdf`;
406
- const markdownKey = `markdown/${timestamp}_${baseFileName}.txt`;
407
- const summaryKey = `summaries/${timestamp}_${baseFileName}_summary.txt`;
408
-
409
- console.log(`📄 Processing PDF: ${file.originalname} for user: ${user.username}`);
410
-
411
- // Upload original PDF to S3
412
- await uploadToS3(user.bucketName, pdfKey, file.buffer, 'application/pdf');
413
-
414
- res.json({
415
- success: true,
416
- message: 'PDF uploaded successfully',
417
- fileInfo: {
418
- originalName: file.originalname,
419
- size: file.size,
420
- uploadedAt: timestamp,
421
- pdfKey,
422
- markdownKey,
423
- summaryKey,
424
- baseFileName
425
- }
426
- });
427
-
428
- } catch (error) {
429
- console.error('❌ PDF upload error:', error);
430
- res.status(500).json({ error: 'PDF upload failed', details: error.message });
431
- }
432
- });
433
-
434
- // Process markdown and summary
435
- app.post('/process-content', authenticateToken, async (req, res) => {
436
- try {
437
- const { markdown, fileInfo } = req.body;
438
-
439
- if (!markdown || !fileInfo) {
440
- return res.status(400).json({ error: 'Markdown content and file info are required' });
441
- }
442
-
443
- const user = req.user;
444
-
445
- console.log(`🔄 Processing content for user: ${user.username}`);
446
-
447
- // Upload markdown as .txt file to S3
448
- await uploadToS3(
449
- user.bucketName,
450
- fileInfo.markdownKey,
451
- Buffer.from(markdown, 'utf8'),
452
- 'text/plain'
453
- );
454
-
455
- // Generate AI summary
456
- const summary = await getSummaryFromAnthropic(markdown);
457
-
458
- // Upload summary as .txt file to S3
459
- await uploadToS3(
460
- user.bucketName,
461
- fileInfo.summaryKey,
462
- Buffer.from(summary, 'utf8'),
463
- 'text/plain'
464
- );
465
-
466
- // Generate S3 URLs for download
467
- const pdfUrl = s3.getSignedUrl('getObject', {
468
- Bucket: user.bucketName,
469
- Key: fileInfo.pdfKey,
470
- Expires: 3600 // 1 hour
471
- });
472
-
473
- const markdownUrl = s3.getSignedUrl('getObject', {
474
- Bucket: user.bucketName,
475
- Key: fileInfo.markdownKey,
476
- Expires: 3600
477
- });
478
-
479
- const summaryUrl = s3.getSignedUrl('getObject', {
480
- Bucket: user.bucketName,
481
- Key: fileInfo.summaryKey,
482
- Expires: 3600
483
- });
484
-
485
- console.log(`✅ Content processed successfully for user: ${user.username}`);
486
-
487
- res.json({
488
- success: true,
489
- message: 'Content processed and stored successfully',
490
- data: {
491
- markdown,
492
- summary,
493
- downloadUrls: {
494
- pdf: pdfUrl,
495
- markdown: markdownUrl,
496
- summary: summaryUrl
497
- },
498
- fileInfo
499
- }
500
- });
501
-
502
- } catch (error) {
503
- console.error('❌ Content processing error:', error);
504
- res.status(500).json({ error: 'Content processing failed', details: error.message });
505
- }
506
- });
507
-
508
- // Get user's files list
509
- app.get('/files', authenticateToken, async (req, res) => {
510
- try {
511
- const user = req.user;
512
-
513
- const params = {
514
- Bucket: user.bucketName,
515
- MaxKeys: 1000
516
- };
517
-
518
- const data = await s3.listObjectsV2(params).promise();
519
-
520
- const files = data.Contents.map(file => ({
521
- key: file.Key,
522
- size: file.Size,
523
- lastModified: file.LastModified,
524
- type: file.Key.includes('/') ? file.Key.split('/')[0] : 'other',
525
- downloadUrl: s3.getSignedUrl('getObject', {
526
- Bucket: user.bucketName,
527
- Key: file.Key,
528
- Expires: 3600
529
- })
530
- }));
531
-
532
- res.json({
533
- success: true,
534
- files,
535
- bucketName: user.bucketName,
536
- totalFiles: files.length
537
- });
538
-
539
- } catch (error) {
540
- console.error('❌ Error listing files:', error);
541
- res.status(500).json({ error: 'Failed to list files', details: error.message });
542
- }
543
- });
544
-
545
- // Delete file
546
- app.delete('/files/:key(*)', authenticateToken, async (req, res) => {
547
- try {
548
- const user = req.user;
549
- const key = req.params.key;
550
-
551
- await s3.deleteObject({
552
- Bucket: user.bucketName,
553
- Key: key
554
- }).promise();
555
-
556
- console.log(`🗑️ File deleted: ${key} by user: ${user.username}`);
557
-
558
- res.json({
559
- success: true,
560
- message: 'File deleted successfully'
561
- });
562
-
563
- } catch (error) {
564
- console.error('❌ Error deleting file:', error);
565
- res.status(500).json({ error: 'Failed to delete file', details: error.message });
566
- }
567
- });
568
-
569
- // ========================================
570
- // ANTHROPIC API FUNCTION
571
- // ========================================
572
-
573
- async function getSummaryFromAnthropic(markdown) {
574
- try {
575
- console.log(`🤖 Generating summary for ${markdown.length} characters of markdown...`);
576
-
577
- const response = await fetch('https://api.anthropic.com/v1/messages', {
578
- method: 'POST',
579
- headers: {
580
- 'Content-Type': 'application/json',
581
- 'x-api-key': ANTHROPIC_API_KEY,
582
- 'anthropic-version': '2023-06-01'
583
- },
584
- body: JSON.stringify({
585
- model: 'claude-3-sonnet-20240229',
586
- max_tokens: 1000,
587
- messages: [{
588
- role: 'user',
589
- content: `Please provide a concise and comprehensive summary of the following markdown content. Focus on the main points, key findings, important information, and conclusions. Structure your summary with clear sections if the content is complex:\n\n${markdown}`
590
- }]
591
- })
592
- });
593
-
594
- if (!response.ok) {
595
- const errorText = await response.text();
596
- console.error('❌ Anthropic API Error:', response.status, errorText);
597
-
598
- if (response.status === 401) {
599
- throw new Error('Invalid Anthropic API key - check your server configuration');
600
- } else if (response.status === 429) {
601
- throw new Error('Rate limit exceeded - please try again later');
602
- } else if (response.status >= 500) {
603
- throw new Error('Anthropic API server error - please try again later');
604
- } else {
605
- throw new Error(`Anthropic API error: ${response.status} ${response.statusText}`);
606
- }
607
- }
608
-
609
- const data = await response.json();
610
- const summary = data.content[0].text;
611
-
612
- console.log('✅ Summary generated successfully');
613
- return summary;
614
-
615
- } catch (error) {
616
- console.error('❌ Summary generation error:', error);
617
-
618
- if (error.name === 'TypeError' && error.message.includes('fetch')) {
619
- throw new Error('Unable to connect to Anthropic API');
620
- } else if (error.message.includes('API key')) {
621
- throw new Error('API configuration error - check Anthropic API key');
622
- } else {
623
- throw error;
624
- }
625
- }
626
- }
627
-
628
- // ========================================
629
- // ERROR HANDLING
630
- // ========================================
631
-
632
- // Handle multer errors
633
- app.use((error, req, res, next) => {
634
- if (error instanceof multer.MulterError) {
635
- if (error.code === 'LIMIT_FILE_SIZE') {
636
- return res.status(400).json({ error: 'File too large. Maximum size is 50MB.' });
637
- }
638
- return res.status(400).json({ error: 'File upload error: ' + error.message });
639
- }
640
-
641
- if (error.message === 'Only PDF files are allowed') {
642
- return res.status(400).json({ error: 'Only PDF files are allowed' });
643
- }
644
-
645
- console.error('❌ Server error:', error);
646
- res.status(500).json({
647
- error: 'Internal server error',
648
- details: error.message
649
- });
650
- });
651
-
652
- // Handle 404s
653
- app.use((req, res) => {
654
- res.status(404).json({ error: 'Endpoint not found' });
655
- });
656
-
657
- // ========================================
658
- // STARTUP VALIDATION
659
- // ========================================
660
-
661
- function validateConfiguration() {
662
- const errors = [];
663
-
664
- if (!ANTHROPIC_API_KEY || ANTHROPIC_API_KEY === 'YOUR_ANTHROPIC_API_KEY') {
665
- errors.push('❌ Anthropic API key not configured');
666
- }
667
-
668
- if (!AWS_CONFIG.accessKeyId || AWS_CONFIG.accessKeyId === 'YOUR_AWS_ACCESS_KEY_ID') {
669
- errors.push('❌ AWS Access Key ID not configured');
670
- }
671
-
672
- if (!AWS_CONFIG.secretAccessKey || AWS_CONFIG.secretAccessKey === 'YOUR_AWS_SECRET_ACCESS_KEY') {
673
- errors.push('❌ AWS Secret Access Key not configured');
674
- }
675
-
676
- if (!JWT_SECRET || JWT_SECRET === 'YOUR_JWT_SECRET') {
677
- errors.push('❌ JWT Secret not configured');
678
- }
679
-
680
- if (errors.length > 0) {
681
- console.log('🚨 Configuration Errors:');
682
- errors.forEach(error => console.log(error));
683
- console.log('');
684
- console.log('📋 Please update proxy-server.js with your credentials:');
685
- console.log(' 1. Anthropic API Key from: https://console.anthropic.com/');
686
- console.log(' 2. AWS credentials from AWS IAM Console');
687
- console.log(' 3. JWT Secret (generate with: node -e "console.log(require(\'crypto\').randomBytes(64).toString(\'hex\'))")');
688
- console.log('');
689
- process.exit(1);
690
- }
691
- }
692
-
693
- // ========================================
694
- // START SERVER
695
- // ========================================
696
-
697
- validateConfiguration();
698
-
699
- app.listen(port, () => {
700
- console.log('🚀 ========================================');
701
- console.log(`✅ PDF Converter Server running at http://localhost:${port}`);
702
- console.log('🌐 Features: User Auth + AWS S3 Integration + AI Summaries');
703
- console.log('📱 Frontend: Modern responsive interface');
704
- console.log('🔒 Security: JWT auth, individual S3 buckets, encrypted storage');
705
- console.log('🤖 AI: Anthropic Claude for intelligent summaries');
706
- console.log('☁️ Storage: AWS S3 with versioning and encryption');
707
- console.log('🚀 ========================================');
708
- console.log('');
709
- console.log('📞 Access your app at: http://localhost:3001');
710
- console.log('🧪 Test health: curl http://localhost:3001/health');
711
- console.log('📚 Check README.md for complete setup instructions');
712
- console.log('');
713
- });
714
-
715
- module.exports = app;