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
, RouterNoMethodError
, RouterNoPathError
} = 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
= console
, 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
,
67 * Resolve relative and empty paths in url
68 * @param {string} p path
71 const pathNorm
= path
.normalize(p
); // This isn't perfectly correct, but it's easy...
72 return this._stripPrefix(pathNorm
);
77 * Remove a leading portion of url path
78 * N.B. This method gets obliterated if there is no prefix defined at construction
79 * @param {string} p path
82 if (p
.startsWith(this.proxyPrefix
)) {
83 return p
.slice(this.proxyPrefix
.length
);
90 * Returns the path part, and querystring object, from a request url.
94 const [ p
, qs
] = common
.splitFirst(url
, '?');
96 pathPart: this._normalizePath(p
),
97 queryParams: this.querystring
.parse(qs
),
103 * Insert a new path handler
104 * @param {string} method
105 * @param {string} urlPath
106 * @param {fn} handler
108 on(method
, urlPath
, handler
, ...handlerArgs
) {
109 this.router
.on(method
, urlPath
, handler
, handlerArgs
);
114 * Common header tagging for all requests.
115 * Add our own identifier, and persist any external transit identifiers.
116 * @param {http.ClientRequest} req
117 * @param {http.ServerResponse} res
118 * @param {object} ctx
120 static tagContext(req
, res
, ctx
) {
121 const requestId
= common
.requestId();
122 ctx
.requestId
= requestId
;
123 res
.setHeader(Enum
.Header
.RequestId
, requestId
);
124 [Enum
.Header
.XRequestId
, Enum
.Header
.XCorrelationId
].forEach((h
) => {
125 const v
= req
.getHeader(h
);
127 ctx
[h
.replace(/-/g
, '')] = v
;
137 * @param {http.ClientRequest} req
140 // TODO: RFC7239 Forwarded support
141 const address
= (this.trustProxy
&& req
?.getHeader(Enum
.Header
.XForwardedFor
)) ||
142 (this.trustProxy
&& req
?.getHeader(Enum
.Header
.XRealIP
)) ||
143 (req
?.connection
?.remoteAddress
) ||
145 return address
.split(/\s*,\s*/u)[0];
151 * @param {http.ClientRequest} req
154 // TODO: RFC7239 Forwarded support
155 const protocol
= (this.trustProxy
&& req
?.getHeader(Enum
.Header
.XForwardedProto
)) ||
156 ((req
?.connection
?.encrypted
) ? 'https' : 'http');
157 return protocol
.split(/\s*,\s*/u)[0];
163 * @param {http.ClientRequest} req
164 * @param {http.ServerResponse} res
165 * @param {object} ctx
167 clientAddressContext(req
, res
, ctx
) {
168 ctx
.clientAddress
= this._getAddress(req
);
169 ctx
.clientProtocol
= this._getProtocol(req
);
174 * Called before every request handler.
175 * @param {http.ClientRequest} req
176 * @param {http.ServerResponse} res
177 * @param {object} ctx
179 async
preHandler(req
, res
, ctx
) {
180 Dingus
.tagContext(req
, res
, ctx
);
181 this.clientAddressContext(req
, res
, ctx
);
186 * Helper for collecting chunks as array of buffers.
187 * @param {Buffer[]} chunks
188 * @param {string|Buffer} chunk
189 * @param {string} encoding
191 static pushBufChunk(chunks
, chunk
, encoding
= 'utf8') {
193 if (typeof chunk
=== 'string') {
194 chunk
= Buffer
.from(chunk
, encoding
);
202 * Sets ctx.responseBody and calls handler upon res.end().
203 * @param {http.ClientRequest} req
204 * @param {http.ServerResponse} res
205 * @param {object} ctx
206 * @param {*} handler fn(req, res, ctx)
208 static setEndBodyHandler(req
, res
, ctx
, handler
) {
209 const origWrite
= res
.write
.bind(res
);
210 const origEnd
= res
.end
.bind(res
);
212 res
.write = function (chunk
, encoding
, ...rest
) {
213 Dingus
.pushBufChunk(chunks
, chunk
, encoding
);
214 return origWrite(chunk
, encoding
, ...rest
);
216 res
.end = function (data
, encoding
, ...rest
) {
217 Dingus
.pushBufChunk(chunks
, data
, encoding
);
218 ctx
.responseBody
= Buffer
.concat(chunks
);
219 handler(req
, res
, ctx
);
220 return origEnd(data
, encoding
, ...rest
);
226 * Intercept writes for head requests, do not send to client,
227 * but send length, and make body available in context.
228 * N.B. If persisted, ctx.responseBody will be a raw buffer, be aware when logging.
229 * @param {http.ClientRequest} req
230 * @param {http.ServerResponse} res
231 * @param {object} ctx
232 * @param {Boolean} persistResponseBody
234 static setHeadHandler(req
, res
, ctx
, persistResponseBody
= false) {
235 if (req
.method
=== 'HEAD') {
236 const origEnd
= res
.end
.bind(res
);
238 res
.write = function (chunk
, encoding
) {
239 Dingus
.pushBufChunk(chunks
, chunk
, encoding
);
240 // No call to original res.write.
242 res
.end = function (data
, encoding
, ...rest
) {
243 Dingus
.pushBufChunk(chunks
, data
, encoding
);
244 const responseBody
= Buffer
.concat(chunks
);
245 res
.setHeader(Enum
.Header
.ContentLength
, Buffer
.byteLength(responseBody
));
246 if (persistResponseBody
) {
247 ctx
.responseBody
= responseBody
;
249 return origEnd(undefined, encoding
, ...rest
);
256 * Dispatch the handler for a request
257 * @param {http.ClientRequest} req
258 * @param {http.ServerResponse} res
259 * @param {object} ctx
261 async
dispatch(req
, res
, ctx
= {}) {
262 const _scope
= _fileScope('dispatch');
264 const { pathPart
, queryParams
} = this._splitUrl(req
.url
);
265 ctx
.queryParams
= queryParams
;
267 let handler
, handlerArgs
= [];
269 ({ handler
, handlerArgs
} = this.router
.lookup(req
.method
, pathPart
, ctx
));
271 if (e
instanceof RouterNoPathError
) {
272 handler
= this.handlerNotFound
.bind(this);
273 } else if (e
instanceof RouterNoMethodError
) {
274 handler
= this.handlerMethodNotAllowed
.bind(this);
275 } else if (e
instanceof DingusError
) {
276 this.logger
.error(_scope
, 'unknown dingus error', { error: e
});
277 handler
= this.handlerInternalServerError
.bind(this);
278 } else if (e
instanceof URIError
) {
279 handler
= this.handlerBadRequest
.bind(this);
281 this.logger
.error(_scope
, 'lookup failure', { error: e
});
282 handler
= this.handlerInternalServerError
.bind(this);
287 await
this.preHandler(req
, res
, ctx
);
288 return await
handler(req
, res
, ctx
, ...handlerArgs
);
291 this.sendErrorResponse(e
, req
, res
, ctx
);
297 * Return normalized type, without any parameters.
298 * @param {http.ClientRequest} req
301 static getRequestContentType(req
) {
302 const contentType
= req
.getHeader(Enum
.Header
.ContentType
);
303 return (contentType
|| '').split(';')[0].trim().toLowerCase();
308 * Parse rawBody as contentType into ctx.parsedBody.
309 * @param {string} contentType
310 * @param {object} ctx
311 * @param {string|buffer} rawBody
313 parseBody(contentType
, ctx
, rawBody
) {
314 const _scope
= _fileScope('parseBody');
316 switch (contentType
) {
317 case Enum
.ContentType
.ApplicationForm:
318 ctx
.parsedBody
= this.querystring
.parse(rawBody
);
321 case Enum
.ContentType
.ApplicationJson:
323 ctx
.parsedBody
= JSON
.parse(rawBody
);
325 this.logger
.debug(_scope
, 'JSON parse failed', { requestId: ctx
.requestId
, error: e
});
326 throw new ResponseError(Enum
.ErrorResponse
.BadRequest
, e
.message
);
331 this.logger
.debug(_scope
, 'unhandled content-type', { requestId: ctx
.requestId
, contentType
});
332 throw new ResponseError(Enum
.ErrorResponse
.UnsupportedMediaType
);
338 * Return all body data from a request.
339 * @param {http.ClientRequest} req
340 * @param {Number=} maximumBodySize
341 * @param {Boolean=} toString
343 async
bodyData(req
, maximumBodySize
, toString
= true) {
344 const _scope
= _fileScope('bodyData');
345 return new Promise((resolve
, reject
) => {
348 req
.on('data', (chunk
) => {
350 length
+= Buffer
.byteLength(chunk
);
351 if (maximumBodySize
&& length
> maximumBodySize
) {
352 this.logger
.debug(_scope
, 'body data exceeded limit', { length
, maximumBodySize
});
353 reject(new ResponseError(Enum
.ErrorResponse
.RequestEntityTooLarge
));
356 req
.on('end', () => {
357 const bodyBuffer
= Buffer
.concat(body
);
358 resolve(toString
? bodyBuffer
.toString() : bodyBuffer
);
360 req
.on('error', (e
) => {
361 this.logger
.error(_scope
, 'failed', { error: e
});
369 * Read and parse request body data.
370 * @param {http.ClientRequest} req
371 * @param {http.ServerResponse} res
372 * @param {object} ctx
374 * @param {Boolean} .parseEmptyBody
375 * @param {Boolean} .persistRawBody
377 async
ingestBody(req
, res
, ctx
, { parseEmptyBody
= true, persistRawBody
= false, maximumBodySize
} = {}) {
378 const rawBody
= await
this.bodyData(req
, maximumBodySize
);
379 if (persistRawBody
) {
380 ctx
.rawBody
= rawBody
;
382 if (rawBody
|| parseEmptyBody
) {
383 const contentType
= Dingus
.getRequestContentType(req
);
384 this.parseBody(contentType
, ctx
, rawBody
);
390 * Return the best matching response type.
391 * @param {string[]} responseTypes
392 * @param {http.ClientRequest} req
394 static getResponseContentType(responseTypes
, req
) {
395 const acceptHeader
= req
.getHeader(Enum
.Header
.Accept
);
396 return ContentNegotiation
.accept(responseTypes
, acceptHeader
);
401 * Returns a list of the most-preferred content encodings for the response.
402 * @param {string[]} responseEncodings
403 * @param {http.ClientRequest} req
405 static getResponseEncoding(responseEncodings
, req
) {
406 const acceptEncodingHeader
= req
.getHeader(Enum
.Header
.AcceptEncoding
);
407 return ContentNegotiation
.preferred(responseEncodings
, acceptEncodingHeader
);
412 * Set the best content type for the response.
413 * @param {string[]} responseTypes default first
414 * @param {http.ClientRequest} req
415 * @param {http.ServerResponse} res
416 * @param {object} ctx
418 setResponseType(responseTypes
, req
, res
, ctx
) {
419 const _scope
= _fileScope('setResponseType');
420 ctx
.responseType
= Dingus
.getResponseContentType(responseTypes
, req
);
421 if (!ctx
.responseType
) {
422 if (this.strictAccept
) {
423 this.logger
.debug(_scope
, 'unhandled strict accept', { requestId: req
.requestId
});
424 throw new ResponseError(Enum
.ErrorResponse
.NotAcceptable
);
426 ctx
.responseType
= responseTypes
[0];
429 res
.setHeader(Enum
.Header
.ContentType
, ctx
.responseType
);
434 * Inserts an encoding
435 * @param {http.ServerResponse} res
436 * @param {string} encoding
438 static addEncodingHeader(res
, encoding
) {
439 const existingEncodings
= res
.getHeader(Enum
.Header
.ContentEncoding
);
440 if (existingEncodings
) {
441 encoding
= `${encoding}, ${existingEncodings}`;
443 res
.setHeader(Enum
.Header
.ContentEncoding
, encoding
);
448 * Attempt to fetch both data and metadata for a file.
449 * @param {string} filePath
451 async
_readFileInfo(filePath
) {
452 const _scope
= _fileScope('_readFileInfo');
455 // eslint-disable-next-line security/detect-non-literal-fs-filename
456 const stat
= fsPromises
.stat(filePath
);
457 // eslint-disable-next-line security/detect-non-literal-fs-filename
458 const data
= fsPromises
.readFile(filePath
);
459 result
= await Promise
.all([stat
, data
]);
461 if (['ENOENT', 'EACCES', 'EISDIR', 'ENAMETOOLONG', 'EINVAL'].includes(e
.code
)) {
464 this.logger
.error(_scope
, 'fs error', { error: e
, filePath
});
472 * Potentially add additional headers from static file meta-file.
473 * @param {http.ServerResponse} res
474 * @param {string} directory
475 * @param {string} fileName - already normalized and filtered
477 async
_serveFileMetaHeaders(res
, directory
, fileName
) {
478 const _scope
= _fileScope('_serveFileMetaHeaders');
479 this.logger
.debug(_scope
, 'called', { directory
, fileName
});
481 const metaPrefix
= '.';
482 const metaSuffix
= '.meta';
483 const metaFileName
= `${metaPrefix}${fileName}${metaSuffix}`;
484 const metaFilePath
= path
.join(directory
, metaFileName
);
486 const [stat
, data
] = await
this._readFileInfo(metaFilePath
);
491 const lineBreakRE
= /\r\n|\n|\r/;
492 const lines
= data
.toString().split(lineBreakRE
);
493 common
.unfoldHeaderLines(lines
);
495 const headerParseRE
= /^(?<name
>[^:]+): +(?<value
>.*)$/;
496 lines
.forEach((line
) => {
498 const result
= headerParseRE
.exec(line
);
499 const { groups: header
} = result
;
500 res
.setHeader(header
.name
, header
.value
);
507 * Serve a file from a directory, with rudimentary cache awareness.
508 * This will also serve pre-encoded variations if available and requested.
509 * @param {http.ClientRequest} req
510 * @param {http.ServerResponse} res
511 * @param {object} ctx
512 * @param {string} directory
513 * @param {string} fileName
515 async
serveFile(req
, res
, ctx
, directory
, fileName
) {
516 const _scope
= _fileScope('serveFile');
517 this.logger
.debug(_scope
, 'called', { req
, ctx
});
519 // Require a directory field.
521 this.logger
.debug(_scope
, 'rejected unset directory', { fileName
});
522 return this.handlerNotFound(req
, res
, ctx
);
525 // Normalize the supplied path, as encoded path-navigation may have been (maliciously) present.
526 fileName
= path
.normalize(fileName
);
528 // We will not deal with any subdirs, nor any dot-files.
529 // (Note that we could not deal with subdirs even if we wanted, due to simple router matching scheme.)
530 if (fileName
.indexOf(path
.sep
) >= 0
531 || fileName
.startsWith('.')) {
532 this.logger
.debug(_scope
, 'rejected filename', { fileName
});
533 return this.handlerNotFound(req
, res
, ctx
);
536 const filePath
= path
.join(directory
, fileName
);
538 // File must exist, before any alternate static encodings will be considered.
539 let [stat
, data
] = await
this._readFileInfo(filePath
);
541 return this.handlerNotFound(req
, res
, ctx
);
544 // If encodings were requested, check for static versions to serve.
545 // Update stat and data if matching version is found.
546 ctx
.availableEncodings
= Dingus
.getResponseEncoding(Object
.values(Enum
.EncodingType
), req
);
547 if (ctx
.availableEncodings
.length
=== 0) {
548 // Identity encoding was specifically denied, and nothing else available.
549 this.logger
.debug(_scope
, 'no suitable encodings', { ctx
});
550 return this.handlerMethodNotAllowed(req
, res
, ctx
);
552 for (const encoding
of ctx
.availableEncodings
) {
553 if (encoding
=== Enum
.EncodingType
.Identity
) {
556 const suffix
= Enum
.EncodingTypeSuffix
[encoding
];
558 this.logger
.error(_scope
, 'supported encoding missing mapped suffix', { ctx
, encoding
});
561 const encodedFilePath
= `${filePath}${suffix}`;
562 const [ encodedStat
, encodedData
] = await
this._readFileInfo(encodedFilePath
);
564 ([ stat
, data
] = [ encodedStat
, encodedData
]);
565 ctx
.selectedEncoding
= encoding
;
566 Dingus
.addEncodingHeader(res
, encoding
);
567 res
.setHeader(Enum
.Header
.Vary
, Enum
.Header
.AcceptEncoding
);
568 this.logger
.debug(_scope
, 'serving encoded version', { ctx
, encodedFilePath
});
573 const lastModifiedDate
= new Date(stat
.mtimeMs
);
574 res
.setHeader(Enum
.Header
.LastModified
, lastModifiedDate
.toGMTString());
576 const eTag
= common
.generateETag(filePath
, stat
, data
);
577 res
.setHeader(Enum
.Header
.ETag
, eTag
);
579 if (common
.isClientCached(req
, stat
.mtimeMs
, eTag
)) {
580 this.logger
.debug(_scope
, 'client cached file', { filePath
});
581 res
.statusCode
= 304; // Not Modified
586 // Set the type based on extension of un-encoded filename.
587 const ext
= path
.extname(filePath
).slice(1); // Drop the dot
588 const contentType
= extensionToMime(ext
);
589 res
.setHeader(Enum
.Header
.ContentType
, contentType
);
591 // We presume static files are relatively cacheable.
592 res
.setHeader(Enum
.Header
.CacheControl
, 'public');
594 if (this.staticMetadata
) {
595 await
this._serveFileMetaHeaders(res
, directory
, fileName
);
598 this.logger
.debug(_scope
, 'serving file', { filePath
, contentType
});
604 * Return a content-type appropriate rendering of an errorResponse object.
605 * @param {string} type content-type of response
606 * @param {object} err either an Error object, or an error response
607 * @param {number} err.statusCode
608 * @param {string} err.errorMessage
609 * @param {string|string[]} err.details
611 // eslint-disable-next-line class-methods-use-this
612 renderError(contentType
, err
) {
613 switch (contentType
) {
614 case Enum
.ContentType
.ApplicationJson:
615 return JSON
.stringify(err
);
617 case Enum
.ContentType
.TextHTML:
618 return Template
.errorHTML(err
);
620 case Enum
.ContentType
.TextPlain:
622 return [err
.errorMessage
, err
.details
].join('\r\n');
628 * Send an error response. Terminal.
629 * Logs any non-error-response errors as such.
630 * @param {object} err either an Error object, or an error response
631 * @param {http.ClientRequest} req
632 * @param {http.ServerResponse} res
633 * @param {object} ctx
635 sendErrorResponse(err
, req
, res
, ctx
) {
636 const _scope
= _fileScope('sendErrorResponse');
639 // Default to a content type if one is not yet present
640 if (!res
.hasHeader(Enum
.Header
.ContentType
)) {
641 res
.setHeader(Enum
.Header
.ContentType
, Enum
.ContentType
.TextPlain
);
644 if (err
?.statusCode
) {
645 res
.statusCode
= err
.statusCode
;
646 body
= this.renderError(res
.getHeader(Enum
.Header
.ContentType
), err
);
647 this.logger
.debug(_scope
, 'handler error', { err
, req
, res
, ctx
});
649 res
.statusCode
= 500;
650 body
= this.renderError(res
.getHeader(Enum
.Header
.ContentType
), Enum
.ErrorResponse
.InternalServerError
);
651 this.logger
.error(_scope
, 'handler exception', { err
, req
, res
, ctx
});
658 * @param {http.ClientRequest} req
659 * @param {http.ServerResponse} res
660 * @param {object} ctx
661 * @param {String} file - override ctx.params.file
663 async
handlerGetStaticFile(req
, res
, ctx
, file
) {
664 Dingus
.setHeadHandler(req
, res
, ctx
);
666 // Set a default response type to handle any errors; will be re-set to serve actual static content type.
667 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
669 await
this.serveFile(req
, res
, ctx
, this.staticPath
, file
|| ctx
.params
.file
);
674 * @param {http.ClientRequest} req
675 * @param {http.ServerResponse} res
676 * @param {Object} ctx
677 * @param {String} newPath
678 * @param {Number} statusCode
680 async
handlerRedirect(req
, res
, ctx
, newPath
, statusCode
= 307) {
681 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
682 res
.setHeader(Enum
.Header
.Location
, newPath
);
683 res
.statusCode
= statusCode
;
689 * @param {http.ClientRequest} req
690 * @param {http.ServerResponse} res
691 * @param {object} ctx
693 async
handlerMethodNotAllowed(req
, res
, ctx
) {
694 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
695 throw new ResponseError(Enum
.ErrorResponse
.MethodNotAllowed
);
700 * @param {http.ClientRequest} req
701 * @param {http.ServerResponse} res
702 * @param {object} ctx
704 async
handlerNotFound(req
, res
, ctx
) {
705 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
706 throw new ResponseError(Enum
.ErrorResponse
.NotFound
);
711 * @param {http.ClientRequest} req
712 * @param {http.ServerResponse} res
713 * @param {object} ctx
715 async
handlerBadRequest(req
, res
, ctx
) {
716 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
717 throw new ResponseError(Enum
.ErrorResponse
.BadRequest
);
722 * @param {http.ClientRequest} req
723 * @param {http.ServerResponse} res
724 * @param {object} ctx
726 async
handlerInternalServerError(req
, res
, ctx
) {
727 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
728 throw new ResponseError(Enum
.ErrorResponse
.InternalServerError
);
733 module
.exports
= Dingus
;