-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
2624 lines (2267 loc) · 103 KB
/
Copy pathserver.js
File metadata and controls
2624 lines (2267 loc) · 103 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
997
998
999
1000
require('dotenv').config();
const express = require('express');
const http = require('http');
const cors = require('cors');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const mysql = require('mysql2');
const { Server } = require('socket.io');
const multer = require('multer');
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
// Server configuration
const PORT = process.env.PORT || 5000;
const HOST_DOMAIN = process.env.HOST_DOMAIN || 'http://localhost:3000';
const SECRET_KEY = process.env.SECRET_KEY;
if (!SECRET_KEY) {
console.error('SECRET_KEY environment variable is required');
process.exit(1);
}
// Message encryption configuration
const MESSAGE_ENCRYPTION_KEY = process.env.MESSAGE_ENCRYPTION_KEY || SECRET_KEY.substring(0, 32).padEnd(32, '0');
const MESSAGE_ENCRYPTION_ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 16;
const AUTH_TAG_LENGTH = 16;
const ACCESS_TOKEN_EXPIRES_IN = process.env.ACCESS_TOKEN_EXPIRES_IN || '15m';
const parsedRefreshDays = parseInt(process.env.REFRESH_TOKEN_TTL_DAYS || '7', 10);
const REFRESH_TOKEN_TTL_DAYS = Number.isFinite(parsedRefreshDays) && parsedRefreshDays > 0 ? parsedRefreshDays : 7;
const REFRESH_TOKEN_TTL_MS = REFRESH_TOKEN_TTL_DAYS * 24 * 60 * 60 * 1000;
const parsedMaxSessions = parseInt(process.env.MAX_SESSIONS_PER_USER || '10', 10);
const MAX_SESSIONS_PER_USER = Number.isFinite(parsedMaxSessions) && parsedMaxSessions > 0 ? parsedMaxSessions : 10;
const TOKEN_TYPE_ACCESS = 'access';
const TOKEN_TYPE_REFRESH = 'refresh';
const DB_CONFIG = {
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
acquireTimeout: 60000,
timeout: 60000,
reconnect: true,
charset: 'utf8mb4'
};
if (!DB_CONFIG.user || !DB_CONFIG.password || !DB_CONFIG.database) {
console.error('Database configuration is incomplete. Please check your environment variables.');
process.exit(1);
}
const app = express();
const onlineUsers = new Map();
function ensureUserSessionsTable() {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS user_sessions (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
session_id VARCHAR(128) NOT NULL UNIQUE,
refresh_token_hash CHAR(64) NOT NULL,
refresh_expires_at DATETIME NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_used_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_user_sessions_user_id (user_id)
) ENGINE=InnoDB;
`;
db.query(createTableQuery, (err) => {
if (err) {
console.error('Failed to ensure user_sessions table exists:', err);
}
});
}
function generateSessionId() {
return typeof crypto.randomUUID === 'function'
? crypto.randomUUID()
: crypto.randomBytes(16).toString('hex');
}
function createRefreshToken(sessionId) {
return `${sessionId}.${crypto.randomBytes(48).toString('hex')}`;
}
function hashToken(token) {
return crypto.createHash('sha256').update(token).digest('hex');
}
function parseRefreshToken(refreshToken) {
if (!refreshToken || typeof refreshToken !== 'string') {
return null;
}
const [sessionId, secretPart] = refreshToken.split('.');
if (!sessionId || !secretPart) {
return null;
}
return { sessionId };
}
function getRefreshExpiryDate() {
return new Date(Date.now() + REFRESH_TOKEN_TTL_MS);
}
function issueAccessToken({ userId, username, sessionId }) {
return jwt.sign(
{
userId,
username,
sessionId,
type: TOKEN_TYPE_ACCESS
},
SECRET_KEY,
{ expiresIn: ACCESS_TOKEN_EXPIRES_IN }
);
}
function pruneExcessSessions(userId) {
return new Promise((resolve) => {
if (!MAX_SESSIONS_PER_USER) {
return resolve();
}
const pruneQuery = `
DELETE FROM user_sessions
WHERE user_id = ?
AND id NOT IN (
SELECT id FROM (
SELECT id FROM user_sessions
WHERE user_id = ?
ORDER BY last_used_at DESC
LIMIT ?
) AS recent_sessions
)
`;
db.query(pruneQuery, [userId, userId, MAX_SESSIONS_PER_USER], (err) => {
if (err) {
console.error('Failed to prune old sessions:', err);
}
resolve();
});
});
}
// Message encryption/decryption functions
function encryptMessage(text) {
if (!text || text.trim().length === 0) {
return text; // Return empty string as-is
}
try {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(
MESSAGE_ENCRYPTION_ALGORITHM,
Buffer.from(MESSAGE_ENCRYPTION_KEY, 'utf8'),
iv
);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
// Format: iv:authTag:encrypted (all in hex)
return `${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`;
} catch (error) {
console.error('Error encrypting message:', error);
throw new Error('Failed to encrypt message');
}
}
// Helper function to insert system message in group
function insertGroupSystemMessage(groupId, text, ioInstance) {
// Use NULL as sender_id for system messages to avoid foreign key constraint
const query = 'INSERT INTO group_messages (group_id, sender_id, text, message_type, timestamp) VALUES (?, NULL, ?, ?, UTC_TIMESTAMP())';
db.query(query, [groupId, text, 'system'], (err, result) => {
if (err) {
console.error('Error inserting system message:', err);
return;
}
if (ioInstance) {
const messageId = result.insertId;
const emitData = {
id: messageId,
senderId: 0, // Use 0 for frontend display, but NULL in database
groupId,
text: text,
imageUrl: null,
messageType: 'system',
timestamp: new Date().toISOString(),
nickname: null,
avatar: null,
momoCode: null,
replyTo: null,
clientId: null,
isEmoji: false
};
ioInstance.to(`group_${groupId}`).emit('receive_group_message', emitData);
}
});
}
function decryptMessage(encryptedText) {
if (!encryptedText || encryptedText.trim().length === 0) {
return encryptedText; // Return empty string as-is
}
// Check if the text is encrypted (format: iv:authTag:encrypted)
// If it doesn't contain colons, it's likely plaintext
if (!encryptedText.includes(':')) {
return encryptedText; // Return as plaintext
}
try {
const parts = encryptedText.split(':');
if (parts.length !== 3) {
// Invalid format, return as-is
return encryptedText;
}
const [ivHex, authTagHex, encrypted] = parts;
const iv = Buffer.from(ivHex, 'hex');
const authTag = Buffer.from(authTagHex, 'hex');
const decipher = crypto.createDecipheriv(
MESSAGE_ENCRYPTION_ALGORITHM,
Buffer.from(MESSAGE_ENCRYPTION_KEY, 'utf8'),
iv
);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (error) {
console.error('Error decrypting message:', error);
// If decryption fails, return the encrypted text
return encryptedText;
}
}
// Middleware configuration
app.use(cors({
origin: HOST_DOMAIN,
methods: ['GET', 'POST', 'DELETE'],
credentials: true
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Serve static files from React build (only if build directory exists)
const staticBuildPath = path.join(__dirname, 'build');
if (fs.existsSync(staticBuildPath)) {
app.use(express.static(staticBuildPath));
}
// Image access authentication
app.get('/uploads/*', async (req, res) => {
// Extract path without query parameters
const imagePath = req.path.split('?')[0]; // 例如: /uploads/avatars/avatar_1_xxx.jpg
const filePath = path.join(__dirname, imagePath);
// SECURITY CHECK
const normalizedPath = path.normalize(filePath);
const uploadsDir = path.normalize(path.join(__dirname, 'uploads'));
if (!normalizedPath.startsWith(uploadsDir)) {
return res.status(403).json({ error: 'Access denied' });
}
// Check if file exists
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'Image not found' });
}
// Try to get userId from token (priority check - if token is valid, allow access)
let userId = null;
let hasValidToken = false;
const token = req.headers['authorization']?.split(' ')[1] || req.query.token;
if (token) {
try {
const decoded = jwt.verify(token, SECRET_KEY);
const { userId: decodedUserId, sessionId, sessionToken, type } = decoded;
if (type && type !== TOKEN_TYPE_ACCESS) {
throw new Error('Invalid token type');
}
if (decodedUserId && sessionId) {
const [sessions] = await db.promise().query(
'SELECT refresh_expires_at FROM user_sessions WHERE user_id = ? AND session_id = ? LIMIT 1',
[decodedUserId, sessionId]
);
if (sessions.length > 0) {
const expiresAt = new Date(sessions[0].refresh_expires_at);
if (!Number.isNaN(expiresAt.getTime()) && expiresAt.getTime() > Date.now()) {
userId = decodedUserId;
hasValidToken = true;
}
}
} else if (decodedUserId && sessionToken) {
const [results] = await db.promise().query('SELECT session_token FROM users WHERE id = ?', [decodedUserId]);
if (results.length > 0 && results[0].session_token === sessionToken) {
userId = decodedUserId;
hasValidToken = true;
}
}
} catch (err) {
// Token invalid
}
}
// If token is valid, allow access (skip Referer check)
if (hasValidToken) {
// Token is valid, proceed with permission checks below
} else {
// If no valid token, check Referer to prevent direct URL access
const referer = req.get('Referer') || req.get('Referrer');
if (!referer || !referer.startsWith(HOST_DOMAIN)) {
return res.status(403).json({ error: 'Access denied' });
}
}
// Check Access
try {
const filename = imagePath.split('/').pop();
// If user is authenticated, check permissions
if (userId) {
// Check if is avatar (match by exact path or filename)
const [avatarUsers] = await db.promise().query(
'SELECT id FROM users WHERE avatar = ? OR avatar LIKE ? OR avatar LIKE ?',
[imagePath, `%${filename}`, `%/${filename}`]
);
if (avatarUsers.length > 0) {
const avatarOwnerId = avatarUsers[0].id;
// Allow avatar owner and friends to access
if (avatarOwnerId === userId) {
return res.sendFile(filePath);
}
// Check if is friend
const [friendship] = await db.promise().query(
`SELECT * FROM friends
WHERE ((user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?))
AND status = 'accepted'`,
[userId, avatarOwnerId, avatarOwnerId, userId]
);
if (friendship.length > 0) {
return res.sendFile(filePath);
}
}
// Check if is chat image (match by exact path or filename)
const [chatImages] = await db.promise().query(
`SELECT sender_id, receiver_id FROM dms
WHERE (image_url = ? OR image_url LIKE ? OR image_url LIKE ?)
AND (sender_id = ? OR receiver_id = ?)`,
[imagePath, `%${filename}`, `%/${filename}`, userId, userId]
);
if (chatImages.length > 0) {
return res.sendFile(filePath);
}
}
// If no userId but Referer is valid, allow access (from app)
// This handles old images without token
return res.sendFile(filePath);
} catch (error) {
console.error('Error checking image access:', error);
return res.status(500).json({ error: 'Internal server error' });
}
});
// Create uploads directories if they don't exist
const uploadDirs = ['uploads/avatars', 'uploads/chat-images'];
uploadDirs.forEach(dir => {
const dirPath = path.join(__dirname, dir);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
console.log(`Created directory: ${dir}`);
}
});
// Configure multer for file uploads
const storage = multer.memoryStorage(); // Store files in memory for processing with sharp
const fileFilter = (req, file, cb) => {
// Accept images only
if (!file.mimetype.startsWith('image/')) {
return cb(new Error('Only image files are allowed!'), false);
}
cb(null, true);
};
const upload = multer({
storage: storage,
fileFilter: fileFilter,
limits: {
fileSize: 5 * 1024 * 1024 // 5MB limit
}
});
// Database connection
const db = mysql.createPool(DB_CONFIG);
ensureUserSessionsTable();
db.getConnection((err, connection) => {
if (err) {
console.error('Error connecting to the database:', err.message);
process.exit(1);
} else {
console.log('Connected to the database');
connection.release();
}
});
// Momo Code generation function
function generateMomoCode() {
// Generate 12 random digits
let code = '';
for (let i = 0; i < 12; i++) {
code += Math.floor(Math.random() * 10);
}
// Format as xxxx-xxxx-xxxx
return `${code.substring(0, 4)}-${code.substring(4, 8)}-${code.substring(8, 12)}`;
}
async function generateUniqueMomoCode() {
let momoCode;
let isUnique = false;
while (!isUnique) {
momoCode = generateMomoCode();
// Check if this code already exists
const [rows] = await db.promise().query('SELECT id FROM users WHERE momo_code = ?', [momoCode]);
if (rows.length === 0) {
isUnique = true;
}
}
return momoCode;
}
async function generateUniqueGroupCode() {
let groupCode;
let isUnique = false;
while (!isUnique) {
groupCode = generateMomoCode(); // Reuse the same format
// Check if this code already exists
const [rows] = await db.promise().query('SELECT id FROM groups WHERE group_code = ?', [groupCode]);
if (rows.length === 0) {
isUnique = true;
}
}
return groupCode;
}
// Socket.io configuration
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: HOST_DOMAIN,
methods: ['GET', 'POST'],
credentials: true
}
});
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('join_room', (userId) => {
if (userId) {
onlineUsers.set(userId, socket.id);
socket.join(userId.toString());
console.log(`User ${userId} joined room`);
// Join all group rooms the user is a member of
db.query('SELECT group_id FROM group_members WHERE user_id = ?', [userId], (err, groups) => {
if (!err) {
groups.forEach(group => {
socket.join(`group_${group.group_id}`);
});
}
});
// Update last_used_at when user comes online
db.query('UPDATE user_sessions SET last_used_at = NOW() WHERE user_id = ?', [userId], (err) => {
if (err) console.error('Error updating last_used_at on join:', err);
});
notifyFriends(userId, true);
}
});
// Request online status for all friends
socket.on('request_friends_status', (friendIds) => {
if (!Array.isArray(friendIds)) return;
const friendIdsStr = friendIds.join(',');
if (!friendIdsStr) return;
const query = `
SELECT user_id, MAX(last_used_at) AS lastSeen
FROM user_sessions
WHERE user_id IN (${friendIds.map(() => '?').join(',')})
GROUP BY user_id
`;
db.query(query, friendIds, (err, results) => {
if (err) {
console.error('Error fetching lastSeen:', err);
const statusUpdates = friendIds.map(friendId => ({
friendId: friendId,
isOnline: onlineUsers.has(friendId)
}));
socket.emit('friends_status_response', statusUpdates);
return;
}
const lastSeenMap = new Map();
results.forEach(row => {
lastSeenMap.set(row.user_id, row.lastSeen);
});
const statusUpdates = friendIds.map(friendId => {
const isOnline = onlineUsers.has(friendId);
const lastSeen = isOnline ? new Date().toISOString() : (lastSeenMap.get(friendId) || null);
return {
friendId: friendId,
isOnline: isOnline,
lastSeen: lastSeen
};
});
socket.emit('friends_status_response', statusUpdates);
});
});
socket.on('disconnect', () => {
const userId = Array.from(onlineUsers.entries()).find(([, id]) => id === socket.id)?.[0];
if (userId) {
onlineUsers.delete(userId);
notifyFriends(userId, false); //Broadcast user offline
console.log(`User ${userId} disconnected`);
}
});
socket.on('leave_room', (userId) => {
if (userId) {
onlineUsers.delete(userId);
socket.leave(userId.toString());
console.log(`User ${userId} left room`);
}
});
// Baisc Group Message Functions
socket.on('send_group_message', (data) => {
const { senderId, groupId, text, imageUrl, replyTo, clientId, isEmoji } = data;
if (!senderId || !groupId) {
console.error('Invalid group message payload: missing senderId or groupId', data);
return;
}
const hasText = text && text.trim().length > 0;
const hasImage = imageUrl && imageUrl.trim().length > 0;
if (!hasText && !hasImage) {
console.error('Invalid group message payload: missing text and imageUrl', data);
return;
}
// Check if user is a member
db.query('SELECT id FROM group_members WHERE group_id = ? AND user_id = ?', [groupId, senderId], (checkErr, checkResults) => {
if (checkErr || checkResults.length === 0) {
console.error('User is not a member of this group');
return;
}
let messageType = 'text';
if (hasText && hasImage) {
messageType = 'both';
} else if (hasImage) {
messageType = 'image';
}
const textValue = hasText ? text.trim() : '';
const encryptedText = hasText ? encryptMessage(textValue) : '';
let replyToId = null;
let replyToData = null;
if (replyTo) {
if (replyTo.id) {
replyToId = replyTo.id;
} else if (replyTo.senderId && (replyTo.text || replyTo.imageUrl)) {
const findReplyQuery = `
SELECT id FROM group_messages
WHERE group_id = ? AND (text = ? OR image_url = ?)
ORDER BY timestamp DESC LIMIT 1
`;
const replyText = replyTo.text ? encryptMessage(replyTo.text.trim()) : '';
db.query(findReplyQuery, [groupId, replyText || null, replyTo.imageUrl || null], (findErr, findResults) => {
if (!findErr && findResults.length > 0) {
replyToId = findResults[0].id;
insertGroupMessage();
} else {
replyToData = JSON.stringify(replyTo);
insertGroupMessage();
}
});
return;
}
}
function insertGroupMessage() {
const query = 'INSERT INTO group_messages (group_id, sender_id, text, image_url, message_type, reply_to_id, reply_to_data, is_emoji, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP());';
db.query(query, [groupId, senderId, encryptedText, hasImage ? imageUrl : null, messageType, replyToId, replyToData, isEmoji ? 1 : 0], (err, insertResult) => {
if (!err) {
const messageId = insertResult.insertId;
const userQuery = 'SELECT nickname, avatar, momo_code FROM users WHERE id = ?';
db.query(userQuery, [senderId], (userErr, userResults) => {
if (!userErr && userResults.length > 0) {
const { nickname, avatar, momo_code } = userResults[0];
let finalReplyTo = null;
if (replyToId) {
const getReplyQuery = 'SELECT text, image_url, sender_id FROM group_messages WHERE id = ?';
db.query(getReplyQuery, [replyToId], (replyErr, replyResults) => {
if (!replyErr && replyResults.length > 0) {
const replyMsg = replyResults[0];
finalReplyTo = {
id: replyToId,
text: replyMsg.text ? decryptMessage(replyMsg.text) : null,
imageUrl: replyMsg.image_url,
senderId: replyMsg.sender_id
};
}
emitGroupMessage(finalReplyTo);
});
} else if (replyToData) {
try {
finalReplyTo = JSON.parse(replyToData);
} catch (e) {
finalReplyTo = null;
}
emitGroupMessage(finalReplyTo);
} else {
emitGroupMessage(null);
}
function emitGroupMessage(replyToInfo) {
const emitData = {
id: messageId,
senderId,
groupId,
text: hasText ? textValue : null,
imageUrl: hasImage ? imageUrl : null,
messageType,
timestamp: new Date().toISOString(),
nickname,
avatar,
momoCode: momo_code || null,
replyTo: replyToInfo,
clientId,
isEmoji: Boolean(isEmoji)
};
// Send to all group members
io.to(`group_${groupId}`).emit('receive_group_message', emitData);
}
}
});
} else {
console.error('Error saving group message:', err.message);
}
});
}
if (!replyTo || replyTo.id) {
insertGroupMessage();
}
});
});
socket.on('send_message', (data) => {
const { senderId, receiverId, text, imageUrl, replyTo, clientId, isEmoji } = data;
// Validate: must have senderId, receiverId, and at least text or imageUrl
if (!senderId || !receiverId) {
console.error('Invalid message payload: missing senderId or receiverId', data);
return;
}
// Allow self-messaging for multi-device sync
const isSelfMessage = senderId === receiverId;
// Check if text has content (including emoji) or if there's an image
const hasText = text && text.trim().length > 0;
const hasImage = imageUrl && imageUrl.trim().length > 0;
if (!hasText && !hasImage) {
console.error('Invalid message payload: missing text and imageUrl', data);
return;
}
// Determine message type
let messageType = 'text';
if (hasText && hasImage) {
messageType = 'both';
} else if (hasImage) {
messageType = 'image';
}
// Prepare text value: use trimmed text if available, otherwise empty string (since text field is NOT NULL)
const textValue = hasText ? text.trim() : '';
// Encrypt the message text before storing
const encryptedText = hasText ? encryptMessage(textValue) : '';
// Handle replyTo: if replyTo has an id, use it; otherwise, extract reply info
let replyToId = null;
let replyToData = null;
if (replyTo) {
if (replyTo.id) {
replyToId = replyTo.id;
} else if (replyTo.senderId && (replyTo.text || replyTo.imageUrl)) {
// Find the message being replied to by matching sender, text/image, and recent timestamp
const findReplyQuery = `
SELECT id FROM dms
WHERE ((sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?))
AND (text = ? OR image_url = ?)
ORDER BY timestamp DESC
LIMIT 1
`;
const replyText = replyTo.text ? encryptMessage(replyTo.text.trim()) : '';
db.query(findReplyQuery, [
replyTo.senderId, receiverId === replyTo.senderId ? senderId : receiverId,
replyTo.senderId, receiverId === replyTo.senderId ? senderId : receiverId,
replyText || null, replyTo.imageUrl || null
], (findErr, findResults) => {
if (!findErr && findResults.length > 0) {
replyToId = findResults[0].id;
insertMessage();
} else {
// If can't find, still save reply info as JSON
replyToData = JSON.stringify(replyTo);
insertMessage();
}
});
return;
}
}
function insertMessage() {
const query = 'INSERT INTO dms (sender_id, receiver_id, text, image_url, message_type, reply_to_id, reply_to_data, is_emoji, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP());';
db.query(query, [senderId, receiverId, encryptedText, hasImage ? imageUrl : null, messageType, replyToId, replyToData, isEmoji ? 1 : 0], (err, insertResult) => {
if (!err) {
const messageId = insertResult.insertId;
const userQuery = 'SELECT nickname, avatar FROM users WHERE id = ?';
db.query(userQuery, [senderId], (userErr, userResults) => {
if (!userErr && userResults.length > 0) {
const { nickname, avatar } = userResults[0];
// Get replyTo info if it exists
let finalReplyTo = null;
if (replyToId) {
const getReplyQuery = 'SELECT text, image_url, sender_id FROM dms WHERE id = ?';
db.query(getReplyQuery, [replyToId], (replyErr, replyResults) => {
if (!replyErr && replyResults.length > 0) {
const replyMsg = replyResults[0];
finalReplyTo = {
id: replyToId,
text: replyMsg.text ? decryptMessage(replyMsg.text) : null,
imageUrl: replyMsg.image_url,
senderId: replyMsg.sender_id
};
}
emitMessage(finalReplyTo);
});
} else if (replyToData) {
try {
finalReplyTo = JSON.parse(replyToData);
} catch (e) {
finalReplyTo = null;
}
emitMessage(finalReplyTo);
} else {
emitMessage(null);
}
function emitMessage(replyToInfo) {
const emitData = {
id: messageId,
senderId,
receiverId,
text: hasText ? textValue : null,
imageUrl: hasImage ? imageUrl : null,
messageType,
timestamp: new Date().toISOString(),
nickname,
avatar,
replyTo: replyToInfo,
clientId,
isEmoji: Boolean(isEmoji)
};
if (isSelfMessage) {
// Self-message: send to sender's all devices
io.to(senderId.toString()).emit('receive_message', emitData);
} else {
// Regular message: send to receiver's all devices
io.to(receiverId.toString()).emit('receive_message', emitData);
// Also send to sender's other devices for multi-device sync (excluding the sending socket)
socket.to(senderId.toString()).emit('receive_message', emitData);
}
}
} else {
console.error('Error fetching sender info:', userErr ? userErr.message : 'No user found');
}
});
} else {
console.error('Error saving message:', err.message);
}
});
}
if (!replyTo || replyTo.id) {
insertMessage();
}
});
// Handle friend request events
socket.on('send_friend_request', ({ senderId, receiverId, senderUsername }) => {
console.log(`Friend request sent from ${senderId} to ${receiverId}`);
io.to(receiverId.toString()).emit('receive_friend_request', {
senderId,
senderUsername
});
});
socket.on('respond_friend_request', ({ senderId, receiverId, action }) => {
console.log(`Friend request ${action} by ${receiverId}`);
io.to(senderId.toString()).emit('friend_request_responded', { receiverId, action });
if (action === 'accept') {
io.to(senderId.toString()).emit('update_friend_list');
}
});
});
app.get('/api', (req, res) => {
res.json({ message: 'Hello from momotalk api!' });
});
// API ROUTERS
app.post('/register', async (req, res) => {
const { username, email, password, nickname } = req.body;
if (!username || !email || !password || !nickname) {
return res.status(400).json({ error: 'Username, email, password, and nickname are required.' });
}
try {
const hashedPassword = await bcrypt.hash(password, 10);
const momoCode = await generateUniqueMomoCode();
const query = 'INSERT INTO users (username, email, password, nickname, momo_code) VALUES (?, ?, ?, ?, ?)';
db.query(query, [username, email, hashedPassword, nickname, momoCode], (err) => {
if (err) {
if (err.code === 'ER_DUP_ENTRY') {
return res.status(400).json({ error: 'Username or email already exists.' });
}
return res.status(500).json({ error: 'Database error.' });
}
res.json({ message: 'User registered successfully.', momoCode });
});
} catch (error) {
res.status(500).json({ error: 'Internal server error.' });
}
});
app.post('/login', (req, res) => {
const { username, password } = req.body;
const query = 'SELECT * FROM users WHERE username = ?';
db.query(query, [username], async (err, results) => {
if (err) return res.status(500).json({ error: err.message });
if (results.length === 0) return res.status(401).json({ error: 'Invalid credentials' });
const user = results[0];
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const sessionId = generateSessionId();
const refreshToken = createRefreshToken(sessionId);
const refreshTokenHash = hashToken(refreshToken);
const refreshExpiresAt = getRefreshExpiryDate();
const insertSessionQuery = `
INSERT INTO user_sessions (user_id, session_id, refresh_token_hash, refresh_expires_at)
VALUES (?, ?, ?, ?)
`;
db.query(insertSessionQuery, [user.id, sessionId, refreshTokenHash, refreshExpiresAt], (insertErr) => {
if (insertErr) {
console.error('Failed to store session:', insertErr);
return res.status(500).json({ error: 'Failed to create session' });
}
const accessToken = issueAccessToken({
userId: user.id,
username: user.username,
sessionId
});
pruneExcessSessions(user.id).finally(() => {
res.json({
token: accessToken,
accessToken,
refreshToken,
userId: user.id,
username: user.username,
nickname: user.nickname,
avatar: user.avatar || null,
email: user.email,
momoCode: user.momo_code || null,
signature: user.signature || '',
birthday: user.birthday || null,
});
});
});
});
});
app.post('/token/refresh', async (req, res) => {
const { refreshToken } = req.body || {};
if (!refreshToken) {
return res.status(400).json({ error: 'Refresh token is required' });
}
const parsed = parseRefreshToken(refreshToken);
if (!parsed) {
return res.status(401).json({ error: 'Invalid refresh token' });
}
const refreshTokenHash = hashToken(refreshToken);
try {
const [sessions] = await db.promise().query(
'SELECT id, user_id, refresh_expires_at FROM user_sessions WHERE session_id = ? AND refresh_token_hash = ? LIMIT 1',
[parsed.sessionId, refreshTokenHash]
);
if (sessions.length === 0) {
return res.status(401).json({ error: 'Invalid refresh token' });
}
const session = sessions[0];
const expiresAt = new Date(session.refresh_expires_at);
if (Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() <= Date.now()) {
await db.promise().query('DELETE FROM user_sessions WHERE id = ?', [session.id]);
return res.status(401).json({ error: 'Refresh token expired' });
}
const [users] = await db.promise().query('SELECT username FROM users WHERE id = ? LIMIT 1', [session.user_id]);
const username = users.length > 0 ? users[0].username : undefined;
const accessToken = issueAccessToken({
userId: session.user_id,
username,
sessionId: parsed.sessionId
});
const nextRefreshToken = createRefreshToken(parsed.sessionId);
const nextRefreshHash = hashToken(nextRefreshToken);
const nextRefreshExpiry = getRefreshExpiryDate();