Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
996 lines (966 loc) · 48.1 KB
/
Copy pathserver.js
File metadata and controls
996 lines (966 loc) · 48.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
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
import express from "express";
import { createServer } from "http";
import { WebSocketServer } from "ws";
import jwt from "jsonwebtoken";
import axios from "axios";
import * as cheerio from "cheerio";
import cors from "cors";
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";
import { createServer as createViteServer } from "vite";
import { initializeDatabase, query } from "./db.js";
import { verifyToken, generateToken, hashPassword, comparePassword } from "./auth.js";
import nodemailer from "nodemailer";
// ============ WEBSOCKET BROADCAST MAP ============
// userClients: Map<userId, Set<WebSocket>>
const userClients = new Map();
function broadcastToUser(userId, payload, senderWs = null) {
const clients = userClients.get(String(userId));
if (!clients) return;
const msg = JSON.stringify(payload);
for (const ws of clients) {
if (ws !== senderWs && ws.readyState === 1) {
ws.send(msg);
}
}
}
function broadcastToAll(payload) {
const msg = JSON.stringify(payload);
for (const [, clients] of userClients) {
for (const ws of clients) {
if (ws.readyState === 1) ws.send(msg);
}
}
}
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const envFile = path.join(__dirname, '.env');
if (fs.existsSync(envFile)) {
for (const line of fs.readFileSync(envFile, 'utf8').split(/\r?\n/)) {
const match = line.match(/^([^#=]+)=(.*)$/);
if (match && !process.env[match[1].trim()])
process.env[match[1].trim()] = match[2].trim().replace(/^"|"$/g, '');
}
}
const PORT = process.env.PORT || 3000;
// Helper to extract clean video stream IDs or embed configurations
function parseVideoSource(urlStr) {
try {
const u = new URL(urlStr);
const host = u.hostname.replace(/^www\./, '').toLowerCase();
if (host === 'youtu.be') {
return { provider: 'youtube', id: u.pathname.slice(1).split('?')[0] };
}
if (u.hostname.includes('youtube.com')) {
const v = u.searchParams.get('v');
if (v)
return { provider: 'youtube', id: v };
if (u.pathname.startsWith('/shorts/'))
return { provider: 'youtube', id: u.pathname.split('/')[2] };
if (u.pathname.startsWith('/embed/'))
return { provider: 'youtube', id: u.pathname.split('/')[2] };
}
if (u.hostname.includes('vimeo.com')) {
const m = u.pathname.match(/(\d+)/);
if (m)
return { provider: 'vimeo', id: m[1] };
}
if (u.hostname.includes('dailymotion.com')) {
const m = u.pathname.match(/\/video\/([^_/]+)/);
if (m)
return { provider: 'dailymotion', id: m[1] };
}
if (u.hostname.includes('dai.ly')) {
return { provider: 'dailymotion', id: u.pathname.slice(1) };
}
// Direct video files
if (u.pathname.match(/\.(mp4|webm|ogg|mov|m4v)$/i)) {
return { provider: 'native_video', id: urlStr };
}
}
catch (e) {
// Ignore invalid URL formatting
}
return { provider: 'generic', id: null };
}
function absoluteUrl(value, baseUrl) {
if (!value)
return '';
try {
return new URL(value, baseUrl).href;
}
catch (e) {
return value || '';
}
}
async function startServer() {
const app = express();
// Initialize database
let dbConnected = false;
let dbErrorMessage = '';
try {
await initializeDatabase();
dbConnected = true;
console.log('✅ Database initialized successfully');
}
catch (err) {
dbErrorMessage = err?.message || 'Database connection error';
console.warn('⚠️ Database connection warning:', dbErrorMessage);
console.warn('👉 If on Render, please add DATABASE_URL to your Web Service Environment Variables.');
}
// Enable CORS
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'x-admin-password', 'x-admin-secret']
}));
app.use(express.json({ limit: '50mb' }));
// ============ ADMIN MIDDLEWARE ============
const verifyAdmin = async (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) return res.status(401).json({ success: false, error: 'No token provided' });
const token = authHeader.split(' ')[1];
try {
const secret = process.env.JWT_SECRET || 'ownly-secret-key-change-in-production';
const decoded = jwt.verify(token, secret);
if (!decoded.isSuperAdmin) {
return res.status(403).json({ success: false, error: 'Unauthorized: Not a super admin' });
}
req.admin = decoded;
next();
} catch (err) {
return res.status(401).json({ success: false, error: 'Invalid admin token' });
}
};
// Admin standalone login
app.post('/api/admin/login', (req, res) => {
const { email, password } = req.body;
// Admin credentials must be configured securely in server environment variables (Render Dashboard)
const expectedEmail = (process.env.ADMIN_EMAIL || '').trim();
const expectedPassword = (process.env.ADMIN_PASSWORD || '').trim();
if (!expectedEmail || !expectedPassword) {
console.error("ADMIN_EMAIL or ADMIN_PASSWORD is not set in environment variables!");
return res.status(500).json({ success: false, error: 'Admin credentials not configured on the server. Please set ADMIN_EMAIL and ADMIN_PASSWORD in your server environment variables.' });
}
if (email.trim().toLowerCase() === expectedEmail.toLowerCase() && password === expectedPassword) {
const secret = process.env.JWT_SECRET || 'ownly-secret-key-change-in-production';
const adminToken = jwt.sign({ isSuperAdmin: true, email: expectedEmail }, secret, { expiresIn: '24h' });
return res.json({ success: true, token: adminToken });
} else {
return res.status(401).json({ success: false, error: 'Invalid admin email or password' });
}
});
// ============ AUTH ENDPOINTS ============
// Register
app.post('/api/auth/register', async (req, res) => {
try {
const { email, password, name } = req.body;
if (!email || !password) {
return res.status(400).json({ success: false, error: 'Email and password required' });
}
const passwordHash = await hashPassword(password);
// Security: Never grant admin automatically to registering users. Only specific designated accounts have admin.
const result = await query('INSERT INTO users (email, password_hash, name, is_admin) VALUES ($1, $2, $3, $4) RETURNING id, email, name, is_admin', [email.trim().toLowerCase(), passwordHash, name || email.split('@')[0], false]);
const userId = result.rows[0].id;
const token = generateToken(userId);
res.json({ success: true, token, user: result.rows[0] });
}
catch (err) {
if (err.code === '23505') {
return res.status(409).json({ success: false, error: 'Email already exists' });
}
console.error('Register error:', err);
res.status(500).json({ success: false, error: 'Registration failed' });
}
});
// Login
app.post('/api/auth/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ success: false, error: 'Email and password required' });
}
const result = await query('SELECT id, email, name, password_hash, is_admin FROM users WHERE email = $1', [email]);
if (result.rows.length === 0) {
return res.status(401).json({ success: false, error: 'Invalid credentials' });
}
const user = result.rows[0];
const passwordMatch = await comparePassword(password, user.password_hash);
if (!passwordMatch) {
return res.status(401).json({ success: false, error: 'Invalid credentials' });
}
const token = generateToken(user.id);
res.json({ success: true, token, user: { id: user.id, email: user.email, name: user.name, is_admin: user.is_admin } });
}
catch (err) {
console.error('Login error:', err);
res.status(500).json({ success: false, error: 'Login failed' });
}
});
// Forgot password — creates a request and notifies admin
app.post('/api/auth/forgot-password', async (req, res) => {
try {
const { email } = req.body;
if (!email) return res.status(400).json({ success: false, error: 'Email required' });
const result = await query('SELECT id, name FROM users WHERE email = $1', [email]);
// Always return success to not reveal whether email exists
if (result.rows.length === 0) {
return res.json({ success: true, message: 'Your request has been sent to the admin. They will reset your password shortly.' });
}
const user = result.rows[0];
// Create a pending reset request (one per user at a time)
await query(`DELETE FROM password_reset_requests WHERE user_id = $1 AND status = 'pending'`, [user.id]);
await query(
`INSERT INTO password_reset_requests (user_id, email, name) VALUES ($1, $2, $3)`,
[user.id, email, user.name]
);
console.log(`📩 Password reset request created for: ${email}`);
// Email the admin if ADMIN_EMAIL is set
const adminEmail = process.env.ADMIN_EMAIL;
if (adminEmail) {
try {
const adminUrl = `${req.headers.origin || 'https://topfile.onrender.com'}/admin`;
let transporter;
if (process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASS) {
transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT || '587'),
secure: process.env.SMTP_SECURE === 'true',
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});
} else {
// Fallback: ethereal test account
const testAccount = await nodemailer.createTestAccount();
transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email', port: 587, secure: false,
auth: { user: testAccount.user, pass: testAccount.pass },
});
}
const info = await transporter.sendMail({
from: '"Ownly System" <noreply@ownly.app>',
to: adminEmail,
subject: `🔑 Password Reset Request — ${user.name || email}`,
text: `User ${user.name} (${email}) has requested a password reset.\n\nGo to your admin dashboard to reset their password:\n${adminUrl}`,
html: `
<div style="font-family:sans-serif;max-width:500px;margin:auto;padding:32px;background:#111;color:#fff;border-radius:16px;">
<h2 style="color:#d9ad52;margin-bottom:8px;">🔑 Password Reset Request</h2>
<p style="color:#aaa;margin-bottom:24px;">A user has requested a password reset.</p>
<div style="background:#1a1a1a;border-radius:12px;padding:16px;margin-bottom:24px;">
<p style="margin:0;font-size:14px;"><strong>Name:</strong> ${user.name || 'Unknown'}</p>
<p style="margin:8px 0 0;font-size:14px;"><strong>Email:</strong> ${email}</p>
</div>
<a href="${adminUrl}" style="display:inline-block;background:#d9ad52;color:#111;font-weight:bold;padding:12px 24px;border-radius:8px;text-decoration:none;">Open Admin Dashboard</a>
</div>
`,
});
console.log(`📧 Admin notified at ${adminEmail}. Preview: ${nodemailer.getTestMessageUrl(info) || 'N/A'}`);
} catch (emailErr) {
console.warn('⚠️ Failed to email admin, but request is saved in DB:', emailErr.message);
}
}
res.json({ success: true, message: 'Your request has been sent to the admin. They will reset your password shortly.' });
} catch (err) {
console.error('Forgot password error:', err);
res.status(500).json({ success: false, error: 'Failed to process request' });
}
});
// Reset password using token
app.post('/api/auth/reset-password', async (req, res) => {
try {
const { token, newPassword } = req.body;
if (!token || !newPassword) return res.status(400).json({ success: false, error: 'Token and new password required' });
if (newPassword.length < 6) return res.status(400).json({ success: false, error: 'Password must be at least 6 characters' });
const result = await query(`SELECT id FROM users WHERE reset_token = $1 AND reset_token_expires > NOW()`, [token]);
if (result.rows.length === 0) {
return res.status(400).json({ success: false, error: 'Invalid or expired reset token' });
}
const { hashPassword: hp } = await import('./auth.js');
const passwordHash = await hp(newPassword);
await query(`UPDATE users SET password_hash = $1, reset_token = NULL, reset_token_expires = NULL WHERE id = $2`, [passwordHash, result.rows[0].id]);
res.json({ success: true, message: 'Password updated successfully' });
} catch (err) {
console.error('Reset password error:', err);
res.status(500).json({ success: false, error: 'Failed to reset password' });
}
});
// ============ NOTES ENDPOINTS ============
// Get all notes for user
app.get('/api/notes', verifyToken, async (req, res) => {
try {
const result = await query('SELECT * FROM notes WHERE user_id = $1 ORDER BY created_at DESC', [req.user.id]);
res.json({ success: true, notes: result.rows });
}
catch (err) {
console.error('Get notes error:', err);
res.status(500).json({ success: false, error: 'Failed to fetch notes' });
}
});
// Create note
app.post('/api/notes', verifyToken, async (req, res) => {
try {
const { id, title, content, category, colorTag, isPinned, attachments } = req.body;
const attachmentsJson = JSON.stringify(attachments || []);
const result = await query('INSERT INTO notes (id, user_id, title, content, category, color_tag, is_pinned, attachments) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *', [id, req.user.id, title, content, category, colorTag, isPinned || false, attachmentsJson]);
const note = result.rows[0];
res.json({ success: true, note });
broadcastToUser(req.user.id, { type: 'note_created', note });
}
catch (err) {
console.error('Create note error:', err);
res.status(500).json({ success: false, error: 'Failed to create note' });
}
});
// Update note
app.put('/api/notes/:id', verifyToken, async (req, res) => {
try {
const { title, content, category, colorTag, isPinned, attachments } = req.body;
const attachmentsJson = attachments !== undefined ? JSON.stringify(attachments) : null;
let queryStr;
let params;
if (attachmentsJson !== null) {
queryStr = 'UPDATE notes SET title = $1, content = $2, category = $3, color_tag = $4, is_pinned = $5, attachments = $6, updated_at = CURRENT_TIMESTAMP WHERE id = $7 AND user_id = $8 RETURNING *';
params = [title, content, category, colorTag, isPinned, attachmentsJson, req.params.id, req.user.id];
} else {
queryStr = 'UPDATE notes SET title = $1, content = $2, category = $3, color_tag = $4, is_pinned = $5, updated_at = CURRENT_TIMESTAMP WHERE id = $6 AND user_id = $7 RETURNING *';
params = [title, content, category, colorTag, isPinned, req.params.id, req.user.id];
}
const result = await query(queryStr, params);
if (result.rows.length === 0) {
return res.status(404).json({ success: false, error: 'Note not found' });
}
const note = result.rows[0];
res.json({ success: true, note });
broadcastToUser(req.user.id, { type: 'note_updated', note });
}
catch (err) {
console.error('Update note error:', err);
res.status(500).json({ success: false, error: 'Failed to update note' });
}
});
// Delete note
app.delete('/api/notes/:id', verifyToken, async (req, res) => {
try {
const result = await query('DELETE FROM notes WHERE id = $1 AND user_id = $2', [req.params.id, req.user.id]);
if (result.rowCount === 0) {
return res.status(404).json({ success: false, error: 'Note not found' });
}
res.json({ success: true, message: 'Note deleted' });
broadcastToUser(req.user.id, { type: 'note_deleted', id: req.params.id });
}
catch (err) {
console.error('Delete note error:', err);
res.status(500).json({ success: false, error: 'Failed to delete note' });
}
});
// ============ IMAGES ENDPOINTS ============
// Get all images for user (includes data_url so files open instantly without delay, filters out dead blob URLs)
app.get('/api/images', verifyToken, async (req, res) => {
try {
const result = await query("SELECT id, user_id, name, data_url, file_size, dimensions, source, notes, created_at FROM images WHERE user_id = $1 AND data_url NOT LIKE 'blob:%' ORDER BY created_at DESC", [req.user.id]);
res.json({ success: true, images: result.rows });
}
catch (err) {
console.error('Get images error:', err);
res.status(500).json({ success: false, error: 'Failed to fetch images' });
}
});
// Create image
app.post('/api/images', verifyToken, async (req, res) => {
try {
const { id, name, dataUrl, fileSize, dimensions, source, notes: imgNotes } = req.body;
if (dataUrl && dataUrl.startsWith('blob:')) {
return res.status(400).json({ success: false, error: 'Cannot save temporary blob URL. Must be base64 data URL.' });
}
const result = await query('INSERT INTO images (id, user_id, name, data_url, file_size, dimensions, source, notes) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *', [id, req.user.id, name, dataUrl, fileSize, dimensions, source, imgNotes]);
const image = result.rows[0];
res.json({ success: true, image });
broadcastToUser(req.user.id, { type: 'image_created', image });
}
catch (err) {
console.error('Create image error:', err);
res.status(500).json({ success: false, error: 'Failed to create image' });
}
});
// Delete image
app.delete('/api/images/:id', verifyToken, async (req, res) => {
try {
const result = await query('DELETE FROM images WHERE id = $1 AND user_id = $2', [req.params.id, req.user.id]);
if (result.rowCount === 0) {
return res.status(404).json({ success: false, error: 'Image not found' });
}
res.json({ success: true, message: 'Image deleted' });
broadcastToUser(req.user.id, { type: 'image_deleted', id: req.params.id });
}
catch (err) {
console.error('Delete image error:', err);
res.status(500).json({ success: false, error: 'Failed to delete image' });
}
});
// Get single image by id (for preview)
app.get('/api/images/:id', verifyToken, async (req, res) => {
try {
const result = await query('SELECT * FROM images WHERE id = $1 AND user_id = $2', [req.params.id, req.user.id]);
if (result.rows.length === 0) {
return res.status(404).json({ success: false, error: 'Image not found' });
}
res.json({ success: true, image: result.rows[0] });
} catch (err) {
console.error('Get image error:', err);
res.status(500).json({ success: false, error: 'Failed to fetch image' });
}
});
// Rename image
app.patch('/api/images/:id', verifyToken, async (req, res) => {
try {
const { name } = req.body;
if (!name) return res.status(400).json({ success: false, error: 'Name is required' });
const result = await query('UPDATE images SET name = $1 WHERE id = $2 AND user_id = $3 RETURNING *', [name, req.params.id, req.user.id]);
if (result.rowCount === 0) return res.status(404).json({ success: false, error: 'Image not found' });
res.json({ success: true, image: result.rows[0] });
} catch (err) {
console.error('Rename image error:', err);
res.status(500).json({ success: false, error: 'Failed to rename image' });
}
});
// ============ LINKS ENDPOINTS ============
// Get all links for user
app.get('/api/links', verifyToken, async (req, res) => {
try {
const result = await query('SELECT * FROM links WHERE user_id = $1 ORDER BY created_at DESC', [req.user.id]);
res.json({ success: true, links: result.rows });
}
catch (err) {
console.error('Get links error:', err);
res.status(500).json({ success: false, error: 'Failed to fetch links' });
}
});
// Create link
app.post('/api/links', verifyToken, async (req, res) => {
try {
const { id, url, title, description, embedThumb, linkHost, embedProvider, embedId, isPlayable } = req.body;
const result = await query('INSERT INTO links (id, user_id, url, title, description, embed_thumb, link_host, embed_provider, embed_id, is_playable) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *', [id, req.user.id, url, title, description, embedThumb, linkHost, embedProvider, embedId, isPlayable]);
const link = result.rows[0];
res.json({ success: true, link });
broadcastToUser(req.user.id, { type: 'link_created', link });
}
catch (err) {
console.error('Create link error:', err);
res.status(500).json({ success: false, error: 'Failed to create link' });
}
});
// Delete link
app.delete('/api/links/:id', verifyToken, async (req, res) => {
try {
const result = await query('DELETE FROM links WHERE id = $1 AND user_id = $2', [req.params.id, req.user.id]);
if (result.rowCount === 0) {
return res.status(404).json({ success: false, error: 'Link not found' });
}
res.json({ success: true, message: 'Link deleted' });
broadcastToUser(req.user.id, { type: 'link_deleted', id: req.params.id });
}
catch (err) {
console.error('Delete link error:', err);
res.status(500).json({ success: false, error: 'Failed to delete link' });
}
});
// ============ USER PROFILE ENDPOINTS ============
// Get user profile
app.get('/api/user/profile', verifyToken, async (req, res) => {
try {
const result = await query('SELECT id, email, name, avatar_url, joined_date, plan, storage_used_mb, total_storage_mb, is_admin FROM users WHERE id = $1', [req.user.id]);
if (result.rows.length === 0) {
return res.status(404).json({ success: false, error: 'User not found' });
}
res.json({ success: true, user: result.rows[0] });
}
catch (err) {
console.error('Get profile error:', err);
res.status(500).json({ success: false, error: 'Failed to fetch profile' });
}
});
// Update user profile
app.put('/api/user/profile', verifyToken, async (req, res) => {
try {
const { name, avatarUrl } = req.body;
const result = await query('UPDATE users SET name = $1, avatar_url = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3 RETURNING id, email, name, avatar_url, joined_date, plan, storage_used_mb, total_storage_mb, is_admin', [name, avatarUrl, req.user.id]);
const updatedUser = result.rows[0];
res.json({ success: true, user: updatedUser });
broadcastToUser(req.user.id, { type: 'profile_updated', user: updatedUser });
}
catch (err) {
console.error('Update profile error:', err);
res.status(500).json({ success: false, error: 'Failed to update profile' });
}
});
// ============ ADMIN ENDPOINTS ============
// Get all users (with live connected device count and content counts)
app.get('/api/admin/users', verifyAdmin, async (req, res) => {
try {
const result = await query(`
SELECT
u.id, u.email, u.name, u.joined_date, u.plan, u.storage_used_mb, u.is_admin,
(SELECT COUNT(*) FROM notes WHERE user_id = u.id) as notes_count,
(SELECT COUNT(*) FROM images WHERE user_id = u.id) as images_count,
(SELECT COUNT(*) FROM links WHERE user_id = u.id) as links_count
FROM users u
ORDER BY u.joined_date DESC
`);
const users = result.rows.map((u) => ({
...u,
notes_count: parseInt(u.notes_count),
images_count: parseInt(u.images_count),
links_count: parseInt(u.links_count),
online_devices: userClients.get(String(u.id))?.size || 0,
}));
res.json({ success: true, users });
}
catch (err) {
console.error('Admin users error:', err);
res.status(500).json({ success: false, error: 'Failed to fetch users' });
}
});
// Get pending password reset requests
app.get('/api/admin/reset-requests', verifyAdmin, async (req, res) => {
try {
const result = await query(`SELECT * FROM password_reset_requests WHERE status = 'pending' ORDER BY created_at DESC`);
res.json({ success: true, requests: result.rows });
} catch (err) {
res.status(500).json({ success: false, error: 'Failed to fetch requests' });
}
});
// Fulfil a password reset request — admin sets the user's new password
app.put('/api/admin/reset-requests/:id/fulfil', verifyAdmin, async (req, res) => {
try {
const { newPassword } = req.body;
if (!newPassword || newPassword.length < 6) return res.status(400).json({ success: false, error: 'Password must be at least 6 characters' });
const reqResult = await query(`SELECT * FROM password_reset_requests WHERE id = $1 AND status = 'pending'`, [req.params.id]);
if (reqResult.rows.length === 0) return res.status(404).json({ success: false, error: 'Request not found or already fulfilled' });
const resetReq = reqResult.rows[0];
const hash = await hashPassword(newPassword);
await query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, resetReq.user_id]);
await query(`UPDATE password_reset_requests SET status = 'fulfilled', fulfilled_at = NOW() WHERE id = $1`, [req.params.id]);
res.json({ success: true, message: `Password reset for ${resetReq.email}` });
} catch (err) {
console.error('Fulfil reset error:', err);
res.status(500).json({ success: false, error: 'Failed to reset password' });
}
});
// Dismiss a request without resetting
app.delete('/api/admin/reset-requests/:id', verifyAdmin, async (req, res) => {
try {
await query(`UPDATE password_reset_requests SET status = 'dismissed' WHERE id = $1`, [req.params.id]);
res.json({ success: true });
} catch (err) {
res.status(500).json({ success: false, error: 'Failed to dismiss' });
}
});
// Admin stats: total users, total content counts, live connections
app.get('/api/admin/stats', verifyAdmin, async (req, res) => {
try {
const usersCount = await query('SELECT COUNT(*) FROM users');
const notesCount = await query('SELECT COUNT(*) FROM notes');
const imagesCount = await query('SELECT COUNT(*) FROM images');
const linksCount = await query('SELECT COUNT(*) FROM links');
const pendingResets = await query(`SELECT COUNT(*) FROM password_reset_requests WHERE status = 'pending'`);
let liveConnections = 0;
for (const [, clients] of userClients) liveConnections += clients.size;
const liveUsers = userClients.size;
res.json({
success: true,
stats: {
totalUsers: parseInt(usersCount.rows[0].count),
totalNotes: parseInt(notesCount.rows[0].count),
totalImages: parseInt(imagesCount.rows[0].count),
totalLinks: parseInt(linksCount.rows[0].count),
pendingResets: parseInt(pendingResets.rows[0].count),
liveConnections,
liveUsers,
}
});
} catch (err) {
console.error('Admin stats error:', err);
res.status(500).json({ success: false, error: 'Failed to fetch stats' });
}
});
// Get specific user's data
app.get('/api/admin/user/:email', verifyAdmin, async (req, res) => {
try {
const userResult = await query('SELECT * FROM users WHERE email = $1', [req.params.email]);
if (userResult.rows.length === 0) {
return res.status(404).json({ success: false, error: 'User not found' });
}
const userId = userResult.rows[0].id;
const notes = await query('SELECT * FROM notes WHERE user_id = $1', [userId]);
const images = await query('SELECT * FROM images WHERE user_id = $1', [userId]);
const links = await query('SELECT * FROM links WHERE user_id = $1', [userId]);
res.json({
success: true,
user: userResult.rows[0],
notes: notes.rows,
images: images.rows,
links: links.rows
});
}
catch (err) {
console.error('Admin user data error:', err);
res.status(500).json({ success: false, error: 'Failed to fetch user data' });
}
});
// Delete user
app.delete('/api/admin/user/:email', verifyAdmin, async (req, res) => {
try {
const userResult = await query('SELECT id FROM users WHERE email = $1', [req.params.email]);
if (userResult.rows.length === 0) {
return res.status(404).json({ success: false, error: 'User not found' });
}
const userId = userResult.rows[0].id;
await query('DELETE FROM notes WHERE user_id = $1', [userId]);
await query('DELETE FROM images WHERE user_id = $1', [userId]);
await query('DELETE FROM links WHERE user_id = $1', [userId]);
await query('DELETE FROM users WHERE id = $1', [userId]);
res.json({ success: true, message: 'User and all their data deleted' });
}
catch (err) {
console.error('Admin delete error:', err);
res.status(500).json({ success: false, error: 'Failed to delete user' });
}
});
// Admin: promote or demote a user (set is_admin)
app.put('/api/admin/user/:email/role', verifyAdmin, async (req, res) => {
try {
const { isAdmin } = req.body;
const result = await query(
'UPDATE users SET is_admin = $1 WHERE email = $2 RETURNING id, email, name, is_admin',
[!!isAdmin, req.params.email]
);
if (result.rows.length === 0) return res.status(404).json({ success: false, error: 'User not found' });
res.json({ success: true, user: result.rows[0] });
} catch (err) {
console.error('Admin role update error:', err);
res.status(500).json({ success: false, error: 'Failed to update role' });
}
});
// Admin: reset any user's password
app.put('/api/admin/user/:email/password', verifyAdmin, async (req, res) => {
try {
const { newPassword } = req.body;
if (!newPassword || newPassword.length < 6) return res.status(400).json({ success: false, error: 'Password must be at least 6 characters' });
const hash = await hashPassword(newPassword);
const result = await query('UPDATE users SET password_hash = $1 WHERE email = $2 RETURNING id', [hash, req.params.email]);
if (result.rows.length === 0) return res.status(404).json({ success: false, error: 'User not found' });
res.json({ success: true, message: 'Password updated successfully' });
} catch (err) {
console.error('Admin reset password error:', err);
res.status(500).json({ success: false, error: 'Failed to reset password' });
}
});
// Test endpoints
app.get('/api', (req, res) => {
res.json({
success: true,
message: 'OWNLY Link Studio Engine is running',
endpoints: {
auth: '/api/auth/register, /api/auth/login',
notes: '/api/notes',
images: '/api/images',
links: '/api/links',
profile: '/api/user/profile'
}
});
});
app.get('/api/test', (req, res) => {
res.json({
success: true,
message: 'Backend is running!',
database: dbConnected ? 'connected' : 'not_connected',
databaseNotice: dbConnected ? undefined : 'Please add DATABASE_URL to your Render Web Service Environment Variables',
timestamp: new Date().toISOString()
});
});
// API Endpoint to securely parse any link
app.post('/api/parse-link', async (req, res) => {
let { url } = req.body;
if (!url) {
return res.status(400).json({
success: false,
error: 'URL is required'
});
}
url = url.trim();
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url;
}
try {
const videoMeta = parseVideoSource(url);
// Fetch target webpage text for rich metadata extraction
let title = '';
let image = '';
let description = '';
let siteName = '';
try {
const response = await axios.get(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
},
timeout: 8000,
maxRedirects: 5
});
const $ = cheerio.load(response.data);
// Scrape OpenGraph Metadata tags
title = $('meta[property="og:title"]').attr('content') ||
$('meta[name="twitter:title"]').attr('content') ||
$('title').text() ||
url;
image = $('meta[property="og:image"]').attr('content') ||
$('meta[name="twitter:image"]').attr('content') ||
'';
description = $('meta[property="og:description"]').attr('content') ||
$('meta[name="twitter:description"]').attr('content') ||
$('meta[name="description"]').attr('content') ||
'';
siteName = $('meta[property="og:site_name"]').attr('content') ||
new URL(url).hostname.replace(/^www\./, '');
}
catch (scrapeErr) {
console.warn('Scraping page metadata failed, falling back to direct parser:', scrapeErr.message);
try {
siteName = new URL(url).hostname.replace(/^www\./, '');
}
catch (e) {
siteName = 'Web Link';
}
title = videoMeta.provider !== 'generic' ? `${videoMeta.provider.toUpperCase()} Video` : siteName;
description = 'Web bookmark';
}
// Auto fallback for youtube thumbnail
if (videoMeta.provider === 'youtube' && (!image || image.length === 0) && videoMeta.id) {
image = `https://img.youtube.com/vi/${videoMeta.id}/hqdefault.jpg`;
}
image = absoluteUrl(image, url);
// Clean up title
title = (title || url).trim().replace(/\s+/g, ' ');
const result = {
success: true,
title: title || url,
description: description ? description.trim() : '',
embedThumb: image || '',
linkHost: siteName || new URL(url).hostname.replace(/^www\./, ''),
embedProvider: videoMeta.provider,
embedId: videoMeta.id,
isPlayable: videoMeta.provider !== 'generic',
url: url
};
res.json(result);
}
catch (error) {
console.error('Error in /api/parse-link:', error.message);
const fallbackMeta = parseVideoSource(url);
let hostName = 'Unknown Site';
try {
hostName = new URL(url).hostname;
}
catch (e) { }
const fallbackResult = {
success: true,
title: fallbackMeta.provider !== 'generic' ? `${fallbackMeta.provider.toUpperCase()} Video` : "Bookmarked Link",
description: "Content loaded successfully",
embedThumb: fallbackMeta.provider === 'youtube' && fallbackMeta.id ? `https://img.youtube.com/vi/${fallbackMeta.id}/hqdefault.jpg` : "",
linkHost: hostName.replace(/^www\./, ''),
embedProvider: fallbackMeta.provider,
embedId: fallbackMeta.id,
isPlayable: fallbackMeta.provider !== 'generic',
url: url
};
}
});
// ============ HIGH-LEVEL MULTI-PROXY LINK & MEDIA BYPASS ============
// Bypasses X-Frame-Options, CSP, and embed restrictions using multi-tier proxy fallbacks
app.all('/api/proxy-link', async (req, res) => {
const targetUrl = req.query.url;
if (!targetUrl || typeof targetUrl !== 'string') {
return res.status(400).send('Missing target url query parameter');
}
let cleanUrl = targetUrl.trim();
if (!cleanUrl.startsWith('http://') && !cleanUrl.startsWith('https://')) {
cleanUrl = 'https://' + cleanUrl;
}
// Multi-tier proxies list: direct fetch with bypass headers first, then fast public proxy endpoints
const proxyFetchers = [
// 1. High performance direct bypass with mobile/desktop user agents
async () => {
return await axios.get(cleanUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
},
timeout: 7000,
maxRedirects: 5,
responseType: 'text'
});
},
// 2. High-speed AllOrigins proxy bypass
async () => {
const proxyUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(cleanUrl)}`;
return await axios.get(proxyUrl, { timeout: 8000, responseType: 'text' });
},
// 3. Fast CORSProxy bypass
async () => {
const proxyUrl = `https://corsproxy.io/?url=${encodeURIComponent(cleanUrl)}`;
return await axios.get(proxyUrl, { timeout: 8000, responseType: 'text' });
},
// 4. CodeTabs bypass
async () => {
const proxyUrl = `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(cleanUrl)}`;
return await axios.get(proxyUrl, { timeout: 8000, responseType: 'text' });
}
];
let content = null;
let lastError = null;
for (const fetcher of proxyFetchers) {
try {
const resp = await fetcher();
if (resp && resp.data) {
content = resp.data;
break;
}
} catch (err) {
lastError = err;
}
}
if (!content) {
console.warn('All proxies failed for URL:', cleanUrl, lastError?.message);
return res.status(502).send(`<html><body style="font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#111;color:#fff;text-align:center;"><div><h2>Unable to bypass preview directly</h2><p style="opacity:0.7">This website restricts embedding.</p><a href="${cleanUrl}" target="_blank" rel="noopener noreferrer" style="color:#e11d48;font-weight:bold;text-decoration:none;padding:10px 20px;background:rgba(225,29,72,0.15);border-radius:20px;display:inline-block;margin-top:10px;">Open in New Tab →</a></div></body></html>`);
}
// Rewrite headers to allow embedding inside OWNLY app iframe
res.removeHeader('X-Frame-Options');
res.removeHeader('Content-Security-Policy');
res.removeHeader('content-security-policy');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'text/html; charset=utf-8');
// Inject <base href="..."> so relative paths, images, and CSS resolve accurately
try {
const urlObj = new URL(cleanUrl);
const baseTag = `<base href="${urlObj.origin}${urlObj.pathname.substring(0, urlObj.pathname.lastIndexOf('/') + 1)}">`;
if (typeof content === 'string') {
if (content.includes('<head>')) {
content = content.replace('<head>', `<head>${baseTag}`);
} else if (content.includes('<HEAD>')) {
content = content.replace('<HEAD>', `<HEAD>${baseTag}`);
} else {
content = baseTag + content;
}
}
} catch (e) {
// keep content as is
}
return res.send(content);
});
// Proxy stream endpoint for videos/audio/assets
app.get('/api/proxy-stream', async (req, res) => {
const streamUrl = req.query.url;
if (!streamUrl || typeof streamUrl !== 'string') {
return res.status(400).send('Missing url query parameter');
}
try {
const response = await axios({
method: 'get',
url: streamUrl,
responseType: 'stream',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
},
timeout: 10000
});
res.setHeader('Access-Control-Allow-Origin', '*');
if (response.headers['content-type']) {
res.setHeader('Content-Type', response.headers['content-type']);
}
response.data.pipe(res);
} catch (err) {
res.status(502).send('Streaming error');
}
});
// Vite integration
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
}
else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
// Dedicated /admin endpoint serving HTML with /admin-manifest.json pre-injected in HTML
app.use((req, res, next) => {
const urlPath = req.path.toLowerCase();
if (urlPath === '/admin' || urlPath.startsWith('/admin/')) {
const indexPath = path.join(distPath, 'index.html');
if (fs.existsSync(indexPath)) {
let html = fs.readFileSync(indexPath, 'utf8');
html = html.replace('/manifest.json', '/admin-manifest.json')
.replace('/apple-touch-icon.png', '/icons/icon-admin-192.svg')
.replace('content="OWNLY"', 'content="OWNLY Admin"')
.replace('<title>OWNLY — Your Personal Knowledge Space</title>', '<title>OWNLY Admin</title>');
res.setHeader('Content-Type', 'text/html; charset=utf-8');
return res.send(html);
}
return res.sendFile(indexPath);
}
next();
});
app.use((req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
// ============ HTTP + WEBSOCKET SERVER ============
const httpServer = createServer(app);
const wss = new WebSocketServer({ server: httpServer, path: '/ws' });
wss.on('connection', (ws, req) => {
let userId = null;
ws.on('message', (raw) => {
try {
const msg = JSON.parse(raw);
// AUTH: client sends { type:'auth', token } on connect
if (msg.type === 'auth') {
try {
const secret = process.env.JWT_SECRET || 'ownly-secret-key-change-in-production';
const decoded = jwt.verify(msg.token, secret);
userId = String(decoded.userId || decoded.id);
if (!userClients.has(userId)) userClients.set(userId, new Set());
userClients.get(userId).add(ws);
ws.send(JSON.stringify({ type: 'auth_ok', userId }));
console.log(`🔌 WS: user ${userId} connected (${userClients.get(userId).size} devices)`);
} catch {
ws.send(JSON.stringify({ type: 'auth_error', error: 'Invalid token' }));
ws.close();
}
return;
}
// PING keep-alive
if (msg.type === 'ping') {
ws.send(JSON.stringify({ type: 'pong' }));
return;
}
} catch { /* ignore malformed messages */ }
});
ws.on('close', () => {
if (userId && userClients.has(userId)) {
userClients.get(userId).delete(ws);
if (userClients.get(userId).size === 0) userClients.delete(userId);
console.log(`❌ WS: user ${userId} disconnected`);
}
});
});
httpServer.listen(Number(PORT), '0.0.0.0', () => {
console.log(`✅ OWNLY server running on http://localhost:${PORT}`);
console.log(`🔌 WebSocket sync active at ws://localhost:${PORT}/ws`);
});
}
startServer().catch(err => {
console.error('Server startup failed:', err);
process.exit(1);
});