tr-apisrv 2.1.0 → 3.0.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/README.md +169 -1
- package/index.js +304 -51
- package/package.json +1 -1
- package/test/test.js +618 -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,22 +729,24 @@ 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);
|
|
610
737
|
if (req.headers['transfer-encoding'] && req.headers['content-length']) {
|
|
611
|
-
error(res, 400, 'Both Transfer-Encoding and Content-Length defined.');
|
|
738
|
+
error(res, 400, 'Both Transfer-Encoding and Content-Length defined.', undefined, ctx('request'));
|
|
612
739
|
return;
|
|
613
740
|
}
|
|
614
741
|
if (req.headers['content-length']) {
|
|
615
742
|
var cl = parseInt(req.headers['content-length'], 10);
|
|
616
743
|
if (!Number.isSafeInteger(cl) || cl < 0) {
|
|
617
|
-
error(res, 400, 'Bad Content-Length header.');
|
|
744
|
+
error(res, 400, 'Bad Content-Length header.', undefined, ctx('request'));
|
|
618
745
|
return;
|
|
619
746
|
}
|
|
620
747
|
declaredContentLength = cl;
|
|
621
748
|
if (this.maxBodySize && (cl > this.maxBodySize)) {
|
|
622
|
-
error(res, 413, 'Request body too large.');
|
|
749
|
+
error(res, 413, 'Request body too large.', undefined, ctx('limit'));
|
|
623
750
|
try {
|
|
624
751
|
req.destroy();
|
|
625
752
|
} catch (ignored) {
|
|
@@ -638,7 +765,7 @@ class ApiSrv {
|
|
|
638
765
|
clearTimeout(timeout);
|
|
639
766
|
timeout = undefined;
|
|
640
767
|
}
|
|
641
|
-
error(res, 400, 'Request body longer than Content-Length.');
|
|
768
|
+
error(res, 400, 'Request body longer than Content-Length.', undefined, ctx('request'));
|
|
642
769
|
try {
|
|
643
770
|
req.destroy();
|
|
644
771
|
} catch (ignored) {
|
|
@@ -651,14 +778,14 @@ class ApiSrv {
|
|
|
651
778
|
clearTimeout(timeout);
|
|
652
779
|
timeout = undefined;
|
|
653
780
|
}
|
|
654
|
-
error(res, 413, 'Request body too large.');
|
|
781
|
+
error(res, 413, 'Request body too large.', undefined, ctx('limit'));
|
|
655
782
|
try {
|
|
656
783
|
req.destroy();
|
|
657
784
|
} catch (ignored) {
|
|
658
785
|
}
|
|
659
786
|
return;
|
|
660
787
|
}
|
|
661
|
-
|
|
788
|
+
chunks.push(data);
|
|
662
789
|
};
|
|
663
790
|
const endCb = async () => {
|
|
664
791
|
if (completed) {
|
|
@@ -669,8 +796,10 @@ class ApiSrv {
|
|
|
669
796
|
clearTimeout(timeout);
|
|
670
797
|
timeout = undefined;
|
|
671
798
|
}
|
|
799
|
+
body = Buffer.concat(chunks, bodySize);
|
|
800
|
+
chunks = [];
|
|
672
801
|
if (declaredContentLength !== undefined && (body.length !== declaredContentLength)) {
|
|
673
|
-
error(res, 400, 'Request body length does not match Content-Length.');
|
|
802
|
+
error(res, 400, 'Request body length does not match Content-Length.', undefined, ctx('request'));
|
|
674
803
|
return;
|
|
675
804
|
}
|
|
676
805
|
if (req.headers['content-type']) {
|
|
@@ -679,7 +808,7 @@ class ApiSrv {
|
|
|
679
808
|
contentType = ct.type;
|
|
680
809
|
contentTypeArgs = ct.params;
|
|
681
810
|
} else {
|
|
682
|
-
error(res, 400, 'Unable to parse content-type.');
|
|
811
|
+
error(res, 400, 'Unable to parse content-type.', undefined, ctx('request'));
|
|
683
812
|
return;
|
|
684
813
|
}
|
|
685
814
|
}
|
|
@@ -688,7 +817,7 @@ class ApiSrv {
|
|
|
688
817
|
case 'POST':
|
|
689
818
|
case 'PUT':
|
|
690
819
|
if (req.url.match(/\?/)) {
|
|
691
|
-
error(res, 400, 'URL for POST or PUT must not contain query parameters.');
|
|
820
|
+
error(res, 400, 'URL for POST or PUT must not contain query parameters.', undefined, ctx('request'));
|
|
692
821
|
return;
|
|
693
822
|
}
|
|
694
823
|
r.url = req.url;
|
|
@@ -698,7 +827,7 @@ class ApiSrv {
|
|
|
698
827
|
case 'GET':
|
|
699
828
|
case 'DELETE':
|
|
700
829
|
if (body.length > 0) {
|
|
701
|
-
error(res, 400, 'Empty body required for ' + req.method + ' requests.');
|
|
830
|
+
error(res, 400, 'Empty body required for ' + req.method + ' requests.', undefined, ctx('request'));
|
|
702
831
|
return;
|
|
703
832
|
}
|
|
704
833
|
var m;
|
|
@@ -712,16 +841,32 @@ class ApiSrv {
|
|
|
712
841
|
r.method = req.method;
|
|
713
842
|
break;
|
|
714
843
|
default:
|
|
715
|
-
error(res, 405, 'Only GET, POST, PUT, and DELETE are allowed.');
|
|
844
|
+
error(res, 405, 'Only GET, POST, PUT, and DELETE are allowed.', undefined, ctx('request'));
|
|
716
845
|
return;
|
|
717
846
|
}
|
|
718
847
|
if (this.rejectDangerousPaths) {
|
|
719
848
|
const reason = detectDangerousPath(r.url);
|
|
720
849
|
if (reason) {
|
|
721
|
-
error(res, 400, reason);
|
|
850
|
+
error(res, 400, reason, undefined, ctx('request'));
|
|
722
851
|
return;
|
|
723
852
|
}
|
|
724
853
|
}
|
|
854
|
+
r.originalUrl = r.url;
|
|
855
|
+
{
|
|
856
|
+
const rewritten = rewritePath(r.url);
|
|
857
|
+
if (rewritten === undefined) {
|
|
858
|
+
error(res, 500, 'Request path rewrite fails.', undefined, ctx('router'));
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
r.url = rewritten;
|
|
862
|
+
if (this.rejectDangerousPaths && (rewritten !== r.originalUrl)) {
|
|
863
|
+
const reason = detectDangerousPath(r.url);
|
|
864
|
+
if (reason) {
|
|
865
|
+
error(res, 400, reason, undefined, ctx('request'));
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
}
|
|
725
870
|
r.headers = req.headers;
|
|
726
871
|
r.res = res;
|
|
727
872
|
r.req = req;
|
|
@@ -731,7 +876,8 @@ class ApiSrv {
|
|
|
731
876
|
r.pathParams = undefined;
|
|
732
877
|
r.params = undefined;
|
|
733
878
|
r.jsonResponse = (data, code, excludeNoCacheHeaders) => {
|
|
734
|
-
var headers = { 'Content-Type': 'application/json; charset=utf-8'
|
|
879
|
+
var headers = { 'Content-Type': 'application/json; charset=utf-8',
|
|
880
|
+
'X-Content-Type-Options': 'nosniff' };
|
|
735
881
|
if (! excludeNoCacheHeaders) {
|
|
736
882
|
headers = Object.assign(headers,
|
|
737
883
|
{ 'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
|
|
@@ -755,6 +901,7 @@ class ApiSrv {
|
|
|
755
901
|
let handler = handlerEntry ? handlerEntry.handler : undefined;
|
|
756
902
|
let handlerOptions = handlerEntry ? handlerEntry.options : undefined;
|
|
757
903
|
let pathParams = handlerEntry ? handlerEntry.params : Object.create(null);
|
|
904
|
+
r.handler = undefined;
|
|
758
905
|
if (!handler) {
|
|
759
906
|
if (this.callback) {
|
|
760
907
|
handler = this.callback;
|
|
@@ -763,14 +910,23 @@ class ApiSrv {
|
|
|
763
910
|
} else {
|
|
764
911
|
const hasOtherMethod = this.#hasHandlerForOtherMethod(r.method, r.url);
|
|
765
912
|
if (hasOtherMethod) {
|
|
766
|
-
jsonError(res, 405, 'Method Not Allowed');
|
|
913
|
+
jsonError(res, 405, 'Method Not Allowed', ctx('router'));
|
|
767
914
|
} else {
|
|
768
|
-
jsonError(res, 404, 'Not Found');
|
|
915
|
+
jsonError(res, 404, 'Not Found', ctx('router'));
|
|
769
916
|
}
|
|
770
917
|
return;
|
|
771
918
|
}
|
|
919
|
+
} else {
|
|
920
|
+
r.handler = {
|
|
921
|
+
method: r.method,
|
|
922
|
+
path: handlerEntry.template,
|
|
923
|
+
meta: handlerOptions ? handlerOptions.meta : undefined
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
let auth = await this.authCallback(r);
|
|
927
|
+
if (auth && handlerOptions && handlerOptions.authCallback) {
|
|
928
|
+
auth = await handlerOptions.authCallback(r);
|
|
772
929
|
}
|
|
773
|
-
const auth = await this.authCallback(r);
|
|
774
930
|
if (auth) {
|
|
775
931
|
const paramSources = new Map();
|
|
776
932
|
const ignoreUrlParams = handlerOptions && handlerOptions.ignoreUrlParams === true;
|
|
@@ -778,13 +934,14 @@ class ApiSrv {
|
|
|
778
934
|
try {
|
|
779
935
|
const result = await validator(value);
|
|
780
936
|
if (!result || typeof result !== 'object') {
|
|
781
|
-
error(res, 500, `${description} validator must return an object
|
|
937
|
+
error(res, 500, `${description} validator must return an object.`, undefined,
|
|
938
|
+
ctx('validator', { stage: description }));
|
|
782
939
|
return { success: false };
|
|
783
940
|
}
|
|
784
941
|
return { success: true, value: result };
|
|
785
942
|
} catch (err) {
|
|
786
943
|
const detail = (err && err.message) ? err.message : `Invalid ${description}.`;
|
|
787
|
-
error(res, 400, detail);
|
|
944
|
+
error(res, 400, detail, undefined, ctx('validator', { stage: description, cause: err }));
|
|
788
945
|
return { success: false };
|
|
789
946
|
}
|
|
790
947
|
};
|
|
@@ -799,6 +956,13 @@ class ApiSrv {
|
|
|
799
956
|
let urlParams;
|
|
800
957
|
if (!ignoreUrlParams) {
|
|
801
958
|
urlParams = parseQuery(rawQueryString);
|
|
959
|
+
if (this.rejectDangerousParamNames) {
|
|
960
|
+
const reserved = findDangerousParamName(urlParams);
|
|
961
|
+
if (reserved) {
|
|
962
|
+
error(res, 400, `Reserved parameter name "${reserved}" in query string.`, undefined, ctx('parser'));
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
802
966
|
if (handlerOptions && handlerOptions.urlParamsValidator) {
|
|
803
967
|
const validation = await runValidator(handlerOptions.urlParamsValidator, urlParams, 'URL parameters');
|
|
804
968
|
if (!validation.success) {
|
|
@@ -816,7 +980,7 @@ class ApiSrv {
|
|
|
816
980
|
break;
|
|
817
981
|
case 'application/json':
|
|
818
982
|
if (contentTypeArgs && contentTypeArgs.charset && (contentTypeArgs.charset !== 'utf-8')) {
|
|
819
|
-
error(res, 400, 'Bad charset for JSON content type.');
|
|
983
|
+
error(res, 400, 'Bad charset for JSON content type.', undefined, ctx('parser'));
|
|
820
984
|
return;
|
|
821
985
|
}
|
|
822
986
|
try {
|
|
@@ -825,13 +989,24 @@ class ApiSrv {
|
|
|
825
989
|
bodyParamsObject = undefined;
|
|
826
990
|
}
|
|
827
991
|
if (!(bodyParamsObject && (typeof bodyParamsObject === 'object'))) {
|
|
828
|
-
error(res, 400, 'Unable to parse JSON query parameters.');
|
|
992
|
+
error(res, 400, 'Unable to parse JSON query parameters.', undefined, ctx('parser'));
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
if (this.requireObjectBody && Array.isArray(bodyParamsObject)) {
|
|
996
|
+
error(res, 400, 'JSON body must be an object.', undefined, ctx('parser'));
|
|
829
997
|
return;
|
|
830
998
|
}
|
|
831
999
|
break;
|
|
832
1000
|
case 'multipart/form-data':
|
|
833
1001
|
default:
|
|
834
|
-
error(res, 400, 'POST or PUT body must be in JSON or www-form-urlencoded format.');
|
|
1002
|
+
error(res, 400, 'POST or PUT body must be in JSON or www-form-urlencoded format.', undefined, ctx('parser'));
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
if (this.rejectDangerousParamNames) {
|
|
1007
|
+
const reserved = findDangerousParamName(bodyParamsObject);
|
|
1008
|
+
if (reserved) {
|
|
1009
|
+
error(res, 400, `Reserved parameter name "${reserved}" in request body.`, undefined, ctx('parser'));
|
|
835
1010
|
return;
|
|
836
1011
|
}
|
|
837
1012
|
}
|
|
@@ -878,8 +1053,8 @@ class ApiSrv {
|
|
|
878
1053
|
console.log(e);
|
|
879
1054
|
}
|
|
880
1055
|
try {
|
|
881
|
-
error(res, 500, 'Request handler fails to execute.');
|
|
882
|
-
} catch(
|
|
1056
|
+
error(res, 500, 'Request handler fails to execute.', undefined, ctx('handler', { cause: e }));
|
|
1057
|
+
} catch(ignored) {
|
|
883
1058
|
}
|
|
884
1059
|
}
|
|
885
1060
|
};
|
|
@@ -892,7 +1067,7 @@ class ApiSrv {
|
|
|
892
1067
|
clearTimeout(timeout);
|
|
893
1068
|
timeout = undefined;
|
|
894
1069
|
}
|
|
895
|
-
error(res, 400, 'Error occured while reading the request data.');
|
|
1070
|
+
error(res, 400, 'Error occured while reading the request data.', undefined, ctx('request'));
|
|
896
1071
|
};
|
|
897
1072
|
const timeoutCb = () => {
|
|
898
1073
|
if (completed) {
|
|
@@ -900,18 +1075,63 @@ class ApiSrv {
|
|
|
900
1075
|
}
|
|
901
1076
|
timeout = undefined;
|
|
902
1077
|
completed = true;
|
|
903
|
-
error(res, 408, 'Timeout occured while reading the request data.');
|
|
1078
|
+
error(res, 408, 'Timeout occured while reading the request data.', undefined, ctx('limit'));
|
|
904
1079
|
};
|
|
905
1080
|
timeout = setTimeout(timeoutCb, this.bodyReadTimeoutMs);
|
|
906
1081
|
req.on('data', dataCb);
|
|
907
1082
|
req.on('end', endCb);
|
|
908
1083
|
req.on('error', errorCb);
|
|
909
1084
|
};
|
|
910
|
-
|
|
1085
|
+
// Offers a server-generated error to the optional errorCallback. The
|
|
1086
|
+
// default response is written when there is no callback, when it returns
|
|
1087
|
+
// (or resolves to) a falsy value, or when it fails.
|
|
1088
|
+
const reportError = (res, context, writeDefault) => {
|
|
1089
|
+
if (!this.errorCallback) {
|
|
1090
|
+
writeDefault();
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
const fallback = () => {
|
|
1094
|
+
if (res.headersSent || res.writableEnded) {
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
try {
|
|
1098
|
+
writeDefault();
|
|
1099
|
+
} catch (ignored) {
|
|
1100
|
+
}
|
|
1101
|
+
};
|
|
1102
|
+
let ret;
|
|
1103
|
+
try {
|
|
1104
|
+
ret = this.errorCallback(context);
|
|
1105
|
+
} catch (e) {
|
|
1106
|
+
if (this.debug) {
|
|
1107
|
+
console.log(e);
|
|
1108
|
+
}
|
|
1109
|
+
fallback();
|
|
1110
|
+
return;
|
|
1111
|
+
}
|
|
1112
|
+
if (ret && (typeof ret.then === 'function')) {
|
|
1113
|
+
ret.then((handled) => {
|
|
1114
|
+
if (!handled) {
|
|
1115
|
+
fallback();
|
|
1116
|
+
}
|
|
1117
|
+
}, (e) => {
|
|
1118
|
+
if (this.debug) {
|
|
1119
|
+
console.log(e);
|
|
1120
|
+
}
|
|
1121
|
+
fallback();
|
|
1122
|
+
});
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
if (!ret) {
|
|
1126
|
+
fallback();
|
|
1127
|
+
}
|
|
1128
|
+
};
|
|
1129
|
+
const error = (res, code, text, RFC6749EC, context) => {
|
|
911
1130
|
if (RFC6749EC) {
|
|
912
1131
|
// RFC6749 wants these errors to be code 400 except in case of 401
|
|
913
1132
|
res.writeHead((code != 401) ? 400 : 401,
|
|
914
|
-
{ 'Content-Type': 'application/json; charset=utf-8'
|
|
1133
|
+
{ 'Content-Type': 'application/json; charset=utf-8',
|
|
1134
|
+
'X-Content-Type-Options': 'nosniff' });
|
|
915
1135
|
res.write(JSON.stringify( { error: RFC6749EC,
|
|
916
1136
|
error_description: (text ?
|
|
917
1137
|
(text +
|
|
@@ -923,25 +1143,42 @@ class ApiSrv {
|
|
|
923
1143
|
null, 2));
|
|
924
1144
|
|
|
925
1145
|
res.write("\n");
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
1146
|
+
res.end();
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
const canonical = HTTP_STATUS_MESSAGES[code] || 'Error';
|
|
1150
|
+
let detail = text ? text.trim() : '';
|
|
1151
|
+
if (detail) {
|
|
1152
|
+
detail = detail.replace(/\.+$/, '');
|
|
1153
|
+
}
|
|
1154
|
+
let message = canonical;
|
|
1155
|
+
if (code === 400 && detail) {
|
|
1156
|
+
message = `${canonical} (${detail})`;
|
|
1157
|
+
}
|
|
1158
|
+
const writeDefault = () => {
|
|
1159
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8',
|
|
1160
|
+
'X-Content-Type-Options': 'nosniff' });
|
|
937
1161
|
res.write(JSON.stringify({ code, message }));
|
|
1162
|
+
res.end();
|
|
1163
|
+
};
|
|
1164
|
+
if (!context) {
|
|
1165
|
+
writeDefault();
|
|
1166
|
+
return;
|
|
938
1167
|
}
|
|
939
|
-
res.
|
|
1168
|
+
reportError(res, Object.assign({ code, message, detail: detail || undefined }, context), writeDefault);
|
|
940
1169
|
};
|
|
941
|
-
const jsonError = (res, code, message) => {
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
1170
|
+
const jsonError = (res, code, message, context) => {
|
|
1171
|
+
const writeDefault = () => {
|
|
1172
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8',
|
|
1173
|
+
'X-Content-Type-Options': 'nosniff' });
|
|
1174
|
+
res.write(JSON.stringify({ message, code }));
|
|
1175
|
+
res.end();
|
|
1176
|
+
};
|
|
1177
|
+
if (!context) {
|
|
1178
|
+
writeDefault();
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
reportError(res, Object.assign({ code, message, detail: undefined }, context), writeDefault);
|
|
945
1182
|
};
|
|
946
1183
|
this.server = proto.createServer(srvOpts, requestCb);
|
|
947
1184
|
if (this.upgradeCallback) {
|
|
@@ -1003,6 +1240,22 @@ class ApiSrv {
|
|
|
1003
1240
|
return removed;
|
|
1004
1241
|
}
|
|
1005
1242
|
|
|
1243
|
+
// Returns the registered request handlers as { method, path, meta }
|
|
1244
|
+
// objects, in registration order for each method.
|
|
1245
|
+
requestHandlerList() {
|
|
1246
|
+
const list = [];
|
|
1247
|
+
for (const [method, store] of this._requestHandlers.entries()) {
|
|
1248
|
+
for (const entry of [...store.exact.values(), ...store.dynamic.values()]) {
|
|
1249
|
+
list.push({
|
|
1250
|
+
method,
|
|
1251
|
+
path: entry.template,
|
|
1252
|
+
meta: entry.options ? entry.options.meta : undefined
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
return list;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1006
1259
|
#matchRequestHandler(method, path) {
|
|
1007
1260
|
const store = this._requestHandlers.get(method.toUpperCase());
|
|
1008
1261
|
if (!store) {
|