Example #1
0
File: index.js Project: refack/etag
  return function *etag(next){
    yield next;

    // no body
    var body = this.body;
    if (!body || this.response.get('ETag')) return;

    // type
    var status = this.status / 100 | 0;
    var type = typeof body;
    var etag;

    // 2xx
    if (2 != status) return;

    // hash
    if (body instanceof Stream) {
      if (!body.path) return;
      if (!(yield exists(body.path))) return;
      var s = yield stat(body.path);
      etag = crc(s.size + '.' + s.mtime);
    } else if ('string' == type || Buffer.isBuffer(body)) {
      etag = crc(body);
    } else {
      etag = crc(JSON.stringify(body));
    }

    // add etag
    if (etag) this.set('ETag', '"' + etag + '"');
  }
Example #2
0
    res.on('header', function(){
      // removed
      if (!req.session) {
	debug('clear session');
	cookie.expires = new Date(0);
	res.setHeader('Set-Cookie', cookie.serialize(key, ''));
	return;
      }

      delete req.session.cookie;

      // check security
      var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()
	, tls = req.connection.encrypted || (trustProxy && 'https' == proto)
	, secured = cookie.secure && tls;

      // only send secure cookies via https
      if (cookie.secure && !secured) return debug('not secured');

      // serialize
      debug('serializing %j', req.session);
      var val = 'j:' + JSON.stringify(req.session);

      // compare hashes, no need to set-cookie if unchanged
      if (originalHash == crc32.signed(val)) return debug('unmodified session');

      // set-cookie
      val = 's:' + signature.sign(val, secret);
      val = cookie.serialize(key, val);
      debug('set-cookie %j', cookie);
      res.setHeader('Set-Cookie', val);
    });
Example #3
0
var construct = function(header, data) {
  var block = this._blocks[header.id];
  if (block) {
    block.found++;
    clearTimeout(block.sleep);
  } else {
    block = this._blocks[header.id] = {
      found: 1,
      check: header.check,
      blocks: Math.ceil(header.length / (this.blockSize - 36)),
      buffer: new Buffer(header.length)
    };
    // workaround
    block.buffer._info = data._info;
  }
  data.copy(block.buffer, header.offset);
  if (block.found === block.blocks) {
    delete this._blocks[header.id];
    var check = crc32.signed(block.buffer);
    if (check === block.check)
      this.push(block.buffer);
    else if (!this.ignoreDataErrors)
      this.emit('error', new Error('block checksum failed'));
  } else {
    block.sleep = setTimeout(kill.bind(this, header.id), this.blockTimeout);
  }
};
Example #4
0
WrapStream.prototype._transform = function(chunk, encoding, callback) {
  // generate the header
  var header = new Buffer(28);
  // allow the endpoint to filter out bad data
  header.write('WRAP', 0, 4);
  // assign the header a random id
  crypto.randomBytes(16).copy(header, 4);
  // write the checksum for the chunk
  var check = crc32.signed(chunk);
  header.writeInt32BE(check, 20, true);
  // include the length of the entire chunk
  header.writeUInt32BE(chunk.length, 24, true);

  // calculate the size of the messages in the blocks, and the number of blocks
  var messageSize = this.blockSize - 36;
  var count = Math.ceil(chunk.length / messageSize);

  // generate the blocks
  for (var i = 0; i < count; i++) {
    var length = i + 1 === count ? chunk.length % messageSize : messageSize;
    var block = new Buffer(length + 36);
    var offset = i * messageSize;
    header.copy(block);
    block.writeUInt32BE(block.length, 28, true);
    block.writeUInt32BE(offset, 32, true);
    chunk.copy(block, 36, offset, offset + length);
    // workaround
    block._info = chunk._info;
    this.push(block);
  }

  // notify Transform that we've processed the chunk
  callback();
};
Example #5
0
function encodeMessage(message) {
    var m = new Buffermaker()
        .Int8(message.magic)
        .Int8(message.attributes);

    var key = message.key;
    if (key) {
        m.Int32BE(message.key.length);
        m.string(message.key);
    } else {
        m.Int32BE(-1);
    }

    var value = message.value;

    if (value !== null) {
        if (Buffer.isBuffer(value)) {
            m.Int32BE(value.length);
        } else {
            if (typeof value !== 'string') value = value.toString();
            m.Int32BE(Buffer.byteLength(value));
        }
        m.string(value);
    } else {
        m.Int32BE(-1);
    }
    m = m.make();
    var crc = crc32.signed(m);
    return new Buffermaker()
        .Int32BE(crc)
        .string(m)
        .make();
}
Example #6
0
  sepro.on('websocket:start', function (req, socket, head, target) {
    if (!req._seproStickyCookieReduce) return

    var targetStr = getKey(target)
    self.cache.set( crc32.signed(targetStr)
                  , targetStr
                  )
  })
