index.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 && res._header) {
  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 (res._header) {
  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. * Send response.
  188. *
  189. * @param {IncomingMessage} req
  190. * @param {OutgoingMessage} res
  191. * @param {number} status
  192. * @param {object} headers
  193. * @param {string} message
  194. * @private
  195. */
  196. function send (req, res, status, headers, message) {
  197. function write () {
  198. // response body
  199. var body = createHtmlDocument(message)
  200. // response status
  201. res.statusCode = status
  202. res.statusMessage = statuses[status]
  203. // response headers
  204. setHeaders(res, headers)
  205. // security headers
  206. res.setHeader('Content-Security-Policy', "default-src 'self'")
  207. res.setHeader('X-Content-Type-Options', 'nosniff')
  208. // standard headers
  209. res.setHeader('Content-Type', 'text/html; charset=utf-8')
  210. res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))
  211. if (req.method === 'HEAD') {
  212. res.end()
  213. return
  214. }
  215. res.end(body, 'utf8')
  216. }
  217. if (isFinished(req)) {
  218. write()
  219. return
  220. }
  221. // unpipe everything from the request
  222. unpipe(req)
  223. // flush the request
  224. onFinished(req, write)
  225. req.resume()
  226. }
  227. /**
  228. * Set response headers from an object.
  229. *
  230. * @param {OutgoingMessage} res
  231. * @param {object} headers
  232. * @private
  233. */
  234. function setHeaders (res, headers) {
  235. if (!headers) {
  236. return
  237. }
  238. var keys = Object.keys(headers)
  239. for (var i = 0; i < keys.length; i++) {
  240. var key = keys[i]
  241. res.setHeader(key, headers[key])
  242. }
  243. }