sign-stream.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*global module*/
  2. var Buffer = require('safe-buffer').Buffer;
  3. var DataStream = require('./data-stream');
  4. var jwa = require('jwa');
  5. var Stream = require('stream');
  6. var toString = require('./tostring');
  7. var util = require('util');
  8. function base64url(string, encoding) {
  9. return Buffer
  10. .from(string, encoding)
  11. .toString('base64')
  12. .replace(/=/g, '')
  13. .replace(/\+/g, '-')
  14. .replace(/\//g, '_');
  15. }
  16. function jwsSecuredInput(header, payload, encoding) {
  17. encoding = encoding || 'utf8';
  18. var encodedHeader = base64url(toString(header), 'binary');
  19. var encodedPayload = base64url(toString(payload), encoding);
  20. return util.format('%s.%s', encodedHeader, encodedPayload);
  21. }
  22. function jwsSign(opts) {
  23. var header = opts.header;
  24. var payload = opts.payload;
  25. var secretOrKey = opts.secret || opts.privateKey;
  26. var encoding = opts.encoding;
  27. var algo = jwa(header.alg);
  28. var securedInput = jwsSecuredInput(header, payload, encoding);
  29. var signature = algo.sign(securedInput, secretOrKey);
  30. return util.format('%s.%s', securedInput, signature);
  31. }
  32. function SignStream(opts) {
  33. var secret = opts.secret||opts.privateKey||opts.key;
  34. var secretStream = new DataStream(secret);
  35. this.readable = true;
  36. this.header = opts.header;
  37. this.encoding = opts.encoding;
  38. this.secret = this.privateKey = this.key = secretStream;
  39. this.payload = new DataStream(opts.payload);
  40. this.secret.once('close', function () {
  41. if (!this.payload.writable && this.readable)
  42. this.sign();
  43. }.bind(this));
  44. this.payload.once('close', function () {
  45. if (!this.secret.writable && this.readable)
  46. this.sign();
  47. }.bind(this));
  48. }
  49. util.inherits(SignStream, Stream);
  50. SignStream.prototype.sign = function sign() {
  51. try {
  52. var signature = jwsSign({
  53. header: this.header,
  54. payload: this.payload.buffer,
  55. secret: this.secret.buffer,
  56. encoding: this.encoding
  57. });
  58. this.emit('done', signature);
  59. this.emit('data', signature);
  60. this.emit('end');
  61. this.readable = false;
  62. return signature;
  63. } catch (e) {
  64. this.readable = false;
  65. this.emit('error', e);
  66. this.emit('close');
  67. }
  68. };
  69. SignStream.sign = jwsSign;
  70. module.exports = SignStream;