Skip to content
Closed
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
39 changes: 39 additions & 0 deletions doc/ws.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
- [websocket.send(data[, options][, callback])](#websocketsenddata-options-callback)
- [websocket.terminate()](#websocketterminate)
- [websocket.url](#websocketurl)
- [Class: HandshakeRequest](#class-handshakerequest)
- [Class: HandshakeValidator](#class-handshakevalidator)
- [createWebSocketStream(websocket[, options])](#createwebsocketstreamwebsocket-options)
- [Environment variables](#environment-variables)
- [WS_NO_BUFFER_UTIL](#ws_no_buffer_util)
Expand Down Expand Up @@ -318,6 +320,12 @@ This class represents a WebSocket. It extends the `EventEmitter`.
takes a `Buffer` that must be filled synchronously and is called before a
message is sent, for each message. By default, the buffer is filled with
cryptographically strong random bytes.
- `handshakeRequest` {HandshakeRequest} A
[`HandshakeRequest`](#class-handshakerequest) instance used to build the
HTTP upgrade request.
- `handshakeValidator` {HandshakeValidator} A
[`HandshakeValidator`](#class-handshakevalidator) instance used to validate
the server's upgrade response.
- `handshakeTimeout` {Number} Timeout in milliseconds for the handshake
request. This is reset after every redirection.
- `maxPayload` {Number} The maximum allowed message size in bytes. Defaults to
Expand Down Expand Up @@ -628,6 +636,37 @@ Forcibly close the connection. Internally, this calls [`socket.destroy()`][].

The URL of the WebSocket server. Server clients don't have this attribute.

## Class: HandshakeRequest

This class builds the HTTP upgrade request for a WebSocket client handshake.

### handshakeRequest.build(address, protocols, opts[, extensionOfferHeader])

- `address` {String|url.URL} The URL to connect to.
- `protocols` {Array} The subprotocols.
- `opts` {Object} Connection options (as passed to the `WebSocket` constructor).
- `extensionOfferHeader` {String} The `Sec-WebSocket-Extensions` header value.

Build the handshake request. Returns an object containing `parsedUrl` {url.URL},
`key` {String}, `protocolSet` {Set}, and request options suitable for
`http.request()` / `https.request()` (`host`, `port`, `path`, `headers`, etc.).

## Class: HandshakeValidator

This class validates a WebSocket server's upgrade response.

### handshakeValidator.validate(res, key, protocolSet[, perMessageDeflate])

- `res` {http.IncomingMessage} The HTTP upgrade response.
- `key` {String} The `Sec-WebSocket-Key` that was sent.
- `protocolSet` {Set} The subprotocols that were offered.
- `perMessageDeflate` {Object} The `PerMessageDeflate` instance, or `null`.
- Returns: {Object} An object with `protocol` {String} and `extensions` {Object}
properties.

Validate the server's upgrade response and return the negotiated protocol and
extensions. Throws an `Error` if validation fails.

## createWebSocketStream(websocket[, options])

- `websocket` {WebSocket} A `WebSocket` object.
Expand Down
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ WebSocket.createWebSocketStream = require('./lib/stream');
WebSocket.Server = require('./lib/websocket-server');
WebSocket.Receiver = require('./lib/receiver');
WebSocket.Sender = require('./lib/sender');
WebSocket.HandshakeRequest = require('./lib/handshake-request');
WebSocket.HandshakeValidator = require('./lib/handshake-validator');
Comment on lines +9 to +10
Copy link
Member

Choose a reason for hiding this comment

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

I've only looked at this and no, no more spurious keys to the exported WebSocket.


WebSocket.WebSocket = WebSocket;
WebSocket.WebSocketServer = WebSocket.Server;
Expand Down
205 changes: 205 additions & 0 deletions lib/handshake-request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
'use strict';

const { randomBytes } = require('crypto');
const { URL } = require('url');

const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;

/**
* Builds the HTTP request for a WebSocket handshake.
* Individual methods can be subclassed to customize behavior.
*/
class HandshakeRequest {
/**
* @param {(String|URL)} address The URL to connect to
* @param {Array} protocols The subprotocols
* @param {Object} opts Options object
* @param {String} [extensionOfferHeader] The Sec-WebSocket-Extensions value
* @return {Object} An object with `parsedUrl`, `key`, `protocolSet`, and
* fields suitable for `http.request()` / `https.request()`
*/
build(address, protocols, opts, extensionOfferHeader) {
const parsedUrl = this.parseUrl(address);
this.validateUrl(parsedUrl);

const key = this.generateKey();
const protocolSet = this.buildProtocolSet(protocols);

const headers = {};

//
// User headers first, then WS protocol headers (which take precedence).
//
if (opts.headers) {
Object.assign(headers, opts.headers);
}

headers['Sec-WebSocket-Version'] = String(opts.protocolVersion);
headers['Sec-WebSocket-Key'] = key;
headers['Connection'] = 'Upgrade';
headers['Upgrade'] = 'websocket';

if (extensionOfferHeader) {
headers['Sec-WebSocket-Extensions'] = extensionOfferHeader;
}
if (protocolSet.size) {
headers['Sec-WebSocket-Protocol'] = protocols.join(',');
}
if (opts.origin) {
if (opts.protocolVersion < 13) {
headers['Sec-WebSocket-Origin'] = opts.origin;
} else {
headers['Origin'] = opts.origin;
}
}

const isSecure = parsedUrl.protocol === 'wss:';
const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
const defaultPort = isSecure ? 443 : 80;

const host = parsedUrl.hostname.startsWith('[')
? parsedUrl.hostname.slice(1, -1)
: parsedUrl.hostname;

const path = parsedUrl.pathname + parsedUrl.search;

const result = {
parsedUrl,
key,
protocolSet,
host,
port: parsedUrl.port || defaultPort,
path,
defaultPort,
timeout: opts.handshakeTimeout,
headers
};

//
// Handle auth. URL credentials take precedence over opts.auth.
// Node.js http.request() generates the Authorization header from
// opts.auth.
//
if (parsedUrl.username || parsedUrl.password) {
result.auth = `${parsedUrl.username}:${parsedUrl.password}`;
} else if (opts.auth) {
result.auth = opts.auth;
}

if (isIpcUrl) {
const parts = path.split(':');

result.socketPath = parts[0];
result.path = parts[1];
}

return result;
}

parseUrl(address) {
let parsedUrl;

if (address instanceof URL) {
parsedUrl = address;
} else {
try {
parsedUrl = new URL(address);
} catch (e) {
throw new SyntaxError(`Invalid URL: ${address}`);

Check failure on line 108 in lib/handshake-request.js

View workflow job for this annotation

GitHub Actions / test (x64, 22, ubuntu-latest)

There is no `cause` attached to the symptom error being thrown
}
}

if (parsedUrl.protocol === 'http:') {
parsedUrl.protocol = 'ws:';
} else if (parsedUrl.protocol === 'https:') {
parsedUrl.protocol = 'wss:';
}

return parsedUrl;
}

validateUrl(parsedUrl) {
const isSecure = parsedUrl.protocol === 'wss:';
const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
let message;

if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
message =
'The URL\'s protocol must be one of "ws:", "wss:", ' +
'"http:", "https:", or "ws+unix:"';
} else if (isIpcUrl && !parsedUrl.pathname) {
message = "The URL's pathname is empty";
} else if (parsedUrl.hash) {
message = 'The URL contains a fragment identifier';
}

if (message) throw new SyntaxError(message);
}

generateKey() {
return randomBytes(16).toString('base64');
}

initRedirectOptions(options) {
//
// Shallow copy the user provided options so that headers can be changed
// without mutating the original object.
//
const headers = options.headers;
options = { ...options, headers: {} };

if (headers) {
for (const [key, value] of Object.entries(headers)) {
options.headers[key.toLowerCase()] = value;
}
}

return options;
}

stripRedirectAuth(opts, isSameHost) {
//
// Match curl 7.77.0 behavior and drop the following headers. These
// headers are also dropped when following a redirect to a subdomain.
//
delete opts.headers.authorization;
delete opts.headers.cookie;

if (!isSameHost) delete opts.headers.host;

opts.auth = undefined;
}

injectAuthHeader(headers, auth) {
//
// Match curl 7.77.0 behavior and make the first `Authorization` header win.
// If the `Authorization` header is set, then there is nothing to do as it
// will take precedence.
//
if (auth && !headers.authorization) {
headers.authorization = 'Basic ' + Buffer.from(auth).toString('base64');
}
}

buildProtocolSet(protocols) {
const protocolSet = new Set();

for (const protocol of protocols) {
if (
typeof protocol !== 'string' ||
!subprotocolRegex.test(protocol) ||
protocolSet.has(protocol)
) {
throw new SyntaxError(
'An invalid or duplicated subprotocol was specified'
);
}

protocolSet.add(protocol);
}

return protocolSet;
}
}

module.exports = HandshakeRequest;
113 changes: 113 additions & 0 deletions lib/handshake-validator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
'use strict';

const { createHash } = require('crypto');

const { GUID } = require('./constants');
const { parse } = require('./extension');
const PerMessageDeflate = require('./permessage-deflate');

/**
* Validates a WebSocket upgrade response. Subclass and override individual
* methods to customize validation behavior.
*/
class HandshakeValidator {
/**
* @param {Object} res The HTTP upgrade response
* @param {String} key The `Sec-WebSocket-Key` that was sent
* @param {Set} protocolSet The subprotocols that were offered
* @param {Object} [perMessageDeflate] The PerMessageDeflate instance, if any
* @return {{ protocol: String, extensions: Object }}
*/
validate(res, key, protocolSet, perMessageDeflate) {
this.validateUpgrade(res);
this.validateAcceptKey(res.headers['sec-websocket-accept'], key);

const protocol = this.validateSubprotocol(
res.headers['sec-websocket-protocol'],
protocolSet
);

const extensions = this.validateExtensions(
res.headers['sec-websocket-extensions'],
perMessageDeflate
);

return { protocol, extensions };
}

validateUpgrade(res) {
const upgrade = res.headers.upgrade;

if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
throw new Error('Invalid Upgrade header');
}
}

validateAcceptKey(actual, key) {
const expected = createHash('sha1')
.update(key + GUID)
.digest('base64');

if (actual !== expected) {
throw new Error('Invalid Sec-WebSocket-Accept header');
}
}

validateSubprotocol(serverProt, protocolSet) {
if (serverProt !== undefined) {
if (!protocolSet.size) {
throw new Error('Server sent a subprotocol but none was requested');
}

if (!protocolSet.has(serverProt)) {
throw new Error('Server sent an invalid subprotocol');
}

return serverProt;
}

if (protocolSet.size) {
throw new Error('Server sent no subprotocol');
}

return '';
}

validateExtensions(headerValue, perMessageDeflate) {
if (headerValue === undefined) return {};

if (!perMessageDeflate) {
throw new Error(
'Server sent a Sec-WebSocket-Extensions header but no extension ' +
'was requested'
);
}

let extensions;

try {
extensions = parse(headerValue);
} catch (err) {
throw new Error('Invalid Sec-WebSocket-Extensions header');

Check failure on line 91 in lib/handshake-validator.js

View workflow job for this annotation

GitHub Actions / test (x64, 22, ubuntu-latest)

There is no `cause` attached to the symptom error being thrown
}

const extensionNames = Object.keys(extensions);

if (
extensionNames.length !== 1 ||
extensionNames[0] !== PerMessageDeflate.extensionName
) {
throw new Error('Server indicated an extension that was not requested');
}

try {
perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
} catch (err) {
throw new Error('Invalid Sec-WebSocket-Extensions header');

Check failure on line 106 in lib/handshake-validator.js

View workflow job for this annotation

GitHub Actions / test (x64, 22, ubuntu-latest)

There is no `cause` attached to the symptom error being thrown
}

return { [PerMessageDeflate.extensionName]: perMessageDeflate };
}
}

module.exports = HandshakeValidator;
Loading
Loading