wormhole/lib/Wormhole.js

41 lines
1.5 KiB
JavaScript
Raw Normal View History

const EventEmitter = require('events');
const { createLog } = require('./logger');
const constants = require('./constants');
const Socket = require('./Socket');
const ConnectingSocket = require('./ConnectingSocket');
const handshakeLog = createLog([ 'Wormhole', 'Handshake' ]);
class Wormhole extends EventEmitter {
constructor({ urls=[ '/bruh' ], httpServer }) {
super();
this._urls = urls;
this._httpServer = httpServer;
this._sockets = [];
this._httpServer.on('request', (req, res) => {
if (req.method === 'GET' && req.url && this._urls.includes(req.url)) {
handshakeLog(`Got connection request to ${req.url}`);
const websocketKey = req.headers['sec-websocket-key'];
const upgradeHeader = req.headers['upgrade'];
const websocketVersion = req.headers['sec-websocket-version'];
let socket = new Socket({ socket: res.socket, initalState: constants.states.CONNECTING });
let connectingSocket = new ConnectingSocket({ res, socket, upgradeHeader, websocketKey, websocketVersion });
const connectionFunctions = connectingSocket.connectionFunctions();
if (!connectionFunctions) return connectingSocket.rejectConnection(400);
const { accept, reject } = connectionFunctions;
this.emit('connect', { socket, accept, reject });
}
});
}
}
module.exports = Wormhole;