-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup.js
More file actions
335 lines (276 loc) · 10.9 KB
/
backup.js
File metadata and controls
335 lines (276 loc) · 10.9 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
// server.js
const express = require('express')
const http = require('http')
const bcrypt = require('bcrypt')
const session = require('express-session')
const fs = require('fs')
const path = require('path')
const { v4: uuidv4 } = require('uuid')
// Removed generateKeyPairSync, publicEncrypt, privateDecrypt, createCipheriv, createDecipheriv as they are now client-side
const { randomBytes } = require('crypto') // Keep randomBytes for IV generation if needed, or remove if client-side handles all IVs
const { Server } = require('socket.io')
const app = express()
const server = http.createServer(app)
const io = new Server(server)
// rate limiting: track user -> timestamps of sent messages
const messageRateLimit = {} // format: { username: [timestamp1, timestamp2, ...] }
const MESSAGE_LIMIT = 5 // max 5 messages
const TIME_WINDOW_MS = 1000 // per 1 second
const MAX_MESSAGE_LENGTH = 10000
const PORT = 3000
app.use((req, res, next) => {
const origin = req.headers.origin
if (origin && (origin.startsWith('https://') || origin === 'null')) {
res.setHeader('Access-Control-Allow-Origin', origin) // or restrict to 'file://' only
}
res.setHeader('Access-Control-Allow-Credentials', 'true')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
if (req.method === 'OPTIONS') {
return res.sendStatus(200)
}
next()
})
app.use((req, res, next) => {
res.setHeader('X-Frame-Options', 'ALLOWALL') // or remove the header entirely
next()
})
const USERS_DB = path.join(__dirname, 'users.json')
const CHATS_DB = path.join(__dirname, 'chats.json')
const MESSAGES_DB = path.join(__dirname, 'messages.json')
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
const sessionMiddleware = session({
genid: () => uuidv4(),
secret: 'super-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: true, // required for SameSite=None
sameSite: 'none', // allows third-party use in iframe
maxAge: 1000 * 60 * 60 * 2
}
})
app.use(sessionMiddleware)
function loadJSON(file) {
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf-8')) : []
}
function saveJSON(file, data) {
fs.writeFileSync(file, JSON.stringify(data, null, 2))
}
function generateSuffix() {
return Math.floor(1000 + Math.random() * 9000)
}
function normalizeUsername(name) {
return name.trim().toLowerCase()
}
// isAuthenticated middleware is now handled client-side for page display,
// but still used for API route protection.
function isAuthenticated(req, res, next) {
if (req.session && req.session.username) return next()
// For API calls, send 401. Client-side JS will handle redirect.
res.status(401).send('Unauthorized')
}
// share session middleware with socket.io
io.use((socket, next) => {
sessionMiddleware(socket.request, {}, next)
})
// Serve the single merged index.html
// Removed explicit routes for /login.html and /signup.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'))
})
// Signup route: now receives publicKey from client
app.post('/signup', async (req, res) => {
const { username, password, publicKey } = req.body // Receive publicKey from client
// reject if either username or password is too long
if (!username || !password || username.length > 200 || password.length > 200) {
return res.status(400).send('username and password must be less than 200 characters')
}
// Validate publicKey presence
if (!publicKey) {
return res.status(400).send('Public key is required for secure signup.')
}
const users = loadJSON(USERS_DB)
const baseName = normalizeUsername(username)
if (users.find(u => u.baseName === baseName)) {
return res.status(400).send('username taken')
}
const suffix = generateSuffix()
const hashedPassword = await bcrypt.hash(password, 10)
// Store publicKey received from client. privateKey is NOT stored on server.
users.push({ baseName, suffix, password: hashedPassword, publicKey })
saveJSON(USERS_DB, users)
res.status(200).send('Signup successful.')
})
app.post('/logout', (req, res) => {
req.session.destroy(() => {
res.clearCookie('connect.sid')
res.sendStatus(200)
})
})
// Login route: Authenticates user, sets session, does NOT send private key
app.post('/login', async (req, res) => {
const { username, password } = req.body
const users = loadJSON(USERS_DB)
const baseName = normalizeUsername(username)
const user = users.find(u => u.baseName === baseName)
if (!user) return res.status(401).send('User not found')
const match = await bcrypt.compare(password, user.password)
if (!match) return res.status(401).send('Invalid password')
req.session.username = user.baseName
// Private key is no longer stored in session or sent to client
res.status(200).send('Login successful')
})
// API routes for users, chats, messages
app.get('/api/users', isAuthenticated, (req, res) => {
const users = loadJSON(USERS_DB)
const filteredUsers = users.filter(u => u.baseName !== req.session.username)
res.json({
currentUser: req.session.username,
users: filteredUsers.map(u => ({ baseName: u.baseName, suffix: u.suffix, display: `${u.baseName}(${u.suffix})` }))
})
})
// New endpoint to get a user's public key
app.get('/api/user-public-key/:username', isAuthenticated, (req, res) => {
const { username } = req.params
const users = loadJSON(USERS_DB)
const user = users.find(u => normalizeUsername(u.baseName) === normalizeUsername(username))
if (user && user.publicKey) {
res.json({ publicKey: user.publicKey })
} else {
res.status(404).send('User or public key not found')
}
})
// Create chat route: receives already encrypted AES keys from client
app.post('/api/create-chat', isAuthenticated, (req, res) => {
const { users, name, encryptedKeys } = req.body // Receive encryptedKeys from client
const creator = normalizeUsername(req.session.username)
// Ensure creator is always included and that encryptedKeys are provided for all members
const chatMembers = [...new Set([creator, ...users.map(normalizeUsername)])]
if (!encryptedKeys || !Array.isArray(encryptedKeys) || encryptedKeys.length === 0) {
return res.status(400).send('Encrypted keys for chat members are required.')
}
// Validate that encryptedKeys contains entries for all chatMembers
const receivedMembers = new Set(encryptedKeys.map(k => k.memberUsername));
const missingKeys = chatMembers.filter(member => !receivedMembers.has(member));
if (missingKeys.length > 0) {
return res.status(400).send(`Missing encrypted keys for members: ${missingKeys.join(', ')}`);
}
const chats = loadJSON(CHATS_DB)
const chatId = uuidv4()
// Store encryptedKeys as an object for easy lookup by username
const encryptedKeysMap = encryptedKeys.reduce((acc, current) => {
acc[current.memberUsername] = current.encryptedAesKeyBase64;
return acc;
}, {});
chats.push({ chatId, name, members: chatMembers, encryptedKeys: encryptedKeysMap })
saveJSON(CHATS_DB, chats)
// Notify all chat members about the new chat
chatMembers.forEach(member => {
io.to(member).emit('chatCreated', { chatId, name }); // Emit chat details
});
res.status(200).send('Chat created')
})
app.get('/api/chats', isAuthenticated, (req, res) => {
const chats = loadJSON(CHATS_DB)
const userChats = chats.filter(chat => chat.members.includes(req.session.username))
res.json(userChats.map(chat => ({
chatId: chat.chatId,
name: chat.name || 'Unnamed Chat',
// Include the encrypted AES key for the current user for client-side decryption
encryptedAesKeyBase64: chat.encryptedKeys[req.session.username]
})))
})
// Send message route: receives encrypted content and IV from client
app.post('/api/send-message', isAuthenticated, (req, res) => {
const { chatId, encryptedContent, iv } = req.body // Receive encryptedContent and iv from client
if (!encryptedContent || !iv || encryptedContent.length > MAX_MESSAGE_LENGTH) {
return res.status(400).send('Encrypted message content or IV missing/too long.')
}
const username = req.session.username
// rate limit check
const now = Date.now()
if (!messageRateLimit[username]) {
messageRateLimit[username] = []
}
// keep only recent timestamps within the window
messageRateLimit[username] = messageRateLimit[username].filter(ts => now - ts < TIME_WINDOW_MS)
if (messageRateLimit[username].length >= MESSAGE_LIMIT) {
return res.status(429).send('Rate limit exceeded')
}
messageRateLimit[username].push(now)
const chats = loadJSON(CHATS_DB)
const chat = chats.find(c => c.chatId === chatId)
if (!chat || !chat.members.includes(username)) {
return res.status(403).send('Not allowed to send message to this chat.')
}
const messages = loadJSON(MESSAGES_DB)
messages.push({
chatId,
from: username,
iv: iv, // Store IV as-is (base64 string from client)
content: encryptedContent // Store encrypted content as-is (base64 string from client)
})
saveJSON(MESSAGES_DB, messages)
// notify all chat members
chat.members.forEach(member => {
io.to(member).emit('newMessage', {
chatId,
from: username,
iv: iv,
content: encryptedContent
})
})
res.status(200).send('Message sent')
})
// Get messages route: returns encrypted messages and encrypted AES key for client-side decryption
app.get('/api/messages/:chatId', isAuthenticated, (req, res) => {
const { chatId } = req.params
const messages = loadJSON(MESSAGES_DB).filter(m => m.chatId === chatId)
const chats = loadJSON(CHATS_DB)
const chat = chats.find(c => c.chatId === chatId)
if (!chat || !chat.members.includes(req.session.username)) {
return res.status(403).send('Unauthorized to view messages in this chat.')
}
const encryptedAesKeyBase64 = chat.encryptedKeys[req.session.username]
if (!encryptedAesKeyBase64) {
return res.status(500).send('Missing encrypted chat key for user.')
}
// Return encrypted messages and the encrypted AES key for the current user
res.json({
messages: messages.map(m => ({
from: m.from,
iv: m.iv,
content: m.content
})),
encryptedAesKeyBase64: encryptedAesKeyBase64
})
})
// socket.io connections
io.on('connection', socket => {
const session = socket.request.session
if (!session || !session.username) {
socket.disconnect()
return
}
const username = session.username
// join room with username for private messages
socket.join(username)
// join all chat rooms user is a member of
const chats = loadJSON(CHATS_DB)
chats.forEach(chat => {
if (chat.members.includes(username)) {
socket.join(chat.chatId)
}
})
// handle chat list refresh request from client
socket.on('refreshChats', () => {
socket.emit('chatsUpdated')
})
socket.on('disconnect', () => {
// handle if needed
})
})
server.listen(PORT, () => console.log(`running on http://localhost:${PORT}`))