All files client.js

84.34% Statements 70/83
71.43% Branches 15/21
94.74% Functions 18/19
84.81% Lines 67/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182  1x 1x 1x 1x 1x 1x 1x   1x       6x             6x   6x 6x 6x   6x 42x   6x 6x         12x             343x             6x   6x 6x   6x   6x             6x 6x               6x   6x     6x 6x   24x 18x   6x   6x   6x 6x 6x                   6x     6x                       6x         6x   6x 12x   6x         4x 8x 4x   114x   114x   114x     114x 114x   2x 2x 2x       113x 113x             8x 4x     4x 4x 4x   4x 4x   4x             4x 4x          
const
encoding  = require('encoding'),
crypto    = require('crypto'),
Debug     = require('@superhero/debug'),
Socket    = require('net').Socket,
Events    = require('events'),
version   = require('./package.json').version,
Codec     = require('./codec')
 
module.exports = class
{
  constructor(options)
  {
    this.config = Object.assign(
    {
      debug     : true,
      reconnect : false,
      onClose   : false
    }, options)
 
    const debug = new Debug({ debug:this.config.debug, prefix:'ws client:' })
 
    this.log    = debug.log.bind(debug)
    this.events = new Events()
    this.socket = new Socket()
 
    for(let event of ['close','connect','data','drain','end','lookup','ready'])
      this.socket.on(event, () => this.log(event))
 
    for(let event of ['error'])
      this.socket.on(event, (...a) => this.log(event, ...a))
  }
 
  get key()
  {
    return this._key
    ? this._key
    : this._key = crypto.randomBytes(15).toString('base64')
  }
 
  get chunks()
  {
    return this._chunks
    ? this._chunks
    : this._chunks = []
  }
 
  connect(port = 80, host = '127.0.0.1', headers)
  {
    const header = this.composeHeader(headers)
 
    return new Promise((fulfill, reject) =>
      this.socket.connect(port, host, () =>
      {
        this.socket.write(header, (error) =>
        {
          Iif(error)
          {
            this.log('error sending handshake', error)
            reject(error)
          }
          else
          {
            this.log('handshake:', 'sent')
            this.socket.once('data', (data) => fulfill( this.handshake(data) ))
          }
        })
      }))
  }
 
  handshake(data)
  {
    return new Promise((fulfill) =>
    {
      this.log('handshake:', 'received')
 
      const
      headers = data.toString().split('\r\n'),
      foundAcceptHeader = headers.some((line) =>
      {
        if(!line.toLowerCase().startsWith('sec-websocket-accept'))
          return false
 
        const signature = (line.split(':')[1] || '').trim()
 
        Eif(signature === Codec.signature(this.key))
        {
          this.log('handshake:', 'verified')
          this.socket.on('data', this.onData.bind(this))
          fulfill()
        }
        else
        {
          this.log('handshake:', 'invalid:', 'signature:', signature)
          const error = new Error('invalid websocket handshake')
          error.code = 'ERR_WEBSOCKET_HANDSHAKE_INVALID'
          throw error
        }
 
        return true
      })
 
      Iif(!foundAcceptHeader)
      {
        this.log('handshake:', 'missing "Sec-WebSocket-Accept" header')
        const error = new Error('missing "Sec-WebSocket-Accept" header')
        error.code = 'ERR_WEBSOCKET_HANDSHAKE_MISSING_SIGNATURE'
        throw error
      }
    })
  }
 
  composeHeader(headers = {})
  {
    headers = Object.assign(
      { 'User-Agent' : `Superhero Websocket Client/${version}` },
      headers,
      { 'Sec-WebSocket-Key' : this.key })
 
    let header = ''
 
    for(const key in headers)
      header += `${key} : ${headers[key]}\r\n`
 
    return header + '\r\n'
  }
 
  onData(buffer)
  {
    this.log('received message')
    buffer = Buffer.concat([this.buffer, buffer].filter(_ => _))
    for(const decoded of Codec.decode(buffer))
    {
      this.buffer = decoded.buffer
 
      try
      {
        this.chunks.push(decoded.msg)
 
        const
        msg = this.chunks.join(),
        dto = JSON.parse(msg)
 
        this.chunks.length = 0
        this.log('received message:', dto)
        this.events.emit(dto.event, dto.data)
      }
      catch(error)
      {
        this.log(error)
        this.log('a message could not be parsed:', this.chunks)
      }
    }
  }
 
  emit(event, data)
  {
    if(typeof event !== 'string')
      throw new TypeError('event must be a string')
 
    const
    dto     = JSON.stringify({ event, data }),
    masked  = true,
    encoded = Codec.encode(dto, masked)
 
    return new Promise((fulfill, reject) =>
      this.socket.write(encoded, (error) =>
      {
        Iif(error)
        {
          this.log('error emitting:', event, data, error)
          reject(error)
        }
        else
        {
          this.log('emitted:', event, data)
          fulfill()
        }
      }))
  }
}