Example #7
0
res.send = function(body) {
  var req = this.req
  var head = 'HEAD' === req.method
  var len

  if(2 == arguments.length) {
    if('number' != typeof body && 'number' == typeof arguments[1]) {
      this.statusCode = arguments[1]
    } else {
      this.statusCode = body
      body = arguments[1]
    }
  }

  switch(typeof body) {
    case 'number':
      this.get('Content-Type') || this.type('text')
      this.statusCode = body
      body = http.STATUS_CODES[body]
      break
    case 'string':
      if(!this.get('Content-Type')) {
        this.charset = this.charset || 'utf-8'
        this.type('html')
      }
      break
    case 'boolean':
    case 'object':
      if(null == body) body = ''
      else if(Buffer.isBuffer(body)) this.get('Content-Type') || this.type('bin')
      else return this.json(body)
      break
    }

    if(undefined !== body && !this.get('Content-Length')) {
      this.set('Content-Length', len = Buffer.isBuffer(body)
        ? body.length
        : Buffer.byteLength(body))
    }

    if(len > 1024 && 'GET' == req.method) {
      if(!this.get('ETag'))
        this.set('ETag', '"' + crc32.signed(body) + '"')
    }

    if(req.fresh) this.statusCode = 304

    if(204 == this.statusCode || 304 == this.statusCode) {
      this.removeHeader('Content-Type')
      this.removeHeader('Conetnt-Length')
      this.removeHeader('Transfer-Encoding')
      body = ''
    }

    this.end(head ? null : body)

    return this
}
Example #8
0
        .then(function () {
            dataHandlerSpy.should.have.been.called; // eslint-disable-line
            dataHandlerSpy.lastCall.args[0].should.be.an('array').and.have.length(1);
            dataHandlerSpy.lastCall.args[1].should.be.a('string', 'kafka-test-topic');
            dataHandlerSpy.lastCall.args[2].should.be.a('number', 0);

            dataHandlerSpy.lastCall.args[0][0].should.be.an('object');
            dataHandlerSpy.lastCall.args[0][0].should.have.property('message').that.is.an('object');
            dataHandlerSpy.lastCall.args[0][0].message.should.have.property('value');
            crc32.signed(dataHandlerSpy.lastCall.args[0][0].message.value).should.be.eql(crc);
        });
Example #9
0
  sepro.on('start', function (req, res, target) {
    if (!req._seproStickyCookieReduce) return

    var targetStr = getKey(target)
      , value = crc32.signed(targetStr)

    self.cache.set(value, targetStr)

    res.setHeader('Set-Cookie', cookie.serialize( self.cookieName
                                                , value
                                                , { path: '/', httpOnly: true }
                                                ))
  })
Example #10
0
    write: function (value) { // {attributes, magicByte, key, value}
        var _o1 = this.offset, _o2;
        this
            .skip(4)
            .Int8(value.magicByte || 0)
            .MessageAttributes(value.attributes || {})
            .bytes(value.key)
            .bytes(value.value);

        _o2 = this.offset;
        this.offset = _o1;
        this.Int32BE(crc32.signed(this.buffer.slice(_o1 + 4, _o2)));
        this.offset = _o2;
    }
Example #11
0
function encodeMessage(message) {
    var m = new Buffermaker()
        .Int8(message.magic)
        .Int8(message.attributes)
        .Int32BE(message.key.length)
        .string(message.key)
        .Int32BE(Buffer.isBuffer(message.value) ? message.value.length : Buffer.byteLength(message.value))
        .string(message.value).make();
    var crc = crc32.signed(m);
    return new Buffermaker()
        .Int32BE(crc)
        .string(m)
        .make();
}
Example #12
0
handlers[EMsg.ChannelEncryptRequest] = function(data) {
	// assume server isn't dead
	this._connection.setTimeout(0);

//  var encRequest = Schema.MsgChannelEncryptRequest.decode(data);
	this.emit('debug', 'encrypt request');

	var sessionKey = SteamCrypto.generateSessionKey();
	this._tempSessionKey = sessionKey.plain;
	var keyCrc = BufferCRC32.signed(sessionKey.encrypted);

	var encResp = new Schema.MsgChannelEncryptResponse().encode();
	var body = new ByteBuffer(encResp.limit + 128 + 4 + 4, ByteBuffer.LITTLE_ENDIAN); // key, crc, trailer

	body.append(encResp);
	body.append(sessionKey.encrypted);
	body.writeInt32(keyCrc);
	body.writeUint32(0); // TODO: check if the trailer is required
	body.flip();

	this.send({"msg": EMsg.ChannelEncryptResponse}, body.toBuffer());
};
Example #13
0
    it('should be able to grow receive buffer', function () {
        var buf = new Buffer(384 * 1024), crc = crc32.signed(buf);

        dataHandlerSpy.reset();

        return producer.send({
            topic: 'kafka-test-topic',
            partition: 0,
            message: { value: buf }
        })
        .delay(300)
        .then(function () {
            dataHandlerSpy.should.have.been.called; // eslint-disable-line
            dataHandlerSpy.lastCall.args[0].should.be.an('array').and.have.length(1);
            dataHandlerSpy.lastCall.args[1].should.be.a('string', 'kafka-test-topic');
            dataHandlerSpy.lastCall.args[2].should.be.a('number', 0);

            dataHandlerSpy.lastCall.args[0][0].should.be.an('object');
            dataHandlerSpy.lastCall.args[0][0].should.have.property('message').that.is.an('object');
            dataHandlerSpy.lastCall.args[0][0].message.should.have.property('value');
            crc32.signed(dataHandlerSpy.lastCall.args[0][0].message.value).should.be.eql(crc);
        });
    });
