index.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /*!
  2. * finalhandler
  3. * Copyright(c) 2014-2022 Douglas Christopher Wilson
  4. * MIT Licensed
  5. */
  6. 'use strict'
  7. /**
  8. * Module dependencies.
  9. * @private
  10. */
  11. var debug = require('debug')('finalhandler')
  12. var encodeUrl = require('encodeurl')
  13. var escapeHtml = require('escape-html')
  14. var onFinished = require('on-finished')
  15. var parseUrl = require('parseurl')
  16. var statuses = require('statuses')
  17. var unpipe = require('unpipe')
  18. /**
  19. * Module variables.
  20. * @private
  21. */
  22. var DOUBLE_SPACE_REGEXP = /\x20{2}/g
  23. var NEWLINE_REGEXP = /\n/g
  24. /* istanbul ignore next */
  25. var defer = typeof setImmediate === 'function'
  26. ? setImmediate
  27. : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) }
  28. var isFinished = onFinished.isFinished
  29. /**
  30. * Create a minimal HTML document.
  31. *
  32. * @param {string} message
  33. * @private
  34. */
  35. function createHtmlDocument (message) {
  36. var body = escapeHtml(message)
  37. .replace(NEWLINE_REGEXP, '<br>')
  38. .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;')
  39. return '<!DOCTYPE html>\n' +
  40. '<html lang="en">\n' +
  41. '<head>\n' +
  42. '<meta charset="utf-8">\n' +
  43. '<title>Error</title>\n' +
  44. '</head>\n' +
  45. '<body>\n' +
  46. '<pre>' + body + '</pre>\n' +
  47. '</body>\n' +
  48. '</html>\n'
  49. }
  50. /**
  51. * Module exports.
  52. * @public
  53. */
  54. module.exports = finalhandler
  55. /**
  56. * Create a function to handle the final response.
  57. *
  58. * @param {Request} req
  59. * @param {Response} res
  60. * @param {Object} [options]
  61. * @return {Function}
  62. * @public
  63. */
  64. function finalhandler (req, res, options) {
  65. var opts = options || {}
  66. // get environment
  67. var env = opts.env || process.env.NODE_ENV || 'development'
  68. // get error callback
  69. var onerror = opts.onerror
  70. return function (err) {
  71. var headers
  72. var msg
  73. var status
  74. // ignore 404 on in-flight response
  75. if (!err && headersSent(res)) {
  76. debug('cannot 404 after headers sent')
  77. return
  78. }
  79. // unhandled error
  80. if (err) {
  81. // respect status code from error
  82. status = getErrorStatusCode(err)
  83. if (status === undefined) {
  84. // fallback to status code on response
  85. status = getResponseStatusCode(res)
  86. } else {
  87. // respect headers from error
  88. headers = getErrorHeaders(err)
  89. }
  90. // get error message
  91. msg = getErrorMessage(err, status, env)
  92. } else {
  93. // not found
  94. status = 404
  95. msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req))
  96. }
  97. debug('default %s', status)
  98. // schedule onerror callback
  99. if (err && onerror) {
  100. defer(onerror, err, req, res)
  101. }
  102. // cannot actually respond
  103. if (headersSent(res)) {
  104. debug('cannot %d after headers sent', status)
  105. if (req.socket) {
  106. req.socket.destroy()
  107. }
  108. return
  109. }
  110. // send response
  111. send(req, res, status, headers, msg)
  112. }
  113. }
  114. /**
  115. * Get headers from Error object.
  116. *
  117. * @param {Error} err
  118. * @return {object}
  119. * @private
  120. */
  121. function getErrorHeaders (err) {
  122. if (!err.headers || typeof err.headers !== 'object') {
  123. return undefined
  124. }
  125. var headers = Object.create(null)
  126. var keys = Object.keys(err.headers)
  127. for (var i = 0; i < keys.length; i++) {
  128. var key = keys[i]
  129. headers[key] = err.headers[key]
  130. }
  131. return headers
  132. }
  133. /**
  134. * Get message from Error object, fallback to status message.
  135. *
  136. * @param {Error} err
  137. * @param {number} status
  138. * @param {string} env
  139. * @return {string}
  140. * @private
  141. */
  142. function getErrorMessage (err, status, env) {
  143. var msg
  144. if (env !== 'production') {
  145. // use err.stack, which typically includes err.message
  146. msg = err.stack
  147. // fallback to err.toString() when possible
  148. if (!msg && typeof err.toString === 'function') {
  149. msg = err.toString()
  150. }
  151. }
  152. return msg || statuses.message[status]
  153. }
  154. /**
  155. * Get status code from Error object.
  156. *
  157. * @param {Error} err
  158. * @return {number}
  159. * @private
  160. */
  161. function getErrorStatusCode (err) {
  162. // check err.status
  163. if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
  164. return err.status
  165. }
  166. // check err.statusCode
  167. if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
  168. return err.statusCode
  169. }
  170. return undefined
  171. }
  172. /**
  173. * Get resource name for the request.
  174. *
  175. * This is typically just the original pathname of the request
  176. * but will fallback to "resource" is that cannot be determined.
  177. *
  178. * @param {IncomingMessage} req
  179. * @return {string}
  180. * @private
  181. */
  182. function getResourceName (req) {
  183. try {
  184. return parseUrl.original(req).pathname
  185. } catch (e) {
  186. return 'resource'
  187. }
  188. }
  189. /**
  190. * Get status code from response.
  191. *
  192. * @param {OutgoingMessage} res
  193. * @return {number}
  194. * @private
  195. */
  196. function getResponseStatusCode (res) {
  197. var status = res.statusCode
  198. // default status code to 500 if outside valid range
  199. if (typeof status !== 'number' || status < 400 || status > 599) {
  200. status = 500
  201. }
  202. return status
  203. }
  204. /**
  205. * Determine if the response headers have been sent.
  206. *
  207. * @param {object} res
  208. * @returns {boolean}
  209. * @private
  210. */
  211. function headersSent (res) {
  212. return typeof res.headersSent !== 'boolean'
  213. ? Boolean(res._header)
  214. : res.headersSent
  215. }
  216. /**
  217. * Send response.
  218. *
  219. * @param {IncomingMessage} req
  220. * @param {OutgoingMessage} res
  221. * @param {number} status
  222. * @param {object} headers
  223. * @param {string} message
  224. * @private
  225. */
  226. function send (req, res, status, headers, message) {
  227. function write () {
  228. // response body
  229. var body = createHtmlDocument(message)
  230. // response status
  231. res.statusCode = status
  232. if (req.httpVersionMajor < 2) {
  233. res.statusMessage = statuses.message[status]
  234. }
  235. // remove any content headers
  236. res.removeHeader('Content-Encoding')
  237. res.removeHeader('Content-Language')
  238. res.removeHeader('Content-Range')
  239. // response headers
  240. setHeaders(res, headers)
  241. // security headers
  242. res.setHeader('Content-Security-Policy', "default-src 'none'")
  243. res.setHeader('X-Content-Type-Options', 'nosniff')
  244. // standard headers
  245. res.setHeader('Content-Type', 'text/html; charset=utf-8')
  246. res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))
  247. if (req.method === 'HEAD') {
  248. res.end()
  249. return
  250. }
  251. res.end(body, 'utf8')
  252. }
  253. if (isFinished(req)) {
  254. write()
  255. return
  256. }
  257. // unpipe everything from the request
  258. unpipe(req)
  259. // flush the request
  260. onFinished(req, write)
  261. req.resume()
  262. }
  263. /**
  264. * Set response headers from an object.
  265. *
  266. * @param {OutgoingMessage} res
  267. * @param {object} headers
  268. * @private
  269. */
  270. function setHeaders (res, headers) {
  271. if (!headers) {
  272. return
  273. }
  274. var keys = Object.keys(headers)
  275. for (var i = 0; i < keys.length; i++) {
  276. var key = keys[i]
  277. res.setHeader(key, headers[key])
  278. }
  279. }