-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Extract handshake generation & validation into composable replaceable parts #2313
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
Closed
+1,275
−210
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}`); | ||
| } | ||
| } | ||
|
|
||
| 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; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| } | ||
|
|
||
| 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'); | ||
| } | ||
|
|
||
| return { [PerMessageDeflate.extensionName]: perMessageDeflate }; | ||
| } | ||
| } | ||
|
|
||
| module.exports = HandshakeValidator; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.