Node express + websockets with REST route to send/receive websocket messages - node.js

Using node, I'm trying to create a server in express with a route for websockets and a REST route to send and receive websocket messages. Basically, it should work like this:
A client connects to the server via http://localhost:3000/client.
The server returns a JS script
The script sets a cookie and establishes a websocket connection back to the server via ws://localhost:3000/websocket
The script is also set to reply to websocket messages with document.cookie
The websocket connection assigns a UID to the client
A GET request is made by a different system to http://localhost:3000/api?uid= (clientUID = someUID in this example)
The server loops through all websocket clients to find the correct client/UID
A message is sent to the client
The client responds with document.cookie
The server responds to the GET request with the message returned to the websocket server
The last part is what isn't working. How can I capture the message returned to the websocket server and send it as a response to requests to the /api route?
const express = require('express');
const WebSocketServer = require('ws');
const http = require("http");
const app = express();
const server = http.createServer(app);
const port = 3000;
server.listen(port);
const wss = new WebSocketServer.Server({ server: server, path: '/websocket' });
// Each new websocket will be given a UID. This example uses a static UID of
// `someUID` for convenience
wss.on("connection", function connection(ws, req) {
ws.uid = 'someUID';
ws.on("message", data => {
// I want to send this data as a response to calls to `/api`
console.log(`${data}`);
});
});
// This route sends a message to the client specified by the `uid` URL param.
// The client will respond (above) with the value of `document.cookie`
app.get('/api', (req, res) => {
wss.clients.forEach(function (client) {
if (client.uid == req.query.uid) {
// I want to send the response of this message via `res.send()`
client.send();
}
});
});
// Set up a client with a cookie and establish a websocket connection. When the
// client receives a message, it should return document.cookie.
app.get('/client', (req, res) => {
res.send(' \
<script> \
document.cookie = "cookieName=cookieValue;"; \
let url = "ws://localhost:3000/websocket"; \
let connection = new WebSocket(url); \
connection.onmessage = (e) => { \
connection.send(document.cookie); \
} \
</script> \
')
});

Related

How to prevent people from connecting to any id with sockeIO?

I just set up SocketIO in my PHP project. I am completly new to websockets at all so bear with me.
I am defining the socketIO variable globally
let socketIO = io("http://localhost:3000");
When people are logging in to my application, they are connected to it with their ID comming from the database. The login script just gives back true which redirects the user in very simplified terms:
// get component
$.get(url, data, (data) => {
if (data.status) {
// connect with Node JS server
socketIO.emit("connected", data.user_id);
// redirect
load_new_page("/users/" + data.user_id);
}
});
My concern here now is that people could just go and change the data.user_id to anything they want and receive what ever the chosen id would receive.
My server.js:
// initialize express server
var express = require("express");
var app = express();
// create http server from express instance
var http = require("http").createServer(app);
// include socket IO
var socketIO = require("socket.io")(http, {
cors: {
origin: ["http://localhost"],
},
});
// start the HTTP server at port 3000
http.listen(process.env.PORT || 3000, function () {
console.log("Server started running...");
// an array to save all connected users IDs
var users = [];
// called when the io() is called from client
socketIO.on("connection", function (socket) {
// called manually from client to connect the user with server
socket.on("connected", function (id) {
users[id] = socket.id;
});
});
});
How can I prevent something like this?

How to send websocket message to client from the serverside

