You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

331 lines
13 KiB

4 years ago
  1. # websocket-extensions [![Build status](https://secure.travis-ci.org/faye/websocket-extensions-node.svg)](http://travis-ci.org/faye/websocket-extensions-node)
  2. A minimal framework that supports the implementation of WebSocket extensions in
  3. a way that's decoupled from the main protocol. This library aims to allow a
  4. WebSocket extension to be written and used with any protocol library, by
  5. defining abstract representations of frames and messages that allow modules to
  6. co-operate.
  7. `websocket-extensions` provides a container for registering extension plugins,
  8. and provides all the functions required to negotiate which extensions to use
  9. during a session via the `Sec-WebSocket-Extensions` header. By implementing the
  10. APIs defined in this document, an extension may be used by any WebSocket library
  11. based on this framework.
  12. ## Installation
  13. ```
  14. $ npm install websocket-extensions
  15. ```
  16. ## Usage
  17. There are two main audiences for this library: authors implementing the
  18. WebSocket protocol, and authors implementing extensions. End users of a
  19. WebSocket library or an extension should be able to use any extension by passing
  20. it as an argument to their chosen protocol library, without needing to know how
  21. either of them work, or how the `websocket-extensions` framework operates.
  22. The library is designed with the aim that any protocol implementation and any
  23. extension can be used together, so long as they support the same abstract
  24. representation of frames and messages.
  25. ### Data types
  26. The APIs provided by the framework rely on two data types; extensions will
  27. expect to be given data and to be able to return data in these formats:
  28. #### *Frame*
  29. *Frame* is a structure representing a single WebSocket frame of any type. Frames
  30. are simple objects that must have at least the following properties, which
  31. represent the data encoded in the frame:
  32. | property | description |
  33. | ------------ | ------------------------------------------------------------------ |
  34. | `final` | `true` if the `FIN` bit is set, `false` otherwise |
  35. | `rsv1` | `true` if the `RSV1` bit is set, `false` otherwise |
  36. | `rsv2` | `true` if the `RSV2` bit is set, `false` otherwise |
  37. | `rsv3` | `true` if the `RSV3` bit is set, `false` otherwise |
  38. | `opcode` | the numeric opcode (`0`, `1`, `2`, `8`, `9`, or `10`) of the frame |
  39. | `masked` | `true` if the `MASK` bit is set, `false` otherwise |
  40. | `maskingKey` | a 4-byte `Buffer` if `masked` is `true`, otherwise `null` |
  41. | `payload` | a `Buffer` containing the (unmasked) application data |
  42. #### *Message*
  43. A *Message* represents a complete application message, which can be formed from
  44. text, binary and continuation frames. It has the following properties:
  45. | property | description |
  46. | -------- | ----------------------------------------------------------------- |
  47. | `rsv1` | `true` if the first frame of the message has the `RSV1` bit set |
  48. | `rsv2` | `true` if the first frame of the message has the `RSV2` bit set |
  49. | `rsv3` | `true` if the first frame of the message has the `RSV3` bit set |
  50. | `opcode` | the numeric opcode (`1` or `2`) of the first frame of the message |
  51. | `data` | the concatenation of all the frame payloads in the message |
  52. ### For driver authors
  53. A driver author is someone implementing the WebSocket protocol proper, and who
  54. wishes end users to be able to use WebSocket extensions with their library.
  55. At the start of a WebSocket session, on both the client and the server side,
  56. they should begin by creating an extension container and adding whichever
  57. extensions they want to use.
  58. ```js
  59. var Extensions = require('websocket-extensions'),
  60. deflate = require('permessage-deflate');
  61. var exts = new Extensions();
  62. exts.add(deflate);
  63. ```
  64. In the following examples, `exts` refers to this `Extensions` instance.
  65. #### Client sessions
  66. Clients will use the methods `generateOffer()` and `activate(header)`.
  67. As part of the handshake process, the client must send a
  68. `Sec-WebSocket-Extensions` header to advertise that it supports the registered
  69. extensions. This header should be generated using:
  70. ```js
  71. request.headers['sec-websocket-extensions'] = exts.generateOffer();
  72. ```
  73. This returns a string, for example `"permessage-deflate;
  74. client_max_window_bits"`, that represents all the extensions the client is
  75. offering to use, and their parameters. This string may contain multiple offers
  76. for the same extension.
  77. When the client receives the handshake response from the server, it should pass
  78. the incoming `Sec-WebSocket-Extensions` header in to `exts` to activate the
  79. extensions the server has accepted:
  80. ```js
  81. exts.activate(response.headers['sec-websocket-extensions']);
  82. ```
  83. If the server has sent any extension responses that the client does not
  84. recognize, or are in conflict with one another for use of RSV bits, or that use
  85. invalid parameters for the named extensions, then `exts.activate()` will
  86. `throw`. In this event, the client driver should fail the connection with
  87. closing code `1010`.
  88. #### Server sessions
  89. Servers will use the method `generateResponse(header)`.
  90. A server session needs to generate a `Sec-WebSocket-Extensions` header to send
  91. in its handshake response:
  92. ```js
  93. var clientOffer = request.headers['sec-websocket-extensions'],
  94. extResponse = exts.generateResponse(clientOffer);
  95. response.headers['sec-websocket-extensions'] = extResponse;
  96. ```
  97. Calling `exts.generateResponse(header)` activates those extensions the client
  98. has asked to use, if they are registered, asks each extension for a set of
  99. response parameters, and returns a string containing the response parameters for
  100. all accepted extensions.
  101. #### In both directions
  102. Both clients and servers will use the methods `validFrameRsv(frame)`,
  103. `processIncomingMessage(message)` and `processOutgoingMessage(message)`.
  104. The WebSocket protocol requires that frames do not have any of the `RSV` bits
  105. set unless there is an extension in use that allows otherwise. When processing
  106. an incoming frame, sessions should pass a *Frame* object to:
  107. ```js
  108. exts.validFrameRsv(frame)
  109. ```
  110. If this method returns `false`, the session should fail the WebSocket connection
  111. with closing code `1002`.
  112. To pass incoming messages through the extension stack, a session should
  113. construct a *Message* object according to the above datatype definitions, and
  114. call:
  115. ```js
  116. exts.processIncomingMessage(message, function(error, msg) {
  117. // hand the message off to the application
  118. });
  119. ```
  120. If any extensions fail to process the message, then the callback will yield an
  121. error and the session should fail the WebSocket connection with closing code
  122. `1010`. If `error` is `null`, then `msg` should be passed on to the application.
  123. To pass outgoing messages through the extension stack, a session should
  124. construct a *Message* as before, and call:
  125. ```js
  126. exts.processOutgoingMessage(message, function(error, msg) {
  127. // write message to the transport
  128. });
  129. ```
  130. If any extensions fail to process the message, then the callback will yield an
  131. error and the session should fail the WebSocket connection with closing code
  132. `1010`. If `error` is `null`, then `message` should be converted into frames
  133. (with the message's `rsv1`, `rsv2`, `rsv3` and `opcode` set on the first frame)
  134. and written to the transport.
  135. At the end of the WebSocket session (either when the protocol is explicitly
  136. ended or the transport connection disconnects), the driver should call:
  137. ```js
  138. exts.close(function() {})
  139. ```
  140. The callback is invoked when all extensions have finished processing any
  141. messages in the pipeline and it's safe to close the socket.
  142. ### For extension authors
  143. An extension author is someone implementing an extension that transforms
  144. WebSocket messages passing between the client and server. They would like to
  145. implement their extension once and have it work with any protocol library.
  146. Extension authors will not install `websocket-extensions` or call it directly.
  147. Instead, they should implement the following API to allow their extension to
  148. plug into the `websocket-extensions` framework.
  149. An `Extension` is any object that has the following properties:
  150. | property | description |
  151. | -------- | ---------------------------------------------------------------------------- |
  152. | `name` | a string containing the name of the extension as used in negotiation headers |
  153. | `type` | a string, must be `"permessage"` |
  154. | `rsv1` | either `true` if the extension uses the RSV1 bit, `false` otherwise |
  155. | `rsv2` | either `true` if the extension uses the RSV2 bit, `false` otherwise |
  156. | `rsv3` | either `true` if the extension uses the RSV3 bit, `false` otherwise |
  157. It must also implement the following methods:
  158. ```js
  159. ext.createClientSession()
  160. ```
  161. This returns a *ClientSession*, whose interface is defined below.
  162. ```js
  163. ext.createServerSession(offers)
  164. ```
  165. This takes an array of offer params and returns a *ServerSession*, whose
  166. interface is defined below. For example, if the client handshake contains the
  167. offer header:
  168. ```
  169. Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; server_max_window_bits=8, \
  170. permessage-deflate; server_max_window_bits=15
  171. ```
  172. then the `permessage-deflate` extension will receive the call:
  173. ```js
  174. ext.createServerSession([
  175. {server_no_context_takeover: true, server_max_window_bits: 8},
  176. {server_max_window_bits: 15}
  177. ]);
  178. ```
  179. The extension must decide which set of parameters it wants to accept, if any,
  180. and return a *ServerSession* if it wants to accept the parameters and `null`
  181. otherwise.
  182. #### *ClientSession*
  183. A *ClientSession* is the type returned by `ext.createClientSession()`. It must
  184. implement the following methods, as well as the *Session* API listed below.
  185. ```js
  186. clientSession.generateOffer()
  187. // e.g. -> [
  188. // {server_no_context_takeover: true, server_max_window_bits: 8},
  189. // {server_max_window_bits: 15}
  190. // ]
  191. ```
  192. This must return a set of parameters to include in the client's
  193. `Sec-WebSocket-Extensions` offer header. If the session wants to offer multiple
  194. configurations, it can return an array of sets of parameters as shown above.
  195. ```js
  196. clientSession.activate(params) // -> true
  197. ```
  198. This must take a single set of parameters from the server's handshake response
  199. and use them to configure the client session. If the client accepts the given
  200. parameters, then this method must return `true`. If it returns any other value,
  201. the framework will interpret this as the client rejecting the response, and will
  202. `throw`.
  203. #### *ServerSession*
  204. A *ServerSession* is the type returned by `ext.createServerSession(offers)`. It
  205. must implement the following methods, as well as the *Session* API listed below.
  206. ```js
  207. serverSession.generateResponse()
  208. // e.g. -> {server_max_window_bits: 8}
  209. ```
  210. This returns the set of parameters the server session wants to send in its
  211. `Sec-WebSocket-Extensions` response header. Only one set of parameters is
  212. returned to the client per extension. Server sessions that would confict on
  213. their use of RSV bits are not activated.
  214. #### *Session*
  215. The *Session* API must be implemented by both client and server sessions. It
  216. contains two methods, `processIncomingMessage(message)` and
  217. `processOutgoingMessage(message)`.
  218. ```js
  219. session.processIncomingMessage(message, function(error, msg) { ... })
  220. ```
  221. The session must implement this method to take an incoming *Message* as defined
  222. above, transform it in any way it needs, then return it via the callback. If
  223. there is an error processing the message, this method should yield an error as
  224. the first argument.
  225. ```js
  226. session.processOutgoingMessage(message, function(error, msg) { ... })
  227. ```
  228. The session must implement this method to take an outgoing *Message* as defined
  229. above, transform it in any way it needs, then return it via the callback. If
  230. there is an error processing the message, this method should yield an error as
  231. the first argument.
  232. Note that both `processIncomingMessage()` and `processOutgoingMessage()` can
  233. perform their logic asynchronously, are allowed to process multiple messages
  234. concurrently, and are not required to complete working on messages in the same
  235. order the messages arrive. `websocket-extensions` will reorder messages as your
  236. extension emits them and will make sure every extension is given messages in the
  237. order they arrive from the driver. This allows extensions to maintain state that
  238. depends on the messages' wire order, for example keeping a DEFLATE compression
  239. context between messages.
  240. ```js
  241. session.close()
  242. ```
  243. The framework will call this method when the WebSocket session ends, allowing
  244. the session to release any resources it's using.
  245. ## Examples
  246. * Consumer: [websocket-driver](https://github.com/faye/websocket-driver-node)
  247. * Provider: [permessage-deflate](https://github.com/faye/permessage-deflate-node)