tr-apisrv 1.0.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.
Files changed (4) hide show
  1. package/README.md +254 -68
  2. package/index.js +700 -70
  3. package/package.json +1 -1
  4. package/test/test.js +952 -10
package/index.js CHANGED
@@ -2,6 +2,58 @@
2
2
 
3
3
  const http = require('http');
4
4
  const https = require('https');
5
+
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'
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
+ }
5
57
  function parseQuery(str) {
6
58
  const params = Object.create(null);
7
59
  if (!str) {
@@ -44,7 +96,350 @@ function parseContentType(str) {
44
96
  return { type, params };
45
97
  }
46
98
 
47
- var ApiSrv = function(opts) {
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) {
48
443
  var proto = http;
49
444
  var srvOpts = {};
50
445
  if (!(opts && (typeof(opts) === 'object'))) {
@@ -61,6 +456,13 @@ var ApiSrv = function(opts) {
61
456
  }
62
457
  this.debug = opts.debug ? true : false;
63
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
+ }
64
466
  if (Number.isSafeInteger(opts.port) && (opts.port > 0) && (opts.port < 65536)) {
65
467
  this.port = opts.port;
66
468
  } else {
@@ -71,10 +473,44 @@ var ApiSrv = function(opts) {
71
473
  } else if (opts.address) {
72
474
  throw new Error(`Bad address for ApiSrv constructor: ${opts.address}`);
73
475
  }
74
- if (typeof(opts.callback) === 'function') {
75
- this.callback = opts.callback;
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
+ }
76
482
  } else {
77
- throw new Error(`Bad callback for ApiSrv constructor: ${opts.callback}`);
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
+ }
78
514
  }
79
515
  if ((opts.authCallback !== undefined) && (opts.authCallback !== null)) {
80
516
  if (typeof(opts.authCallback) === 'function') {
@@ -86,7 +522,7 @@ var ApiSrv = function(opts) {
86
522
  if (this.debug) {
87
523
  console.log('No authentication callback set.');
88
524
  }
89
- this.authCallback = function(r) { return true; }.bind(this);
525
+ this.authCallback = (r) => true;
90
526
  }
91
527
  if ((opts.upgradeCallback !== undefined) && (opts.upgradeCallback !== null)) {
92
528
  if (typeof(opts.upgradeCallback) === 'function') {
@@ -118,21 +554,31 @@ var ApiSrv = function(opts) {
118
554
  srvOpts.headersTimeout = this.bodyReadTimeoutMs;
119
555
  srvOpts.requestTimeout = this.bodyReadTimeoutMs + 1;
120
556
 
121
- var upgradeCb = async function(req, s, head) {
557
+ const upgradeCb = async (req, s, head) => {
122
558
  var m, r = {};
123
559
  r.method = req.method;
560
+ let rawQueryString;
124
561
  if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
125
562
  r.url = m[1];
126
- r.params = parseQuery(m[2].toString('utf8'));
563
+ rawQueryString = m[2].toString('utf8');
127
564
  } else {
128
565
  r.url = req.url;
129
- r.params = {};
566
+ rawQueryString = undefined;
130
567
  }
568
+ r.bodyParams = undefined;
569
+ r.urlParams = undefined;
570
+ r.pathParams = undefined;
571
+ r.params = undefined;
131
572
  r.headers = req.headers;
132
573
  r.req = req;
133
574
  try {
134
575
  const ret = await this.authCallback(r);
135
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);
136
582
  r.head = head;
137
583
  r.s = s;
138
584
  const cbRet = await opts.upgradeCallback(r);
@@ -156,8 +602,8 @@ var ApiSrv = function(opts) {
156
602
  }
157
603
  return false;
158
604
  }
159
- }.bind(this);
160
- var requestCb = function(req, res) {
605
+ };
606
+ const requestCb = (req, res) => {
161
607
  var completed = false, body = Buffer.alloc(0), r = {}, timeout, bodySize = 0;
162
608
  var contentType, contentTypeArgs;
163
609
  var declaredContentLength;
@@ -181,7 +627,7 @@ var ApiSrv = function(opts) {
181
627
  return;
182
628
  }
183
629
  }
184
- var dataCb = function(data) {
630
+ const dataCb = (data) => {
185
631
  if (completed) {
186
632
  return;
187
633
  }
@@ -213,8 +659,8 @@ var ApiSrv = function(opts) {
213
659
  return;
214
660
  }
215
661
  body = Buffer.concat( [ body, data ] );
216
- }.bind(this);
217
- var endCb = async function() {
662
+ };
663
+ const endCb = async () => {
218
664
  if (completed) {
219
665
  return;
220
666
  }
@@ -237,6 +683,7 @@ var ApiSrv = function(opts) {
237
683
  return;
238
684
  }
239
685
  }
686
+ let rawQueryString;
240
687
  switch (req.method) {
241
688
  case 'POST':
242
689
  case 'PUT':
@@ -246,34 +693,7 @@ var ApiSrv = function(opts) {
246
693
  }
247
694
  r.url = req.url;
248
695
  r.method = req.method;
249
- switch (contentType) {
250
- case 'application/x-www-form-urlencoded':
251
- case 'application/www-form-urlencoded':
252
- r.params = parseQuery(body.toString('utf8'));
253
- break;
254
- case 'application/json':
255
- if (contentTypeArgs && contentTypeArgs.charset && (contentTypeArgs.charset !== 'utf-8')) {
256
- error(res, 400, 'Bad charset for JSON content type.');
257
- return;
258
- }
259
- try {
260
- r.params = JSON.parse(body.toString('utf8'));
261
- } catch(e) {
262
- r.params = undefined;
263
- }
264
- if (! (r.params && (typeof(r.params) === 'object'))) {
265
- error(res, 400, 'Unable to parse JSON query parameters.');
266
- return;
267
- }
268
- break;
269
- case 'multipart/form-data':
270
- // We know this, but only wankers would use it here.
271
- // RFC6749 anyways says that application/x-www-form-urlencoded
272
- // is the "correct" way to go.
273
- default:
274
- error(res, 400, 'POST or PUT body must be in JSON or www-form-urlencoded format.');
275
- return;
276
- }
696
+ rawQueryString = undefined;
277
697
  break;
278
698
  case 'GET':
279
699
  case 'DELETE':
@@ -284,10 +704,10 @@ var ApiSrv = function(opts) {
284
704
  var m;
285
705
  if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
286
706
  r.url = m[1];
287
- r.params = parseQuery(m[2].toString('utf8'));
707
+ rawQueryString = m[2].toString('utf8');
288
708
  } else {
289
709
  r.url = req.url;
290
- r.params = {};
710
+ rawQueryString = undefined;
291
711
  }
292
712
  r.method = req.method;
293
713
  break;
@@ -295,9 +715,22 @@ var ApiSrv = function(opts) {
295
715
  error(res, 405, 'Only GET, POST, PUT, and DELETE are allowed.');
296
716
  return;
297
717
  }
718
+ if (this.rejectDangerousPaths) {
719
+ const reason = detectDangerousPath(r.url);
720
+ if (reason) {
721
+ error(res, 400, reason);
722
+ return;
723
+ }
724
+ }
298
725
  r.headers = req.headers;
299
726
  r.res = res;
300
- r.jsonResponse = function(data, code, excludeNoCacheHeaders) {
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) => {
301
734
  var headers = { 'Content-Type': 'application/json; charset=utf-8' };
302
735
  if (! excludeNoCacheHeaders) {
303
736
  headers = Object.assign(headers,
@@ -313,11 +746,127 @@ var ApiSrv = function(opts) {
313
746
  res.write(JSON.stringify(data));
314
747
  }
315
748
  res.end();
316
- }.bind(this);
749
+ };
750
+ r.errorResponse = (code, detail) => {
751
+ return error(res, code, detail);
752
+ };
317
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
+ }
318
773
  const auth = await this.authCallback(r);
319
774
  if (auth) {
320
- const ret = await this.callback(r);
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);
321
870
  if (ret !== false && this.debug) {
322
871
  console.log('Request successfully processed (resource :' + r.url + ').');
323
872
  }
@@ -333,8 +882,8 @@ var ApiSrv = function(opts) {
333
882
  } catch(e) {
334
883
  }
335
884
  }
336
- }.bind(this);
337
- var errorCb = function() {
885
+ };
886
+ const errorCb = () => {
338
887
  if (completed) {
339
888
  return;
340
889
  }
@@ -344,21 +893,21 @@ var ApiSrv = function(opts) {
344
893
  timeout = undefined;
345
894
  }
346
895
  error(res, 400, 'Error occured while reading the request data.');
347
- }.bind(this);
348
- var timeoutCb = function() {
896
+ };
897
+ const timeoutCb = () => {
349
898
  if (completed) {
350
899
  return;
351
900
  }
352
901
  timeout = undefined;
353
902
  completed = true;
354
903
  error(res, 408, 'Timeout occured while reading the request data.');
355
- }.bind(this);
904
+ };
356
905
  timeout = setTimeout(timeoutCb, this.bodyReadTimeoutMs);
357
906
  req.on('data', dataCb);
358
907
  req.on('end', endCb);
359
908
  req.on('error', errorCb);
360
- }.bind(this);
361
- var error = function(res, code, text, RFC6749EC) {
909
+ };
910
+ const error = (res, code, text, RFC6749EC) => {
362
911
  if (RFC6749EC) {
363
912
  // RFC6749 wants these errors to be code 400 except in case of 401
364
913
  res.writeHead((code != 401) ? 400 : 401,
@@ -372,15 +921,28 @@ var ApiSrv = function(opts) {
372
921
  ('HTTP code ' +
373
922
  code.toString())) },
374
923
  null, 2));
375
-
924
+
376
925
  res.write("\n");
377
926
  } else {
378
- res.writeHead(code, { 'Content-Type': 'text/plain' });
379
- res.write(text);
380
- res.write("\n");
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 }));
381
938
  }
382
939
  res.end();
383
- }.bind(this);
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
+ };
384
946
  this.server = proto.createServer(srvOpts, requestCb);
385
947
  if (this.upgradeCallback) {
386
948
  this.server.on('upgrade', upgradeCb);
@@ -396,21 +958,89 @@ var ApiSrv = function(opts) {
396
958
  this.server.headersTimeout = this.bodyReadTimeoutMs;
397
959
  this.server.requestTimeout = this.bodyReadTimeoutMs + 1;
398
960
  this.server.listen(this.port, this.address);
399
- };
961
+ }
400
962
 
401
- ApiSrv.prototype.close = function() {
402
- return new Promise((resolve, reject) => {
403
- this.server.close((err) => {
404
- if (err) {
405
- reject(err);
406
- } else {
407
- resolve();
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
+ }
408
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
+ });
409
1036
  });
410
- });
411
- };
1037
+ }
412
1038
 
413
- // Backward compatible shutdown helper
414
- ApiSrv.prototype.shutdown = ApiSrv.prototype.close;
1039
+ // Backward compatible shutdown helper
1040
+ shutdown() {
1041
+ return this.close();
1042
+ }
1043
+
1044
+ }
415
1045
 
416
1046
  module.exports = ApiSrv;