tr-apisrv 2.1.0 → 3.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/CHANGELOG.md +22 -0
- package/README.md +173 -2
- package/index.js +330 -65
- package/package.json +1 -1
- package/test/test.js +639 -0
package/index.js
CHANGED
|
@@ -30,9 +30,12 @@ const HANDLER_OPTION_KEYS = new Set([
|
|
|
30
30
|
'pathParamsValidator',
|
|
31
31
|
'urlParamsValidator',
|
|
32
32
|
'bodyParamsValidator',
|
|
33
|
-
'ignoreUrlParams'
|
|
33
|
+
'ignoreUrlParams',
|
|
34
|
+
'authCallback',
|
|
35
|
+
'meta'
|
|
34
36
|
]);
|
|
35
37
|
const PARAM_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
38
|
+
const DANGEROUS_PARAM_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
|
|
36
39
|
const DEFAULT_SPLAT_MIN = 1;
|
|
37
40
|
const DEFAULT_SPLAT_MAX = 32;
|
|
38
41
|
|
|
@@ -145,6 +148,15 @@ function normalizeHandlerOptions(method, path, options) {
|
|
|
145
148
|
normalized.ignoreUrlParams = true;
|
|
146
149
|
}
|
|
147
150
|
}
|
|
151
|
+
if (options.authCallback !== undefined) {
|
|
152
|
+
if (typeof options.authCallback !== 'function') {
|
|
153
|
+
throw new Error(`authCallback must be a function for ${method} ${path}`);
|
|
154
|
+
}
|
|
155
|
+
normalized.authCallback = options.authCallback;
|
|
156
|
+
}
|
|
157
|
+
if (options.meta !== undefined) {
|
|
158
|
+
normalized.meta = options.meta;
|
|
159
|
+
}
|
|
148
160
|
return Object.keys(normalized).length > 0 ? normalized : undefined;
|
|
149
161
|
}
|
|
150
162
|
|
|
@@ -202,7 +214,7 @@ function compilePathTemplate(path) {
|
|
|
202
214
|
if ((match = part.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/))) {
|
|
203
215
|
hasDynamic = true;
|
|
204
216
|
const name = match[1];
|
|
205
|
-
if (!PARAM_NAME_RE.test(name)) {
|
|
217
|
+
if (!PARAM_NAME_RE.test(name) || (name === '__proto__')) {
|
|
206
218
|
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
207
219
|
}
|
|
208
220
|
segments.push({ type: 'param', name });
|
|
@@ -210,7 +222,7 @@ function compilePathTemplate(path) {
|
|
|
210
222
|
hasDynamic = true;
|
|
211
223
|
hasSplat = true;
|
|
212
224
|
const name = match[1];
|
|
213
|
-
if (!PARAM_NAME_RE.test(name)) {
|
|
225
|
+
if (!PARAM_NAME_RE.test(name) || (name === '__proto__')) {
|
|
214
226
|
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
215
227
|
}
|
|
216
228
|
let minItems = DEFAULT_SPLAT_MIN;
|
|
@@ -377,11 +389,48 @@ function assignParams(target, source, sourceType, sources) {
|
|
|
377
389
|
console.warn(`ApiSrv warning: parameter "${key}" from ${currentLabel} overrides value from ${prevLabel}.`);
|
|
378
390
|
}
|
|
379
391
|
}
|
|
380
|
-
|
|
392
|
+
// A plain assignment of the key "__proto__" would replace the
|
|
393
|
+
// prototype of the target instead of creating a parameter.
|
|
394
|
+
Object.defineProperty(target, key, {
|
|
395
|
+
value,
|
|
396
|
+
writable: true,
|
|
397
|
+
enumerable: true,
|
|
398
|
+
configurable: true
|
|
399
|
+
});
|
|
381
400
|
sources.set(key, sourceType);
|
|
382
401
|
}
|
|
383
402
|
}
|
|
384
403
|
|
|
404
|
+
// Returns the first own key named __proto__, constructor or prototype found
|
|
405
|
+
// in value at any depth, or undefined when there is none.
|
|
406
|
+
function findDangerousParamName(value) {
|
|
407
|
+
const stack = [value];
|
|
408
|
+
while (stack.length > 0) {
|
|
409
|
+
const current = stack.pop();
|
|
410
|
+
if (!current || (typeof current !== 'object')) {
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
if (Array.isArray(current)) {
|
|
414
|
+
for (const item of current) {
|
|
415
|
+
if (item && (typeof item === 'object')) {
|
|
416
|
+
stack.push(item);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
for (const key of Object.keys(current)) {
|
|
422
|
+
if (DANGEROUS_PARAM_NAMES.has(key)) {
|
|
423
|
+
return key;
|
|
424
|
+
}
|
|
425
|
+
const item = current[key];
|
|
426
|
+
if (item && (typeof item === 'object')) {
|
|
427
|
+
stack.push(item);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return undefined;
|
|
432
|
+
}
|
|
433
|
+
|
|
385
434
|
function normalizeMethod(method) {
|
|
386
435
|
if (typeof method !== 'string') {
|
|
387
436
|
throw new Error(`Bad request handler method: ${method}`);
|
|
@@ -417,22 +466,27 @@ function findMatchInStore(store, path) {
|
|
|
417
466
|
if (!store) {
|
|
418
467
|
return null;
|
|
419
468
|
}
|
|
469
|
+
// A request target that is not a path (e.g. "*" or an absolute URL)
|
|
470
|
+
// matches no handler.
|
|
471
|
+
if ((typeof path !== 'string') || !path.startsWith('/')) {
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
420
474
|
let exact = store.exact.get(path);
|
|
421
475
|
if (exact) {
|
|
422
|
-
return { handler: exact.handler, options: exact.options, params: {} };
|
|
476
|
+
return { handler: exact.handler, options: exact.options, params: {}, template: exact.template };
|
|
423
477
|
}
|
|
424
478
|
if ((path.length > 1) && path.endsWith('/')) {
|
|
425
479
|
const trimmed = path.slice(0, -1);
|
|
426
480
|
exact = store.exact.get(trimmed);
|
|
427
481
|
if (exact && !exact.hasTrailingSlash) {
|
|
428
|
-
return { handler: exact.handler, options: exact.options, params: {} };
|
|
482
|
+
return { handler: exact.handler, options: exact.options, params: {}, template: exact.template };
|
|
429
483
|
}
|
|
430
484
|
}
|
|
431
485
|
const pathInfo = describePath(path);
|
|
432
486
|
for (const entry of store.dynamic.values()) {
|
|
433
487
|
const params = matchCompiledPath(entry, pathInfo);
|
|
434
488
|
if (params) {
|
|
435
|
-
return { handler: entry.handler, options: entry.options, params };
|
|
489
|
+
return { handler: entry.handler, options: entry.options, params, template: entry.template };
|
|
436
490
|
}
|
|
437
491
|
}
|
|
438
492
|
return null;
|
|
@@ -551,9 +605,66 @@ class ApiSrv {
|
|
|
551
605
|
} else {
|
|
552
606
|
this.maxBodySize = 1024 * 1024;
|
|
553
607
|
}
|
|
608
|
+
if ((opts.errorCallback !== undefined) && (opts.errorCallback !== null)) {
|
|
609
|
+
if (typeof(opts.errorCallback) === 'function') {
|
|
610
|
+
this.errorCallback = opts.errorCallback;
|
|
611
|
+
} else {
|
|
612
|
+
throw new Error(`Bad errorCallback for ApiSrv constructor: ${opts.errorCallback}`);
|
|
613
|
+
}
|
|
614
|
+
} else {
|
|
615
|
+
this.errorCallback = undefined;
|
|
616
|
+
}
|
|
617
|
+
if ((opts.pathRewrite !== undefined) && (opts.pathRewrite !== null)) {
|
|
618
|
+
if (typeof(opts.pathRewrite) === 'function') {
|
|
619
|
+
this.pathRewrite = opts.pathRewrite;
|
|
620
|
+
} else {
|
|
621
|
+
throw new Error(`Bad pathRewrite for ApiSrv constructor: ${opts.pathRewrite}`);
|
|
622
|
+
}
|
|
623
|
+
} else {
|
|
624
|
+
this.pathRewrite = undefined;
|
|
625
|
+
}
|
|
626
|
+
if (opts.requireObjectBody === undefined) {
|
|
627
|
+
this.requireObjectBody = false;
|
|
628
|
+
} else if (typeof opts.requireObjectBody === 'boolean') {
|
|
629
|
+
this.requireObjectBody = opts.requireObjectBody;
|
|
630
|
+
} else {
|
|
631
|
+
throw new Error(`Bad requireObjectBody for ApiSrv constructor: ${opts.requireObjectBody}`);
|
|
632
|
+
}
|
|
633
|
+
if (opts.rejectDangerousParamNames === undefined) {
|
|
634
|
+
this.rejectDangerousParamNames = false;
|
|
635
|
+
} else if (typeof opts.rejectDangerousParamNames === 'boolean') {
|
|
636
|
+
this.rejectDangerousParamNames = opts.rejectDangerousParamNames;
|
|
637
|
+
} else {
|
|
638
|
+
throw new Error(`Bad rejectDangerousParamNames for ApiSrv constructor: ${opts.rejectDangerousParamNames}`);
|
|
639
|
+
}
|
|
554
640
|
srvOpts.headersTimeout = this.bodyReadTimeoutMs;
|
|
555
641
|
srvOpts.requestTimeout = this.bodyReadTimeoutMs + 1;
|
|
556
642
|
|
|
643
|
+
// Applies the optional pathRewrite to a request path. Returns the path to
|
|
644
|
+
// use, or undefined when the rewrite fails or returns something that is
|
|
645
|
+
// not a path.
|
|
646
|
+
const rewritePath = (path) => {
|
|
647
|
+
if (!this.pathRewrite) {
|
|
648
|
+
return path;
|
|
649
|
+
}
|
|
650
|
+
let rewritten;
|
|
651
|
+
try {
|
|
652
|
+
rewritten = this.pathRewrite(path);
|
|
653
|
+
} catch (e) {
|
|
654
|
+
if (this.debug) {
|
|
655
|
+
console.log(e);
|
|
656
|
+
}
|
|
657
|
+
return undefined;
|
|
658
|
+
}
|
|
659
|
+
if ((rewritten === undefined) || (rewritten === null)) {
|
|
660
|
+
return path;
|
|
661
|
+
}
|
|
662
|
+
if ((typeof rewritten !== 'string') || !rewritten.startsWith('/')) {
|
|
663
|
+
return undefined;
|
|
664
|
+
}
|
|
665
|
+
return rewritten;
|
|
666
|
+
};
|
|
667
|
+
|
|
557
668
|
const upgradeCb = async (req, s, head) => {
|
|
558
669
|
var m, r = {};
|
|
559
670
|
r.method = req.method;
|
|
@@ -565,6 +676,15 @@ class ApiSrv {
|
|
|
565
676
|
r.url = req.url;
|
|
566
677
|
rawQueryString = undefined;
|
|
567
678
|
}
|
|
679
|
+
r.originalUrl = r.url;
|
|
680
|
+
{
|
|
681
|
+
const rewritten = rewritePath(r.url);
|
|
682
|
+
if (rewritten === undefined) {
|
|
683
|
+
s.destroy();
|
|
684
|
+
return false;
|
|
685
|
+
}
|
|
686
|
+
r.url = rewritten;
|
|
687
|
+
}
|
|
568
688
|
r.bodyParams = undefined;
|
|
569
689
|
r.urlParams = undefined;
|
|
570
690
|
r.pathParams = undefined;
|
|
@@ -575,6 +695,11 @@ class ApiSrv {
|
|
|
575
695
|
const ret = await this.authCallback(r);
|
|
576
696
|
if (ret) {
|
|
577
697
|
const queryOnlyParams = parseQuery(rawQueryString);
|
|
698
|
+
if (this.rejectDangerousParamNames && findDangerousParamName(queryOnlyParams)) {
|
|
699
|
+
s.destroy();
|
|
700
|
+
s = undefined;
|
|
701
|
+
return false;
|
|
702
|
+
}
|
|
578
703
|
r.urlParams = queryOnlyParams;
|
|
579
704
|
r.params = queryOnlyParams;
|
|
580
705
|
r.bodyParams = Object.create(null);
|
|
@@ -604,26 +729,48 @@ class ApiSrv {
|
|
|
604
729
|
}
|
|
605
730
|
};
|
|
606
731
|
const requestCb = (req, res) => {
|
|
607
|
-
var completed = false, body = Buffer.alloc(0), r = {}, timeout, bodySize = 0;
|
|
732
|
+
var completed = false, body = Buffer.alloc(0), chunks = [], r = {}, timeout, bodySize = 0;
|
|
608
733
|
var contentType, contentTypeArgs;
|
|
609
734
|
var declaredContentLength;
|
|
735
|
+
// What an errorCallback is told about an error of this request.
|
|
736
|
+
const ctx = (source, extra) => Object.assign({ source, req, res, request: r }, extra);
|
|
737
|
+
// Reject a request whose body is not read. The connection is
|
|
738
|
+
// closed, but only once the response has been written:
|
|
739
|
+
// destroying it at once could lose the response.
|
|
740
|
+
const rejectBody = (code, text, source) => {
|
|
741
|
+
const socket = req.socket;
|
|
742
|
+
const kill = () => {
|
|
743
|
+
if (socket && !socket.destroyed) {
|
|
744
|
+
socket.destroy();
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
// Also when an errorCallback never responds.
|
|
748
|
+
const fallback = setTimeout(kill, this.bodyReadTimeoutMs);
|
|
749
|
+
fallback.unref();
|
|
750
|
+
res.once('finish', () => {
|
|
751
|
+
clearTimeout(fallback);
|
|
752
|
+
if (socket && !socket.destroyed) {
|
|
753
|
+
socket.end();
|
|
754
|
+
setTimeout(kill, 1000).unref();
|
|
755
|
+
}
|
|
756
|
+
});
|
|
757
|
+
res.once('close', () => clearTimeout(fallback));
|
|
758
|
+
res.setHeader('Connection', 'close');
|
|
759
|
+
error(res, code, text, undefined, ctx(source));
|
|
760
|
+
};
|
|
610
761
|
if (req.headers['transfer-encoding'] && req.headers['content-length']) {
|
|
611
|
-
error(res, 400, 'Both Transfer-Encoding and Content-Length defined.');
|
|
762
|
+
error(res, 400, 'Both Transfer-Encoding and Content-Length defined.', undefined, ctx('request'));
|
|
612
763
|
return;
|
|
613
764
|
}
|
|
614
765
|
if (req.headers['content-length']) {
|
|
615
766
|
var cl = parseInt(req.headers['content-length'], 10);
|
|
616
767
|
if (!Number.isSafeInteger(cl) || cl < 0) {
|
|
617
|
-
error(res, 400, 'Bad Content-Length header.');
|
|
768
|
+
error(res, 400, 'Bad Content-Length header.', undefined, ctx('request'));
|
|
618
769
|
return;
|
|
619
770
|
}
|
|
620
771
|
declaredContentLength = cl;
|
|
621
|
-
if (
|
|
622
|
-
|
|
623
|
-
try {
|
|
624
|
-
req.destroy();
|
|
625
|
-
} catch (ignored) {
|
|
626
|
-
}
|
|
772
|
+
if (cl > this.maxBodySize) {
|
|
773
|
+
rejectBody(413, 'Request body too large.', 'limit');
|
|
627
774
|
return;
|
|
628
775
|
}
|
|
629
776
|
}
|
|
@@ -638,27 +785,19 @@ class ApiSrv {
|
|
|
638
785
|
clearTimeout(timeout);
|
|
639
786
|
timeout = undefined;
|
|
640
787
|
}
|
|
641
|
-
|
|
642
|
-
try {
|
|
643
|
-
req.destroy();
|
|
644
|
-
} catch (ignored) {
|
|
645
|
-
}
|
|
788
|
+
rejectBody(400, 'Request body longer than Content-Length.', 'request');
|
|
646
789
|
return;
|
|
647
790
|
}
|
|
648
|
-
if (
|
|
791
|
+
if (bodySize > this.maxBodySize) {
|
|
649
792
|
completed = true;
|
|
650
793
|
if (timeout) {
|
|
651
794
|
clearTimeout(timeout);
|
|
652
795
|
timeout = undefined;
|
|
653
796
|
}
|
|
654
|
-
|
|
655
|
-
try {
|
|
656
|
-
req.destroy();
|
|
657
|
-
} catch (ignored) {
|
|
658
|
-
}
|
|
797
|
+
rejectBody(413, 'Request body too large.', 'limit');
|
|
659
798
|
return;
|
|
660
799
|
}
|
|
661
|
-
|
|
800
|
+
chunks.push(data);
|
|
662
801
|
};
|
|
663
802
|
const endCb = async () => {
|
|
664
803
|
if (completed) {
|
|
@@ -669,8 +808,10 @@ class ApiSrv {
|
|
|
669
808
|
clearTimeout(timeout);
|
|
670
809
|
timeout = undefined;
|
|
671
810
|
}
|
|
811
|
+
body = Buffer.concat(chunks, bodySize);
|
|
812
|
+
chunks = [];
|
|
672
813
|
if (declaredContentLength !== undefined && (body.length !== declaredContentLength)) {
|
|
673
|
-
error(res, 400, 'Request body length does not match Content-Length.');
|
|
814
|
+
error(res, 400, 'Request body length does not match Content-Length.', undefined, ctx('request'));
|
|
674
815
|
return;
|
|
675
816
|
}
|
|
676
817
|
if (req.headers['content-type']) {
|
|
@@ -679,7 +820,7 @@ class ApiSrv {
|
|
|
679
820
|
contentType = ct.type;
|
|
680
821
|
contentTypeArgs = ct.params;
|
|
681
822
|
} else {
|
|
682
|
-
error(res, 400, 'Unable to parse content-type.');
|
|
823
|
+
error(res, 400, 'Unable to parse content-type.', undefined, ctx('request'));
|
|
683
824
|
return;
|
|
684
825
|
}
|
|
685
826
|
}
|
|
@@ -688,7 +829,7 @@ class ApiSrv {
|
|
|
688
829
|
case 'POST':
|
|
689
830
|
case 'PUT':
|
|
690
831
|
if (req.url.match(/\?/)) {
|
|
691
|
-
error(res, 400, 'URL for POST or PUT must not contain query parameters.');
|
|
832
|
+
error(res, 400, 'URL for POST or PUT must not contain query parameters.', undefined, ctx('request'));
|
|
692
833
|
return;
|
|
693
834
|
}
|
|
694
835
|
r.url = req.url;
|
|
@@ -698,7 +839,7 @@ class ApiSrv {
|
|
|
698
839
|
case 'GET':
|
|
699
840
|
case 'DELETE':
|
|
700
841
|
if (body.length > 0) {
|
|
701
|
-
error(res, 400, 'Empty body required for ' + req.method + ' requests.');
|
|
842
|
+
error(res, 400, 'Empty body required for ' + req.method + ' requests.', undefined, ctx('request'));
|
|
702
843
|
return;
|
|
703
844
|
}
|
|
704
845
|
var m;
|
|
@@ -712,15 +853,31 @@ class ApiSrv {
|
|
|
712
853
|
r.method = req.method;
|
|
713
854
|
break;
|
|
714
855
|
default:
|
|
715
|
-
error(res, 405, 'Only GET, POST, PUT, and DELETE are allowed.');
|
|
856
|
+
error(res, 405, 'Only GET, POST, PUT, and DELETE are allowed.', undefined, ctx('request'));
|
|
716
857
|
return;
|
|
717
858
|
}
|
|
718
859
|
if (this.rejectDangerousPaths) {
|
|
719
860
|
const reason = detectDangerousPath(r.url);
|
|
720
861
|
if (reason) {
|
|
721
|
-
error(res, 400, reason);
|
|
862
|
+
error(res, 400, reason, undefined, ctx('request'));
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
r.originalUrl = r.url;
|
|
867
|
+
{
|
|
868
|
+
const rewritten = rewritePath(r.url);
|
|
869
|
+
if (rewritten === undefined) {
|
|
870
|
+
error(res, 500, 'Request path rewrite fails.', undefined, ctx('router'));
|
|
722
871
|
return;
|
|
723
872
|
}
|
|
873
|
+
r.url = rewritten;
|
|
874
|
+
if (this.rejectDangerousPaths && (rewritten !== r.originalUrl)) {
|
|
875
|
+
const reason = detectDangerousPath(r.url);
|
|
876
|
+
if (reason) {
|
|
877
|
+
error(res, 400, reason, undefined, ctx('request'));
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
724
881
|
}
|
|
725
882
|
r.headers = req.headers;
|
|
726
883
|
r.res = res;
|
|
@@ -731,7 +888,8 @@ class ApiSrv {
|
|
|
731
888
|
r.pathParams = undefined;
|
|
732
889
|
r.params = undefined;
|
|
733
890
|
r.jsonResponse = (data, code, excludeNoCacheHeaders) => {
|
|
734
|
-
var headers = { 'Content-Type': 'application/json; charset=utf-8'
|
|
891
|
+
var headers = { 'Content-Type': 'application/json; charset=utf-8',
|
|
892
|
+
'X-Content-Type-Options': 'nosniff' };
|
|
735
893
|
if (! excludeNoCacheHeaders) {
|
|
736
894
|
headers = Object.assign(headers,
|
|
737
895
|
{ 'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
|
|
@@ -755,6 +913,7 @@ class ApiSrv {
|
|
|
755
913
|
let handler = handlerEntry ? handlerEntry.handler : undefined;
|
|
756
914
|
let handlerOptions = handlerEntry ? handlerEntry.options : undefined;
|
|
757
915
|
let pathParams = handlerEntry ? handlerEntry.params : Object.create(null);
|
|
916
|
+
r.handler = undefined;
|
|
758
917
|
if (!handler) {
|
|
759
918
|
if (this.callback) {
|
|
760
919
|
handler = this.callback;
|
|
@@ -763,14 +922,23 @@ class ApiSrv {
|
|
|
763
922
|
} else {
|
|
764
923
|
const hasOtherMethod = this.#hasHandlerForOtherMethod(r.method, r.url);
|
|
765
924
|
if (hasOtherMethod) {
|
|
766
|
-
jsonError(res, 405, 'Method Not Allowed');
|
|
925
|
+
jsonError(res, 405, 'Method Not Allowed', ctx('router'));
|
|
767
926
|
} else {
|
|
768
|
-
jsonError(res, 404, 'Not Found');
|
|
927
|
+
jsonError(res, 404, 'Not Found', ctx('router'));
|
|
769
928
|
}
|
|
770
929
|
return;
|
|
771
930
|
}
|
|
931
|
+
} else {
|
|
932
|
+
r.handler = {
|
|
933
|
+
method: r.method,
|
|
934
|
+
path: handlerEntry.template,
|
|
935
|
+
meta: handlerOptions ? handlerOptions.meta : undefined
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
let auth = await this.authCallback(r);
|
|
939
|
+
if (auth && handlerOptions && handlerOptions.authCallback) {
|
|
940
|
+
auth = await handlerOptions.authCallback(r);
|
|
772
941
|
}
|
|
773
|
-
const auth = await this.authCallback(r);
|
|
774
942
|
if (auth) {
|
|
775
943
|
const paramSources = new Map();
|
|
776
944
|
const ignoreUrlParams = handlerOptions && handlerOptions.ignoreUrlParams === true;
|
|
@@ -778,13 +946,14 @@ class ApiSrv {
|
|
|
778
946
|
try {
|
|
779
947
|
const result = await validator(value);
|
|
780
948
|
if (!result || typeof result !== 'object') {
|
|
781
|
-
error(res, 500, `${description} validator must return an object
|
|
949
|
+
error(res, 500, `${description} validator must return an object.`, undefined,
|
|
950
|
+
ctx('validator', { stage: description }));
|
|
782
951
|
return { success: false };
|
|
783
952
|
}
|
|
784
953
|
return { success: true, value: result };
|
|
785
954
|
} catch (err) {
|
|
786
955
|
const detail = (err && err.message) ? err.message : `Invalid ${description}.`;
|
|
787
|
-
error(res, 400, detail);
|
|
956
|
+
error(res, 400, detail, undefined, ctx('validator', { stage: description, cause: err }));
|
|
788
957
|
return { success: false };
|
|
789
958
|
}
|
|
790
959
|
};
|
|
@@ -799,6 +968,13 @@ class ApiSrv {
|
|
|
799
968
|
let urlParams;
|
|
800
969
|
if (!ignoreUrlParams) {
|
|
801
970
|
urlParams = parseQuery(rawQueryString);
|
|
971
|
+
if (this.rejectDangerousParamNames) {
|
|
972
|
+
const reserved = findDangerousParamName(urlParams);
|
|
973
|
+
if (reserved) {
|
|
974
|
+
error(res, 400, `Reserved parameter name "${reserved}" in query string.`, undefined, ctx('parser'));
|
|
975
|
+
return;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
802
978
|
if (handlerOptions && handlerOptions.urlParamsValidator) {
|
|
803
979
|
const validation = await runValidator(handlerOptions.urlParamsValidator, urlParams, 'URL parameters');
|
|
804
980
|
if (!validation.success) {
|
|
@@ -816,7 +992,7 @@ class ApiSrv {
|
|
|
816
992
|
break;
|
|
817
993
|
case 'application/json':
|
|
818
994
|
if (contentTypeArgs && contentTypeArgs.charset && (contentTypeArgs.charset !== 'utf-8')) {
|
|
819
|
-
error(res, 400, 'Bad charset for JSON content type.');
|
|
995
|
+
error(res, 400, 'Bad charset for JSON content type.', undefined, ctx('parser'));
|
|
820
996
|
return;
|
|
821
997
|
}
|
|
822
998
|
try {
|
|
@@ -825,13 +1001,24 @@ class ApiSrv {
|
|
|
825
1001
|
bodyParamsObject = undefined;
|
|
826
1002
|
}
|
|
827
1003
|
if (!(bodyParamsObject && (typeof bodyParamsObject === 'object'))) {
|
|
828
|
-
error(res, 400, 'Unable to parse JSON query parameters.');
|
|
1004
|
+
error(res, 400, 'Unable to parse JSON query parameters.', undefined, ctx('parser'));
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
if (this.requireObjectBody && Array.isArray(bodyParamsObject)) {
|
|
1008
|
+
error(res, 400, 'JSON body must be an object.', undefined, ctx('parser'));
|
|
829
1009
|
return;
|
|
830
1010
|
}
|
|
831
1011
|
break;
|
|
832
1012
|
case 'multipart/form-data':
|
|
833
1013
|
default:
|
|
834
|
-
error(res, 400, 'POST or PUT body must be in JSON or www-form-urlencoded format.');
|
|
1014
|
+
error(res, 400, 'POST or PUT body must be in JSON or www-form-urlencoded format.', undefined, ctx('parser'));
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
if (this.rejectDangerousParamNames) {
|
|
1019
|
+
const reserved = findDangerousParamName(bodyParamsObject);
|
|
1020
|
+
if (reserved) {
|
|
1021
|
+
error(res, 400, `Reserved parameter name "${reserved}" in request body.`, undefined, ctx('parser'));
|
|
835
1022
|
return;
|
|
836
1023
|
}
|
|
837
1024
|
}
|
|
@@ -878,8 +1065,8 @@ class ApiSrv {
|
|
|
878
1065
|
console.log(e);
|
|
879
1066
|
}
|
|
880
1067
|
try {
|
|
881
|
-
error(res, 500, 'Request handler fails to execute.');
|
|
882
|
-
} catch(
|
|
1068
|
+
error(res, 500, 'Request handler fails to execute.', undefined, ctx('handler', { cause: e }));
|
|
1069
|
+
} catch(ignored) {
|
|
883
1070
|
}
|
|
884
1071
|
}
|
|
885
1072
|
};
|
|
@@ -892,7 +1079,7 @@ class ApiSrv {
|
|
|
892
1079
|
clearTimeout(timeout);
|
|
893
1080
|
timeout = undefined;
|
|
894
1081
|
}
|
|
895
|
-
error(res, 400, 'Error occured while reading the request data.');
|
|
1082
|
+
error(res, 400, 'Error occured while reading the request data.', undefined, ctx('request'));
|
|
896
1083
|
};
|
|
897
1084
|
const timeoutCb = () => {
|
|
898
1085
|
if (completed) {
|
|
@@ -900,18 +1087,63 @@ class ApiSrv {
|
|
|
900
1087
|
}
|
|
901
1088
|
timeout = undefined;
|
|
902
1089
|
completed = true;
|
|
903
|
-
error(res, 408, 'Timeout occured while reading the request data.');
|
|
1090
|
+
error(res, 408, 'Timeout occured while reading the request data.', undefined, ctx('limit'));
|
|
904
1091
|
};
|
|
905
1092
|
timeout = setTimeout(timeoutCb, this.bodyReadTimeoutMs);
|
|
906
1093
|
req.on('data', dataCb);
|
|
907
1094
|
req.on('end', endCb);
|
|
908
1095
|
req.on('error', errorCb);
|
|
909
1096
|
};
|
|
910
|
-
|
|
1097
|
+
// Offers a server-generated error to the optional errorCallback. The
|
|
1098
|
+
// default response is written when there is no callback, when it returns
|
|
1099
|
+
// (or resolves to) a falsy value, or when it fails.
|
|
1100
|
+
const reportError = (res, context, writeDefault) => {
|
|
1101
|
+
if (!this.errorCallback) {
|
|
1102
|
+
writeDefault();
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
const fallback = () => {
|
|
1106
|
+
if (res.headersSent || res.writableEnded) {
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
try {
|
|
1110
|
+
writeDefault();
|
|
1111
|
+
} catch (ignored) {
|
|
1112
|
+
}
|
|
1113
|
+
};
|
|
1114
|
+
let ret;
|
|
1115
|
+
try {
|
|
1116
|
+
ret = this.errorCallback(context);
|
|
1117
|
+
} catch (e) {
|
|
1118
|
+
if (this.debug) {
|
|
1119
|
+
console.log(e);
|
|
1120
|
+
}
|
|
1121
|
+
fallback();
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
if (ret && (typeof ret.then === 'function')) {
|
|
1125
|
+
ret.then((handled) => {
|
|
1126
|
+
if (!handled) {
|
|
1127
|
+
fallback();
|
|
1128
|
+
}
|
|
1129
|
+
}, (e) => {
|
|
1130
|
+
if (this.debug) {
|
|
1131
|
+
console.log(e);
|
|
1132
|
+
}
|
|
1133
|
+
fallback();
|
|
1134
|
+
});
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
if (!ret) {
|
|
1138
|
+
fallback();
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
const error = (res, code, text, RFC6749EC, context) => {
|
|
911
1142
|
if (RFC6749EC) {
|
|
912
1143
|
// RFC6749 wants these errors to be code 400 except in case of 401
|
|
913
1144
|
res.writeHead((code != 401) ? 400 : 401,
|
|
914
|
-
{ 'Content-Type': 'application/json; charset=utf-8'
|
|
1145
|
+
{ 'Content-Type': 'application/json; charset=utf-8',
|
|
1146
|
+
'X-Content-Type-Options': 'nosniff' });
|
|
915
1147
|
res.write(JSON.stringify( { error: RFC6749EC,
|
|
916
1148
|
error_description: (text ?
|
|
917
1149
|
(text +
|
|
@@ -923,25 +1155,42 @@ class ApiSrv {
|
|
|
923
1155
|
null, 2));
|
|
924
1156
|
|
|
925
1157
|
res.write("\n");
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
1158
|
+
res.end();
|
|
1159
|
+
return;
|
|
1160
|
+
}
|
|
1161
|
+
const canonical = HTTP_STATUS_MESSAGES[code] || 'Error';
|
|
1162
|
+
let detail = text ? text.trim() : '';
|
|
1163
|
+
if (detail) {
|
|
1164
|
+
detail = detail.replace(/\.+$/, '');
|
|
1165
|
+
}
|
|
1166
|
+
let message = canonical;
|
|
1167
|
+
if (code === 400 && detail) {
|
|
1168
|
+
message = `${canonical} (${detail})`;
|
|
1169
|
+
}
|
|
1170
|
+
const writeDefault = () => {
|
|
1171
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8',
|
|
1172
|
+
'X-Content-Type-Options': 'nosniff' });
|
|
937
1173
|
res.write(JSON.stringify({ code, message }));
|
|
1174
|
+
res.end();
|
|
1175
|
+
};
|
|
1176
|
+
if (!context) {
|
|
1177
|
+
writeDefault();
|
|
1178
|
+
return;
|
|
938
1179
|
}
|
|
939
|
-
res.
|
|
1180
|
+
reportError(res, Object.assign({ code, message, detail: detail || undefined }, context), writeDefault);
|
|
940
1181
|
};
|
|
941
|
-
const jsonError = (res, code, message) => {
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
1182
|
+
const jsonError = (res, code, message, context) => {
|
|
1183
|
+
const writeDefault = () => {
|
|
1184
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8',
|
|
1185
|
+
'X-Content-Type-Options': 'nosniff' });
|
|
1186
|
+
res.write(JSON.stringify({ message, code }));
|
|
1187
|
+
res.end();
|
|
1188
|
+
};
|
|
1189
|
+
if (!context) {
|
|
1190
|
+
writeDefault();
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
reportError(res, Object.assign({ code, message, detail: undefined }, context), writeDefault);
|
|
945
1194
|
};
|
|
946
1195
|
this.server = proto.createServer(srvOpts, requestCb);
|
|
947
1196
|
if (this.upgradeCallback) {
|
|
@@ -1003,6 +1252,22 @@ class ApiSrv {
|
|
|
1003
1252
|
return removed;
|
|
1004
1253
|
}
|
|
1005
1254
|
|
|
1255
|
+
// Returns the registered request handlers as { method, path, meta }
|
|
1256
|
+
// objects, in registration order for each method.
|
|
1257
|
+
requestHandlerList() {
|
|
1258
|
+
const list = [];
|
|
1259
|
+
for (const [method, store] of this._requestHandlers.entries()) {
|
|
1260
|
+
for (const entry of [...store.exact.values(), ...store.dynamic.values()]) {
|
|
1261
|
+
list.push({
|
|
1262
|
+
method,
|
|
1263
|
+
path: entry.template,
|
|
1264
|
+
meta: entry.options ? entry.options.meta : undefined
|
|
1265
|
+
});
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
return list;
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1006
1271
|
#matchRequestHandler(method, path) {
|
|
1007
1272
|
const store = this._requestHandlers.get(method.toUpperCase());
|
|
1008
1273
|
if (!store) {
|