Skip to content
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

Firefox can't establish a connection to the server at wss://localhost/peerjs?key=peerjs&id=ZNfSEBbys&token=cklszm3tnu. #239

Open
CuAnnan opened this issue Mar 6, 2021 · 13 comments
Labels

Comments

@CuAnnan
Copy link

CuAnnan commented Mar 6, 2021

const createError = require('http-errors');
const express = require('express');
const session = require('express-session');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const debug = require('debug')('nodesaken:server');
const MongoDBStore = require('connect-mongodb-session')(session);
const mongoose = require('mongoose');
const app = express();
const conf = require('./conf.js');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;


// CORS
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use(session({
    'secret':conf.sessionSecret,
    resave: false,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

require('./passportConfig')(passport);



/*
 * Exposing request to locals
 */
app.use(function(req, res, next) {
    app.locals.user = req.user;
    next();
})



/*
 * Routes
 */
const indexRouter = require('./routes/index')(app, passport);
const usersRouter = require('./routes/users')(app, passport);
app.use('/', indexRouter);
app.use('/users', usersRouter);

let peer = ExpressPeerServer(app,{debug:true});
peer.on('connection', (client)=>{
    console.log('Have client connection');
});
app.use('/peerjs', peer);



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});




debug("Hoisting Mongoose");

mongoose.Promise = global.Promise;
mongoose.connect(conf.mongoose.getURI(), {useNewUrlParser:true, useFindAndModify: false, useUnifiedTopology:true})
    .then(
        ()=>{
          debug('Mongoose raised');
        }
    ).catch(
    (err)=>{
      debug(err);
    }
);
debug("Mongoose hoisted");

module.exports = app;

www.js, which is what is run by npm looks like so


/**
 * Module dependencies.
 */

const app = require('../app');
const debug = require('debug')('imbas:server');
const https = require('https');
const fs = require('fs');


/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '443');
app.set('port', port);

/**
 * Create HTTPS server.
 */
let privateKey = fs.readFileSync('./ssh/key.pem');
let certificate = fs.readFileSync('./ssh/cert.pem');
let ssl = {
    key: privateKey,
    cert: certificate
};

var httpsServer = https.createServer(ssl,app);


httpsServer.listen(port);
httpsServer.on('error', onError);
httpsServer.on('listening', onListening);


/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = httpsServer.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

The front end code looks like

<script src="/js/peerjs.min.js"></script>
<script type="text/javascript">
    (function($) {
        $(function() {
            console.log("Onload event fired");
            const peer = new Peer(
                    '<%- peerId %>',
                    {
                        host:'localhost',
                        path:'/',
                        port:443
                    }
            );
            peer.on('open', function (id) {
                console.log("Peer connection up and running");
            });
        });
    })(window.jQuery);
</script>

https://localhost/peerjs returns the expected JSON

Any attempt to hoist a peerjs connection fails.

@CuAnnan
Copy link
Author

CuAnnan commented Mar 6, 2021

Response headers to wss://localhost/peerjs?key=peerjs&id=ZNfSEBbys&token=5h161q1gq5m

X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Content-Type: application/json; charset=utf-8
Content-Length: 140
ETag: W/"8c-OP0zOSq0rX5Ungn973BP6obbpvw"
Date: Sat, 06 Mar 2021 00:50:44 GMT
Connection: keep-alive
Keep-Alive: timeout=5```

@CuAnnan
Copy link
Author

CuAnnan commented Mar 6, 2021

Request headers

GET /peerjs?key=peerjs&id=ZNfSEBbys&token=5h161q1gq5m HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0
Accept: */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate, br
Sec-WebSocket-Version: 13
Origin: https://localhost
Sec-WebSocket-Extensions: permessage-deflate
Sec-WebSocket-Key: zFe2XGvoXp3MyZYltsfI6w==
Connection: keep-alive, Upgrade
Cookie: Webstorm-cf2e11d5=e50d0aaf-a3c1-4984-9c30-c8f689fa2285; connect.sid=s%3AN5N56581C46EBCdR8SJxHhEf1TG81-MP.sc%2BdT4wfucHdVUc6bPsoqiytqmPhss9c0t9MrgXliZk
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket```

@CuAnnan
Copy link
Author