Hello I have two backends laravel and Nodejs
and There will be one frontend.
So if the front end requests something on laravel and laravel requests to node and Node has to send a message to the client through WebSocket.
How to do It?
Index.js
const app = require('express')();
const http = require('http');
const WebSocket = require('ws')
//initialize a simple http server
const server = http.createServer(app);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
let sendNotification;
//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });
let socketapi = require('./socketapi')
socketapi.start(wss)
//start our server
server.listen(process.env.PORT || 5555, () => {
console.log(`Server started on port ${server.address().port} :)`);
});
socketapi.js
module.exports ={
start: (wss) => {
wss.on('connection', (ws) => {
console.log('connected!!!');
console.log(socketIds)
//connection is up, let's add a simple simple event
// triggerMessage('data');
ws.id=uuidv4()
ws.on('message', (message) => {
console.log('received: %s', message);
// ws.send(`Hello, you sent -> ${message}`);
});
}
}
}
Now I want to use this socket in the controller file and send it as I get a request.
When I export and import socket it logs as undefined.
I have stored and ws in array with particular Id and that Id was associated with data in DB so I can use that Id to get ws and send through that ws on function calling

SocketIO send message to client via API route

I have a route in my express API where I want to emit messages using a websocket to a client. In this case, the client is another Node.js app. In this Node.js app, I try to connect to the socket and print messages received. Both the API and the Node app are on different ports. Can someone help me make this work?
Here's how I pass my socket to my express routes:
const server = app.listen(PORT, () => {
console.log(`Server on port ${PORT}`);
});
const io = require("socket.io")(server);
app.set("socketio", io);
Here's my REST API route:
exports.getAll = function(req,res){
var io = req.app.get('socketio');
io.emit('hi!');
}
Here's my socket io client, it uses socket.io-client
const socket = io('http://localhost:3000');
socket.on("message", data => {
console.log(data);
});
Unfortunately, I don't receive the 'hi' message from my API.
When I call /api/getAll I don't receive the message in my client app.
When emitting an event via socket.io you have you define the event name before the data.
Example:
exports.getAll = function(req, res){
var io = req.app.get("socketio");
io.emit("message", "hi!");
}
Now you'll be able to receive the message event from the client.
Reference:
https://socket.io/docs/v4/emitting-events/

WebSocket in Node routes

I have a REST API backend. I'm trying to send WebSocket messages back to the client app when a site administrator invokes a route (i.e. updates user credentials);
let express = require("express");
let router = express.Router();
//update user credentials
router.put('/admin/user/:id', (req, res)=>{
// 1. Admin updates target user's profile/credentials
// 2. WebSocket message sent to target user client
// 3. Route sends res.status(200) to admin
});
I've seen a few WebSocket examples using 'ws', 'net', 'websocket' libraries, but they all show a simple event handling socket server that responds to socket messages outside of any express routes - let alone responds to a separate client.
Also, the event notification should be visible only to the target user and not all the other users connected to the socket server.
Figured it out. The WebSocket server is independent of the route.
const WebSocket = require("ws");
const wss = new WebSocket.Server({port: 5555});
// handle socket communications
wss.on('connection', (session)=> {
session.send("HELLO SESSION: "+ session.userid);
session.on('message', (message)=> {
console.log(`MSG: "${message}" recived.`);
session.send("Got it.");
});
});
// close
wss.on('close', function close() {
clearInterval(interval);
});
module.exports = wss;
Then, in the route, just include the service and use it to iterate through web socket connections like so:
let wss = require('./mysocketservice')
...
function sendAMessageTo(user, msg) {
wss.clients.forEach(function each(s) {
if(session.user = user)
session.send("still there?.. ");
}
}

Node.js http module doesn't receive WS request (using https-proxy-agent)

The concept is simple, creating a http server that forward websocket request to another port.
Here is the code on my server side:
http.createServer(onRequest).listen(9999);
function onRequest(request, response) {
console.log(request);
...
}
So if the http server receive any request at all it should print out the request in console.
Then on the client side (also a node.js application), the code is:
var HttpsProxyAgent = require('https-proxy-agent');
var WebSocket = require('ws');
...
var proxy = `http://${config.proxy.host}:${config.proxy.port}`;
var options = url.parse(proxy);
agent = new HttpsProxyAgent(options);
ws = new WebSocket(target, {
protocol: 'binary',
agent: agent
});
Now, when I use Charles to intercept the request, the client did indeed emit a request, here is the curl form captured by Charles:
curl -H 'Host: target.host.com:8080' -X CONNECT 'https://target.host.com:8080'
the problem seems to be that
function onRequest(request, response) {
console.log(request);
...
}
didn't actually receive any -X CONNECT 'https://proxy.host.com:9999' request, or at least it didn't print it out (obviously it didn't work either).
var server = http.createServer(onRequest).listen(9999);
server.on('connect', (req, cltSocket, head) => {
const srvSocket = net.connect('8080', '127.0.0.1', () => {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
srvSocket.write(head);
srvSocket.pipe(cltSocket);
cltSocket.pipe(srvSocket);
});
});

Resources