This repository has been archived by the owner on May 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 264
/
wsapi_client.js
190 lines (171 loc) · 5.32 KB
/
wsapi_client.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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* this is a small standalone abstraction which lets scripts be
* browserid WSAPI clients. It handles CSRF token fetching and
* extraction/resending of cookies. It also allows one to have
* any number of "client contexts" which are just objects, and lets
* you simulated different simultaneous sessions.
*/
const
http = require('http'),
https = require('https'),
url = require('url'),
querystring = require('querystring');
// this client library keeps timing stats to allow higher level code
// (like loadgen) to output latency numbers
var numberOfRequests = 0;
// consider latency over the last N requests
const LATENCY_DECAY = 300;
var recentLatency = 0;
function startRequest() {
return new Date();
}
exports.recentLatency = function() { return recentLatency; };
function completeRequest(startTime) {
numberOfRequests++;
var num = numberOfRequests < LATENCY_DECAY ? numberOfRequests : LATENCY_DECAY;
recentLatency = ((new Date() - startTime) + (recentLatency * (num - 1))) / num;
}
function injectCookies(ctx, headers) {
if (ctx.cookieJar && Object.keys(ctx.cookieJar).length) {
headers.Cookie = "";
for (var k in ctx.cookieJar) {
headers.Cookie += k + "=" + ctx.cookieJar[k];
}
}
}
function extractCookies(ctx, res) {
if (ctx.cookieJar === undefined) ctx.cookieJar = {};
if (res.headers['set-cookie']) {
res.headers['set-cookie'].forEach(function(cookie) {
var m = /^([^;]+)(?:;.*)$/.exec(cookie);
if (m) {
var x = m[1].split('=');
ctx.cookieJar[x[0]] = x[1];
}
});
}
}
exports.clearCookies = function(ctx) {
if (ctx && ctx.cookieJar) delete ctx.cookieJar;
if (ctx && ctx.session) delete ctx.session;
};
exports.getCookie = function(ctx, which) {
if (typeof which === 'string') which = new RegExp('/^' + which + '$/');
var cookieNames = Object.keys(ctx.cookieJar);
for (var i = 0; i < cookieNames.length; i++) {
if (which.test(cookieNames[i])) return ctx.cookieJar[cookieNames[i]];
}
return null;
};
exports.injectCookies = injectCookies;
exports.get = function(cfg, path, context, getArgs, cb) {
// parse the server URL (cfg.browserid)
var uObj;
var meth;
try {
uObj = url.parse(cfg.browserid);
meth = uObj.protocol === 'http:' ? http : https;
} catch(e) {
cb("can't parse url: " + e);
return;
}
var headers = { };
injectCookies(context, headers);
if (typeof getArgs === 'object')
path += "?" + querystring.stringify(getArgs);
var timingHandle = startRequest();
meth.get({
host: uObj.hostname,
port: uObj.port,
path: path,
headers: headers,
agent: false // disable node.js connection pooling
}, function(res) {
extractCookies(context, res);
var body = '';
res.on('data', function(chunk) { body += chunk; })
.on('end', function() {
completeRequest(timingHandle);
if (cb) cb(null, {code: res.statusCode, headers: res.headers, body: body});
cb = null;
});
}).on('error', function (e) {
if (cb) cb(e);
cb = null;
});
};
function withCSRF(cfg, context, cb) {
if (context.session && context.session.csrf_token) cb(null, context.session.csrf_token);
else {
exports.get(cfg, '/wsapi/session_context', context, undefined, function(err, r) {
if (err) return cb(err);
try {
if (r.code !== 200)
return cb({what: "http error", resp: r}); // report first error
context.session = JSON.parse(r.body);
context.sessionStartedAt = new Date().getTime();
cb(null, context.session.csrf_token);
} catch(e) {
console.log('error getting csrf token: ', e);
cb(e);
}
});
}
}
exports.post = function(cfg, path, context, postArgs, cb) {
withCSRF(cfg, context, function(err, csrf) {
if (err) {
if (err.what === "http error") {
// let the session_context HTTP return code speak for the overall
// POST
return cb(null, err.resp);
}
return cb(err);
}
// parse the server URL (cfg.browserid)
var uObj;
var meth;
var body;
try {
uObj = url.parse(cfg.browserid);
meth = uObj.protocol === 'http:' ? http : https;
} catch(e) {
cb("can't parse url: " + e);
return;
}
var headers = {
'Content-Type': 'application/json'
};
injectCookies(context, headers);
if (typeof postArgs === 'object') {
postArgs.csrf = csrf;
body = JSON.stringify(postArgs);
headers['Content-Length'] = Buffer.byteLength(body);
}
var timingHandle = startRequest();
var req = meth.request({
host: uObj.hostname,
port: uObj.port,
path: path,
headers: headers,
method: "POST",
agent: false // disable node.js connection pooling
}, function(res) {
extractCookies(context, res);
var body = '';
res.on('data', function(chunk) { body += chunk; })
.on('end', function() {
completeRequest(timingHandle);
if (cb) cb(null, {code: res.statusCode, headers: res.headers, body: body});
cb = null;
});
}).on('error', function (e) {
if (cb) cb(e);
cb = null;
});
req.write(body);
req.end();
});
};