sign-stream.js
2.15 KB
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
/*global module*/
var Buffer = require('safe-buffer').Buffer;
var DataStream = require('./data-stream');
var jwa = require('jwa');
var Stream = require('stream');
var toString = require('./tostring');
var util = require('util');
function base64url(string, encoding) {
return Buffer
.from(string, encoding)
.toString('base64')
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
function jwsSecuredInput(header, payload, encoding) {
encoding = encoding || 'utf8';
var encodedHeader = base64url(toString(header), 'binary');
var encodedPayload = base64url(toString(payload), encoding);
return util.format('%s.%s', encodedHeader, encodedPayload);
}
function jwsSign(opts) {
var header = opts.header;
var payload = opts.payload;
var secretOrKey = opts.secret || opts.privateKey;
var encoding = opts.encoding;
var algo = jwa(header.alg);
var securedInput = jwsSecuredInput(header, payload, encoding);
var signature = algo.sign(securedInput, secretOrKey);
return util.format('%s.%s', securedInput, signature);
}
function SignStream(opts) {
var secret = opts.secret||opts.privateKey||opts.key;
var secretStream = new DataStream(secret);
this.readable = true;
this.header = opts.header;
this.encoding = opts.encoding;
this.secret = this.privateKey = this.key = secretStream;
this.payload = new DataStream(opts.payload);
this.secret.once('close', function () {
if (!this.payload.writable && this.readable)
this.sign();
}.bind(this));
this.payload.once('close', function () {
if (!this.secret.writable && this.readable)
this.sign();
}.bind(this));
}
util.inherits(SignStream, Stream);
SignStream.prototype.sign = function sign() {
try {
var signature = jwsSign({
header: this.header,
payload: this.payload.buffer,
secret: this.secret.buffer,
encoding: this.encoding
});
this.emit('done', signature);
this.emit('data', signature);
this.emit('end');
this.readable = false;
return signature;
} catch (e) {
this.readable = false;
this.emit('error', e);
this.emit('close');
}
};
SignStream.sign = jwsSign;
module.exports = SignStream;