Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reminder: Suggested handleUpgrade and connection flow #2

Closed
trasherdk opened this issue Dec 6, 2021 · 2 comments
Closed

Reminder: Suggested handleUpgrade and connection flow #2

trasherdk opened this issue Dec 6, 2021 · 2 comments

Comments

@trasherdk
Copy link
Owner

It's probably a good idea to stick to something like this:

import WebSocket from 'ws';
import { createServer } from 'http';

const server = createServer();
const wss = new WebSocketServer({ noServer: true });

server.on('upgrade', function upgrade(request, socket, head) {
  // This function is not defined on purpose. Implement it with your own logic.
  authenticate(request, (err, client) => {
    if (err || !client) {
      socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
      socket.destroy();
      return;
    }

    wss.handleUpgrade(request, socket, head, function done(ws) {
      // You are done. `ws` is your `WebSocket` instance, you can do
      // whatever you want with it.
    });
  });
});

server.listen(8080);

as discussed in websockets#1966 (comment)

Same discussion, just older: websockets#377 (comment)

const http = require('http');
const WebSocket = require('ws');

const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });

wss.on('connection', function connection(ws, request, ...args) {
  // ...
});

server.on('upgrade', async function upgrade(request, socket, head) {
  // Do what you normally do in `verifyClient()` here and then use
  // `WebSocketServer.prototype.handleUpgrade()`.
  let args;

  try {
    args = await getDataAsync();
  } catch (e) {
    socket.destroy();
    return;
  }

  wss.handleUpgrade(request, socket, head, function done(ws) {
    wss.emit('connection', ws, request, ...args);
  });
});

server.listen(8080);
@trasherdk
Copy link
Owner Author

trasherdk commented Dec 6, 2021

And an even older suggestion, with some potential: websockets#377 (comment)

const userRequestMap = new WeakMap();
const WebSocket = require('ws');

const wss = new WebSocket.Server({
    port,
    verifyClient: (info, done) => {
        const user = authenticateUser(info);
        userRequestMap.set(info.req, user);
        done(user !== null);
    },
});

wss.on('connection', (connection, request) =>{
    const user = userRequestMap.get(request);
});

EDIT: Change server to wss for consistency.

@trasherdk
Copy link
Owner Author

Another one, pretty much the same as the userRequestMap above. From: websockets#377 (comment)

const { WebSocketServer } = require('ws');

const wss = new WebSocketServer({
  port: 8080, verifyClient: async ({ req }, cb) => {
    const { headers } = req;
    if (headers.token) {
      const decodedToken = await decodeToken(headers.token);
      // req.headers.decodedToken = JSON.stringify(decodedToken);
      // As noted. The token can just as well be added directly to req
      req.decodedToken = JSON.stringify(decodedToken);
      cb(true);
    } else {
      cb(false, 401, 'Unauthorized');
    }
  }
});

wss.on('connection', (ws, req)=> {
  console.log("on Connection decodedToken ==> ", JSON.parse(req.decodedToken));
});

Need expansion in the if (headers.token) block. Error handling, wrapping in try / catch or chaining.

Repository owner locked and limited conversation to collaborators Mar 22, 2022
@trasherdk trasherdk converted this issue into discussion #7 Mar 22, 2022
@trasherdk trasherdk reopened this May 5, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant