1 /* eslint-disable security/detect-object-injection */
5 * A very minimal API server framework.
6 * Just a self-contained router and some request glue.
10 const { promises: fsPromises
} = require('fs');
11 const path
= require('path');
12 const querystring
= require('querystring');
13 const common
= require('./common');
14 const ContentNegotiation
= require('./content-negotiation');
15 const Enum
= require('./enum');
16 const { DingusError
, ResponseError
} = require('./errors');
17 const { extensionToMime
} = require('./mime-helper');
18 const Router
= require('./router');
19 const Template
= require('./template');
22 const _fileScope
= common
.fileScope(__filename
);
24 const defaultOptions
= {
25 ignoreTrailingSlash: false,
30 staticPath: undefined, // no reasonable default
37 * @param {Object} logger object which implements logging methods
38 * @param {Object} options
39 * @param {Boolean} options.ignoreTrailingSlash
40 * @param {string} options.proxyPrefix leading part of url path to strip
41 * @param {Boolean} options.strictAccept whether to error on unsupported Accept type
42 * @param {string} options.selfBaseUrl for constructing links
43 * @param {Boolean} options.staticMetadata serve static headers with static files
44 * @param {Boolean} options.trustProxy trust some header data to be provided by proxy
45 * @param {Object} options.querystring alternate qs parser to use
47 constructor(logger
= common
.nullLogger
, options
= {}) {
48 common
.setOptions(this, defaultOptions
, options
);
50 this.router
= new Router(options
);
52 if (!this.proxyPrefix
) {
53 this._stripPrefix
= (p
) => p
;
56 this.responseTypes
= [
57 Enum
.ContentType
.TextHTML
,
58 Enum
.ContentType
.TextPlain
,
59 Enum
.ContentType
.ApplicationJson
,
63 common
.ensureLoggerLevels(this.logger
);
68 * Resolve relative and empty paths in url
69 * @param {string} p path
72 const pathNorm
= path
.normalize(p
); // This isn't perfectly correct, but it's easy...
73 return this._stripPrefix(pathNorm
);
78 * Remove a leading portion of url path
79 * N.B. This method gets obliterated if there is no prefix defined at construction
80 * @param {string} p path
83 if (p
.startsWith(this.proxyPrefix
)) {
84 return p
.slice(this.proxyPrefix
.length
);
91 * Returns the path part, and querystring object, from a request url.
95 const [ p
, qs
] = common
.splitFirst(url
, '?');
97 pathPart: this._normalizePath(p
),
98 queryParams: this.querystring
.parse(qs
),
104 * Insert a new path handler
105 * @param {string} method
106 * @param {string} urlPath
107 * @param {fn} handler
109 on(method
, urlPath
, handler
, ...handlerArgs
) {
110 this.router
.on(method
, urlPath
, handler
, handlerArgs
);
115 * Common header tagging for all requests.
116 * Add our own identifier, and persist any external transit identifiers.
117 * @param {http.ClientRequest} req
118 * @param {http.ServerResponse} res
119 * @param {object} ctx
121 static tagContext(req
, res
, ctx
) {
122 const requestId
= common
.requestId();
123 ctx
.requestId
= requestId
;
124 res
.setHeader(Enum
.Header
.RequestId
, requestId
);
125 [Enum
.Header
.XRequestId
, Enum
.Header
.XCorrelationId
].forEach((h
) => {
126 const v
= req
.getHeader(h
);
128 ctx
[h
.replace(/-/g
, '')] = v
;
138 * @param {http.ClientRequest} req
141 // TODO: RFC7239 Forwarded support
142 const address
= (this.trustProxy
&& req
&& req
.getHeader(Enum
.Header
.XForwardedFor
)) ||
143 (this.trustProxy
&& req
&& req
.getHeader(Enum
.Header
.XRealIP
)) ||
144 (req
&& req
.connection
&& req
.connection
.remoteAddress
) ||
146 return address
.split(/\s*,\s*/u)[0];
152 * @param {http.ClientRequest} req
155 // TODO: RFC7239 Forwarded support
156 const protocol
= (this.trustProxy
&& req
&& req
.getHeader(Enum
.Header
.XForwardedProto
)) ||
157 ((req
&& req
.connection
&& req
.connection
.encrypted
) ? 'https' : 'http');
158 return protocol
.split(/\s*,\s*/u)[0];
164 * @param {http.ClientRequest} req
165 * @param {http.ServerResponse} res
166 * @param {object} ctx
168 clientAddressContext(req
, res
, ctx
) {
169 ctx
.clientAddress
= this._getAddress(req
);
170 ctx
.clientProtocol
= this._getProtocol(req
);
175 * Called before every request handler.
176 * @param {http.ClientRequest} req
177 * @param {http.ServerResponse} res
178 * @param {object} ctx
180 async
preHandler(req
, res
, ctx
) {
181 Dingus
.tagContext(req
, res
, ctx
);
182 this.clientAddressContext(req
, res
, ctx
);
187 * Helper for collecting chunks as array of buffers.
188 * @param {Buffer[]} chunks
189 * @param {string|Buffer} chunk
190 * @param {string} encoding
192 static pushBufChunk(chunks
, chunk
, encoding
= 'utf8') {
194 if (typeof chunk
=== 'string') {
195 chunk
= Buffer
.from(chunk
, encoding
);
203 * Sets ctx.responseBody and calls handler upon res.end().
204 * @param {http.ClientRequest} req
205 * @param {http.ServerResponse} res
206 * @param {object} ctx
207 * @param {*} handler fn(req, res, ctx)
209 static setEndBodyHandler(req
, res
, ctx
, handler
) {
210 const origWrite
= res
.write
.bind(res
);
211 const origEnd
= res
.end
.bind(res
);
213 res
.write = function (chunk
, encoding
, ...rest
) {
214 Dingus
.pushBufChunk(chunks
, chunk
, encoding
);
215 return origWrite(chunk
, encoding
, ...rest
);
217 res
.end = function (data
, encoding
, ...rest
) {
218 Dingus
.pushBufChunk(chunks
, data
, encoding
);
219 ctx
.responseBody
= Buffer
.concat(chunks
);
220 handler(req
, res
, ctx
);
221 return origEnd(data
, encoding
, ...rest
);
227 * Intercept writes for head requests, do not send to client,
228 * but send length, and make body available in context.
229 * N.B. If persisted, ctx.responseBody will be a raw buffer, be aware when logging.
230 * @param {http.ClientRequest} req
231 * @param {http.ServerResponse} res
232 * @param {object} ctx
233 * @param {Boolean} persistResponseBody
235 static setHeadHandler(req
, res
, ctx
, persistResponseBody
= false) {
236 if (req
.method
=== 'HEAD') {
237 const origEnd
= res
.end
.bind(res
);
239 res
.write = function (chunk
, encoding
) {
240 Dingus
.pushBufChunk(chunks
, chunk
, encoding
);
241 // No call to original res.write.
243 res
.end = function (data
, encoding
, ...rest
) {
244 Dingus
.pushBufChunk(chunks
, data
, encoding
);
245 const responseBody
= Buffer
.concat(chunks
);
246 res
.setHeader(Enum
.Header
.ContentLength
, Buffer
.byteLength(responseBody
));
247 if (persistResponseBody
) {
248 ctx
.responseBody
= responseBody
;
250 return origEnd(undefined, encoding
, ...rest
);
257 * Dispatch the handler for a request
258 * @param {http.ClientRequest} req
259 * @param {http.ServerResponse} res
260 * @param {object} ctx
262 async
dispatch(req
, res
, ctx
= {}) {
263 const _scope
= _fileScope('dispatch');
265 const { pathPart
, queryParams
} = this._splitUrl(req
.url
);
266 ctx
.queryParams
= queryParams
;
268 let handler
, handlerArgs
= [];
270 ({ handler
, handlerArgs
} = this.router
.lookup(req
.method
, pathPart
, ctx
));
272 if (e
instanceof DingusError
) {
275 handler
= this.handlerNotFound
.bind(this);
278 handler
= this.handlerMethodNotAllowed
.bind(this);
281 this.logger
.error(_scope
, 'unknown dingus error', { error: e
});
282 handler
= this.handlerInternalServerError
.bind(this);
284 } else if (e
instanceof URIError
) {
285 handler
= this.handlerBadRequest
.bind(this);
287 this.logger
.error(_scope
, 'lookup failure', { error: e
});
288 handler
= this.handlerInternalServerError
.bind(this);
293 await
this.preHandler(req
, res
, ctx
);
294 return await
handler(req
, res
, ctx
, ...handlerArgs
);
297 this.sendErrorResponse(e
, req
, res
, ctx
);
303 * Return normalized type, without any parameters.
304 * @param {http.ClientRequest} req
307 static getRequestContentType(req
) {
308 const contentType
= req
.getHeader(Enum
.Header
.ContentType
);
309 return (contentType
|| '').split(';')[0].trim().toLowerCase();
314 * Parse rawBody as contentType into ctx.parsedBody.
315 * @param {string} contentType
316 * @param {object} ctx
317 * @param {string|buffer}
319 parseBody(contentType
, ctx
, rawBody
) {
320 const _scope
= _fileScope('parseBody');
323 // 1.2.4 and earlier expected rawBody on context
324 rawBody
= ctx
.rawBody
;
327 switch (contentType
) {
328 case Enum
.ContentType
.ApplicationForm:
329 ctx
.parsedBody
= this.querystring
.parse(rawBody
);
332 case Enum
.ContentType
.ApplicationJson:
334 ctx
.parsedBody
= JSON
.parse(rawBody
);
336 this.logger
.debug(_scope
, 'JSON parse failed', { requestId: ctx
.requestId
, error: e
});
337 throw new ResponseError(Enum
.ErrorResponse
.BadRequest
, e
.message
);
342 this.logger
.debug(_scope
, 'unhandled content-type', { requestId: ctx
.requestId
, contentType
});
343 throw new ResponseError(Enum
.ErrorResponse
.UnsupportedMediaType
);
349 * Return all body data from a request.
350 * @param {http.ClientRequest} req
351 * @param {Number=} maximumBodySize
353 async
bodyData(req
, maximumBodySize
) {
354 const _scope
= _fileScope('bodyData');
355 return new Promise((resolve
, reject
) => {
358 req
.on('data', (chunk
) => {
360 length
+= Buffer
.byteLength(chunk
);
361 if (maximumBodySize
&& length
> maximumBodySize
) {
362 this.logger
.debug(_scope
, 'body data exceeded limit', { length
, maximumBodySize
});
363 reject(new ResponseError(Enum
.ErrorResponse
.RequestEntityTooLarge
));
366 req
.on('end', () => resolve(Buffer
.concat(body
).toString()));
367 req
.on('error', (e
) => {
368 this.logger
.error(_scope
, 'failed', { error: e
});
376 * Read and parse request body data.
377 * @param {http.ClientRequest} req
378 * @param {http.ServerResponse} res
379 * @param {object} ctx
381 * @param {Boolean} .parseEmptyBody
382 * @param {Boolean} .persistRawBody
384 async
ingestBody(req
, res
, ctx
, { parseEmptyBody
= true, persistRawBody
= false, maximumBodySize
} = {}) {
385 const rawBody
= await
this.bodyData(req
, maximumBodySize
);
386 if (persistRawBody
) {
387 ctx
.rawBody
= rawBody
;
389 if (rawBody
|| parseEmptyBody
) {
390 const contentType
= Dingus
.getRequestContentType(req
);
391 this.parseBody(contentType
, ctx
, rawBody
);
397 * Return the best matching response type.
398 * @param {string[]} responseTypes
399 * @param {http.ClientRequest} req
401 static getResponseContentType(responseTypes
, req
) {
402 const acceptHeader
= req
.getHeader(Enum
.Header
.Accept
);
403 return ContentNegotiation
.accept(responseTypes
, acceptHeader
);
408 * Returns a list of the most-preferred content encodings for the response.
409 * @param {string[]} responseEncodings
410 * @param {http.ClientRequest} req
412 static getResponseEncoding(responseEncodings
, req
) {
413 const acceptEncodingHeader
= req
.getHeader(Enum
.Header
.AcceptEncoding
);
414 return ContentNegotiation
.preferred(responseEncodings
, acceptEncodingHeader
);
419 * Set the best content type for the response.
420 * @param {string[]} responseTypes default first
421 * @param {http.ClientRequest} req
422 * @param {http.ServerResponse} res
423 * @param {object} ctx
425 setResponseType(responseTypes
, req
, res
, ctx
) {
426 const _scope
= _fileScope('setResponseType');
427 ctx
.responseType
= Dingus
.getResponseContentType(responseTypes
, req
);
428 if (!ctx
.responseType
) {
429 if (this.strictAccept
) {
430 this.logger
.debug(_scope
, 'unhandled strict accept', { requestId: req
.requestId
});
431 throw new ResponseError(Enum
.ErrorResponse
.NotAcceptable
);
433 ctx
.responseType
= responseTypes
[0];
436 res
.setHeader(Enum
.Header
.ContentType
, ctx
.responseType
);
441 * Inserts an encoding
442 * @param {http.ServerResponse} res
443 * @param {string} encoding
445 static addEncodingHeader(res
, encoding
) {
446 const existingEncodings
= res
.getHeader(Enum
.Header
.ContentEncoding
);
447 if (existingEncodings
) {
448 encoding
= `${encoding}, ${existingEncodings}`;
450 res
.setHeader(Enum
.Header
.ContentEncoding
, encoding
);
455 * Attempt to fetch both data and metadata for a file.
456 * @param {string} filePath
458 async
_readFileInfo(filePath
) {
459 const _scope
= _fileScope('_readFileInfo');
462 // eslint-disable-next-line security/detect-non-literal-fs-filename
463 const stat
= fsPromises
.stat(filePath
);
464 // eslint-disable-next-line security/detect-non-literal-fs-filename
465 const data
= fsPromises
.readFile(filePath
);
466 result
= await Promise
.all([stat
, data
]);
468 if (['ENOENT', 'EACCES', 'EISDIR', 'ENAMETOOLONG', 'EINVAL'].includes(e
.code
)) {
471 this.logger
.error(_scope
, 'fs error', { error: e
, filePath
});
479 * Potentially add additional headers from static file meta-file.
480 * @param {http.ServerResponse} res
481 * @param {string} directory
482 * @param {string} fileName - already normalized and filtered
484 async
_serveFileMetaHeaders(res
, directory
, fileName
) {
485 const _scope
= _fileScope('_serveFileMetaHeaders');
486 this.logger
.debug(_scope
, 'called', { directory
, fileName
});
488 const metaPrefix
= '.';
489 const metaSuffix
= '.meta';
490 const metaFileName
= `${metaPrefix}${fileName}${metaSuffix}`;
491 const metaFilePath
= path
.join(directory
, metaFileName
);
493 const [stat
, data
] = await
this._readFileInfo(metaFilePath
);
498 const lineBreakRE
= /\r\n|\n|\r/;
499 const lines
= data
.toString().split(lineBreakRE
);
500 common
.unfoldHeaderLines(lines
);
502 const headerParseRE
= /^(?<name
>[^:]+): +(?<value
>.*)$/;
503 lines
.forEach((line
) => {
505 const result
= headerParseRE
.exec(line
);
506 const { groups: header
} = result
;
507 res
.setHeader(header
.name
, header
.value
);
514 * Serve a file from a directory, with rudimentary cache awareness.
515 * This will also serve pre-encoded variations if available and requested.
516 * @param {http.ClientRequest} req
517 * @param {http.ServerResponse} res
518 * @param {object} ctx
519 * @param {string} directory
520 * @param {string} fileName
522 async
serveFile(req
, res
, ctx
, directory
, fileName
) {
523 const _scope
= _fileScope('serveFile');
524 this.logger
.debug(_scope
, 'called', { req: common
.requestLogData(req
), ctx
});
526 // Require a directory field.
528 this.logger
.debug(_scope
, 'rejected unset directory', { fileName
});
529 return this.handlerNotFound(req
, res
, ctx
);
532 // Normalize the supplied path, as encoded path-navigation may have been (maliciously) present.
533 fileName
= path
.normalize(fileName
);
535 // We will not deal with any subdirs, nor any dot-files.
536 // (Note that we could not deal with subdirs even if we wanted, due to simple router matching scheme.)
537 if (fileName
.indexOf(path
.sep
) >= 0
538 || fileName
.charAt(0) === '.') {
539 this.logger
.debug(_scope
, 'rejected filename', { fileName
});
540 return this.handlerNotFound(req
, res
, ctx
);
543 const filePath
= path
.join(directory
, fileName
);
545 // File must exist, before any alternate static encodings will be considered.
546 let [stat
, data
] = await
this._readFileInfo(filePath
);
548 return this.handlerNotFound(req
, res
, ctx
);
551 // If encodings were requested, check for static versions to serve.
552 // Update stat and data if matching version is found.
553 ctx
.availableEncodings
= Dingus
.getResponseEncoding(Object
.values(Enum
.EncodingType
), req
);
554 if (ctx
.availableEncodings
.length
=== 0) {
555 // Identity encoding was specifically denied, and nothing else available.
556 this.logger
.debug(_scope
, 'no suitable encodings', { ctx
});
557 return this.handlerMethodNotAllowed(req
, res
, ctx
);
559 for (const encoding
of ctx
.availableEncodings
) {
560 if (encoding
=== Enum
.EncodingType
.Identity
) {
563 const suffix
= Enum
.EncodingTypeSuffix
[encoding
];
565 const encodedFilePath
= `${filePath}${suffix}`;
566 const [ encodedStat
, encodedData
] = await
this._readFileInfo(encodedFilePath
);
568 ([ stat
, data
] = [ encodedStat
, encodedData
]);
569 ctx
.selectedEncoding
= encoding
;
570 Dingus
.addEncodingHeader(res
, encoding
);
571 res
.setHeader(Enum
.Header
.Vary
, Enum
.Header
.AcceptEncoding
);
572 this.logger
.debug(_scope
, 'serving encoded version', { ctx
, encodedFilePath
});
578 const lastModifiedDate
= new Date(stat
.mtimeMs
);
579 res
.setHeader(Enum
.Header
.LastModified
, lastModifiedDate
.toGMTString());
581 const eTag
= common
.generateETag(filePath
, stat
, data
);
582 res
.setHeader(Enum
.Header
.ETag
, eTag
);
584 if (common
.isClientCached(req
, stat
.mtimeMs
, eTag
)) {
585 this.logger
.debug(_scope
, 'client cached file', { filePath
});
586 res
.statusCode
= 304; // Not Modified
591 // Set the type based on extension of un-encoded filename.
592 const ext
= path
.extname(filePath
).slice(1); // Drop the dot
593 const contentType
= extensionToMime(ext
);
594 res
.setHeader(Enum
.Header
.ContentType
, contentType
);
596 // We presume static files are relatively cacheable.
597 res
.setHeader(Enum
.Header
.CacheControl
, 'public');
599 if (this.staticMetadata
) {
600 await
this._serveFileMetaHeaders(res
, directory
, fileName
);
603 this.logger
.debug(_scope
, 'serving file', { filePath
, contentType
});
609 * Return a content-type appropriate rendering of an errorResponse object.
610 * @param {string} type content-type of response
611 * @param {object} err either an Error object, or an error response
612 * @param {number} err.statusCode
613 * @param {string} err.errorMessage
614 * @param {string|string[]} err.details
616 // eslint-disable-next-line class-methods-use-this
617 renderError(contentType
, err
) {
618 switch (contentType
) {
619 case Enum
.ContentType
.ApplicationJson:
620 return JSON
.stringify(err
);
622 case Enum
.ContentType
.TextHTML:
623 return Template
.errorHTML(err
);
625 case Enum
.ContentType
.TextPlain:
627 return [err
.errorMessage
, err
.details
].join('\r\n');
633 * Send an error response. Terminal.
634 * Logs any non-error-response errors as such.
635 * @param {object} err either an Error object, or an error response
636 * @param {http.ClientRequest} req
637 * @param {http.ServerResponse} res
638 * @param {object} ctx
640 sendErrorResponse(err
, req
, res
, ctx
) {
641 const _scope
= _fileScope('sendErrorResponse');
644 // Default to a content type if one is not yet present
645 if (!res
.hasHeader(Enum
.Header
.ContentType
)) {
646 res
.setHeader(Enum
.Header
.ContentType
, Enum
.ContentType
.TextPlain
);
649 if (err
&& err
.statusCode
) {
650 res
.statusCode
= err
.statusCode
;
651 body
= this.renderError(res
.getHeader(Enum
.Header
.ContentType
), err
);
652 this.logger
.debug(_scope
, 'handler error', { err
, ...common
.handlerLogData(req
, res
, ctx
) });
654 res
.statusCode
= 500;
655 body
= this.renderError(res
.getHeader(Enum
.Header
.ContentType
), Enum
.ErrorResponse
.InternalServerError
);
656 this.logger
.error(_scope
, 'handler exception', { err
, ...common
.handlerLogData(req
, res
, ctx
) });
663 * @param {http.ClientRequest} req
664 * @param {http.ServerResponse} res
665 * @param {object} ctx
666 * @param {String} file - override ctx.params.file
668 async
handlerGetStaticFile(req
, res
, ctx
, file
) {
669 Dingus
.setHeadHandler(req
, res
, ctx
);
671 // Set a default response type to handle any errors; will be re-set to serve actual static content type.
672 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
674 await
this.serveFile(req
, res
, ctx
, this.staticPath
, file
|| ctx
.params
.file
);
679 * @param {http.ClientRequest} req
680 * @param {http.ServerResponse} res
681 * @param {Object} ctx
682 * @param {String} newPath
683 * @param {Number} statusCode
685 async
handlerRedirect(req
, res
, ctx
, newPath
, statusCode
= 307) {
686 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
687 res
.setHeader(Enum
.Header
.Location
, newPath
);
688 res
.statusCode
= statusCode
;
694 * @param {http.ClientRequest} req
695 * @param {http.ServerResponse} res
696 * @param {object} ctx
698 async
handlerMethodNotAllowed(req
, res
, ctx
) {
699 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
700 throw new ResponseError(Enum
.ErrorResponse
.MethodNotAllowed
);
705 * @param {http.ClientRequest} req
706 * @param {http.ServerResponse} res
707 * @param {object} ctx
709 async
handlerNotFound(req
, res
, ctx
) {
710 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
711 throw new ResponseError(Enum
.ErrorResponse
.NotFound
);
716 * @param {http.ClientRequest} req
717 * @param {http.ServerResponse} res
718 * @param {object} ctx
720 async
handlerBadRequest(req
, res
, ctx
) {
721 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
722 throw new ResponseError(Enum
.ErrorResponse
.BadRequest
);
727 * @param {http.ClientRequest} req
728 * @param {http.ServerResponse} res
729 * @param {object} ctx
731 async
handlerInternalServerError(req
, res
, ctx
) {
732 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
733 throw new ResponseError(Enum
.ErrorResponse
.InternalServerError
);
738 module
.exports
= Dingus
;