CuAnnan commented Mar 6, 2021

<script type="text/javascript">
    (function($) {
        $(function() {
            console.log("Onload event fired");
            const peer = new Peer(
                    'ZNfSEBbys',
                    {
                        host:'localhost',
                        port:443,
                        debug: 3,
                        secure:true
                    }
            );
            peer.on('open', function (id) {
                console.log("Peer connection up and running");
            });
        });
    })(window.jQuery);
</script>

@CuAnnan
Copy link
Author

CuAnnan commented Mar 6, 2021

Console output

PeerJS:  Socket closed. 
close { target: WebSocket, isTrusted: true, wasClean: false, code: 1006, reason: "", srcElement: WebSocket, currentTarget: WebSocket, eventPhase: 2, bubbles: false, cancelable: false, … }
logger.ts:57:12
ERROR PeerJS:  Error: Lost connection to server. logger.ts:61:12
PeerJS:  Disconnect peer with ID:ZNfSEBbys```

@CuAnnan
Copy link
Author

CuAnnan commented Mar 6, 2021

https://localhost/peerjs responds with

{"name":"PeerJS Server","description":"A server side element to broker connections between PeerJS clients.","website":"https://peerjs.com/"}

@CuAnnan
Copy link
Author

CuAnnan commented Mar 6, 2021

https://localhost/peerjs/id responds with a 404

@CuAnnan
Copy link
Author

CuAnnan commented Mar 6, 2021

I've tried giving it the path /peerjs in both front and back end, but it results in identical behaviour.

@CuAnnan
Copy link
Author

CuAnnan commented Mar 6, 2021

NotFoundError: Not Found
    at projectPath\app.js:84:8
    at Layer.handle [as handle_request] (projectPath\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (projectPath\node_modules\express\lib\router\index.js:317:13)
    at projectPath\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (projectPath\node_modules\express\lib\router\index.js:335:12)
    at next (projectPath\node_modules\express\lib\router\index.js:275:10)
    at projectPath\node_modules\express\lib\application.js:233:9
    at projectPath\node_modules\peer\node_modules\express\lib\router\index.js:635:15
    at next (projectPath\node_modules\peer\node_modules\express\lib\router\index.js:260:14)
    at expressInit (projectPath\node_modules\peer\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (projectPath\node_modules\peer\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (projectPath\node_modules\peer\node_modules\express\lib\router\index.js:317:13)
    at projectPath\node_modules\peer\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (projectPath\node_modules\peer\node_modules\express\lib\router\index.js:335:12)
    at next (projectPath\node_modules\peer\node_modules\express\lib\router\index.js:275:10)
    at query (projectPath\node_modules\peer\node_modules\express\lib\middleware\query.js:45:5)

@CuAnnan
Copy link
Author

CuAnnan commented Mar 6, 2021

Which makes it look like router is taking over and not respecting app.use('/peerjs', peer);

I've tried moving it up and down, but to no avail.

@CuAnnan
Copy link
Author

CuAnnan commented Mar 7, 2021 via email

@CuAnnan
Copy link
Author

CuAnnan commented Mar 7, 2021

If I set the path on the back end to /rtc, then the URI localhost https://localhost/peerjs/rtc/ resolves and returns the expected JSON
but the WSS request wss://localhost/peerjs/rtc/peerjs?key=peerjs&id=ZNfSEBbys&token=506gn78m2y5 fails with a 404

@CuAnnan
Copy link
Author

CuAnnan commented Mar 7, 2021

The body of the 404, provided by node, is

NotFoundError: Not Found
    at projectPath\app.js:83:8
    at Layer.handle [as handle_request] (projectPath\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (projectPath\node_modules\express\lib\router\index.js:317:13)
    at projectPath\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (projectPath\node_modules\express\lib\router\index.js:335:12)
    at next (projectPath\node_modules\express\lib\router\index.js:275:10)
    at Immediate.<anonymous> (projectPath\node_modules\express\lib\application.js:233:9)
    at Immediate._onImmediate (projectPath\node_modules\peer\node_modules\express\lib\router\index.js:635:15)
    at processImmediate (internal/timers.js:463:21)

@spine001
Copy link

I went through most of the trouble that you have and ended up with this combination not producing the error, may be it will help you to take a look at it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants