All files server.js

83.33% Statements 80/96
52% Branches 13/25
84.21% Functions 16/19
85.23% Lines 75/88

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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207  1x 1x 1x 1x   1x       7x           7x   7x 7x 7x 7x           7x   7x 21x   7x 7x   7x         6x   6x 36x   6x 6x   6x 6x 6x   6x 6x         11x     22x   11x 6x   11x 11x         6x 6x         6x 6x 6x       6x 6x 6x 24x 6x   12x 12x   6x 6x   6x             6x             6x   6x 6x     6x                 6x                           11x   4x         4x                 4x   4x     4x 4x   4x 4x 4x                         3x     3x 3x   3x   3x 3x   3x   3x             3x 3x       3x      
const
Debug  = require('@superhero/debug'),
Server = require('net').Server,
Events = require('events'),
Codec  = require('./codec')
 
module.exports = class
{
  constructor(options)
  {
    this.config = Object.assign(
    {
      debug   : true,
      onClose : false
    }, options)
 
    const debug = new Debug({ debug:this.config.debug, prefix:'ws server:' })
 
    this.log      = debug.log.bind(debug)
    this.events   = new Events()
    this.server   = new Server()
    this.sockets  = []
 
    // ping-pong to keep the connection alive
    // this is not part of the standard, but it's required becouse of
    // limitations in the browser api
    // https://tools.ietf.org/html/rfc6455#page-29
    this.events.on('ping', (socket) => socket.emit('pong'))
 
    for(let event of ['close','connection','listening'])
      this.server.on(event, () => this.log(event))
 
    for(let event of ['error'])
      this.server.on(event, (...a) => this.log(event, ...a))
 
    this.server.on('connection', this.onConnection.bind(this))
  }
 
  onConnection(socket)
  {
    this.sockets.push(socket)
 
    for(let event of ['close','connection','drain','end','lookup','timeout'])
      socket.on(event, () => this.log('socket:', event))
 
    for(let event of ['error'])
      socket.on(event, (...a) => this.log('socket:', event, ...a))
 
    const ctx   = { socket }
    ctx.emit    = this.emit.bind(this, socket)
    ctx.chunks  = []
 
    socket.on('data',  this.onData .bind(this, ctx))
    socket.on('close', this.onClose.bind(this, ctx))
  }
 
  onData(ctx, data)
  {
    this.log('socket:', 'data')
 
    // messages can come in multiple chunks that needs to be glued together
    ctx.buffer = Buffer.concat([ctx.buffer, data].filter(_ => _))
 
    if(!ctx.headers)
      this.handshake(ctx)
 
    Eif(ctx.headers)
      this.dispatch(ctx)
  }
 
  onClose(ctx)
  {
    this.sockets.splice(this.sockets.indexOf(ctx.socket), 1)
    this.config.onClose && this.config.onClose(ctx)
  }
 
  handshake(ctx)
  {
    this.log('socket:', 'handshake:', 'received')
    const s = ctx.buffer.toString()
    Eif(s.match(/\r\n\r\n/))
    {
      // parse headers and store remaining buffer
      const
      parts     = s.split('\r\n\r\n'),
      rows      = parts.shift().split('\r\n'),
      buffer    = parts.join(''),
      divided   = rows.map((row) => row.split(':').map((item) => item.trim())),
      headers   = divided.reduce((obj, header) =>
      {
        obj[header[0].toLowerCase()] = header[1]
        return obj
      }, {}),
      key       = headers['sec-websocket-key'],
      signature = Codec.signature(key)
 
      Iif(!key)
      {
        this.log('socket:', 'handshake:', 'sec-websocket-key missing')
        ctx.socket.destroy()
        return
      }
 
      Iif(key.length < 10)
      {
        this.log('socket:', 'handshake:', 'sec-websocket-key to short', key)
        socket.destroy()
        return
      }
 
      this.log('socket:', 'handshake:', 'received:', 'key:', key)
 
      ctx.headers = headers
      ctx.buffer  = Buffer.from(buffer)
 
      // write headers back to the client and establish a handshake
      ctx.socket.write(
      [
        'HTTP/1.1 101 Switching Protocols',
        'Upgrade: WebSocket',
        'Connection: Upgrade',
        'Sec-WebSocket-Accept: ' + signature
      ].join('\r\n') + '\r\n\r\n',
      (error) =>
      {
        error
        ? this.log('socket:', 'handshake:', 'error:', error)
        : this.log('socket:', 'handshake:', 'sent:', 'signature:', signature)
      })
    }
    else
    {
      this.log('socket:', 'handshake:', 'header incomplete')
    }
  }
 
  dispatch(ctx)
  {
    // messages can also come in the same chunk that needs to be divided...
    for(const decoded of Codec.decode(ctx.buffer))
    {
      ctx.buffer = decoded.buffer
 
      // destroys the socket if specific 2 bytes
      // well, this works.. but I have no clue why, the specifications
      // states [0xFF][0x00]. Or if older protocol: [0x00][message][0xFF]
      Iif(decoded.msg.length == 2
      &&(decoded.msg.charCodeAt(0) == 3 && decoded.msg.charCodeAt(1) == 233)
      ||(decoded.msg.charCodeAt(0) == 3 && decoded.msg.charCodeAt(1) == 65533))
      {
        ctx.socket.destroy()
        break
      }
      else
      {
        try
        {
          ctx.chunks.push(decoded.msg)
 
          const
          msg = ctx.chunks.join(),
          dto = JSON.parse(msg)
 
          ctx.chunks.length = 0
          this.log('received message:', dto)
          this.events.emit(dto.event, ctx, dto.data)
        }
        catch(error)
        {
          this.log(error)
          this.log('a message could not be parsed:', ctx.chunks)
        }
      }
    }
  }
 
  emit(socket, event, data, toAll)
  {
    this.log('emitting, to everyone:', !!toAll, 'event:', event, 'data:', data)
 
    const
    dto     = JSON.stringify({ event, data }),
    encoded = Codec.encode(dto)
 
    const promises = []
 
    for(let soc of (toAll ? this.sockets : [socket]))
      promises.push(
        new Promise((fulfill, reject) =>
          soc.write(encoded, (error) =>
          {
            Iif(error)
            {
              this.log('error emitting:', event, data, error)
              reject(error)
            }
            else
            {
              this.log('emitted:', event, data)
              fulfill()
            }
          })))
 
    return Promise.all(promises)
  }
}