index.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /*!
  2. * finalhandler
  3. * Copyright(c) 2014-2017 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. // respect headers from error
  84. if (status !== undefined) {
  85. headers = getErrorHeaders(err)
  86. }
  87. // fallback to status code on response
  88. if (status === undefined) {
  89. status = getResponseStatusCode(res)
  90. }
  91. // get error message
  92. msg = getErrorMessage(err, status, env)
  93. } else {
  94. // not found
  95. status = 404
  96. msg = 'Cannot ' + req.method + ' ' + encodeUrl(parseUrl.original(req).pathname)
  97. }
  98. debug('default %s', status)
  99. // schedule onerror callback
  100. if (err && onerror) {
  101. defer(onerror, err, req, res)
  102. }
  103. // cannot actually respond
  104. if (headersSent(res)) {
  105. debug('cannot %d after headers sent', status)
  106. req.socket.destroy()
  107. return
  108. }
  109. // send response
  110. send(req, res, status, headers, msg)
  111. }
  112. }
  113. /**
  114. * Get headers from Error object.
  115. *
  116. * @param {Error} err
  117. * @return {object}
  118. * @private
  119. */
  120. function getErrorHeaders (err) {
  121. if (!err.headers || typeof err.headers !== 'object') {
  122. return undefined
  123. }
  124. var headers = Object.create(null)
  125. var keys = Object.keys(err.headers)
  126. for (var i = 0; i < keys.length; i++) {
  127. var key = keys[i]
  128. headers[key] = err.headers[key]
  129. }
  130. return headers
  131. }
  132. /**
  133. * Get message from Error object, fallback to status message.
  134. *
  135. * @param {Error} err
  136. * @param {number} status
  137. * @param {string} env
  138. * @return {string}
  139. * @private
  140. */
  141. function getErrorMessage (err, status, env) {
  142. var msg
  143. if (env !== 'production') {
  144. // use err.stack, which typically includes err.message
  145. msg = err.stack
  146. // fallback to err.toString() when possible
  147. if (!msg && typeof err.toString === 'function') {
  148. msg = err.toString()
  149. }
  150. }
  151. return msg || statuses[status]
  152. }
  153. /**
  154. * Get status code from Error object.
  155. *
  156. * @param {Error} err
  157. * @return {number}
  158. * @private
  159. */
  160. function getErrorStatusCode (err) {
  161. // check err.status
  162. if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
  163. return err.status
  164. }
  165. // check err.statusCode
  166. if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
  167. return err.statusCode
  168. }
  169. return undefined
  170. }
  171. /**
  172. * Get status code from response.
  173. *
  174. * @param {OutgoingMessage} res
  175. * @return {number}
  176. * @private
  177. */
  178. function getResponseStatusCode (res) {
  179. var status = res.statusCode
  180. // default status code to 500 if outside valid range
  181. if (typeof status !== 'number' || status < 400 || status > 599) {
  182. status = 500
  183. }
  184. return status
  185. }
  186. /**
  187. * Determine if the response headers have been sent.
  188. *
  189. * @param {object} res
  190. * @returns {boolean}
  191. * @private
  192. */
  193. function headersSent (res) {
  194. return typeof res.headersSent !== 'boolean'
  195. ? Boolean(res._header)
  196. : res.headersSent
  197. }
  198. /**
  199. * Send response.
  200. *
  201. * @param {IncomingMessage} req
  202. * @param {OutgoingMessage} res
  203. * @param {number} status
  204. * @param {object} headers
  205. * @param {string} message
  206. * @private
  207. */
  208. function send (req, res, status, headers, message) {
  209. function write () {
  210. // response body
  211. var body = createHtmlDocument(message)
  212. // response status
  213. res.statusCode = status
  214. res.statusMessage = statuses[status]
  215. // response headers
  216. setHeaders(res, headers)
  217. // security headers
  218. res.setHeader('Content-Security-Policy', "default-src 'self'")
  219. res.setHeader('X-Content-Type-Options', 'nosniff')
  220. // standard headers
  221. res.setHeader('Content-Type', 'text/html; charset=utf-8')
  222. res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))
  223. if (req.method === 'HEAD') {
  224. res.end()
  225. return
  226. }
  227. res.end(body, 'utf8')
  228. }
  229. if (isFinished(req)) {
  230. write()
  231. return
  232. }
  233. // unpipe everything from the request
  234. unpipe(req)
  235. // flush the request
  236. onFinished(req, write)
  237. req.resume()
  238. }
  239. /**
  240. * Set response headers from an object.
  241. *
  242. * @param {OutgoingMessage} res
  243. * @param {object} headers
  244. * @private
  245. */
  246. function setHeaders (res, headers) {
  247. if (!headers) {
  248. return
  249. }
  250. var keys = Object.keys(headers)
  251. for (var i = 0; i < keys.length; i++) {
  252. var key = keys[i]
  253. res.setHeader(key, headers[key])
  254. }
  255. }