diff --git a/package-lock.json b/package-lock.json index 2fe5972..ce6b68e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,7 @@ "body-parser": "^1.20.2", "cors": "^2.8.5", "discreetly-claimcodes": "^1.1.3", - "discreetly-interfaces": "^0.1.22", + "discreetly-interfaces": "^0.1.23", "dotenv": "^16.3.1", "express": "^4.18.2", "express-basic-auth": "^1.2.1", @@ -5454,9 +5454,9 @@ "integrity": "sha512-2QnlhYUPIGLl11XgxIxl6ZKIJZoS2T1ABIHbqjBbec0YYQ2qfWZ7JWH53OZm0mqeO8Dbjon5zK3YNoGiuYJ1Gg==" }, "node_modules/discreetly-interfaces": { - "version": "0.1.22", - "resolved": "https://registry.npmjs.org/discreetly-interfaces/-/discreetly-interfaces-0.1.22.tgz", - "integrity": "sha512-p7HuKOE0Zan3Nf3Rg6auzsxNeKrtH4GMRoSMhsb+6YGO9AlF6ffnlHV4L4SSxLbJr2XInGEf0TUzsKkXwkQKoQ==", + "version": "0.1.23", + "resolved": "https://registry.npmjs.org/discreetly-interfaces/-/discreetly-interfaces-0.1.23.tgz", + "integrity": "sha512-C1mqzLZY52aW83XHUBr3lxe8F7HFagx4V+MzigxPf5GTjDGhelIbnmihhV3RUtWb1uddo1Gm1CImD+meygf1bg==", "dependencies": { "poseidon-lite": "^0.2.0", "rlnjs": "^3.1.4" diff --git a/package.json b/package.json index d0de8aa..a2377b4 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "body-parser": "^1.20.2", "cors": "^2.8.5", "discreetly-claimcodes": "^1.1.3", - "discreetly-interfaces": "^0.1.22", + "discreetly-interfaces": "^0.1.23", "dotenv": "^16.3.1", "express": "^4.18.2", "express-basic-auth": "^1.2.1", diff --git a/src/config/serverConfig.ts b/src/config/serverConfig.ts index cb01e4a..24acfbb 100644 --- a/src/config/serverConfig.ts +++ b/src/config/serverConfig.ts @@ -1,21 +1,24 @@ import type { ServerI } from 'discreetly-interfaces'; import 'dotenv/config'; -// TODO THIS SHOULD BE AN ENVIRONMENTAL VARIABLE STORED IN .env FILE -// IF THIS FILE DOESN'T EXIST, GENERATE A RANDOM ID AND STORE IT IN THE FILE -let serverID: bigint; +let SERVER_ID: bigint; +let NAME: string; try { - serverID = process.env.SERVERID ? (process.env.SERVERID as unknown as bigint) : 0n; + SERVER_ID = process.env.SERVER_ID ? (process.env.SERVER_ID as unknown as bigint) : 0n; } catch (error) { console.error('Error reading serverID from .env file!'); } -console.log('SERVERID:', serverID); +console.log('SERVERID:', SERVER_ID); + +try { + NAME = process.env.SERVER_NAME ? process.env.SERVER_NAME : 'localhost'; +} catch (err) { + console.error('Error reading PORT from .env file!'); +} export const serverConfig: ServerI = { - id: serverID, - name: 'Localhost', - serverInfoEndpoint: 'localhost:3001', - messageHandlerSocket: 'localhost:3002', - version: '0.0.1' + id: SERVER_ID, + name: NAME, + version: '0.0.2' }; diff --git a/src/data/db.ts b/src/data/db.ts index 22a33e8..70f6544 100644 --- a/src/data/db.ts +++ b/src/data/db.ts @@ -42,26 +42,61 @@ export function getRoomByID(id: string): Promise | null { }); } -export function getRoomsByIdentity(identity: string): RoomI[] { +export async function getRoomsByIdentity(identity: string): Promise { /* TODO Need to create a system here where the client needs to provide a proof they know the secrets to some Identity Commitment with a unix epoch time stamp to prevent replay attacks + + https://github.com/Discreetly/IdentityCommitmentNullifierCircuit <- Circuit and JS to do this */ - prisma.rooms - .findMany({ + const r: string[] = []; + try { + const rooms = await prisma.rooms.findMany({ where: { identities: { has: identity } } - }) - .then((rooms) => { - return rooms.map((room) => { - room.roomId; - }); - }) - .catch((err) => console.error(err)); - return []; + }); + rooms.forEach((room) => { + r.push(room.roomId); + }); + console.log(r); + return r; + } catch (err) { + console.error(err); + return []; + } +} + +export function findClaimCode(code: string): Promise { + return prisma.claimCodes.findUnique({ + where: { claimcode: code } + }); +} + +export function updateClaimCode(code: string): Promise { + return prisma.claimCodes.update({ + where: { claimcode: code }, + data: { claimed: true } + }); +} + +export function updateRoomIdentities(idc: string, roomIds: string[]): Promise { + return prisma.rooms.updateMany({ + where: { id: { in: roomIds } }, + data: { + identities: { + push: idc + } + } + }); +} + +export function findUpdatedRooms(roomIds: string[]): Promise { + return prisma.rooms.findMany({ + where: { id: { in: roomIds } } + }); } /** @@ -107,33 +142,3 @@ export async function createRoom( .catch((err) => console.error(err)); return false; } - -export function findClaimCode(code: string): Promise { - return prisma.claimCodes.findUnique({ - where: { claimcode: code } - }); -} - -export function updateClaimCode(code: string): Promise { - return prisma.claimCodes.update({ - where: { claimcode: code }, - data: { claimed: true } - }); -} - -export function updateRoomIdentities(idc: string, roomIds: string[]): Promise { - return prisma.rooms.updateMany({ - where: { id: { in: roomIds } }, - data: { - identities: { - push: idc - } - } - }); -} - -export function findUpdatedRooms(roomIds: string[]): Promise { - return prisma.rooms.findMany({ - where: { id: { in: roomIds } } - }); -} diff --git a/src/endpoints/index.ts b/src/endpoints/index.ts index 4ff2e4b..dadb783 100644 --- a/src/endpoints/index.ts +++ b/src/endpoints/index.ts @@ -22,7 +22,7 @@ export function initEndpoints(app: Express, adminAuth: RequestHandler) { res.status(200).json(serverConfig); }); - app.get('/api/room/:id', (req, res) => { + app.get(['/room/:id', '/api/room/:id'], (req, res) => { pp(String('Express: fetching room info for ' + req.params.id)); getRoomByID(req.params.id) .then((room: RoomI) => { @@ -36,14 +36,15 @@ export function initEndpoints(app: Express, adminAuth: RequestHandler) { .catch((err) => console.error(err)); }); - app.get('/api/rooms/:idc', (req, res) => { + app.get(['/rooms/:idc', '/api/rooms/:idc'], (req, res) => { pp(String('Express: fetching rooms by identityCommitment ' + req.params.idc)); res.json(getRoomsByIdentity(req.params.idc)); }); - app.post('/join', (req, res) => { - const { code, idc }: { code: string; idc: string } = req.body; + app.post(['/join', '/api/join'], (req, res) => { + const { code, idc }: { code: string; idc: string } = req.body; + console.log('Invite Code:', code); findClaimCode(code) .then((codeStatus) => { if (codeStatus && codeStatus.claimed === false) { @@ -69,7 +70,7 @@ export function initEndpoints(app: Express, adminAuth: RequestHandler) { }); /* ~~~~ ADMIN ENDPOINTS ~~~~ */ - app.post('/room/add', adminAuth, (req, res) => { + app.post(['/room/add', '/api/room/add'], adminAuth, (req, res) => { interface RoomData { roomName: string; rateLimit: number; @@ -94,7 +95,26 @@ export function initEndpoints(app: Express, adminAuth: RequestHandler) { } }); - app.get('/logclaimcodes', adminAuth, (req, res) => { + app.get('/api/room/:id/messages', (req, res) => { + const { id } = req.params; + prisma.messages + .findMany({ + where: { + roomId: id + } + }) + .then((messages) => { + pp('Express: fetching messages for room ' + id) + res.status(200).json(messages); + }) + .catch((error: Error) => { + pp(error, 'error') + res.status(500).send('Error fetching messages'); + }); + }) + + app.get(['/logclaimcodes', '/api/logclaimcodes'], adminAuth, (req, res) => { + pp('Express: fetching claim codes'); prisma.claimCodes .findMany() @@ -107,7 +127,7 @@ export function initEndpoints(app: Express, adminAuth: RequestHandler) { }); }); - app.get('/api/rooms', adminAuth, (req, res) => { + app.get(['/rooms', '/api/rooms'], adminAuth, (req, res) => { pp(String('Express: fetching all rooms')); prisma.rooms .findMany() diff --git a/src/server.ts b/src/server.ts index 5c0c6f5..d2cc29b 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,10 +1,9 @@ -import { Server } from 'http'; import express from 'express'; +import http from 'http'; import cors from 'cors'; import helmet from 'helmet'; import basicAuth from 'express-basic-auth'; import { Server as SocketIOServer } from 'socket.io'; - import { serverConfig } from './config/serverConfig'; import { pp, shim } from './utils'; import mock from './data/mock'; @@ -16,7 +15,6 @@ import { listEndpoints } from './endpoints/utils'; // TODO https://www.npmjs.com/package/winston const app = express(); -const socket_server = new Server(app); shim(); app.use(express.json()); @@ -39,23 +37,11 @@ const adminAuth = basicAuth({ } }); -const io = new SocketIOServer(socket_server, { - cors: { - origin: '*' - } -}); - -function initAppListeners() { - const expressServerPort = serverConfig.serverInfoEndpoint.split(':')[1]; - const socketServerPort = serverConfig.messageHandlerSocket.split(':')[1]; - app.listen(expressServerPort, () => { - pp(`Express Http Server is running at port ${expressServerPort}`); +function initAppListeners(PORT) { + const httpServer = http.createServer(app).listen(PORT, () => { + pp(`Server is running at port ${PORT}`); }); - - socket_server.listen(socketServerPort, () => { - pp(`SocketIO Server is running at port ${socketServerPort}`); - }); - return app; + return app } /** @@ -64,17 +50,19 @@ function initAppListeners() { let _app if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') { console.log('~~~~DEVELOPMENT MODE~~~~'); - initWebsockets(io); + console.log(serverConfig); + const PORT = 3001; initEndpoints(app, adminAuth); - listEndpoints(app); - _app = initAppListeners(); - mock(io); + _app = initAppListeners(PORT); + initWebsockets(_app); + listEndpoints(_app); + mock(_app); // TODO! This is dangerous and only for development console.log('Admin password: ' + admin_password); } else { - initWebsockets(io); initEndpoints(app, adminAuth); - _app = initAppListeners(); + _app = initAppListeners(process.env.PORT); + initWebsockets(_app); }