-
Notifications
You must be signed in to change notification settings - Fork 0
/
rooms.ts
346 lines (329 loc) · 11.5 KB
/
rooms.ts
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
import express from 'express';
import type { Request, Response } from 'express';
import { limiter } from '../middleware';
import asyncHandler from 'express-async-handler';
import { PrismaClient } from '@prisma/client';
// import { verifyIdentityProof } from '../../crypto/idcVerifier/verifier';
import { pp } from '../../utils';
// import { IDCProof } from 'idc-nullifier/dist/types/types';
import { addRoomData } from '../../types';
import {
findRoomById,
// findRoomsByIdentity,
createRoom,
removeRoom,
removeMessage
} from '../../data/db/';
import { MessageI, RoomI } from 'discreetly-interfaces';
import { RLNFullProof } from 'rlnjs';
import basicAuth from 'express-basic-auth';
import { generateRandomClaimCode } from 'discreetly-claimcodes';
import { IDCProof } from 'idc-nullifier';
import { verifyIdentityProof } from '../../crypto/idcVerifier/verifier';
const router = express.Router();
const prisma = new PrismaClient();
const adminPassword = process.env.PASSWORD
? process.env.PASSWORD
: // eslint-disable-next-line @typescript-eslint/no-unsafe-call
(generateRandomClaimCode(4) as string);
const adminAuth = basicAuth({
users: {
admin: adminPassword
}
});
// This code gets a room by its ID, and then checks if room is null.
// If room is null, it returns a 500 error.
// Otherwise, it returns a 200 status code and the room object.
router.get('/:id', limiter, (req, res) => {
if (!req.params.id) {
res.status(400).json({ error: 'Bad Request' });
} else {
const requestRoomId = req.params.id ?? '0';
pp(String('Express: fetching room info for ' + req.params.id));
findRoomById(requestRoomId)
.then((room: RoomI) => {
if (!room) {
res.status(500).json({ error: 'Internal Server Error' });
} else {
const {
roomId,
name,
rateLimit,
userMessageLimit,
membershipType,
adminIdentities,
identities,
bandadaAddress,
bandadaGroupId,
encrypted,
ephemeral
} = room || {};
const id = String(roomId);
const roomResult: RoomI = {
id,
roomId,
name,
rateLimit,
userMessageLimit,
membershipType,
adminIdentities,
encrypted,
ephemeral
};
// Add null check before accessing properties of room object
if (membershipType === 'BANDADA_GROUP') {
roomResult.bandadaAddress = bandadaAddress;
roomResult.bandadaGroupId = bandadaGroupId;
}
if (membershipType === 'IDENTITY_LIST') {
roomResult.identities = identities;
}
res.status(200).json(roomResult);
}
})
.catch((err) => console.error(err));
}
});
/** createRoom is used to create a new room in the database
* @param {string} roomName - The name of the room
* @param {number} rateLimit - The rate limit of the room
* @param {number} userMessageLimit - The user message limit of the room
* @param {number} numClaimCodes - The number of claim codes to generate
* @param {number} approxNumMockUsers - The approximate number of mock users to generate
* @param {string[]} adminIdentities - The identities of the admins of the room
* @param {string} type - The type of room
* @param {string} bandadaAddress - The address of the Bandada group
* @param {string} bandadaGroupId - The id of the Bandada group
* @param {string} bandadaAPIKey - The API key of the Bandada group
* @param {string} membershipType - The type of membership
* @param {string} roomId - The id of the room
* @param {string[]} discordIds - The ids of the discord users to add to the room
* @returns {void}
* @example {
* "roomName": "string",
* "rateLimit": number,
* "userMessageLimit": number,
* "numClaimCodes": number, // optional
* "approxNumMockUsers": number, // optional
* "adminIdentities": string[], // optional
* "roomType": "string", // optional
* "bandadaAddress": "string", // optional
* "bandadaGroupId": "string", // optional
* "bandadaAPIKey": "string", // optional
* "membershipType": "string" // optional if not an IDENTITY_LIST
* "roomId": "string", // optional
* "discordIds": string[] // optional
* }
*/
router.post('/add', adminAuth, (req, res) => {
const roomMetadata = req.body as unknown as addRoomData;
const roomName = roomMetadata.roomName;
const rateLimit = roomMetadata.rateLimit;
const userMessageLimit = roomMetadata.userMessageLimit;
const numClaimCodes = roomMetadata.numClaimCodes ?? 0;
const adminIdentities = roomMetadata.adminIdentities;
const approxNumMockUsers = roomMetadata.approxNumMockUsers;
const type = roomMetadata.roomType as unknown as string;
const bandadaAddress = roomMetadata.bandadaAddress;
const bandadaGroupId = roomMetadata.bandadaGroupId;
const bandadaAPIKey = roomMetadata.bandadaAPIKey;
const membershipType = roomMetadata.membershipType;
const roomId = roomMetadata.roomId;
createRoom(
roomName,
rateLimit,
userMessageLimit,
numClaimCodes,
approxNumMockUsers,
type,
adminIdentities,
bandadaAddress,
bandadaGroupId,
bandadaAPIKey,
membershipType,
roomId
)
.then((result) => {
const response =
result === null
? { status: 400, message: 'Room already exists' }
: result
? {
status: 200,
message: 'Room created successfully',
roomId: result.roomId,
claimCodes: result.claimCodes
}
: { status: 500, error: 'Internal Server Error' };
res.status(response.status).json(response);
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: String(err) });
});
});
/**
* This code is used to delete a room from the database.
* It takes in the roomId from the request body, and pass it to the removeRoom function.
* If removeRoom returns true, it means the room is deleted successfully, and the server returns a 200 status code.
* If removeRoom returns false, the server returns a 500 status code.
* If removeRoom throws an error, the server returns a 500 status code.
* @param {string} roomId - The id of the room to be deleted
* @returns {void}
* */
router.post('/:roomId/delete', adminAuth, (req: Request, res: Response) => {
const { roomId } = req.body as { roomId: string };
removeRoom(roomId)
.then((result) => {
if (result) {
res.status(200).json({ message: 'Room deleted successfully' });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: String(err) });
});
});
/**
* This code deletes a message from a room
* It takes in the roomId and messageId from the request body, and pass it to the removeMessage function.
* If removeMessage returns true, it means the message is deleted successfully, and the server returns a 200 status code.
* If removeMessage returns false, the server returns a 500 status code.
* If removeMessage throws an error, the server returns a 500 status code.
* @param {string} roomId - The id of the room to be deleted
* @param {string} messageId - The id of the message to be deleted
* @returns {void}
* */
router.post('/:roomId/message/delete', adminAuth, (req, res) => {
const { roomId } = req.params;
const { messageId } = req.body as { messageId: string };
removeMessage(roomId, messageId)
.then((result) => {
if (result) {
res.status(200).json({ message: 'Message deleted successfully' });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: String(err) });
});
});
/**
* This code handles the get request to get a list of messages for a particular room.
* It uses the Prisma client to query the database and return the messages for a particular room.
* It also parses the proof from a string to a JSON object.
* @param {string} id - The id of the room to get messages for
* @returns {void}
*/
router.get('/:id/messages', limiter, (req, res) => {
const { id } = req.params;
prisma.messages
.findMany({
take: 500,
orderBy: {
timeStamp: 'desc'
},
where: {
roomId: id
},
select: {
id: false,
message: true,
messageId: true,
proof: true,
roomId: true,
timeStamp: true,
sessionId: true,
messageType: true
}
})
.then((messages) => {
messages.map((message: MessageI) => {
message.timeStamp = new Date(message.timeStamp as Date).getTime();
message.proof = JSON.parse(message.proof as string) as RLNFullProof;
message.epoch = message.proof.epoch;
});
pp('Express: fetching messages for room ' + id);
res.status(200).json(messages.reverse());
})
.catch((error: Error) => {
pp(error, 'error');
res.status(500).send('Error fetching messages');
});
});
router.post('/checkpasswordhash/:id', limiter, (req: Request, res: Response) => {
const { id } = req.params;
const { passwordHash } = req.body as { passwordHash: string };
prisma.rooms
.findUnique({
where: {
roomId: id
},
select: {
passwordHash: true,
encrypted: true
}
})
.then((room) => {
if (room && !room.passwordHash && room.encrypted === 'AES') {
res.status(200).json({ success: false, message: 'Room is not initialized, no password set' });
return;
}
if (room && room.passwordHash === passwordHash) {
res.status(200).json({ success: true });
} else {
res.status(400).json({ success: false });
}
})
.catch((error: Error) => {
pp(error, 'error');
res.status(500).send('Error fetching room');
});
})
router.post('/setpassword/:id', limiter, asyncHandler(async (req: Request, res: Response) => {
const { id } = req.params;
const { passwordHash, proof } = req.body as { passwordHash: string, proof: IDCProof };
const isValid = await verifyIdentityProof(proof);
if (isValid) {
prisma.rooms.findUnique({
where: {
roomId: id
},
select: {
adminIdentities: true
}
}).then((room) => {
if (room) {
if (!room.adminIdentities.includes(proof.publicSignals.identityCommitment)) {
res.status(401).json({ success: false, message: 'Identity not authorized' });
return;
}
prisma.rooms.update({
where: {
roomId: id
},
data: {
passwordHash
}
}).then(() => {
res.status(200).json({ success: true, message: 'Password set successfully' });
}).catch((error: Error) => {
pp(error, 'error');
res.status(500).json({ success: false, message: 'Error setting password' });
})
} else {
res.status(500).json({ success: false, message: 'Error finding room' });
}
}).catch((error: Error) => {
pp(error, 'error');
res.status(500).send('Error finding room');
})
} else {
res.status(401).json({ success: false, message: 'Unauthorized' });
}
}))
export default router;