tr-apisrv 1.0.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 +416 -62
- package/index.js +974 -91
- package/package.json +1 -1
- package/test/test.js +1570 -10
package/index.js
CHANGED
|
@@ -2,6 +2,61 @@
|
|
|
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
|
+
'authCallback',
|
|
35
|
+
'meta'
|
|
36
|
+
]);
|
|
37
|
+
const PARAM_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
38
|
+
const DANGEROUS_PARAM_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
|
|
39
|
+
const DEFAULT_SPLAT_MIN = 1;
|
|
40
|
+
const DEFAULT_SPLAT_MAX = 32;
|
|
41
|
+
|
|
42
|
+
function detectDangerousPath(path) {
|
|
43
|
+
if (typeof path !== 'string') {
|
|
44
|
+
return 'invalid request path';
|
|
45
|
+
}
|
|
46
|
+
if (path === '/') {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
if (path.includes('//')) {
|
|
50
|
+
return 'empty path segment';
|
|
51
|
+
}
|
|
52
|
+
if ((path === '/.') || path.endsWith('/.') || path.includes('/./')) {
|
|
53
|
+
return 'dangerous path segment "."';
|
|
54
|
+
}
|
|
55
|
+
if ((path === '/..') || path.endsWith('/..') || path.includes('/../')) {
|
|
56
|
+
return 'dangerous path segment ".."';
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
5
60
|
function parseQuery(str) {
|
|
6
61
|
const params = Object.create(null);
|
|
7
62
|
if (!str) {
|
|
@@ -44,7 +99,401 @@ function parseContentType(str) {
|
|
|
44
99
|
return { type, params };
|
|
45
100
|
}
|
|
46
101
|
|
|
47
|
-
|
|
102
|
+
function isPlainObject(value) {
|
|
103
|
+
return !!value && (typeof value === 'object') && !Array.isArray(value);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function normalizeHandlerOptions(method, path, options) {
|
|
107
|
+
if (options === undefined) {
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
if (!isPlainObject(options)) {
|
|
111
|
+
throw new Error(`Bad request handler options for ${method} ${path}`);
|
|
112
|
+
}
|
|
113
|
+
for (const key of Object.keys(options)) {
|
|
114
|
+
if (!HANDLER_OPTION_KEYS.has(key)) {
|
|
115
|
+
throw new Error(`Unsupported request handler option "${key}" for ${method} ${path}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const normalized = {};
|
|
119
|
+
if (options.paramsValidator !== undefined) {
|
|
120
|
+
if (typeof options.paramsValidator !== 'function') {
|
|
121
|
+
throw new Error(`paramsValidator must be a function for ${method} ${path}`);
|
|
122
|
+
}
|
|
123
|
+
normalized.paramsValidator = options.paramsValidator;
|
|
124
|
+
}
|
|
125
|
+
if (options.pathParamsValidator !== undefined) {
|
|
126
|
+
if (typeof options.pathParamsValidator !== 'function') {
|
|
127
|
+
throw new Error(`pathParamsValidator must be a function for ${method} ${path}`);
|
|
128
|
+
}
|
|
129
|
+
normalized.pathParamsValidator = options.pathParamsValidator;
|
|
130
|
+
}
|
|
131
|
+
if (options.urlParamsValidator !== undefined) {
|
|
132
|
+
if (typeof options.urlParamsValidator !== 'function') {
|
|
133
|
+
throw new Error(`urlParamsValidator must be a function for ${method} ${path}`);
|
|
134
|
+
}
|
|
135
|
+
normalized.urlParamsValidator = options.urlParamsValidator;
|
|
136
|
+
}
|
|
137
|
+
if (options.bodyParamsValidator !== undefined) {
|
|
138
|
+
if (typeof options.bodyParamsValidator !== 'function') {
|
|
139
|
+
throw new Error(`bodyParamsValidator must be a function for ${method} ${path}`);
|
|
140
|
+
}
|
|
141
|
+
normalized.bodyParamsValidator = options.bodyParamsValidator;
|
|
142
|
+
}
|
|
143
|
+
if (options.ignoreUrlParams !== undefined) {
|
|
144
|
+
if (typeof options.ignoreUrlParams !== 'boolean') {
|
|
145
|
+
throw new Error(`ignoreUrlParams must be a boolean for ${method} ${path}`);
|
|
146
|
+
}
|
|
147
|
+
if (options.ignoreUrlParams) {
|
|
148
|
+
normalized.ignoreUrlParams = true;
|
|
149
|
+
}
|
|
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
|
+
}
|
|
160
|
+
return Object.keys(normalized).length > 0 ? normalized : undefined;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function describePath(path) {
|
|
164
|
+
if (typeof path !== 'string' || !path.startsWith('/')) {
|
|
165
|
+
throw new Error(`Bad request path: ${path}`);
|
|
166
|
+
}
|
|
167
|
+
if (path === '/') {
|
|
168
|
+
return { segments: [], hasTrailingSlash: false };
|
|
169
|
+
}
|
|
170
|
+
const hasTrailingSlash = (path.length > 1) && path.endsWith('/');
|
|
171
|
+
const trimmed = hasTrailingSlash ? path.slice(0, -1) : path;
|
|
172
|
+
if (trimmed === '/') {
|
|
173
|
+
return { segments: [], hasTrailingSlash: true };
|
|
174
|
+
}
|
|
175
|
+
const segments = trimmed.slice(1).split('/');
|
|
176
|
+
return { segments, hasTrailingSlash };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function decodePathSegment(segment) {
|
|
180
|
+
try {
|
|
181
|
+
return decodeURIComponent(segment);
|
|
182
|
+
} catch (e) {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function compilePathTemplate(path) {
|
|
188
|
+
if (typeof path !== 'string' || !path.startsWith('/')) {
|
|
189
|
+
throw new Error(`Bad request handler path: ${path}`);
|
|
190
|
+
}
|
|
191
|
+
if (path === '/') {
|
|
192
|
+
return {
|
|
193
|
+
isExact: true,
|
|
194
|
+
template: path,
|
|
195
|
+
segments: [],
|
|
196
|
+
hasTrailingSlash: false,
|
|
197
|
+
hasSplat: false,
|
|
198
|
+
minSegments: 0,
|
|
199
|
+
minSegmentsFrom: [0]
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
const hasTrailingSlash = (path.length > 1) && path.endsWith('/');
|
|
203
|
+
const trimmed = hasTrailingSlash ? path.slice(0, -1) : path;
|
|
204
|
+
const rawSegments = trimmed.slice(1).split('/');
|
|
205
|
+
const segments = [];
|
|
206
|
+
let hasDynamic = false;
|
|
207
|
+
let hasSplat = false;
|
|
208
|
+
for (const part of rawSegments) {
|
|
209
|
+
if (part === '') {
|
|
210
|
+
segments.push({ type: 'literal', value: '' });
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
let match;
|
|
214
|
+
if ((match = part.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/))) {
|
|
215
|
+
hasDynamic = true;
|
|
216
|
+
const name = match[1];
|
|
217
|
+
if (!PARAM_NAME_RE.test(name) || (name === '__proto__')) {
|
|
218
|
+
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
219
|
+
}
|
|
220
|
+
segments.push({ type: 'param', name });
|
|
221
|
+
} else if ((match = part.match(/^\[([A-Za-z_][A-Za-z0-9_]*)(?::(\d+)(?::(\d+))?)?\]$/))) {
|
|
222
|
+
hasDynamic = true;
|
|
223
|
+
hasSplat = true;
|
|
224
|
+
const name = match[1];
|
|
225
|
+
if (!PARAM_NAME_RE.test(name) || (name === '__proto__')) {
|
|
226
|
+
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
227
|
+
}
|
|
228
|
+
let minItems = DEFAULT_SPLAT_MIN;
|
|
229
|
+
let maxItems = DEFAULT_SPLAT_MAX;
|
|
230
|
+
if (match[2] !== undefined) {
|
|
231
|
+
const first = Number.parseInt(match[2], 10);
|
|
232
|
+
if (!Number.isSafeInteger(first)) {
|
|
233
|
+
throw new Error(`Invalid array length constraint for "${name}" in ${path}`);
|
|
234
|
+
}
|
|
235
|
+
if (match[3] === undefined) {
|
|
236
|
+
minItems = first;
|
|
237
|
+
maxItems = first;
|
|
238
|
+
} else {
|
|
239
|
+
const second = Number.parseInt(match[3], 10);
|
|
240
|
+
if (!Number.isSafeInteger(second)) {
|
|
241
|
+
throw new Error(`Invalid array length constraint for "${name}" in ${path}`);
|
|
242
|
+
}
|
|
243
|
+
minItems = first;
|
|
244
|
+
maxItems = second;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (minItems < 1) {
|
|
248
|
+
throw new Error(`Invalid minimum length for "${name}" in ${path}`);
|
|
249
|
+
}
|
|
250
|
+
if (maxItems < minItems) {
|
|
251
|
+
throw new Error(`Invalid length range for "${name}" in ${path}`);
|
|
252
|
+
}
|
|
253
|
+
segments.push({ type: 'splat', name, minItems, maxItems });
|
|
254
|
+
} else if (part.startsWith('{') && part.endsWith('}')) {
|
|
255
|
+
const name = part.slice(1, -1);
|
|
256
|
+
if (!PARAM_NAME_RE.test(name)) {
|
|
257
|
+
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
258
|
+
}
|
|
259
|
+
throw new Error(`Invalid path parameter segment "${part}" in ${path}`);
|
|
260
|
+
} else if (part.startsWith('[') && part.endsWith(']')) {
|
|
261
|
+
const inner = part.slice(1, -1);
|
|
262
|
+
const name = inner.split(':', 1)[0];
|
|
263
|
+
if (!PARAM_NAME_RE.test(name)) {
|
|
264
|
+
throw new Error(`Invalid path parameter name "${name}" in ${path}`);
|
|
265
|
+
}
|
|
266
|
+
throw new Error(`Invalid path parameter segment "${part}" in ${path}`);
|
|
267
|
+
} else {
|
|
268
|
+
segments.push({ type: 'literal', value: part });
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const minSegmentsFrom = new Array(segments.length + 1);
|
|
272
|
+
minSegmentsFrom[segments.length] = 0;
|
|
273
|
+
for (let i = segments.length - 1; i >= 0; i--) {
|
|
274
|
+
const segment = segments[i];
|
|
275
|
+
const minCount = segment.type === 'splat' ? segment.minItems : 1;
|
|
276
|
+
minSegmentsFrom[i] = minSegmentsFrom[i + 1] + minCount;
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
isExact: !hasDynamic,
|
|
280
|
+
template: path,
|
|
281
|
+
segments,
|
|
282
|
+
hasTrailingSlash,
|
|
283
|
+
hasSplat,
|
|
284
|
+
minSegments: minSegmentsFrom[0],
|
|
285
|
+
minSegmentsFrom
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function matchCompiledPath(compiled, pathInfo) {
|
|
290
|
+
if (compiled.hasTrailingSlash && !pathInfo.hasTrailingSlash) {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
if (pathInfo.segments.length < compiled.minSegments) {
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
if (!compiled.hasSplat && (pathInfo.segments.length !== compiled.segments.length)) {
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
if (compiled.segments.length === 0) {
|
|
300
|
+
return pathInfo.segments.length === 0 ? {} : null;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const segments = compiled.segments;
|
|
304
|
+
const reqSegments = pathInfo.segments;
|
|
305
|
+
|
|
306
|
+
function matchRecursive(tIndex, rIndex) {
|
|
307
|
+
if (tIndex === segments.length) {
|
|
308
|
+
return (rIndex === reqSegments.length) ? {} : null;
|
|
309
|
+
}
|
|
310
|
+
const segment = segments[tIndex];
|
|
311
|
+
if (segment.type === 'literal') {
|
|
312
|
+
if ((rIndex >= reqSegments.length) || (segment.value !== reqSegments[rIndex])) {
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
return matchRecursive(tIndex + 1, rIndex + 1);
|
|
316
|
+
}
|
|
317
|
+
if (segment.type === 'param') {
|
|
318
|
+
if (rIndex >= reqSegments.length) {
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
const decoded = decodePathSegment(reqSegments[rIndex]);
|
|
322
|
+
if (decoded === null) {
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
const rest = matchRecursive(tIndex + 1, rIndex + 1);
|
|
326
|
+
if (!rest) {
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
rest[segment.name] = decoded;
|
|
330
|
+
return rest;
|
|
331
|
+
}
|
|
332
|
+
if (segment.type === 'splat') {
|
|
333
|
+
if (rIndex >= reqSegments.length) {
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
const minRemaining = compiled.minSegmentsFrom[tIndex + 1];
|
|
337
|
+
const minLen = segment.minItems;
|
|
338
|
+
const available = reqSegments.length - rIndex - minRemaining;
|
|
339
|
+
if (available < minLen) {
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
const maxLen = Math.min(segment.maxItems, available);
|
|
343
|
+
if (maxLen < minLen) {
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
for (let len = minLen; len <= maxLen; len++) {
|
|
347
|
+
const slice = reqSegments.slice(rIndex, rIndex + len);
|
|
348
|
+
if (slice.length !== len) {
|
|
349
|
+
break;
|
|
350
|
+
}
|
|
351
|
+
const decodedSlice = [];
|
|
352
|
+
let failed = false;
|
|
353
|
+
for (const part of slice) {
|
|
354
|
+
const decoded = decodePathSegment(part);
|
|
355
|
+
if (decoded === null) {
|
|
356
|
+
failed = true;
|
|
357
|
+
break;
|
|
358
|
+
}
|
|
359
|
+
decodedSlice.push(decoded);
|
|
360
|
+
}
|
|
361
|
+
if (failed) {
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
const rest = matchRecursive(tIndex + 1, rIndex + len);
|
|
365
|
+
if (!rest) {
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
rest[segment.name] = decodedSlice;
|
|
369
|
+
return rest;
|
|
370
|
+
}
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
return matchRecursive(0, 0);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function assignParams(target, source, sourceType, sources) {
|
|
380
|
+
if (!source) {
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
for (const [key, value] of Object.entries(source)) {
|
|
384
|
+
if (Object.prototype.hasOwnProperty.call(target, key)) {
|
|
385
|
+
const previous = sources.get(key);
|
|
386
|
+
if (previous && previous !== sourceType) {
|
|
387
|
+
const prevLabel = PARAM_SOURCE_LABELS[previous] || previous;
|
|
388
|
+
const currentLabel = PARAM_SOURCE_LABELS[sourceType] || sourceType;
|
|
389
|
+
console.warn(`ApiSrv warning: parameter "${key}" from ${currentLabel} overrides value from ${prevLabel}.`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
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
|
+
});
|
|
400
|
+
sources.set(key, sourceType);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
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
|
+
|
|
434
|
+
function normalizeMethod(method) {
|
|
435
|
+
if (typeof method !== 'string') {
|
|
436
|
+
throw new Error(`Bad request handler method: ${method}`);
|
|
437
|
+
}
|
|
438
|
+
const upper = method.toUpperCase();
|
|
439
|
+
if (!SUPPORTED_METHODS.has(upper)) {
|
|
440
|
+
throw new Error(`Unsupported request handler method: ${method}`);
|
|
441
|
+
}
|
|
442
|
+
return upper;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function getMethodStore(map, method, createIfMissing) {
|
|
446
|
+
let store = map.get(method);
|
|
447
|
+
if (!store && createIfMissing) {
|
|
448
|
+
store = { exact: new Map(), dynamic: new Map() };
|
|
449
|
+
map.set(method, store);
|
|
450
|
+
}
|
|
451
|
+
return store;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function removeFromStore(store, path) {
|
|
455
|
+
let removed = false;
|
|
456
|
+
if (store.exact.delete(path)) {
|
|
457
|
+
removed = true;
|
|
458
|
+
}
|
|
459
|
+
if (store.dynamic.delete(path)) {
|
|
460
|
+
removed = true;
|
|
461
|
+
}
|
|
462
|
+
return removed;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function findMatchInStore(store, path) {
|
|
466
|
+
if (!store) {
|
|
467
|
+
return null;
|
|
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
|
+
}
|
|
474
|
+
let exact = store.exact.get(path);
|
|
475
|
+
if (exact) {
|
|
476
|
+
return { handler: exact.handler, options: exact.options, params: {}, template: exact.template };
|
|
477
|
+
}
|
|
478
|
+
if ((path.length > 1) && path.endsWith('/')) {
|
|
479
|
+
const trimmed = path.slice(0, -1);
|
|
480
|
+
exact = store.exact.get(trimmed);
|
|
481
|
+
if (exact && !exact.hasTrailingSlash) {
|
|
482
|
+
return { handler: exact.handler, options: exact.options, params: {}, template: exact.template };
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
const pathInfo = describePath(path);
|
|
486
|
+
for (const entry of store.dynamic.values()) {
|
|
487
|
+
const params = matchCompiledPath(entry, pathInfo);
|
|
488
|
+
if (params) {
|
|
489
|
+
return { handler: entry.handler, options: entry.options, params, template: entry.template };
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return null;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
class ApiSrv {
|
|
496
|
+
constructor(opts) {
|
|
48
497
|
var proto = http;
|
|
49
498
|
var srvOpts = {};
|
|
50
499
|
if (!(opts && (typeof(opts) === 'object'))) {
|
|
@@ -61,6 +510,13 @@ var ApiSrv = function(opts) {
|
|
|
61
510
|
}
|
|
62
511
|
this.debug = opts.debug ? true : false;
|
|
63
512
|
this.prettyPrintJsonResponses = opts.prettyPrintJsonResponses ? true : false;
|
|
513
|
+
if (opts.rejectDangerousPaths === undefined) {
|
|
514
|
+
this.rejectDangerousPaths = true;
|
|
515
|
+
} else if (typeof opts.rejectDangerousPaths === 'boolean') {
|
|
516
|
+
this.rejectDangerousPaths = opts.rejectDangerousPaths;
|
|
517
|
+
} else {
|
|
518
|
+
throw new Error(`Bad rejectDangerousPaths for ApiSrv constructor: ${opts.rejectDangerousPaths}`);
|
|
519
|
+
}
|
|
64
520
|
if (Number.isSafeInteger(opts.port) && (opts.port > 0) && (opts.port < 65536)) {
|
|
65
521
|
this.port = opts.port;
|
|
66
522
|
} else {
|
|
@@ -71,10 +527,44 @@ var ApiSrv = function(opts) {
|
|
|
71
527
|
} else if (opts.address) {
|
|
72
528
|
throw new Error(`Bad address for ApiSrv constructor: ${opts.address}`);
|
|
73
529
|
}
|
|
74
|
-
if (
|
|
75
|
-
|
|
530
|
+
if (opts.callback !== undefined) {
|
|
531
|
+
if (typeof(opts.callback) === 'function') {
|
|
532
|
+
this.callback = opts.callback;
|
|
533
|
+
} else {
|
|
534
|
+
throw new Error(`Bad callback for ApiSrv constructor: ${opts.callback}`);
|
|
535
|
+
}
|
|
76
536
|
} else {
|
|
77
|
-
|
|
537
|
+
this.callback = undefined;
|
|
538
|
+
}
|
|
539
|
+
this._requestHandlers = new Map();
|
|
540
|
+
if (opts.requestHandlers !== undefined) {
|
|
541
|
+
if (!isPlainObject(opts.requestHandlers)) {
|
|
542
|
+
throw new Error('requestHandlers must be an object.');
|
|
543
|
+
}
|
|
544
|
+
for (const [method, handlers] of Object.entries(opts.requestHandlers)) {
|
|
545
|
+
if (!isPlainObject(handlers)) {
|
|
546
|
+
throw new Error(`Bad requestHandlers for method ${method}`);
|
|
547
|
+
}
|
|
548
|
+
for (const [path, handlerDef] of Object.entries(handlers)) {
|
|
549
|
+
if (typeof handlerDef === 'function') {
|
|
550
|
+
this.requestHandleAdd(method, path, handlerDef);
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
if (isPlainObject(handlerDef)) {
|
|
554
|
+
for (const key of Object.keys(handlerDef)) {
|
|
555
|
+
if (key !== 'callback' && key !== 'options') {
|
|
556
|
+
throw new Error(`Unsupported request handler definition key "${key}" for ${method} ${path}`);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
if (typeof handlerDef.callback !== 'function') {
|
|
560
|
+
throw new Error(`Bad request handler callback for ${method} ${path}`);
|
|
561
|
+
}
|
|
562
|
+
this.requestHandleAdd(method, path, handlerDef.callback, handlerDef.options);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
throw new Error(`Bad request handler callback for ${method} ${path}`);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
78
568
|
}
|
|
79
569
|
if ((opts.authCallback !== undefined) && (opts.authCallback !== null)) {
|
|
80
570
|
if (typeof(opts.authCallback) === 'function') {
|
|
@@ -86,7 +576,7 @@ var ApiSrv = function(opts) {
|
|
|
86
576
|
if (this.debug) {
|
|
87
577
|
console.log('No authentication callback set.');
|
|
88
578
|
}
|
|
89
|
-
this.authCallback =
|
|
579
|
+
this.authCallback = (r) => true;
|
|
90
580
|
}
|
|
91
581
|
if ((opts.upgradeCallback !== undefined) && (opts.upgradeCallback !== null)) {
|
|
92
582
|
if (typeof(opts.upgradeCallback) === 'function') {
|
|
@@ -115,24 +605,105 @@ var ApiSrv = function(opts) {
|
|
|
115
605
|
} else {
|
|
116
606
|
this.maxBodySize = 1024 * 1024;
|
|
117
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
|
+
}
|
|
118
640
|
srvOpts.headersTimeout = this.bodyReadTimeoutMs;
|
|
119
641
|
srvOpts.requestTimeout = this.bodyReadTimeoutMs + 1;
|
|
120
642
|
|
|
121
|
-
|
|
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
|
+
|
|
668
|
+
const upgradeCb = async (req, s, head) => {
|
|
122
669
|
var m, r = {};
|
|
123
670
|
r.method = req.method;
|
|
671
|
+
let rawQueryString;
|
|
124
672
|
if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
|
|
125
673
|
r.url = m[1];
|
|
126
|
-
|
|
674
|
+
rawQueryString = m[2].toString('utf8');
|
|
127
675
|
} else {
|
|
128
676
|
r.url = req.url;
|
|
129
|
-
|
|
677
|
+
rawQueryString = undefined;
|
|
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;
|
|
130
687
|
}
|
|
688
|
+
r.bodyParams = undefined;
|
|
689
|
+
r.urlParams = undefined;
|
|
690
|
+
r.pathParams = undefined;
|
|
691
|
+
r.params = undefined;
|
|
131
692
|
r.headers = req.headers;
|
|
132
693
|
r.req = req;
|
|
133
694
|
try {
|
|
134
695
|
const ret = await this.authCallback(r);
|
|
135
696
|
if (ret) {
|
|
697
|
+
const queryOnlyParams = parseQuery(rawQueryString);
|
|
698
|
+
if (this.rejectDangerousParamNames && findDangerousParamName(queryOnlyParams)) {
|
|
699
|
+
s.destroy();
|
|
700
|
+
s = undefined;
|
|
701
|
+
return false;
|
|
702
|
+
}
|
|
703
|
+
r.urlParams = queryOnlyParams;
|
|
704
|
+
r.params = queryOnlyParams;
|
|
705
|
+
r.bodyParams = Object.create(null);
|
|
706
|
+
r.pathParams = Object.create(null);
|
|
136
707
|
r.head = head;
|
|
137
708
|
r.s = s;
|
|
138
709
|
const cbRet = await opts.upgradeCallback(r);
|
|
@@ -156,24 +727,26 @@ var ApiSrv = function(opts) {
|
|
|
156
727
|
}
|
|
157
728
|
return false;
|
|
158
729
|
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
var completed = false, body = Buffer.alloc(0), r = {}, timeout, bodySize = 0;
|
|
730
|
+
};
|
|
731
|
+
const requestCb = (req, res) => {
|
|
732
|
+
var completed = false, body = Buffer.alloc(0), chunks = [], r = {}, timeout, bodySize = 0;
|
|
162
733
|
var contentType, contentTypeArgs;
|
|
163
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);
|
|
164
737
|
if (req.headers['transfer-encoding'] && req.headers['content-length']) {
|
|
165
|
-
error(res, 400, 'Both Transfer-Encoding and Content-Length defined.');
|
|
738
|
+
error(res, 400, 'Both Transfer-Encoding and Content-Length defined.', undefined, ctx('request'));
|
|
166
739
|
return;
|
|
167
740
|
}
|
|
168
741
|
if (req.headers['content-length']) {
|
|
169
742
|
var cl = parseInt(req.headers['content-length'], 10);
|
|
170
743
|
if (!Number.isSafeInteger(cl) || cl < 0) {
|
|
171
|
-
error(res, 400, 'Bad Content-Length header.');
|
|
744
|
+
error(res, 400, 'Bad Content-Length header.', undefined, ctx('request'));
|
|
172
745
|
return;
|
|
173
746
|
}
|
|
174
747
|
declaredContentLength = cl;
|
|
175
748
|
if (this.maxBodySize && (cl > this.maxBodySize)) {
|
|
176
|
-
error(res, 413, 'Request body too large.');
|
|
749
|
+
error(res, 413, 'Request body too large.', undefined, ctx('limit'));
|
|
177
750
|
try {
|
|
178
751
|
req.destroy();
|
|
179
752
|
} catch (ignored) {
|
|
@@ -181,7 +754,7 @@ var ApiSrv = function(opts) {
|
|
|
181
754
|
return;
|
|
182
755
|
}
|
|
183
756
|
}
|
|
184
|
-
|
|
757
|
+
const dataCb = (data) => {
|
|
185
758
|
if (completed) {
|
|
186
759
|
return;
|
|
187
760
|
}
|
|
@@ -192,7 +765,7 @@ var ApiSrv = function(opts) {
|
|
|
192
765
|
clearTimeout(timeout);
|
|
193
766
|
timeout = undefined;
|
|
194
767
|
}
|
|
195
|
-
error(res, 400, 'Request body longer than Content-Length.');
|
|
768
|
+
error(res, 400, 'Request body longer than Content-Length.', undefined, ctx('request'));
|
|
196
769
|
try {
|
|
197
770
|
req.destroy();
|
|
198
771
|
} catch (ignored) {
|
|
@@ -205,16 +778,16 @@ var ApiSrv = function(opts) {
|
|
|
205
778
|
clearTimeout(timeout);
|
|
206
779
|
timeout = undefined;
|
|
207
780
|
}
|
|
208
|
-
error(res, 413, 'Request body too large.');
|
|
781
|
+
error(res, 413, 'Request body too large.', undefined, ctx('limit'));
|
|
209
782
|
try {
|
|
210
783
|
req.destroy();
|
|
211
784
|
} catch (ignored) {
|
|
212
785
|
}
|
|
213
786
|
return;
|
|
214
787
|
}
|
|
215
|
-
|
|
216
|
-
}
|
|
217
|
-
|
|
788
|
+
chunks.push(data);
|
|
789
|
+
};
|
|
790
|
+
const endCb = async () => {
|
|
218
791
|
if (completed) {
|
|
219
792
|
return;
|
|
220
793
|
}
|
|
@@ -223,8 +796,10 @@ var ApiSrv = function(opts) {
|
|
|
223
796
|
clearTimeout(timeout);
|
|
224
797
|
timeout = undefined;
|
|
225
798
|
}
|
|
799
|
+
body = Buffer.concat(chunks, bodySize);
|
|
800
|
+
chunks = [];
|
|
226
801
|
if (declaredContentLength !== undefined && (body.length !== declaredContentLength)) {
|
|
227
|
-
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'));
|
|
228
803
|
return;
|
|
229
804
|
}
|
|
230
805
|
if (req.headers['content-type']) {
|
|
@@ -233,72 +808,76 @@ var ApiSrv = function(opts) {
|
|
|
233
808
|
contentType = ct.type;
|
|
234
809
|
contentTypeArgs = ct.params;
|
|
235
810
|
} else {
|
|
236
|
-
error(res, 400, 'Unable to parse content-type.');
|
|
811
|
+
error(res, 400, 'Unable to parse content-type.', undefined, ctx('request'));
|
|
237
812
|
return;
|
|
238
813
|
}
|
|
239
814
|
}
|
|
815
|
+
let rawQueryString;
|
|
240
816
|
switch (req.method) {
|
|
241
817
|
case 'POST':
|
|
242
818
|
case 'PUT':
|
|
243
819
|
if (req.url.match(/\?/)) {
|
|
244
|
-
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'));
|
|
245
821
|
return;
|
|
246
822
|
}
|
|
247
823
|
r.url = req.url;
|
|
248
824
|
r.method = req.method;
|
|
249
|
-
|
|
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
|
-
}
|
|
825
|
+
rawQueryString = undefined;
|
|
277
826
|
break;
|
|
278
827
|
case 'GET':
|
|
279
828
|
case 'DELETE':
|
|
280
829
|
if (body.length > 0) {
|
|
281
|
-
error(res, 400, 'Empty body required for ' + req.method + ' requests.');
|
|
830
|
+
error(res, 400, 'Empty body required for ' + req.method + ' requests.', undefined, ctx('request'));
|
|
282
831
|
return;
|
|
283
832
|
}
|
|
284
833
|
var m;
|
|
285
834
|
if (m = req.url.match(/^([^\?]*)\?(.*)$/)) {
|
|
286
835
|
r.url = m[1];
|
|
287
|
-
|
|
836
|
+
rawQueryString = m[2].toString('utf8');
|
|
288
837
|
} else {
|
|
289
838
|
r.url = req.url;
|
|
290
|
-
|
|
839
|
+
rawQueryString = undefined;
|
|
291
840
|
}
|
|
292
841
|
r.method = req.method;
|
|
293
842
|
break;
|
|
294
843
|
default:
|
|
295
|
-
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'));
|
|
296
845
|
return;
|
|
297
846
|
}
|
|
847
|
+
if (this.rejectDangerousPaths) {
|
|
848
|
+
const reason = detectDangerousPath(r.url);
|
|
849
|
+
if (reason) {
|
|
850
|
+
error(res, 400, reason, undefined, ctx('request'));
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
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
|
+
}
|
|
298
870
|
r.headers = req.headers;
|
|
299
871
|
r.res = res;
|
|
300
|
-
r.
|
|
301
|
-
|
|
872
|
+
r.req = req;
|
|
873
|
+
r.requestPayloadBuffer = body;
|
|
874
|
+
r.bodyParams = undefined;
|
|
875
|
+
r.urlParams = undefined;
|
|
876
|
+
r.pathParams = undefined;
|
|
877
|
+
r.params = undefined;
|
|
878
|
+
r.jsonResponse = (data, code, excludeNoCacheHeaders) => {
|
|
879
|
+
var headers = { 'Content-Type': 'application/json; charset=utf-8',
|
|
880
|
+
'X-Content-Type-Options': 'nosniff' };
|
|
302
881
|
if (! excludeNoCacheHeaders) {
|
|
303
882
|
headers = Object.assign(headers,
|
|
304
883
|
{ 'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
|
|
@@ -313,11 +892,156 @@ var ApiSrv = function(opts) {
|
|
|
313
892
|
res.write(JSON.stringify(data));
|
|
314
893
|
}
|
|
315
894
|
res.end();
|
|
316
|
-
}
|
|
895
|
+
};
|
|
896
|
+
r.errorResponse = (code, detail) => {
|
|
897
|
+
return error(res, code, detail);
|
|
898
|
+
};
|
|
317
899
|
try {
|
|
318
|
-
|
|
900
|
+
let handlerEntry = this.#matchRequestHandler(r.method, r.url);
|
|
901
|
+
let handler = handlerEntry ? handlerEntry.handler : undefined;
|
|
902
|
+
let handlerOptions = handlerEntry ? handlerEntry.options : undefined;
|
|
903
|
+
let pathParams = handlerEntry ? handlerEntry.params : Object.create(null);
|
|
904
|
+
r.handler = undefined;
|
|
905
|
+
if (!handler) {
|
|
906
|
+
if (this.callback) {
|
|
907
|
+
handler = this.callback;
|
|
908
|
+
handlerOptions = undefined;
|
|
909
|
+
pathParams = Object.create(null);
|
|
910
|
+
} else {
|
|
911
|
+
const hasOtherMethod = this.#hasHandlerForOtherMethod(r.method, r.url);
|
|
912
|
+
if (hasOtherMethod) {
|
|
913
|
+
jsonError(res, 405, 'Method Not Allowed', ctx('router'));
|
|
914
|
+
} else {
|
|
915
|
+
jsonError(res, 404, 'Not Found', ctx('router'));
|
|
916
|
+
}
|
|
917
|
+
return;
|
|
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);
|
|
929
|
+
}
|
|
319
930
|
if (auth) {
|
|
320
|
-
const
|
|
931
|
+
const paramSources = new Map();
|
|
932
|
+
const ignoreUrlParams = handlerOptions && handlerOptions.ignoreUrlParams === true;
|
|
933
|
+
const runValidator = async (validator, value, description) => {
|
|
934
|
+
try {
|
|
935
|
+
const result = await validator(value);
|
|
936
|
+
if (!result || typeof result !== 'object') {
|
|
937
|
+
error(res, 500, `${description} validator must return an object.`, undefined,
|
|
938
|
+
ctx('validator', { stage: description }));
|
|
939
|
+
return { success: false };
|
|
940
|
+
}
|
|
941
|
+
return { success: true, value: result };
|
|
942
|
+
} catch (err) {
|
|
943
|
+
const detail = (err && err.message) ? err.message : `Invalid ${description}.`;
|
|
944
|
+
error(res, 400, detail, undefined, ctx('validator', { stage: description, cause: err }));
|
|
945
|
+
return { success: false };
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
let normalizedPathParams = (pathParams && (typeof pathParams === 'object')) ? pathParams : Object.create(null);
|
|
949
|
+
if (handlerOptions && handlerOptions.pathParamsValidator) {
|
|
950
|
+
const validation = await runValidator(handlerOptions.pathParamsValidator, normalizedPathParams, 'path parameters');
|
|
951
|
+
if (!validation.success) {
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
normalizedPathParams = validation.value;
|
|
955
|
+
}
|
|
956
|
+
let urlParams;
|
|
957
|
+
if (!ignoreUrlParams) {
|
|
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
|
+
}
|
|
966
|
+
if (handlerOptions && handlerOptions.urlParamsValidator) {
|
|
967
|
+
const validation = await runValidator(handlerOptions.urlParamsValidator, urlParams, 'URL parameters');
|
|
968
|
+
if (!validation.success) {
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
urlParams = validation.value;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
let bodyParamsObject;
|
|
975
|
+
if (req.method === 'POST' || req.method === 'PUT') {
|
|
976
|
+
switch (contentType) {
|
|
977
|
+
case 'application/x-www-form-urlencoded':
|
|
978
|
+
case 'application/www-form-urlencoded':
|
|
979
|
+
bodyParamsObject = parseQuery(body.toString('utf8'));
|
|
980
|
+
break;
|
|
981
|
+
case 'application/json':
|
|
982
|
+
if (contentTypeArgs && contentTypeArgs.charset && (contentTypeArgs.charset !== 'utf-8')) {
|
|
983
|
+
error(res, 400, 'Bad charset for JSON content type.', undefined, ctx('parser'));
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
try {
|
|
987
|
+
bodyParamsObject = JSON.parse(body.toString('utf8'));
|
|
988
|
+
} catch(e) {
|
|
989
|
+
bodyParamsObject = undefined;
|
|
990
|
+
}
|
|
991
|
+
if (!(bodyParamsObject && (typeof bodyParamsObject === 'object'))) {
|
|
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'));
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
999
|
+
break;
|
|
1000
|
+
case 'multipart/form-data':
|
|
1001
|
+
default:
|
|
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'));
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
let effectiveBodyParams = (bodyParamsObject && (typeof bodyParamsObject === 'object')) ? bodyParamsObject : Object.create(null);
|
|
1014
|
+
if (handlerOptions && handlerOptions.bodyParamsValidator) {
|
|
1015
|
+
const validation = await runValidator(handlerOptions.bodyParamsValidator, effectiveBodyParams, 'body parameters');
|
|
1016
|
+
if (!validation.success) {
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
effectiveBodyParams = validation.value;
|
|
1020
|
+
}
|
|
1021
|
+
const mergedParams = {};
|
|
1022
|
+
assignParams(mergedParams, effectiveBodyParams, 'body', paramSources);
|
|
1023
|
+
let safeUrlParams;
|
|
1024
|
+
if (!ignoreUrlParams) {
|
|
1025
|
+
safeUrlParams = (urlParams && (typeof urlParams === 'object')) ? urlParams : Object.create(null);
|
|
1026
|
+
assignParams(mergedParams, safeUrlParams, 'query', paramSources);
|
|
1027
|
+
r.urlParams = safeUrlParams;
|
|
1028
|
+
}
|
|
1029
|
+
assignParams(mergedParams, (normalizedPathParams && (typeof normalizedPathParams === 'object')) ? normalizedPathParams : Object.create(null), 'path', paramSources);
|
|
1030
|
+
if (handlerOptions && handlerOptions.paramsValidator) {
|
|
1031
|
+
const validation = await runValidator(handlerOptions.paramsValidator, mergedParams, 'request parameters');
|
|
1032
|
+
if (!validation.success) {
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
r.params = validation.value;
|
|
1036
|
+
} else {
|
|
1037
|
+
r.params = mergedParams;
|
|
1038
|
+
}
|
|
1039
|
+
r.bodyParams = effectiveBodyParams;
|
|
1040
|
+
r.pathParams = (normalizedPathParams && (typeof normalizedPathParams === 'object')) ? normalizedPathParams : Object.create(null);
|
|
1041
|
+
if (ignoreUrlParams) {
|
|
1042
|
+
delete r.urlParams;
|
|
1043
|
+
}
|
|
1044
|
+
const ret = await handler.call(this, r);
|
|
321
1045
|
if (ret !== false && this.debug) {
|
|
322
1046
|
console.log('Request successfully processed (resource :' + r.url + ').');
|
|
323
1047
|
}
|
|
@@ -329,12 +1053,12 @@ var ApiSrv = function(opts) {
|
|
|
329
1053
|
console.log(e);
|
|
330
1054
|
}
|
|
331
1055
|
try {
|
|
332
|
-
error(res, 500, 'Request handler fails to execute.');
|
|
333
|
-
} catch(
|
|
1056
|
+
error(res, 500, 'Request handler fails to execute.', undefined, ctx('handler', { cause: e }));
|
|
1057
|
+
} catch(ignored) {
|
|
334
1058
|
}
|
|
335
1059
|
}
|
|
336
|
-
}
|
|
337
|
-
|
|
1060
|
+
};
|
|
1061
|
+
const errorCb = () => {
|
|
338
1062
|
if (completed) {
|
|
339
1063
|
return;
|
|
340
1064
|
}
|
|
@@ -343,26 +1067,71 @@ var ApiSrv = function(opts) {
|
|
|
343
1067
|
clearTimeout(timeout);
|
|
344
1068
|
timeout = undefined;
|
|
345
1069
|
}
|
|
346
|
-
error(res, 400, 'Error occured while reading the request data.');
|
|
347
|
-
}
|
|
348
|
-
|
|
1070
|
+
error(res, 400, 'Error occured while reading the request data.', undefined, ctx('request'));
|
|
1071
|
+
};
|
|
1072
|
+
const timeoutCb = () => {
|
|
349
1073
|
if (completed) {
|
|
350
1074
|
return;
|
|
351
1075
|
}
|
|
352
1076
|
timeout = undefined;
|
|
353
1077
|
completed = true;
|
|
354
|
-
error(res, 408, 'Timeout occured while reading the request data.');
|
|
355
|
-
}
|
|
1078
|
+
error(res, 408, 'Timeout occured while reading the request data.', undefined, ctx('limit'));
|
|
1079
|
+
};
|
|
356
1080
|
timeout = setTimeout(timeoutCb, this.bodyReadTimeoutMs);
|
|
357
1081
|
req.on('data', dataCb);
|
|
358
1082
|
req.on('end', endCb);
|
|
359
1083
|
req.on('error', errorCb);
|
|
360
|
-
}
|
|
361
|
-
|
|
1084
|
+
};
|
|
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) => {
|
|
362
1130
|
if (RFC6749EC) {
|
|
363
1131
|
// RFC6749 wants these errors to be code 400 except in case of 401
|
|
364
1132
|
res.writeHead((code != 401) ? 400 : 401,
|
|
365
|
-
{ 'Content-Type': 'application/json; charset=utf-8'
|
|
1133
|
+
{ 'Content-Type': 'application/json; charset=utf-8',
|
|
1134
|
+
'X-Content-Type-Options': 'nosniff' });
|
|
366
1135
|
res.write(JSON.stringify( { error: RFC6749EC,
|
|
367
1136
|
error_description: (text ?
|
|
368
1137
|
(text +
|
|
@@ -372,15 +1141,45 @@ var ApiSrv = function(opts) {
|
|
|
372
1141
|
('HTTP code ' +
|
|
373
1142
|
code.toString())) },
|
|
374
1143
|
null, 2));
|
|
375
|
-
|
|
376
|
-
res.write("\n");
|
|
377
|
-
} else {
|
|
378
|
-
res.writeHead(code, { 'Content-Type': 'text/plain' });
|
|
379
|
-
res.write(text);
|
|
1144
|
+
|
|
380
1145
|
res.write("\n");
|
|
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})`;
|
|
381
1157
|
}
|
|
382
|
-
|
|
383
|
-
|
|
1158
|
+
const writeDefault = () => {
|
|
1159
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8',
|
|
1160
|
+
'X-Content-Type-Options': 'nosniff' });
|
|
1161
|
+
res.write(JSON.stringify({ code, message }));
|
|
1162
|
+
res.end();
|
|
1163
|
+
};
|
|
1164
|
+
if (!context) {
|
|
1165
|
+
writeDefault();
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
reportError(res, Object.assign({ code, message, detail: detail || undefined }, context), writeDefault);
|
|
1169
|
+
};
|
|
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);
|
|
1182
|
+
};
|
|
384
1183
|
this.server = proto.createServer(srvOpts, requestCb);
|
|
385
1184
|
if (this.upgradeCallback) {
|
|
386
1185
|
this.server.on('upgrade', upgradeCb);
|
|
@@ -396,21 +1195,105 @@ var ApiSrv = function(opts) {
|
|
|
396
1195
|
this.server.headersTimeout = this.bodyReadTimeoutMs;
|
|
397
1196
|
this.server.requestTimeout = this.bodyReadTimeoutMs + 1;
|
|
398
1197
|
this.server.listen(this.port, this.address);
|
|
399
|
-
}
|
|
1198
|
+
}
|
|
400
1199
|
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
1200
|
+
requestHandleAdd(method, path, handler, options) {
|
|
1201
|
+
const normalizedMethod = normalizeMethod(method);
|
|
1202
|
+
if (typeof handler !== 'function') {
|
|
1203
|
+
throw new Error(`Bad request handler callback for ${normalizedMethod} ${path}`);
|
|
1204
|
+
}
|
|
1205
|
+
const normalizedOptions = normalizeHandlerOptions(normalizedMethod, path, options);
|
|
1206
|
+
const compiled = compilePathTemplate(path);
|
|
1207
|
+
compiled.handler = handler;
|
|
1208
|
+
compiled.options = normalizedOptions;
|
|
1209
|
+
const store = getMethodStore(this._requestHandlers, normalizedMethod, true);
|
|
1210
|
+
if (compiled.isExact) {
|
|
1211
|
+
store.exact.set(compiled.template, compiled);
|
|
1212
|
+
} else {
|
|
1213
|
+
store.dynamic.set(compiled.template, compiled);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
requestHandleDelete(method, path) {
|
|
1218
|
+
if (typeof path !== 'string' || !path.startsWith('/')) {
|
|
1219
|
+
throw new Error(`Bad request handler path: ${path}`);
|
|
1220
|
+
}
|
|
1221
|
+
if (method === '*') {
|
|
1222
|
+
let removed = false;
|
|
1223
|
+
for (const [key, store] of this._requestHandlers.entries()) {
|
|
1224
|
+
removed = removeFromStore(store, path) || removed;
|
|
1225
|
+
if ((store.exact.size === 0) && (store.dynamic.size === 0)) {
|
|
1226
|
+
this._requestHandlers.delete(key);
|
|
1227
|
+
}
|
|
408
1228
|
}
|
|
1229
|
+
return removed;
|
|
1230
|
+
}
|
|
1231
|
+
const normalizedMethod = normalizeMethod(method);
|
|
1232
|
+
const store = this._requestHandlers.get(normalizedMethod);
|
|
1233
|
+
if (!store) {
|
|
1234
|
+
return false;
|
|
1235
|
+
}
|
|
1236
|
+
const removed = removeFromStore(store, path);
|
|
1237
|
+
if ((store.exact.size === 0) && (store.dynamic.size === 0)) {
|
|
1238
|
+
this._requestHandlers.delete(normalizedMethod);
|
|
1239
|
+
}
|
|
1240
|
+
return removed;
|
|
1241
|
+
}
|
|
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
|
+
|
|
1259
|
+
#matchRequestHandler(method, path) {
|
|
1260
|
+
const store = this._requestHandlers.get(method.toUpperCase());
|
|
1261
|
+
if (!store) {
|
|
1262
|
+
return null;
|
|
1263
|
+
}
|
|
1264
|
+
return findMatchInStore(store, path);
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
#hasHandlerForOtherMethod(method, path) {
|
|
1268
|
+
const normalizedMethod = typeof method === 'string' ? method.toUpperCase() : method;
|
|
1269
|
+
for (const [key, store] of this._requestHandlers.entries()) {
|
|
1270
|
+
if (key === normalizedMethod) {
|
|
1271
|
+
continue;
|
|
1272
|
+
}
|
|
1273
|
+
if (findMatchInStore(store, path)) {
|
|
1274
|
+
return true;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
return false;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
close() {
|
|
1281
|
+
return new Promise((resolve, reject) => {
|
|
1282
|
+
this.server.close((err) => {
|
|
1283
|
+
if (err) {
|
|
1284
|
+
reject(err);
|
|
1285
|
+
} else {
|
|
1286
|
+
resolve();
|
|
1287
|
+
}
|
|
1288
|
+
});
|
|
409
1289
|
});
|
|
410
|
-
}
|
|
411
|
-
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
// Backward compatible shutdown helper
|
|
1293
|
+
shutdown() {
|
|
1294
|
+
return this.close();
|
|
1295
|
+
}
|
|
412
1296
|
|
|
413
|
-
|
|
414
|
-
ApiSrv.prototype.shutdown = ApiSrv.prototype.close;
|
|
1297
|
+
}
|
|
415
1298
|
|
|
416
1299
|
module.exports = ApiSrv;
|