Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,13 @@ cd sarge/

```sh
pnpm install
cd src/ws && pnpm install
```

3. Setup the .env file

```
# in the project's root directory
mv .env.example .env
```

Expand Down
2 changes: 1 addition & 1 deletion src/ws/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ RUN corepack enable pnpm
COPY package.json index.js pnpm-lock.yaml* ./
RUN pnpm install

CMD ["node", "index.js"]
CMD ["node", "index.js"]
79 changes: 76 additions & 3 deletions src/ws/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,82 @@
import { WebSocketServer } from 'ws';
import { jwtVerify } from 'jose';

const ws = new WebSocketServer({ port: 8080 });
const secret = new TextEncoder().encode(process.env.JWT_SECRET);

ws.on('connection', (ws) => {
ws.on('message', (data) => {
ws.send(data.toString('utf-8'));
console.log('Sarge WS server listening on 8080');

// <userId, socket>
const clients = new Map();

const HEARTBEAT_INTERVAL = 5000;

function getTokenFromRequest(request) {
return new URL(request.url ?? '/', 'ws://x').searchParams.get('token');
}

async function verifyToken(token) {
const { payload } = await jwtVerify(token, secret);
return payload;
}

function startHeartbeat(socket) {
return setInterval(() => {
if (!socket.isAlive) {
// TODO: add an offline timer before the socket gets terminated unique to each user
// Once done, send an API request back to server to end the OA

// terminate() jumps to socket.on('close')
socket.terminate();
return;
}
socket.isAlive = false;
socket.ping();
}, HEARTBEAT_INTERVAL);
}

ws.on('connection', async (socket, request) => {
const token = getTokenFromRequest(request);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where does the token get initially added to the connection request? I'm assuming this is something we will set up when configuring the websocket on the client (aka in the react code)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah the token will be generated using our client and API. As long as the secrets are the same, this will be a successful operation. If not, then the catch will drop the connection.

try {
const payload = await verifyToken(token ?? '');
socket.userId = payload.userId;
socket.isAlive = true;
clients.set(payload.userId, socket);
} catch {
socket.close(1008, 'Unauthorized');
return;
}

socket.heartbeat = startHeartbeat(socket);

socket.on('message', (data) => {
socket.send(data.toString('utf-8'));
});

socket.on('pong', () => {
socket.isAlive = true;
});

socket.on('close', (code, reason) => {
if (!socket.userId) return;
clearInterval(socket.heartbeat);
clients.delete(socket.userId);
console.log(
`Client ${socket.userId} disconnected | code: ${code}, reason: ${reason.toString()}`
);
});

socket.on('error', (err) => {
console.error(`Socket error for ${socket.userId}:`, err.message);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to send an error message to our main server if it's broken? Lmk if this is even feasible.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Let's add this when developing the client side logic.

});
});

ws.on('error', (err) => {
console.error('Socket error: ', err);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

});

ws.on('close', () => {
for (const socket of clients.values()) {
socket.close(1001, 'Shutting down server');
}
});
7 changes: 6 additions & 1 deletion src/ws/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"jose": "^6.2.2",
"ws": "^8.20.0"
},
"devDependencies": {
"nodemon": "^3.1.14"
}
}
Loading
Loading