Example #14
0
  return function cookieSession(req, res, next) {

    // req.secret is for backwards compatibility
    var secret = options.secret || req.secret;
    if (!secret) throw new Error('`secret` option required for cookie sessions');

    // default session
    req.session = {};
    var cookie = req.session.cookie = new Cookie(options.cookie);

    // pathname mismatch
    if (0 != req.originalUrl.indexOf(cookie.path)) return next();

    // cookieParser secret
    if (!options.secret && req.secret) {
      req.session = req.signedCookies[key] || {};
      req.session.cookie = cookie;
    } else {
      // TODO: refactor
      var rawCookie = req.cookies[key];
      if (rawCookie) {
	var unsigned = utils.parseSignedCookie(rawCookie, secret);
	if (unsigned) {
	  var originalHash = crc32.signed(unsigned);
	  req.session = utils.parseJSONCookie(unsigned) || {};
	  req.session.cookie = cookie;
	}
      }
    }

    res.on('header', function(){
      // removed
      if (!req.session) {
	debug('clear session');
	cookie.expires = new Date(0);
	res.setHeader('Set-Cookie', cookie.serialize(key, ''));
	return;
      }

      delete req.session.cookie;

      // check security
      var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()
	, tls = req.connection.encrypted || (trustProxy && 'https' == proto)
	, secured = cookie.secure && tls;

      // only send secure cookies via https
      if (cookie.secure && !secured) return debug('not secured');

      // serialize
      debug('serializing %j', req.session);
      var val = 'j:' + JSON.stringify(req.session);

      // compare hashes, no need to set-cookie if unchanged
      if (originalHash == crc32.signed(val)) return debug('unmodified session');

      // set-cookie
      val = 's:' + signature.sign(val, secret);
      val = cookie.serialize(key, val);
      debug('set-cookie %j', cookie);
      res.setHeader('Set-Cookie', val);
    });

    next();
  };
Example #15
0
exports.etag = function(body){
  return '"' + crc32.signed(body) + '"';
};
Example #16
0
var hash = function (session) {
  return crc.signed(JSON.stringify(session));
};
Example #17
0
/**
 * get the hash of a session include cookie options.
 */
function hash(sess) {
  return crc32.signed(JSON.stringify(sess));
}
Example #18
0
utils.etag = function etag(body) {
  var crc32 = require('buffer-crc32');

  return '"' + crc32.signed(body) + '"';
}
Example #19
0
 client.get(req.url + '/', function(err, reply) {
     assert.equal(JSON.parse(reply).etag, '"' + crc32.signed(JSON.stringify(data, replacer, spaces)) + '"');
     done();
 });
Example #20
0
function hash(sess) {
  return crc32.signed(JSON.stringify(sess, function(key, val){
    if ('cookie' != key) return val;
  }));
}
Example #21
0
module.exports = function send (req, res, body, cb) {
  if (cb) {
    res.on('finish', cb)
    res.on('close', cb)
  }

  var head = req.method == 'HEAD'
    , type
    , stream
    , status = res.statusCode || 200

  if (body == null) {
    type = 'text/html'
    body = ''
  } else if (typeof body == 'string') {
    type = 'text/html'
    body = new Buffer(body)
  } else if (body.pipe) {
    type = 'application/octet-stream'
    stream = body
    body = null
  } else  { // buffer
    type = 'application/octet-stream'
  }

  if (!res.getHeader('Content-Type')) {
    res.setHeader('Content-Type', type)
  }

  if (!res.getHeader('Content-Length') && body != null) {
    res.setHeader('Content-Length', String(body.length))
  }

  // ETag support
  if (body && body.length > 1024 && !res.getHeader('ETag')) {
    res.setHeader('ETag', '"' + crc(body) + '"')
  }

  res.statusCode = status >= 200 && status < 300 && fresh(req.headers, res._headers)
    ? 304
    : status

  // strip irrelevant headers
  if (204 == res.statusCode || 304 == res.statusCode) {
    res.removeHeader('Content-Type')
    res.removeHeader('Content-Length')
    res.removeHeader('Transfer-Encoding') // https://github.com/visionmedia/express/pull/1451
    body = stream = null
  }

  if (head) {
    res.end()
  } else if (stream) {
    res.on('close', function () {
      stream.unpipe(res)
    })
    stream.pipe(res)
  } else {
    res.end(body)
  }
}