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,
36 * @param {Object} logger object which implements logging methods
37 * @param {Object} options
38 * @param {Boolean} options.ignoreTrailingSlash
39 * @param {string} options.proxyPrefix leading part of url path to strip
40 * @param {Boolean} options.strictAccept whether to error on unsupported Accept type
41 * @param {string} options.selfBaseUrl for constructing links
42 * @param {Boolean} options.staticMetadata serve static headers with static files
43 * @param {Boolean} options.trustProxy trust some header data to be provided by proxy
44 * @param {Object} options.querystring alternate qs parser to use
46 constructor(logger
= common
.nullLogger
, options
= {}) {
47 common
.setOptions(this, defaultOptions
, options
);
49 this.router
= new Router(options
);
51 if (!this.proxyPrefix
) {
52 this._stripPrefix
= (p
) => p
;
55 this.responseTypes
= [
56 Enum
.ContentType
.TextHTML
,
57 Enum
.ContentType
.TextPlain
,
58 Enum
.ContentType
.ApplicationJson
,
62 common
.ensureLoggerLevels(this.logger
);
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
&& req
.getHeader(Enum
.Header
.XForwardedFor
)) ||
142 (this.trustProxy
&& req
&& req
.getHeader(Enum
.Header
.XRealIP
)) ||
143 (req
&& req
.connection
&& 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
&& req
.getHeader(Enum
.Header
.XForwardedProto
)) ||
156 ((req
&& req
.connection
&& 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 * @param {http.ClientRequest} req
229 * @param {http.ServerResponse} res
230 * @param {object} ctx
232 static setHeadHandler(req
, res
, ctx
) {
233 if (req
.method
=== 'HEAD') {
234 const origEnd
= res
.end
.bind(res
);
236 res
.write = function (chunk
, encoding
) {
237 Dingus
.pushBufChunk(chunks
, chunk
, encoding
);
238 // No call to original res.write.
240 res
.end = function (data
, encoding
, ...rest
) {
241 Dingus
.pushBufChunk(chunks
, data
, encoding
);
242 ctx
.responseBody
= Buffer
.concat(chunks
);
243 res
.setHeader(Enum
.Header
.ContentLength
, Buffer
.byteLength(ctx
.responseBody
));
244 return origEnd(undefined, encoding
, ...rest
);
251 * Dispatch the handler for a request
252 * @param {http.ClientRequest} req
253 * @param {http.ServerResponse} res
254 * @param {object} ctx
256 async
dispatch(req
, res
, ctx
= {}) {
257 const _scope
= _fileScope('dispatch');
259 const { pathPart
, queryParams
} = this._splitUrl(req
.url
);
260 ctx
.queryParams
= queryParams
;
262 let handler
, handlerArgs
= [];
264 ({ handler
, handlerArgs
} = this.router
.lookup(req
.method
, pathPart
, ctx
));
266 if (e
instanceof DingusError
) {
269 handler
= this.handlerNotFound
.bind(this);
272 handler
= this.handlerMethodNotAllowed
.bind(this);
275 this.logger
.error(_scope
, 'unknown dingus error', { error: e
});
276 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 from ctx as contentType into parsedBody.
309 * @param {string} contentType
310 * @param {object} ctx
312 parseBody(contentType
, ctx
) {
313 const _scope
= _fileScope('parseBody');
315 switch (contentType
) {
316 case Enum
.ContentType
.ApplicationForm:
317 ctx
.parsedBody
= this.querystring
.parse(ctx
.rawBody
);
320 case Enum
.ContentType
.ApplicationJson:
322 ctx
.parsedBody
= JSON
.parse(ctx
.rawBody
);
324 this.logger
.debug(_scope
, 'JSON parse failed', { requestId: ctx
.requestId
, error: e
});
325 throw new ResponseError(Enum
.ErrorResponse
.BadRequest
, e
.message
);
330 this.logger
.debug(_scope
, 'unhandled content-type', { requestId: ctx
.requestId
, contentType
});
331 throw new ResponseError(Enum
.ErrorResponse
.UnsupportedMediaType
);
337 * Return all body data from a request.
338 * @param {http.ClientRequest} req
340 async
bodyData(req
) {
341 const _scope
= _fileScope('bodyData');
342 return new Promise((resolve
, reject
) => {
344 req
.on('data', (chunk
) => body
.push(chunk
));
345 req
.on('end', () => resolve(Buffer
.concat(body
).toString()));
346 req
.on('error', (e
) => {
347 this.logger
.error(_scope
, 'failed', { error: e
});
355 * Read and parse request body data.
356 * @param {http.ClientRequest} req
357 * @param {http.ServerResponse} res
358 * @param {object} ctx
360 async
ingestBody(req
, res
, ctx
) {
361 ctx
.rawBody
= await
this.bodyData(req
);
362 const contentType
= Dingus
.getRequestContentType(req
);
363 this.parseBody(contentType
, ctx
);
368 * Return the best matching response type.
369 * @param {string[]} responseTypes
370 * @param {http.ClientRequest} req
372 static getResponseContentType(responseTypes
, req
) {
373 const acceptHeader
= req
.getHeader(Enum
.Header
.Accept
);
374 return ContentNegotiation
.accept(responseTypes
, acceptHeader
);
379 * Returns a list of the most-preferred content encodings for the response.
380 * @param {string[]} responseEncodings
381 * @param {http.ClientRequest} req
383 static getResponseEncoding(responseEncodings
, req
) {
384 const acceptEncodingHeader
= req
.getHeader(Enum
.Header
.AcceptEncoding
);
385 return ContentNegotiation
.preferred(responseEncodings
, acceptEncodingHeader
);
390 * Set the best content type for the response.
391 * @param {string[]} responseTypes default first
392 * @param {http.ClientRequest} req
393 * @param {http.ServerResponse} res
394 * @param {object} ctx
396 setResponseType(responseTypes
, req
, res
, ctx
) {
397 const _scope
= _fileScope('setResponseType');
398 ctx
.responseType
= Dingus
.getResponseContentType(responseTypes
, req
);
399 if (!ctx
.responseType
) {
400 if (this.strictAccept
) {
401 this.logger
.debug(_scope
, 'unhandled strict accept', { requestId: req
.requestId
});
402 throw new ResponseError(Enum
.ErrorResponse
.NotAcceptable
);
404 ctx
.responseType
= responseTypes
[0];
407 res
.setHeader(Enum
.Header
.ContentType
, ctx
.responseType
);
412 * Inserts an encoding
413 * @param {http.ServerResponse} res
414 * @param {string} encoding
416 static addEncodingHeader(res
, encoding
) {
417 const existingEncodings
= res
.getHeader(Enum
.Header
.ContentEncoding
);
418 if (existingEncodings
) {
419 encoding
= `${encoding}, ${existingEncodings}`;
421 res
.setHeader(Enum
.Header
.ContentEncoding
, encoding
);
426 * Attempt to fetch both data and metadata for a file.
427 * @param {string} filePath
429 async
_readFileInfo(filePath
) {
430 const _scope
= _fileScope('_readFileInfo');
433 // eslint-disable-next-line security/detect-non-literal-fs-filename
434 const stat
= fsPromises
.stat(filePath
);
435 // eslint-disable-next-line security/detect-non-literal-fs-filename
436 const data
= fsPromises
.readFile(filePath
);
437 result
= await Promise
.all([stat
, data
]);
439 if (['ENOENT', 'EACCES', 'EISDIR', 'ENAMETOOLONG', 'EINVAL'].includes(e
.code
)) {
442 this.logger
.error(_scope
, 'fs error', { error: e
, filePath
});
450 * Potentially add additional headers from static file meta-file.
451 * @param {http.ServerResponse} res
452 * @param {string} directory
453 * @param {string} fileName - already normalized and filtered
455 async
_serveFileMetaHeaders(res
, directory
, fileName
) {
456 const _scope
= _fileScope('_serveFileMetaHeaders');
457 this.logger
.debug(_scope
, 'called', { directory
, fileName
});
459 const metaPrefix
= '.';
460 const metaSuffix
= '.meta';
461 const metaFileName
= `${metaPrefix}${fileName}${metaSuffix}`;
462 const metaFilePath
= path
.join(directory
, metaFileName
);
464 const [stat
, data
] = await
this._readFileInfo(metaFilePath
);
469 const lineBreakRE
= /\r\n|\n|\r/;
470 const lines
= data
.toString().split(lineBreakRE
);
471 common
.unfoldHeaderLines(lines
);
473 const headerParseRE
= /^(?<name
>[^:]+): +(?<value
>.*)$/;
474 lines
.forEach((line
) => {
476 const result
= headerParseRE
.exec(line
);
477 const { groups: header
} = result
;
478 res
.setHeader(header
.name
, header
.value
);
485 * Serve a file from a directory, with rudimentary cache awareness.
486 * This will also serve pre-encoded variations if available and requested.
487 * @param {http.ClientRequest} req
488 * @param {http.ServerResponse} res
489 * @param {object} ctx
490 * @param {string} directory
491 * @param {string} fileName
493 async
serveFile(req
, res
, ctx
, directory
, fileName
) {
494 const _scope
= _fileScope('serveFile');
495 this.logger
.debug(_scope
, 'called', { req: common
.requestLogData(req
), ctx
});
497 // Normalize the supplied path, as encoded path-navigation may have been (maliciously) present.
498 fileName
= path
.normalize(fileName
);
500 // We will not deal with any subdirs, nor any dot-files.
501 // (Note that we could not deal with subdirs even if we wanted, due to simple router matching scheme.)
502 if (fileName
.indexOf(path
.sep
) >= 0
503 || fileName
.charAt(0) === '.') {
504 this.logger
.debug(_scope
, 'rejected filename', { fileName
});
505 return this.handlerNotFound(req
, res
, ctx
);
508 const filePath
= path
.join(directory
, fileName
);
510 // File must exist, before any alternate static encodings will be considered.
511 let [stat
, data
] = await
this._readFileInfo(filePath
);
513 return this.handlerNotFound(req
, res
, ctx
);
516 // If encodings were requested, check for static versions to serve.
517 // Update stat and data if matching version is found.
518 ctx
.availableEncodings
= Dingus
.getResponseEncoding(Object
.values(Enum
.EncodingType
), req
);
519 if (ctx
.availableEncodings
.length
=== 0) {
520 // Identity encoding was specifically denied, and nothing else available.
521 this.logger
.debug(_scope
, 'no suitable encodings', { ctx
});
522 return this.handlerMethodNotAllowed(req
, res
, ctx
);
524 for (const encoding
of ctx
.availableEncodings
) {
525 if (encoding
=== Enum
.EncodingType
.Identity
) {
528 const suffix
= Enum
.EncodingTypeSuffix
[encoding
];
530 const encodedFilePath
= `${filePath}${suffix}`;
531 const [ encodedStat
, encodedData
] = await
this._readFileInfo(encodedFilePath
);
533 ([ stat
, data
] = [ encodedStat
, encodedData
]);
534 ctx
.selectedEncoding
= encoding
;
535 Dingus
.addEncodingHeader(res
, encoding
);
536 res
.setHeader(Enum
.Header
.Vary
, Enum
.Header
.AcceptEncoding
);
537 this.logger
.debug(_scope
, 'serving encoded version', { ctx
, encodedFilePath
});
543 const lastModifiedDate
= new Date(stat
.mtimeMs
);
544 res
.setHeader(Enum
.Header
.LastModified
, lastModifiedDate
.toGMTString());
546 const eTag
= common
.generateETag(filePath
, stat
, data
);
547 res
.setHeader(Enum
.Header
.ETag
, eTag
);
549 if (common
.isClientCached(req
, stat
.mtimeMs
, eTag
)) {
550 this.logger
.debug(_scope
, 'client cached file', { filePath
});
551 res
.statusCode
= 304; // Not Modified
556 // Set the type based on extension of un-encoded filename.
557 const ext
= path
.extname(filePath
).slice(1); // Drop the dot
558 const contentType
= extensionToMime(ext
);
559 res
.setHeader(Enum
.Header
.ContentType
, contentType
);
561 // We presume static files are relatively cacheable.
562 res
.setHeader(Enum
.Header
.CacheControl
, 'public');
564 if (this.staticMetadata
) {
565 await
this._serveFileMetaHeaders(res
, directory
, fileName
);
568 this.logger
.debug(_scope
, 'serving file', { filePath
, contentType
});
574 * Return a content-type appropriate rendering of an errorResponse object.
575 * @param {string} type content-type of response
576 * @param {object} err either an Error object, or an error response
577 * @param {number} err.statusCode
578 * @param {string} err.errorMessage
579 * @param {string|string[]} err.details
581 // eslint-disable-next-line class-methods-use-this
582 renderError(contentType
, err
) {
583 switch (contentType
) {
584 case Enum
.ContentType
.ApplicationJson:
585 return JSON
.stringify(err
);
587 case Enum
.ContentType
.TextHTML:
588 return Template
.errorHTML(err
);
590 case Enum
.ContentType
.TextPlain:
592 return [err
.errorMessage
, err
.details
].join('\r\n');
598 * Send an error response. Terminal.
599 * Logs any non-error-response errors as such.
600 * @param {object} err either an Error object, or an error response
601 * @param {http.ClientRequest} req
602 * @param {http.ServerResponse} res
603 * @param {object} ctx
605 sendErrorResponse(err
, req
, res
, ctx
) {
606 const _scope
= _fileScope('sendErrorResponse');
609 // Default to a content type if one is not yet present
610 if (!res
.hasHeader(Enum
.Header
.ContentType
)) {
611 res
.setHeader(Enum
.Header
.ContentType
, Enum
.ContentType
.TextPlain
);
614 if (err
&& err
.statusCode
) {
615 res
.statusCode
= err
.statusCode
;
616 body
= this.renderError(res
.getHeader(Enum
.Header
.ContentType
), err
);
617 this.logger
.debug(_scope
, 'handler error', { err
, ...common
.handlerLogData(req
, res
, ctx
) });
619 res
.statusCode
= 500;
620 body
= this.renderError(res
.getHeader(Enum
.Header
.ContentType
), Enum
.ErrorResponse
.InternalServerError
);
621 this.logger
.error(_scope
, 'handler exception', { err
, ...common
.handlerLogData(req
, res
, ctx
) });
628 * @param {http.ClientRequest} req
629 * @param {http.ServerResponse} res
630 * @param {object} ctx
631 * @param {String} file - override ctx.params.file
633 async
handlerGetStaticFile(req
, res
, ctx
, file
) {
634 Dingus
.setHeadHandler(req
, res
, ctx
);
636 // Set a default response type to handle any errors; will be re-set to serve actual static content type.
637 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
639 await
this.serveFile(req
, res
, ctx
, this.staticPath
, file
|| ctx
.params
.file
);
644 * @param {http.ClientRequest} req
645 * @param {http.ServerResponse} res
646 * @param {Object} ctx
647 * @param {String} newPath
648 * @param {Number} statusCode
650 async
handlerRedirect(req
, res
, ctx
, newPath
, statusCode
= 307) {
651 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
652 res
.setHeader(Enum
.Header
.Location
, newPath
);
653 res
.statusCode
= statusCode
;
659 * @param {http.ClientRequest} req
660 * @param {http.ServerResponse} res
661 * @param {object} ctx
663 async
handlerMethodNotAllowed(req
, res
, ctx
) {
664 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
665 throw new ResponseError(Enum
.ErrorResponse
.MethodNotAllowed
);
670 * @param {http.ClientRequest} req
671 * @param {http.ServerResponse} res
672 * @param {object} ctx
674 async
handlerNotFound(req
, res
, ctx
) {
675 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
676 throw new ResponseError(Enum
.ErrorResponse
.NotFound
);
681 * @param {http.ClientRequest} req
682 * @param {http.ServerResponse} res
683 * @param {object} ctx
685 async
handlerBadRequest(req
, res
, ctx
) {
686 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
687 throw new ResponseError(Enum
.ErrorResponse
.BadRequest
);
692 * @param {http.ClientRequest} req
693 * @param {http.ServerResponse} res
694 * @param {object} ctx
696 async
handlerInternalServerError(req
, res
, ctx
) {
697 this.setResponseType(this.responseTypes
, req
, res
, ctx
);
698 throw new ResponseError(Enum
.ErrorResponse
.InternalServerError
);
703 module
.exports
= Dingus
;