tr-apisrv 0.2.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/MIT-RINNE +1 -1
- package/README.md +269 -24
- package/index.js +1038 -304
- package/package.json +3 -3
- package/test/test.js +1203 -2
package/index.js
CHANGED
|
@@ -2,311 +2,1045 @@
|
|
|
2
2
|
|
|
3
3
|
const http = require('http');
|
|
4
4
|
const https = require('https');
|
|
5
|
-
const qs = require('querystring')
|
|
6
5
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
if (typeof(opts.address) === 'string') {
|
|
30
|
-
this.address = opts.address;
|
|
31
|
-
} else if (opts.address) {
|
|
32
|
-
throw new Error('Bad address for ApiSrv constructor');
|
|
33
|
-
}
|
|
34
|
-
if (typeof(opts.callback) === 'function') {
|
|
35
|
-
this.callback = opts.callback;
|
|
36
|
-
} else {
|
|
37
|
-
throw new Error('Bad callback for ApiSrv constructor');
|
|
38
|
-
}
|
|
39
|
-
if ((opts.authCallback !== undefined) && (opts.authCallback !== null)) {
|
|
40
|
-
if (typeof(opts.authCallback) === 'function') {
|
|
41
|
-
this.authCallback = opts.authCallback;
|
|
42
|
-
} else {
|
|
43
|
-
throw new Error('Bad authCallback for ApiSrv constructor');
|
|
44
|
-
}
|
|
45
|
-
} else {
|
|
46
|
-
if (this.debug) {
|
|
47
|
-
console.log('No authentication callback set.');
|
|
48
|
-
}
|
|
49
|
-
this.authCallback = function(r) { return true; }.bind(this);
|
|
50
|
-
}
|
|
51
|
-
if ((opts.upgradeCallback !== undefined) && (opts.upgradeCallback !== null)) {
|
|
52
|
-
if (typeof(opts.upgradeCallback) === 'function') {
|
|
53
|
-
this.upgradeCallback = opts.upgradeCallback;
|
|
54
|
-
} else {
|
|
55
|
-
throw new Error('Bad upgradeCallback for ApiSrv constructor');
|
|
56
|
-
}
|
|
57
|
-
} else {
|
|
58
|
-
this.upgradeCallback = undefined
|
|
59
|
-
}
|
|
60
|
-
if ((opts.bodyReadTimeoutMs !== undefined) && (opts.bodyReadTimeoutMs !== null)) {
|
|
61
|
-
if (Number.isSafeInteger(opts.bodyReadTimeoutMs) && (opts.bodyReadTimeoutMs > 0)) {
|
|
62
|
-
this.bodyReadTimeoutMs = opts.bodyReadTimeoutMs;
|
|
63
|
-
} else {
|
|
64
|
-
throw new Error('Bad bodyReadTimeoutMs for ApiSrv constructor');
|
|
65
|
-
}
|
|
66
|
-
} else {
|
|
67
|
-
this.bodyReadTimeoutMs = 2 * 1000;
|
|
68
|
-
}
|
|
69
|
-
srvOpts.headersTimeout = this.bodyReadTimeoutMs;
|
|
70
|
-
srvOpts.requestTimeout = this.bodyReadTimeoutMs + 1;
|
|
71
|
-
|
|
72
|
-
var upgradeCb = function(req, s, head) {
|
|
73
|
-
var m, r = {};
|
|
74
|
-
r.method = req.method;
|
|
75
|
-
if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
|
|
76
|
-
r.url = m[1];
|
|
77
|
-
if (! (r.params = qs.parse(m[2].toString('utf8')))) {
|
|
78
|
-
s.end();
|
|
79
|
-
return;
|
|
80
|
-
}
|
|
81
|
-
} else {
|
|
82
|
-
r.url = req.url;
|
|
83
|
-
r.params = {};
|
|
84
|
-
}
|
|
85
|
-
r.headers = req.headers;
|
|
86
|
-
r.req = req;
|
|
87
|
-
return (Promise.resolve(this.authCallback(r))
|
|
88
|
-
.then(function(ret) {
|
|
89
|
-
if (ret) {
|
|
90
|
-
r.head = head;
|
|
91
|
-
r.s = s;
|
|
92
|
-
return opts.upgradeCallback(r);
|
|
93
|
-
} else {
|
|
94
|
-
s.destroy();
|
|
95
|
-
s = undefined;
|
|
96
|
-
}
|
|
97
|
-
}.bind(this))
|
|
98
|
-
.then(function(ret) {
|
|
99
|
-
if (ret !== false) {
|
|
100
|
-
if (this.debug) {
|
|
101
|
-
console.log('Upgrade successfully processed (resource :' + r.url + ').');
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}.bind(this))
|
|
105
|
-
.catch(function(e) {
|
|
106
|
-
if (s) {
|
|
107
|
-
try {
|
|
108
|
-
s.destroy();
|
|
109
|
-
s = undefined;
|
|
110
|
-
} catch(ignored) {
|
|
111
|
-
s = undefined;
|
|
112
|
-
}
|
|
113
|
-
return false;
|
|
114
|
-
}
|
|
115
|
-
}.bind(this)));
|
|
116
|
-
}.bind(this);
|
|
117
|
-
var requestCb = function(req, res) {
|
|
118
|
-
var completed = false, body = Buffer.alloc(0), r = {}, timeout;
|
|
119
|
-
var contentType, contentTypeArgs;
|
|
120
|
-
var dataCb = function(data) {
|
|
121
|
-
if (completed) {
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
body = Buffer.concat( [ body, data ] );
|
|
125
|
-
}.bind(this);
|
|
126
|
-
var endCb = function() {
|
|
127
|
-
if (completed) {
|
|
128
|
-
return;
|
|
129
|
-
}
|
|
130
|
-
completed = true;
|
|
131
|
-
if (timeout) {
|
|
132
|
-
clearTimeout(timeout);
|
|
133
|
-
timeout = undefined;
|
|
134
|
-
}
|
|
135
|
-
if (req.headers['content-type']) {
|
|
136
|
-
let m = req.headers['content-type'].match(/^\s*([^\s;]+)\s*(|;\s*(|.*[^\s]))\s*$/);
|
|
137
|
-
if (m) {
|
|
138
|
-
contentType = m[1];
|
|
139
|
-
contentTypeArgs = (m[3] && m[3] !== '') ? m[3] : undefined;
|
|
140
|
-
} else {
|
|
141
|
-
error(res, 400, 'Unable to parse content-type.');
|
|
142
|
-
return;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
switch (req.method) {
|
|
146
|
-
case 'POST':
|
|
147
|
-
case 'PUT':
|
|
148
|
-
if (req.url.match(/\?/)) {
|
|
149
|
-
error(res, 400, 'URL for POST or PUT must not contain query parameters.');
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
r.url = req.url;
|
|
153
|
-
r.method = req.method;
|
|
154
|
-
switch (contentType) {
|
|
155
|
-
case 'application/x-www-form-urlencoded':
|
|
156
|
-
case 'application/www-form-urlencoded':
|
|
157
|
-
if (! (r.params = qs.parse(body.toString('utf8')))) {
|
|
158
|
-
error(res, 400, 'Unable to parse query parameters.');
|
|
159
|
-
return;
|
|
160
|
-
}
|
|
161
|
-
break;
|
|
162
|
-
case 'application/json':
|
|
163
|
-
if (contentTypeArgs && (contentTypeArgs.toLowerCase() !== 'charset=utf-8')) {
|
|
164
|
-
error(res, 400, 'Bad charset for JSON content type.');
|
|
165
|
-
}
|
|
166
|
-
try {
|
|
167
|
-
r.params = JSON.parse(body.toString('utf8'));
|
|
168
|
-
} catch(e) {
|
|
169
|
-
r.params = undefined;
|
|
170
|
-
}
|
|
171
|
-
if (! (r.params && (typeof(r.params) === 'object'))) {
|
|
172
|
-
error(res, 400, 'Unable to parse JSON query parameters.');
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
break;
|
|
176
|
-
case 'multipart/form-data':
|
|
177
|
-
// We know this, but only wankers would use it here.
|
|
178
|
-
// RFC6749 anyways says that application/x-www-form-urlencoded
|
|
179
|
-
// is the "correct" way to go.
|
|
180
|
-
default:
|
|
181
|
-
error(res, 400, 'POST or PUT body must be in JSON or www-form-urlencoded format.');
|
|
182
|
-
return;
|
|
183
|
-
}
|
|
184
|
-
break;
|
|
185
|
-
case 'GET':
|
|
186
|
-
case 'DELETE':
|
|
187
|
-
if (body.length > 0) {
|
|
188
|
-
error(res, 400, 'Empty body required for ' + req.method + ' requests.');
|
|
189
|
-
return;
|
|
190
|
-
}
|
|
191
|
-
var m;
|
|
192
|
-
if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
|
|
193
|
-
r.url = m[1];
|
|
194
|
-
if (! (r.params = qs.parse(m[2].toString('utf8')))) {
|
|
195
|
-
error(res, 400, 'Unable to parse query parameters.');
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
} else {
|
|
199
|
-
r.url = req.url;
|
|
200
|
-
r.params = {};
|
|
201
|
-
}
|
|
202
|
-
r.method = req.method;
|
|
203
|
-
break;
|
|
204
|
-
default:
|
|
205
|
-
error(res, 405, 'Only GET, POST, PUT, and DELETE are allowed.');
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
r.headers = req.headers;
|
|
209
|
-
r.res = res;
|
|
210
|
-
r.jsonResponse = function(data, code, excludeNoCacheHeaders) {
|
|
211
|
-
var headers = { 'Content-Type': 'application/json; charset=utf-8' };
|
|
212
|
-
if (! excludeNoCacheHeaders) {
|
|
213
|
-
headers = Object.assign(headers,
|
|
214
|
-
{ 'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
|
|
215
|
-
'Expires': 'Wed, 01 Jan 2020 12:00:00 GMT',
|
|
216
|
-
'Pragma': 'no-cache' });
|
|
217
|
-
}
|
|
218
|
-
res.writeHead(code ? code : 200, headers);
|
|
219
|
-
if (this.prettyPrintJsonResponses) {
|
|
220
|
-
res.write(JSON.stringify(data, null, 2));
|
|
221
|
-
res.write("\n");
|
|
222
|
-
} else {
|
|
223
|
-
res.write(JSON.stringify(data));
|
|
224
|
-
}
|
|
225
|
-
res.end();
|
|
226
|
-
}.bind(this);
|
|
227
|
-
return (Promise.resolve(this.authCallback(r))
|
|
228
|
-
.then(function(ret) {
|
|
229
|
-
if (ret) {
|
|
230
|
-
return this.callback(r);
|
|
231
|
-
} else if (this.debug) {
|
|
232
|
-
console.log('Authentication failed (resource :' + r.url + ').');
|
|
233
|
-
}
|
|
234
|
-
return false;
|
|
235
|
-
}.bind(this))
|
|
236
|
-
.then(function(ret) {
|
|
237
|
-
if (ret !== false) {
|
|
238
|
-
if (this.debug) {
|
|
239
|
-
console.log('Request successfully processed (resource :' + r.url + ').');
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
}.bind(this))
|
|
243
|
-
.catch(function(e) {
|
|
244
|
-
if (this.debug) {
|
|
245
|
-
console.log(e);
|
|
246
|
-
}
|
|
247
|
-
try {
|
|
248
|
-
error(res, 500, 'Request handler fails to execute.');
|
|
249
|
-
} catch(e) {
|
|
250
|
-
}
|
|
251
|
-
}.bind(this)));
|
|
252
|
-
}.bind(this);
|
|
253
|
-
var errorCb = function() {
|
|
254
|
-
if (completed) {
|
|
255
|
-
return;
|
|
256
|
-
}
|
|
257
|
-
completed = true;
|
|
258
|
-
if (timeout) {
|
|
259
|
-
clearTimeout(timeout);
|
|
260
|
-
timeout = undefined;
|
|
261
|
-
}
|
|
262
|
-
error(res, 400, 'Error occured while reading the request data.');
|
|
263
|
-
}.bind(this);
|
|
264
|
-
var timeoutCb = function() {
|
|
265
|
-
if (completed) {
|
|
266
|
-
return;
|
|
267
|
-
}
|
|
268
|
-
timeout = undefined;
|
|
269
|
-
completed = true;
|
|
270
|
-
error(res, 408, 'Timeout occured while reading the request data.');
|
|
271
|
-
}.bind(this);
|
|
272
|
-
timeout = setTimeout(timeoutCb, this.bodyReadTimeoutMs);
|
|
273
|
-
req.on('data', dataCb);
|
|
274
|
-
req.on('end', endCb);
|
|
275
|
-
req.on('error', errorCb);
|
|
276
|
-
}.bind(this);
|
|
277
|
-
var error = function(res, code, text, RFC6749EC) {
|
|
278
|
-
if (RFC6749EC) {
|
|
279
|
-
// RFC6749 wants these errors to be code 400 except in case of 401
|
|
280
|
-
res.writeHead((code != 401) ? 400 : 401,
|
|
281
|
-
{ 'Content-Type': 'application/json; charset=utf-8' });
|
|
282
|
-
res.write(JSON.stringify( { error: RFC6749EC,
|
|
283
|
-
error_description: (text ?
|
|
284
|
-
(text +
|
|
285
|
-
' (HTTP code ' +
|
|
286
|
-
code.toString() +
|
|
287
|
-
')') :
|
|
288
|
-
('HTTP code ' +
|
|
289
|
-
code.toString())) },
|
|
290
|
-
null, 2));
|
|
291
|
-
|
|
292
|
-
res.write("\n");
|
|
293
|
-
} else {
|
|
294
|
-
res.writeHead(code, { 'Content-Type': 'text/plain' });
|
|
295
|
-
res.write(text);
|
|
296
|
-
res.write("\n");
|
|
297
|
-
}
|
|
298
|
-
res.end();
|
|
299
|
-
}.bind(this);
|
|
300
|
-
this.server = proto.createServer(srvOpts, requestCb);
|
|
301
|
-
if (this.upgradeCallback) {
|
|
302
|
-
this.server.on('upgrade', upgradeCb);
|
|
303
|
-
}
|
|
304
|
-
this.server.on('error', function(e) {
|
|
305
|
-
console.log('Unable to start HTTP server');
|
|
306
|
-
process.exit(1);
|
|
307
|
-
});
|
|
308
|
-
this.server.headersTimeout = 2000;
|
|
309
|
-
this.server.listen(this.port, this.address);
|
|
6
|
+
const SUPPORTED_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE']);
|
|
7
|
+
const HTTP_STATUS_MESSAGES = {
|
|
8
|
+
400: 'Bad Request',
|
|
9
|
+
401: 'Unauthorized',
|
|
10
|
+
403: 'Forbidden',
|
|
11
|
+
404: 'Not Found',
|
|
12
|
+
405: 'Method Not Allowed',
|
|
13
|
+
406: 'Not Acceptable',
|
|
14
|
+
408: 'Request Timeout',
|
|
15
|
+
409: 'Conflict',
|
|
16
|
+
413: 'Payload Too Large',
|
|
17
|
+
415: 'Unsupported Media Type',
|
|
18
|
+
429: 'Too Many Requests',
|
|
19
|
+
500: 'Internal Server Error',
|
|
20
|
+
501: 'Not Implemented',
|
|
21
|
+
503: 'Service Unavailable'
|
|
22
|
+
};
|
|
23
|
+
const PARAM_SOURCE_LABELS = {
|
|
24
|
+
body: 'request body',
|
|
25
|
+
query: 'query string',
|
|
26
|
+
path: 'path template'
|
|
310
27
|
};
|
|
28
|
+
const HANDLER_OPTION_KEYS = new Set([
|
|
29
|
+
'paramsValidator',
|
|
30
|
+
'pathParamsValidator',
|
|
31
|
+
'urlParamsValidator',
|
|
32
|
+
'bodyParamsValidator',
|
|
33
|
+
'ignoreUrlParams'
|
|
34
|
+
]);
|
|
35
|
+
const PARAM_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
36
|
+
const DEFAULT_SPLAT_MIN = 1;
|
|
37
|
+
const DEFAULT_SPLAT_MAX = 32;
|
|
38
|
+
|
|
39
|
+
function detectDangerousPath(path) {
|
|
40
|
+
if (typeof path !== 'string') {
|
|
41
|
+
return 'invalid request path';
|
|
42
|
+
}
|
|
43
|
+
if (path === '/') {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
if (path.includes('//')) {
|
|
47
|
+
return 'empty path segment';
|
|
48
|
+
}
|
|
49
|
+
if ((path === '/.') || path.endsWith('/.') || path.includes('/./')) {
|
|
50
|
+
return 'dangerous path segment "."';
|
|
51
|
+
}
|
|
52
|
+
if ((path === '/..') || path.endsWith('/..') || path.includes('/../')) {
|
|
53
|
+
return 'dangerous path segment ".."';
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
function parseQuery(str) {
|
|
58
|
+
const params = Object.create(null);
|
|
59
|
+
if (!str) {
|
|
60
|
+
return params;
|
|
61
|
+
}
|
|
62
|
+
const usp = new URLSearchParams(str.replace(/\+/g, '%20'));
|
|
63
|
+
for (const [key, value] of usp.entries()) {
|
|
64
|
+
if (Object.prototype.hasOwnProperty.call(params, key)) {
|
|
65
|
+
const cur = params[key];
|
|
66
|
+
if (Array.isArray(cur)) {
|
|
67
|
+
cur.push(value);
|
|
68
|
+
} else {
|
|
69
|
+
params[key] = [cur, value];
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
params[key] = value;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return params;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function parseContentType(str) {
|
|
79
|
+
const parts = str.split(';').map(p => p.trim()).filter(p => p !== '');
|
|
80
|
+
if (parts.length === 0) {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
const type = parts.shift().toLowerCase();
|
|
84
|
+
const params = Object.create(null);
|
|
85
|
+
for (const part of parts) {
|
|
86
|
+
const m = part.match(/^([!#$%&'*+.^_`|~0-9A-Za-z-]+)=((?:"(?:[^"\\]|\\.)*"|[^\s;]+))$/);
|
|
87
|
+
if (!m) {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
let val = m[2];
|
|
91
|
+
if (val.startsWith('"')) {
|
|
92
|
+
val = val.slice(1, -1);
|
|
93
|
+
}
|
|
94
|
+
params[m[1].toLowerCase()] = val.toLowerCase();
|
|
95
|
+
}
|
|
96
|
+
return { type, params };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function isPlainObject(value) {
|
|
100
|
+
return !!value && (typeof value === 'object') && !Array.isArray(value);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function normalizeHandlerOptions(method, path, options) {
|
|
104
|
+
if (options === undefined) {
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
if (!isPlainObject(options)) {
|
|
108
|
+
throw new Error(`Bad request handler options for ${method} ${path}`);
|
|
109
|
+
}
|
|
110
|
+
for (const key of Object.keys(options)) {
|
|
111
|
+
if (!HANDLER_OPTION_KEYS.has(key)) {
|
|
112
|
+
throw new Error(`Unsupported request handler option "${key}" for ${method} ${path}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const normalized = {};
|
|
116
|
+
if (options.paramsValidator !== undefined) {
|
|
117
|
+
if (typeof options.paramsValidator !== 'function') {
|
|
118
|
+
throw new Error(`paramsValidator must be a function for ${method} ${path}`);
|
|
119
|
+
}
|
|
120
|
+
normalized.paramsValidator = options.paramsValidator;
|
|
121
|
+
}
|
|
122
|
+
if (options.pathParamsValidator !== undefined) {
|
|
123
|
+
if (typeof options.pathParamsValidator !== 'function') {
|
|
124
|
+
throw new Error(`pathParamsValidator must be a function for ${method} ${path}`);
|
|
125
|
+
}
|
|
126
|
+
normalized.pathParamsValidator = options.pathParamsValidator;
|
|
127
|
+
}
|
|
128
|
+
if (options.urlParamsValidator !== undefined) {
|
|
129
|
+
if (typeof options.urlParamsValidator !== 'function') {
|
|
130
|
+
throw new Error(`urlParamsValidator must be a function for ${method} ${path}`);
|
|
131
|
+
}
|
|
132
|
+
normalized.urlParamsValidator = options.urlParamsValidator;
|
|
133
|
+
}
|
|
134
|
+
if (options.bodyParamsValidator !== undefined) {
|
|
135
|
+
if (typeof options.bodyParamsValidator !== 'function') {
|
|
136
|
+
throw new Error(`bodyParamsValidator must be a function for ${method} ${path}`);
|
|
137
|
+
}
|
|
138
|
+
normalized.bodyParamsValidator = options.bodyParamsValidator;
|
|
139
|
+
}
|
|
140
|
+
if (options.ignoreUrlParams !== undefined) {
|
|
141
|
+
if (typeof options.ignoreUrlParams !== 'boolean') {
|
|
142
|
+
throw new Error(`ignoreUrlParams must be a boolean for ${method} ${path}`);
|
|
143
|
+
}
|
|
144
|
+
if (options.ignoreUrlParams) {
|
|
145
|
+
normalized.ignoreUrlParams = true;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return Object.keys(normalized).length > 0 ? normalized : undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function describePath(path) {
|
|
152
|
+
if (typeof path !== 'string' || !path.startsWith('/')) {
|
|
153
|
+
throw new Error(`Bad request path: ${path}`);
|
|
154
|
+
}
|
|
155
|
+
if (path === '/') {
|
|
156
|
+
return { segments: [], hasTrailingSlash: false };
|
|
157
|
+
}
|
|
158
|
+
const hasTrailingSlash = (path.length > 1) && path.endsWith('/');
|
|
159
|
+
const trimmed = hasTrailingSlash ? path.slice(0, -1) : path;
|
|
160
|
+
if (trimmed === '/') {
|
|
161
|
+
return { segments: [], hasTrailingSlash: true };
|
|
162
|
+
}
|
|
163
|
+
const segments = trimmed.slice(1).split('/');
|
|
164
|
+
return { segments, hasTrailingSlash };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function decodePathSegment(segment) {
|
|
168
|
+
try {
|
|
169
|
+
return decodeURIComponent(segment);
|
|
170
|
+
} catch (e) {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function compilePathTemplate(path) {
|
|
176
|
+
if (typeof path !== 'string' || !path.startsWith('/')) {
|
|
177
|
+
throw new Error(`Bad request handler path: ${path}`);
|
|
178
|
+
}
|
|
179
|
+
if (path === '/') {
|
|
180
|
+
return {
|
|
181
|
+
isExact: true,
|
|
182
|
+
template: path,
|
|
183
|
+
segments: [],
|
|
184
|
+
hasTrailingSlash: false,
|
|
185
|
+
hasSplat: false,
|
|
186
|
+
minSegments: 0,
|
|
187
|
+
minSegmentsFrom: [0]
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
const hasTrailingSlash = (path.length > 1) && path.endsWith('/');
|
|
191
|
+
const trimmed = hasTrailingSlash ? path.slice(0, -1) : path;
|
|
192
|
+
const rawSegments = trimmed.slice(1).split('/');
|
|
193
|
+
const segments = [];
|
|
194
|
+
let hasDynamic = false;
|
|
195
|
+
let hasSplat = false;
|
|
196
|
+
for (const part of rawSegments) {
|
|
197
|
+
if (part === '') {
|
|
198
|
+
segments.push({ type: 'literal', value: '' });
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
let match;
|
|
202
|
+
if ((match = part.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/))) {
|
|
203
|
+
hasDynamic = true;
|
|
204
|
+
const name = match[1];
|
|
205
|
+
if (!PARAM_NAME_RE.test(name)) {
|
|
206
|
+
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
207
|
+
}
|
|
208
|
+
segments.push({ type: 'param', name });
|
|
209
|
+
} else if ((match = part.match(/^\[([A-Za-z_][A-Za-z0-9_]*)(?::(\d+)(?::(\d+))?)?\]$/))) {
|
|
210
|
+
hasDynamic = true;
|
|
211
|
+
hasSplat = true;
|
|
212
|
+
const name = match[1];
|
|
213
|
+
if (!PARAM_NAME_RE.test(name)) {
|
|
214
|
+
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
215
|
+
}
|
|
216
|
+
let minItems = DEFAULT_SPLAT_MIN;
|
|
217
|
+
let maxItems = DEFAULT_SPLAT_MAX;
|
|
218
|
+
if (match[2] !== undefined) {
|
|
219
|
+
const first = Number.parseInt(match[2], 10);
|
|
220
|
+
if (!Number.isSafeInteger(first)) {
|
|
221
|
+
throw new Error(`Invalid array length constraint for "${name}" in ${path}`);
|
|
222
|
+
}
|
|
223
|
+
if (match[3] === undefined) {
|
|
224
|
+
minItems = first;
|
|
225
|
+
maxItems = first;
|
|
226
|
+
} else {
|
|
227
|
+
const second = Number.parseInt(match[3], 10);
|
|
228
|
+
if (!Number.isSafeInteger(second)) {
|
|
229
|
+
throw new Error(`Invalid array length constraint for "${name}" in ${path}`);
|
|
230
|
+
}
|
|
231
|
+
minItems = first;
|
|
232
|
+
maxItems = second;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (minItems < 1) {
|
|
236
|
+
throw new Error(`Invalid minimum length for "${name}" in ${path}`);
|
|
237
|
+
}
|
|
238
|
+
if (maxItems < minItems) {
|
|
239
|
+
throw new Error(`Invalid length range for "${name}" in ${path}`);
|
|
240
|
+
}
|
|
241
|
+
segments.push({ type: 'splat', name, minItems, maxItems });
|
|
242
|
+
} else if (part.startsWith('{') && part.endsWith('}')) {
|
|
243
|
+
const name = part.slice(1, -1);
|
|
244
|
+
if (!PARAM_NAME_RE.test(name)) {
|
|
245
|
+
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
246
|
+
}
|
|
247
|
+
throw new Error(`Invalid path parameter segment "${part}" in ${path}`);
|
|
248
|
+
} else if (part.startsWith('[') && part.endsWith(']')) {
|
|
249
|
+
const inner = part.slice(1, -1);
|
|
250
|
+
const name = inner.split(':', 1)[0];
|
|
251
|
+
if (!PARAM_NAME_RE.test(name)) {
|
|
252
|
+
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
253
|
+
}
|
|
254
|
+
throw new Error(`Invalid path parameter segment "${part}" in ${path}`);
|
|
255
|
+
} else {
|
|
256
|
+
segments.push({ type: 'literal', value: part });
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const minSegmentsFrom = new Array(segments.length + 1);
|
|
260
|
+
minSegmentsFrom[segments.length] = 0;
|
|
261
|
+
for (let i = segments.length - 1; i >= 0; i--) {
|
|
262
|
+
const segment = segments[i];
|
|
263
|
+
const minCount = segment.type === 'splat' ? segment.minItems : 1;
|
|
264
|
+
minSegmentsFrom[i] = minSegmentsFrom[i + 1] + minCount;
|
|
265
|
+
}
|
|
266
|
+
return {
|
|
267
|
+
isExact: !hasDynamic,
|
|
268
|
+
template: path,
|
|
269
|
+
segments,
|
|
270
|
+
hasTrailingSlash,
|
|
271
|
+
hasSplat,
|
|
272
|
+
minSegments: minSegmentsFrom[0],
|
|
273
|
+
minSegmentsFrom
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function matchCompiledPath(compiled, pathInfo) {
|
|
278
|
+
if (compiled.hasTrailingSlash && !pathInfo.hasTrailingSlash) {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
if (pathInfo.segments.length < compiled.minSegments) {
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
if (!compiled.hasSplat && (pathInfo.segments.length !== compiled.segments.length)) {
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
if (compiled.segments.length === 0) {
|
|
288
|
+
return pathInfo.segments.length === 0 ? {} : null;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const segments = compiled.segments;
|
|
292
|
+
const reqSegments = pathInfo.segments;
|
|
293
|
+
|
|
294
|
+
function matchRecursive(tIndex, rIndex) {
|
|
295
|
+
if (tIndex === segments.length) {
|
|
296
|
+
return (rIndex === reqSegments.length) ? {} : null;
|
|
297
|
+
}
|
|
298
|
+
const segment = segments[tIndex];
|
|
299
|
+
if (segment.type === 'literal') {
|
|
300
|
+
if ((rIndex >= reqSegments.length) || (segment.value !== reqSegments[rIndex])) {
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
return matchRecursive(tIndex + 1, rIndex + 1);
|
|
304
|
+
}
|
|
305
|
+
if (segment.type === 'param') {
|
|
306
|
+
if (rIndex >= reqSegments.length) {
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
const decoded = decodePathSegment(reqSegments[rIndex]);
|
|
310
|
+
if (decoded === null) {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
const rest = matchRecursive(tIndex + 1, rIndex + 1);
|
|
314
|
+
if (!rest) {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
rest[segment.name] = decoded;
|
|
318
|
+
return rest;
|
|
319
|
+
}
|
|
320
|
+
if (segment.type === 'splat') {
|
|
321
|
+
if (rIndex >= reqSegments.length) {
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
const minRemaining = compiled.minSegmentsFrom[tIndex + 1];
|
|
325
|
+
const minLen = segment.minItems;
|
|
326
|
+
const available = reqSegments.length - rIndex - minRemaining;
|
|
327
|
+
if (available < minLen) {
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
const maxLen = Math.min(segment.maxItems, available);
|
|
331
|
+
if (maxLen < minLen) {
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
for (let len = minLen; len <= maxLen; len++) {
|
|
335
|
+
const slice = reqSegments.slice(rIndex, rIndex + len);
|
|
336
|
+
if (slice.length !== len) {
|
|
337
|
+
break;
|
|
338
|
+
}
|
|
339
|
+
const decodedSlice = [];
|
|
340
|
+
let failed = false;
|
|
341
|
+
for (const part of slice) {
|
|
342
|
+
const decoded = decodePathSegment(part);
|
|
343
|
+
if (decoded === null) {
|
|
344
|
+
failed = true;
|
|
345
|
+
break;
|
|
346
|
+
}
|
|
347
|
+
decodedSlice.push(decoded);
|
|
348
|
+
}
|
|
349
|
+
if (failed) {
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
const rest = matchRecursive(tIndex + 1, rIndex + len);
|
|
353
|
+
if (!rest) {
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
rest[segment.name] = decodedSlice;
|
|
357
|
+
return rest;
|
|
358
|
+
}
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return matchRecursive(0, 0);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function assignParams(target, source, sourceType, sources) {
|
|
368
|
+
if (!source) {
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
for (const [key, value] of Object.entries(source)) {
|
|
372
|
+
if (Object.prototype.hasOwnProperty.call(target, key)) {
|
|
373
|
+
const previous = sources.get(key);
|
|
374
|
+
if (previous && previous !== sourceType) {
|
|
375
|
+
const prevLabel = PARAM_SOURCE_LABELS[previous] || previous;
|
|
376
|
+
const currentLabel = PARAM_SOURCE_LABELS[sourceType] || sourceType;
|
|
377
|
+
console.warn(`ApiSrv warning: parameter "${key}" from ${currentLabel} overrides value from ${prevLabel}.`);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
target[key] = value;
|
|
381
|
+
sources.set(key, sourceType);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function normalizeMethod(method) {
|
|
386
|
+
if (typeof method !== 'string') {
|
|
387
|
+
throw new Error(`Bad request handler method: ${method}`);
|
|
388
|
+
}
|
|
389
|
+
const upper = method.toUpperCase();
|
|
390
|
+
if (!SUPPORTED_METHODS.has(upper)) {
|
|
391
|
+
throw new Error(`Unsupported request handler method: ${method}`);
|
|
392
|
+
}
|
|
393
|
+
return upper;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function getMethodStore(map, method, createIfMissing) {
|
|
397
|
+
let store = map.get(method);
|
|
398
|
+
if (!store && createIfMissing) {
|
|
399
|
+
store = { exact: new Map(), dynamic: new Map() };
|
|
400
|
+
map.set(method, store);
|
|
401
|
+
}
|
|
402
|
+
return store;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function removeFromStore(store, path) {
|
|
406
|
+
let removed = false;
|
|
407
|
+
if (store.exact.delete(path)) {
|
|
408
|
+
removed = true;
|
|
409
|
+
}
|
|
410
|
+
if (store.dynamic.delete(path)) {
|
|
411
|
+
removed = true;
|
|
412
|
+
}
|
|
413
|
+
return removed;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function findMatchInStore(store, path) {
|
|
417
|
+
if (!store) {
|
|
418
|
+
return null;
|
|
419
|
+
}
|
|
420
|
+
let exact = store.exact.get(path);
|
|
421
|
+
if (exact) {
|
|
422
|
+
return { handler: exact.handler, options: exact.options, params: {} };
|
|
423
|
+
}
|
|
424
|
+
if ((path.length > 1) && path.endsWith('/')) {
|
|
425
|
+
const trimmed = path.slice(0, -1);
|
|
426
|
+
exact = store.exact.get(trimmed);
|
|
427
|
+
if (exact && !exact.hasTrailingSlash) {
|
|
428
|
+
return { handler: exact.handler, options: exact.options, params: {} };
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
const pathInfo = describePath(path);
|
|
432
|
+
for (const entry of store.dynamic.values()) {
|
|
433
|
+
const params = matchCompiledPath(entry, pathInfo);
|
|
434
|
+
if (params) {
|
|
435
|
+
return { handler: entry.handler, options: entry.options, params };
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return null;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
class ApiSrv {
|
|
442
|
+
constructor(opts) {
|
|
443
|
+
var proto = http;
|
|
444
|
+
var srvOpts = {};
|
|
445
|
+
if (!(opts && (typeof(opts) === 'object'))) {
|
|
446
|
+
throw new Error(`Bad opts for ApiSrv constructor: ${opts}`);
|
|
447
|
+
}
|
|
448
|
+
if (opts.key && opts.cert) {
|
|
449
|
+
srvOpts.key = opts.key;
|
|
450
|
+
srvOpts.cert = opts.cert;
|
|
451
|
+
proto = https;
|
|
452
|
+
} else if (opts.key) {
|
|
453
|
+
throw new Error('Key defined without cert');
|
|
454
|
+
} else if (opts.cert) {
|
|
455
|
+
throw new Error('Cert defined without key');
|
|
456
|
+
}
|
|
457
|
+
this.debug = opts.debug ? true : false;
|
|
458
|
+
this.prettyPrintJsonResponses = opts.prettyPrintJsonResponses ? true : false;
|
|
459
|
+
if (opts.rejectDangerousPaths === undefined) {
|
|
460
|
+
this.rejectDangerousPaths = true;
|
|
461
|
+
} else if (typeof opts.rejectDangerousPaths === 'boolean') {
|
|
462
|
+
this.rejectDangerousPaths = opts.rejectDangerousPaths;
|
|
463
|
+
} else {
|
|
464
|
+
throw new Error(`Bad rejectDangerousPaths for ApiSrv constructor: ${opts.rejectDangerousPaths}`);
|
|
465
|
+
}
|
|
466
|
+
if (Number.isSafeInteger(opts.port) && (opts.port > 0) && (opts.port < 65536)) {
|
|
467
|
+
this.port = opts.port;
|
|
468
|
+
} else {
|
|
469
|
+
throw new Error(`Bad port for ApiSrv constructor: ${opts.port}`);
|
|
470
|
+
}
|
|
471
|
+
if (typeof(opts.address) === 'string') {
|
|
472
|
+
this.address = opts.address;
|
|
473
|
+
} else if (opts.address) {
|
|
474
|
+
throw new Error(`Bad address for ApiSrv constructor: ${opts.address}`);
|
|
475
|
+
}
|
|
476
|
+
if (opts.callback !== undefined) {
|
|
477
|
+
if (typeof(opts.callback) === 'function') {
|
|
478
|
+
this.callback = opts.callback;
|
|
479
|
+
} else {
|
|
480
|
+
throw new Error(`Bad callback for ApiSrv constructor: ${opts.callback}`);
|
|
481
|
+
}
|
|
482
|
+
} else {
|
|
483
|
+
this.callback = undefined;
|
|
484
|
+
}
|
|
485
|
+
this._requestHandlers = new Map();
|
|
486
|
+
if (opts.requestHandlers !== undefined) {
|
|
487
|
+
if (!isPlainObject(opts.requestHandlers)) {
|
|
488
|
+
throw new Error('requestHandlers must be an object.');
|
|
489
|
+
}
|
|
490
|
+
for (const [method, handlers] of Object.entries(opts.requestHandlers)) {
|
|
491
|
+
if (!isPlainObject(handlers)) {
|
|
492
|
+
throw new Error(`Bad requestHandlers for method ${method}`);
|
|
493
|
+
}
|
|
494
|
+
for (const [path, handlerDef] of Object.entries(handlers)) {
|
|
495
|
+
if (typeof handlerDef === 'function') {
|
|
496
|
+
this.requestHandleAdd(method, path, handlerDef);
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
if (isPlainObject(handlerDef)) {
|
|
500
|
+
for (const key of Object.keys(handlerDef)) {
|
|
501
|
+
if (key !== 'callback' && key !== 'options') {
|
|
502
|
+
throw new Error(`Unsupported request handler definition key "${key}" for ${method} ${path}`);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
if (typeof handlerDef.callback !== 'function') {
|
|
506
|
+
throw new Error(`Bad request handler callback for ${method} ${path}`);
|
|
507
|
+
}
|
|
508
|
+
this.requestHandleAdd(method, path, handlerDef.callback, handlerDef.options);
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
throw new Error(`Bad request handler callback for ${method} ${path}`);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
if ((opts.authCallback !== undefined) && (opts.authCallback !== null)) {
|
|
516
|
+
if (typeof(opts.authCallback) === 'function') {
|
|
517
|
+
this.authCallback = opts.authCallback;
|
|
518
|
+
} else {
|
|
519
|
+
throw new Error(`Bad authCallback for ApiSrv constructor: ${opts.authCallback}`);
|
|
520
|
+
}
|
|
521
|
+
} else {
|
|
522
|
+
if (this.debug) {
|
|
523
|
+
console.log('No authentication callback set.');
|
|
524
|
+
}
|
|
525
|
+
this.authCallback = (r) => true;
|
|
526
|
+
}
|
|
527
|
+
if ((opts.upgradeCallback !== undefined) && (opts.upgradeCallback !== null)) {
|
|
528
|
+
if (typeof(opts.upgradeCallback) === 'function') {
|
|
529
|
+
this.upgradeCallback = opts.upgradeCallback;
|
|
530
|
+
} else {
|
|
531
|
+
throw new Error(`Bad upgradeCallback for ApiSrv constructor: ${opts.upgradeCallback}`);
|
|
532
|
+
}
|
|
533
|
+
} else {
|
|
534
|
+
this.upgradeCallback = undefined
|
|
535
|
+
}
|
|
536
|
+
if ((opts.bodyReadTimeoutMs !== undefined) && (opts.bodyReadTimeoutMs !== null)) {
|
|
537
|
+
if (Number.isSafeInteger(opts.bodyReadTimeoutMs) && (opts.bodyReadTimeoutMs > 0)) {
|
|
538
|
+
this.bodyReadTimeoutMs = opts.bodyReadTimeoutMs;
|
|
539
|
+
} else {
|
|
540
|
+
throw new Error(`Bad bodyReadTimeoutMs for ApiSrv constructor: ${opts.bodyReadTimeoutMs}`);
|
|
541
|
+
}
|
|
542
|
+
} else {
|
|
543
|
+
this.bodyReadTimeoutMs = 2 * 1000;
|
|
544
|
+
}
|
|
545
|
+
if ((opts.maxBodySize !== undefined) && (opts.maxBodySize !== null)) {
|
|
546
|
+
if (Number.isSafeInteger(opts.maxBodySize) && (opts.maxBodySize >= 0)) {
|
|
547
|
+
this.maxBodySize = opts.maxBodySize;
|
|
548
|
+
} else {
|
|
549
|
+
throw new Error(`Bad maxBodySize for ApiSrv constructor: ${opts.maxBodySize}`);
|
|
550
|
+
}
|
|
551
|
+
} else {
|
|
552
|
+
this.maxBodySize = 1024 * 1024;
|
|
553
|
+
}
|
|
554
|
+
srvOpts.headersTimeout = this.bodyReadTimeoutMs;
|
|
555
|
+
srvOpts.requestTimeout = this.bodyReadTimeoutMs + 1;
|
|
556
|
+
|
|
557
|
+
const upgradeCb = async (req, s, head) => {
|
|
558
|
+
var m, r = {};
|
|
559
|
+
r.method = req.method;
|
|
560
|
+
let rawQueryString;
|
|
561
|
+
if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
|
|
562
|
+
r.url = m[1];
|
|
563
|
+
rawQueryString = m[2].toString('utf8');
|
|
564
|
+
} else {
|
|
565
|
+
r.url = req.url;
|
|
566
|
+
rawQueryString = undefined;
|
|
567
|
+
}
|
|
568
|
+
r.bodyParams = undefined;
|
|
569
|
+
r.urlParams = undefined;
|
|
570
|
+
r.pathParams = undefined;
|
|
571
|
+
r.params = undefined;
|
|
572
|
+
r.headers = req.headers;
|
|
573
|
+
r.req = req;
|
|
574
|
+
try {
|
|
575
|
+
const ret = await this.authCallback(r);
|
|
576
|
+
if (ret) {
|
|
577
|
+
const queryOnlyParams = parseQuery(rawQueryString);
|
|
578
|
+
r.urlParams = queryOnlyParams;
|
|
579
|
+
r.params = queryOnlyParams;
|
|
580
|
+
r.bodyParams = Object.create(null);
|
|
581
|
+
r.pathParams = Object.create(null);
|
|
582
|
+
r.head = head;
|
|
583
|
+
r.s = s;
|
|
584
|
+
const cbRet = await opts.upgradeCallback(r);
|
|
585
|
+
if (cbRet && this.debug) {
|
|
586
|
+
console.log('Upgrade successfully processed (resource :' + r.url + ').');
|
|
587
|
+
}
|
|
588
|
+
return cbRet;
|
|
589
|
+
} else {
|
|
590
|
+
s.destroy();
|
|
591
|
+
s = undefined;
|
|
592
|
+
return false;
|
|
593
|
+
}
|
|
594
|
+
} catch (e) {
|
|
595
|
+
if (s) {
|
|
596
|
+
try {
|
|
597
|
+
s.destroy();
|
|
598
|
+
s = undefined;
|
|
599
|
+
} catch(ignored) {
|
|
600
|
+
s = undefined;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return false;
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
const requestCb = (req, res) => {
|
|
607
|
+
var completed = false, body = Buffer.alloc(0), r = {}, timeout, bodySize = 0;
|
|
608
|
+
var contentType, contentTypeArgs;
|
|
609
|
+
var declaredContentLength;
|
|
610
|
+
if (req.headers['transfer-encoding'] && req.headers['content-length']) {
|
|
611
|
+
error(res, 400, 'Both Transfer-Encoding and Content-Length defined.');
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
if (req.headers['content-length']) {
|
|
615
|
+
var cl = parseInt(req.headers['content-length'], 10);
|
|
616
|
+
if (!Number.isSafeInteger(cl) || cl < 0) {
|
|
617
|
+
error(res, 400, 'Bad Content-Length header.');
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
declaredContentLength = cl;
|
|
621
|
+
if (this.maxBodySize && (cl > this.maxBodySize)) {
|
|
622
|
+
error(res, 413, 'Request body too large.');
|
|
623
|
+
try {
|
|
624
|
+
req.destroy();
|
|
625
|
+
} catch (ignored) {
|
|
626
|
+
}
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
const dataCb = (data) => {
|
|
631
|
+
if (completed) {
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
bodySize += data.length;
|
|
635
|
+
if (declaredContentLength !== undefined && (bodySize > declaredContentLength)) {
|
|
636
|
+
completed = true;
|
|
637
|
+
if (timeout) {
|
|
638
|
+
clearTimeout(timeout);
|
|
639
|
+
timeout = undefined;
|
|
640
|
+
}
|
|
641
|
+
error(res, 400, 'Request body longer than Content-Length.');
|
|
642
|
+
try {
|
|
643
|
+
req.destroy();
|
|
644
|
+
} catch (ignored) {
|
|
645
|
+
}
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
if (this.maxBodySize && (bodySize > this.maxBodySize)) {
|
|
649
|
+
completed = true;
|
|
650
|
+
if (timeout) {
|
|
651
|
+
clearTimeout(timeout);
|
|
652
|
+
timeout = undefined;
|
|
653
|
+
}
|
|
654
|
+
error(res, 413, 'Request body too large.');
|
|
655
|
+
try {
|
|
656
|
+
req.destroy();
|
|
657
|
+
} catch (ignored) {
|
|
658
|
+
}
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
body = Buffer.concat( [ body, data ] );
|
|
662
|
+
};
|
|
663
|
+
const endCb = async () => {
|
|
664
|
+
if (completed) {
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
completed = true;
|
|
668
|
+
if (timeout) {
|
|
669
|
+
clearTimeout(timeout);
|
|
670
|
+
timeout = undefined;
|
|
671
|
+
}
|
|
672
|
+
if (declaredContentLength !== undefined && (body.length !== declaredContentLength)) {
|
|
673
|
+
error(res, 400, 'Request body length does not match Content-Length.');
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
if (req.headers['content-type']) {
|
|
677
|
+
let ct = parseContentType(req.headers['content-type']);
|
|
678
|
+
if (ct) {
|
|
679
|
+
contentType = ct.type;
|
|
680
|
+
contentTypeArgs = ct.params;
|
|
681
|
+
} else {
|
|
682
|
+
error(res, 400, 'Unable to parse content-type.');
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
let rawQueryString;
|
|
687
|
+
switch (req.method) {
|
|
688
|
+
case 'POST':
|
|
689
|
+
case 'PUT':
|
|
690
|
+
if (req.url.match(/\?/)) {
|
|
691
|
+
error(res, 400, 'URL for POST or PUT must not contain query parameters.');
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
r.url = req.url;
|
|
695
|
+
r.method = req.method;
|
|
696
|
+
rawQueryString = undefined;
|
|
697
|
+
break;
|
|
698
|
+
case 'GET':
|
|
699
|
+
case 'DELETE':
|
|
700
|
+
if (body.length > 0) {
|
|
701
|
+
error(res, 400, 'Empty body required for ' + req.method + ' requests.');
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
var m;
|
|
705
|
+
if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
|
|
706
|
+
r.url = m[1];
|
|
707
|
+
rawQueryString = m[2].toString('utf8');
|
|
708
|
+
} else {
|
|
709
|
+
r.url = req.url;
|
|
710
|
+
rawQueryString = undefined;
|
|
711
|
+
}
|
|
712
|
+
r.method = req.method;
|
|
713
|
+
break;
|
|
714
|
+
default:
|
|
715
|
+
error(res, 405, 'Only GET, POST, PUT, and DELETE are allowed.');
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (this.rejectDangerousPaths) {
|
|
719
|
+
const reason = detectDangerousPath(r.url);
|
|
720
|
+
if (reason) {
|
|
721
|
+
error(res, 400, reason);
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
r.headers = req.headers;
|
|
726
|
+
r.res = res;
|
|
727
|
+
r.req = req;
|
|
728
|
+
r.requestPayloadBuffer = body;
|
|
729
|
+
r.bodyParams = undefined;
|
|
730
|
+
r.urlParams = undefined;
|
|
731
|
+
r.pathParams = undefined;
|
|
732
|
+
r.params = undefined;
|
|
733
|
+
r.jsonResponse = (data, code, excludeNoCacheHeaders) => {
|
|
734
|
+
var headers = { 'Content-Type': 'application/json; charset=utf-8' };
|
|
735
|
+
if (! excludeNoCacheHeaders) {
|
|
736
|
+
headers = Object.assign(headers,
|
|
737
|
+
{ 'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
|
|
738
|
+
'Expires': 'Wed, 01 Jan 2020 12:00:00 GMT',
|
|
739
|
+
'Pragma': 'no-cache' });
|
|
740
|
+
}
|
|
741
|
+
res.writeHead(code ? code : 200, headers);
|
|
742
|
+
if (this.prettyPrintJsonResponses) {
|
|
743
|
+
res.write(JSON.stringify(data, null, 2));
|
|
744
|
+
res.write("\n");
|
|
745
|
+
} else {
|
|
746
|
+
res.write(JSON.stringify(data));
|
|
747
|
+
}
|
|
748
|
+
res.end();
|
|
749
|
+
};
|
|
750
|
+
r.errorResponse = (code, detail) => {
|
|
751
|
+
return error(res, code, detail);
|
|
752
|
+
};
|
|
753
|
+
try {
|
|
754
|
+
let handlerEntry = this.#matchRequestHandler(r.method, r.url);
|
|
755
|
+
let handler = handlerEntry ? handlerEntry.handler : undefined;
|
|
756
|
+
let handlerOptions = handlerEntry ? handlerEntry.options : undefined;
|
|
757
|
+
let pathParams = handlerEntry ? handlerEntry.params : Object.create(null);
|
|
758
|
+
if (!handler) {
|
|
759
|
+
if (this.callback) {
|
|
760
|
+
handler = this.callback;
|
|
761
|
+
handlerOptions = undefined;
|
|
762
|
+
pathParams = Object.create(null);
|
|
763
|
+
} else {
|
|
764
|
+
const hasOtherMethod = this.#hasHandlerForOtherMethod(r.method, r.url);
|
|
765
|
+
if (hasOtherMethod) {
|
|
766
|
+
jsonError(res, 405, 'Method Not Allowed');
|
|
767
|
+
} else {
|
|
768
|
+
jsonError(res, 404, 'Not Found');
|
|
769
|
+
}
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
const auth = await this.authCallback(r);
|
|
774
|
+
if (auth) {
|
|
775
|
+
const paramSources = new Map();
|
|
776
|
+
const ignoreUrlParams = handlerOptions && handlerOptions.ignoreUrlParams === true;
|
|
777
|
+
const runValidator = async (validator, value, description) => {
|
|
778
|
+
try {
|
|
779
|
+
const result = await validator(value);
|
|
780
|
+
if (!result || typeof result !== 'object') {
|
|
781
|
+
error(res, 500, `${description} validator must return an object.`);
|
|
782
|
+
return { success: false };
|
|
783
|
+
}
|
|
784
|
+
return { success: true, value: result };
|
|
785
|
+
} catch (err) {
|
|
786
|
+
const detail = (err && err.message) ? err.message : `Invalid ${description}.`;
|
|
787
|
+
error(res, 400, detail);
|
|
788
|
+
return { success: false };
|
|
789
|
+
}
|
|
790
|
+
};
|
|
791
|
+
let normalizedPathParams = (pathParams && (typeof pathParams === 'object')) ? pathParams : Object.create(null);
|
|
792
|
+
if (handlerOptions && handlerOptions.pathParamsValidator) {
|
|
793
|
+
const validation = await runValidator(handlerOptions.pathParamsValidator, normalizedPathParams, 'path parameters');
|
|
794
|
+
if (!validation.success) {
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
normalizedPathParams = validation.value;
|
|
798
|
+
}
|
|
799
|
+
let urlParams;
|
|
800
|
+
if (!ignoreUrlParams) {
|
|
801
|
+
urlParams = parseQuery(rawQueryString);
|
|
802
|
+
if (handlerOptions && handlerOptions.urlParamsValidator) {
|
|
803
|
+
const validation = await runValidator(handlerOptions.urlParamsValidator, urlParams, 'URL parameters');
|
|
804
|
+
if (!validation.success) {
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
urlParams = validation.value;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
let bodyParamsObject;
|
|
811
|
+
if (req.method === 'POST' || req.method === 'PUT') {
|
|
812
|
+
switch (contentType) {
|
|
813
|
+
case 'application/x-www-form-urlencoded':
|
|
814
|
+
case 'application/www-form-urlencoded':
|
|
815
|
+
bodyParamsObject = parseQuery(body.toString('utf8'));
|
|
816
|
+
break;
|
|
817
|
+
case 'application/json':
|
|
818
|
+
if (contentTypeArgs && contentTypeArgs.charset && (contentTypeArgs.charset !== 'utf-8')) {
|
|
819
|
+
error(res, 400, 'Bad charset for JSON content type.');
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
try {
|
|
823
|
+
bodyParamsObject = JSON.parse(body.toString('utf8'));
|
|
824
|
+
} catch(e) {
|
|
825
|
+
bodyParamsObject = undefined;
|
|
826
|
+
}
|
|
827
|
+
if (!(bodyParamsObject && (typeof bodyParamsObject === 'object'))) {
|
|
828
|
+
error(res, 400, 'Unable to parse JSON query parameters.');
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
break;
|
|
832
|
+
case 'multipart/form-data':
|
|
833
|
+
default:
|
|
834
|
+
error(res, 400, 'POST or PUT body must be in JSON or www-form-urlencoded format.');
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
let effectiveBodyParams = (bodyParamsObject && (typeof bodyParamsObject === 'object')) ? bodyParamsObject : Object.create(null);
|
|
839
|
+
if (handlerOptions && handlerOptions.bodyParamsValidator) {
|
|
840
|
+
const validation = await runValidator(handlerOptions.bodyParamsValidator, effectiveBodyParams, 'body parameters');
|
|
841
|
+
if (!validation.success) {
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
effectiveBodyParams = validation.value;
|
|
845
|
+
}
|
|
846
|
+
const mergedParams = {};
|
|
847
|
+
assignParams(mergedParams, effectiveBodyParams, 'body', paramSources);
|
|
848
|
+
let safeUrlParams;
|
|
849
|
+
if (!ignoreUrlParams) {
|
|
850
|
+
safeUrlParams = (urlParams && (typeof urlParams === 'object')) ? urlParams : Object.create(null);
|
|
851
|
+
assignParams(mergedParams, safeUrlParams, 'query', paramSources);
|
|
852
|
+
r.urlParams = safeUrlParams;
|
|
853
|
+
}
|
|
854
|
+
assignParams(mergedParams, (normalizedPathParams && (typeof normalizedPathParams === 'object')) ? normalizedPathParams : Object.create(null), 'path', paramSources);
|
|
855
|
+
if (handlerOptions && handlerOptions.paramsValidator) {
|
|
856
|
+
const validation = await runValidator(handlerOptions.paramsValidator, mergedParams, 'request parameters');
|
|
857
|
+
if (!validation.success) {
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
r.params = validation.value;
|
|
861
|
+
} else {
|
|
862
|
+
r.params = mergedParams;
|
|
863
|
+
}
|
|
864
|
+
r.bodyParams = effectiveBodyParams;
|
|
865
|
+
r.pathParams = (normalizedPathParams && (typeof normalizedPathParams === 'object')) ? normalizedPathParams : Object.create(null);
|
|
866
|
+
if (ignoreUrlParams) {
|
|
867
|
+
delete r.urlParams;
|
|
868
|
+
}
|
|
869
|
+
const ret = await handler.call(this, r);
|
|
870
|
+
if (ret !== false && this.debug) {
|
|
871
|
+
console.log('Request successfully processed (resource :' + r.url + ').');
|
|
872
|
+
}
|
|
873
|
+
} else if (this.debug) {
|
|
874
|
+
console.log('Authentication failed (resource :' + r.url + ').');
|
|
875
|
+
}
|
|
876
|
+
} catch (e) {
|
|
877
|
+
if (this.debug) {
|
|
878
|
+
console.log(e);
|
|
879
|
+
}
|
|
880
|
+
try {
|
|
881
|
+
error(res, 500, 'Request handler fails to execute.');
|
|
882
|
+
} catch(e) {
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
const errorCb = () => {
|
|
887
|
+
if (completed) {
|
|
888
|
+
return;
|
|
889
|
+
}
|
|
890
|
+
completed = true;
|
|
891
|
+
if (timeout) {
|
|
892
|
+
clearTimeout(timeout);
|
|
893
|
+
timeout = undefined;
|
|
894
|
+
}
|
|
895
|
+
error(res, 400, 'Error occured while reading the request data.');
|
|
896
|
+
};
|
|
897
|
+
const timeoutCb = () => {
|
|
898
|
+
if (completed) {
|
|
899
|
+
return;
|
|
900
|
+
}
|
|
901
|
+
timeout = undefined;
|
|
902
|
+
completed = true;
|
|
903
|
+
error(res, 408, 'Timeout occured while reading the request data.');
|
|
904
|
+
};
|
|
905
|
+
timeout = setTimeout(timeoutCb, this.bodyReadTimeoutMs);
|
|
906
|
+
req.on('data', dataCb);
|
|
907
|
+
req.on('end', endCb);
|
|
908
|
+
req.on('error', errorCb);
|
|
909
|
+
};
|
|
910
|
+
const error = (res, code, text, RFC6749EC) => {
|
|
911
|
+
if (RFC6749EC) {
|
|
912
|
+
// RFC6749 wants these errors to be code 400 except in case of 401
|
|
913
|
+
res.writeHead((code != 401) ? 400 : 401,
|
|
914
|
+
{ 'Content-Type': 'application/json; charset=utf-8' });
|
|
915
|
+
res.write(JSON.stringify( { error: RFC6749EC,
|
|
916
|
+
error_description: (text ?
|
|
917
|
+
(text +
|
|
918
|
+
' (HTTP code ' +
|
|
919
|
+
code.toString() +
|
|
920
|
+
')') :
|
|
921
|
+
('HTTP code ' +
|
|
922
|
+
code.toString())) },
|
|
923
|
+
null, 2));
|
|
924
|
+
|
|
925
|
+
res.write("\n");
|
|
926
|
+
} else {
|
|
927
|
+
const canonical = HTTP_STATUS_MESSAGES[code] || 'Error';
|
|
928
|
+
let detail = text ? text.trim() : '';
|
|
929
|
+
if (detail) {
|
|
930
|
+
detail = detail.replace(/\.+$/, '');
|
|
931
|
+
}
|
|
932
|
+
let message = canonical;
|
|
933
|
+
if (code === 400 && detail) {
|
|
934
|
+
message = `${canonical} (${detail})`;
|
|
935
|
+
}
|
|
936
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
937
|
+
res.write(JSON.stringify({ code, message }));
|
|
938
|
+
}
|
|
939
|
+
res.end();
|
|
940
|
+
};
|
|
941
|
+
const jsonError = (res, code, message) => {
|
|
942
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
943
|
+
res.write(JSON.stringify({ message, code }));
|
|
944
|
+
res.end();
|
|
945
|
+
};
|
|
946
|
+
this.server = proto.createServer(srvOpts, requestCb);
|
|
947
|
+
if (this.upgradeCallback) {
|
|
948
|
+
this.server.on('upgrade', upgradeCb);
|
|
949
|
+
}
|
|
950
|
+
this.server.on('error', (e) => {
|
|
951
|
+
const addr = (this.address !== undefined) ? ` address: ${this.address}` : '';
|
|
952
|
+
console.log(`Unable to start HTTP server (port: ${this.port}${addr})`);
|
|
953
|
+
if (this.debug && e) {
|
|
954
|
+
console.log(e);
|
|
955
|
+
}
|
|
956
|
+
process.exit(1);
|
|
957
|
+
});
|
|
958
|
+
this.server.headersTimeout = this.bodyReadTimeoutMs;
|
|
959
|
+
this.server.requestTimeout = this.bodyReadTimeoutMs + 1;
|
|
960
|
+
this.server.listen(this.port, this.address);
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
requestHandleAdd(method, path, handler, options) {
|
|
964
|
+
const normalizedMethod = normalizeMethod(method);
|
|
965
|
+
if (typeof handler !== 'function') {
|
|
966
|
+
throw new Error(`Bad request handler callback for ${normalizedMethod} ${path}`);
|
|
967
|
+
}
|
|
968
|
+
const normalizedOptions = normalizeHandlerOptions(normalizedMethod, path, options);
|
|
969
|
+
const compiled = compilePathTemplate(path);
|
|
970
|
+
compiled.handler = handler;
|
|
971
|
+
compiled.options = normalizedOptions;
|
|
972
|
+
const store = getMethodStore(this._requestHandlers, normalizedMethod, true);
|
|
973
|
+
if (compiled.isExact) {
|
|
974
|
+
store.exact.set(compiled.template, compiled);
|
|
975
|
+
} else {
|
|
976
|
+
store.dynamic.set(compiled.template, compiled);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
requestHandleDelete(method, path) {
|
|
981
|
+
if (typeof path !== 'string' || !path.startsWith('/')) {
|
|
982
|
+
throw new Error(`Bad request handler path: ${path}`);
|
|
983
|
+
}
|
|
984
|
+
if (method === '*') {
|
|
985
|
+
let removed = false;
|
|
986
|
+
for (const [key, store] of this._requestHandlers.entries()) {
|
|
987
|
+
removed = removeFromStore(store, path) || removed;
|
|
988
|
+
if ((store.exact.size === 0) && (store.dynamic.size === 0)) {
|
|
989
|
+
this._requestHandlers.delete(key);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
return removed;
|
|
993
|
+
}
|
|
994
|
+
const normalizedMethod = normalizeMethod(method);
|
|
995
|
+
const store = this._requestHandlers.get(normalizedMethod);
|
|
996
|
+
if (!store) {
|
|
997
|
+
return false;
|
|
998
|
+
}
|
|
999
|
+
const removed = removeFromStore(store, path);
|
|
1000
|
+
if ((store.exact.size === 0) && (store.dynamic.size === 0)) {
|
|
1001
|
+
this._requestHandlers.delete(normalizedMethod);
|
|
1002
|
+
}
|
|
1003
|
+
return removed;
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
#matchRequestHandler(method, path) {
|
|
1007
|
+
const store = this._requestHandlers.get(method.toUpperCase());
|
|
1008
|
+
if (!store) {
|
|
1009
|
+
return null;
|
|
1010
|
+
}
|
|
1011
|
+
return findMatchInStore(store, path);
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
#hasHandlerForOtherMethod(method, path) {
|
|
1015
|
+
const normalizedMethod = typeof method === 'string' ? method.toUpperCase() : method;
|
|
1016
|
+
for (const [key, store] of this._requestHandlers.entries()) {
|
|
1017
|
+
if (key === normalizedMethod) {
|
|
1018
|
+
continue;
|
|
1019
|
+
}
|
|
1020
|
+
if (findMatchInStore(store, path)) {
|
|
1021
|
+
return true;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
return false;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
close() {
|
|
1028
|
+
return new Promise((resolve, reject) => {
|
|
1029
|
+
this.server.close((err) => {
|
|
1030
|
+
if (err) {
|
|
1031
|
+
reject(err);
|
|
1032
|
+
} else {
|
|
1033
|
+
resolve();
|
|
1034
|
+
}
|
|
1035
|
+
});
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// Backward compatible shutdown helper
|
|
1040
|
+
shutdown() {
|
|
1041
|
+
return this.close();
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
}
|
|
311
1045
|
|
|
312
1046
|
module.exports = ApiSrv;
|