-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
97 lines (76 loc) · 2.31 KB
/
index.js
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
var SigningStream = require('./signingstream').SigningStream;
var chars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
signFuction should be the following:
function (cleartext, callback);
- `cleartext`: a `String` var to be signed
- `callback`: a function(err, ciphertext) width:
* `err`: a string containing error if one occured
* `signature`: a string containing ASCII armored signature
Note: a valid PGP signatures matches this format:
> -----BEGIN PGP SIGNATURE-----
> ...
> -----END PGP SIGNATURE-----
**/
module.exports = function sign(signFunction) {
return function sign(req, res, next){
var write = res.write
, end = res.end
, stream
, method
, doSign = req.headers['accept'] == 'multipart/msigned';
// see compress.js #724
req.on('close', function(){
res.write = res.end = function(){};
});
// proxy
res.write = function(chunk, encoding){
if (!this.headerSent) this._implicitHeader();
return stream
? stream.write(new Buffer(chunk, encoding))
: write.call(res, chunk, encoding);
};
res.end = function(chunk, encoding){
if (chunk) {
doSign = doSign && !this.headerSent;
this.write(chunk, encoding);
} else if (!this.headerSent) {
// response size === 0
}
return stream
? stream.end()
: end.call(res);
};
// Rendering fired
res.on('header', function(){
if (!doSign) return;
// head
if ('HEAD' == req.method) return;
var boundary = "";
for (var i = 0; i < 15; i++) {
var num = Math.floor(Math.random() * 100) % 62;
boundary += chars[num];
};
// signature stream
stream = new SigningStream(signFunction, boundary);
// header fields
var contentType = 'multipart/msigned;';
contentType += ' boundary='+boundary+';';
res.setHeader('Content-Type', contentType);
res.removeHeader('Content-Length');
// signature
stream.on('data', function(chunk){
write.call(res, chunk);
});
stream.on('end', function(){
this.sign(function (body) {
end.call(res, body);
});
});
stream.on('drain', function() {
res.emit('drain');
});
});
next();
};
};