proxy.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. const url = require('url')
  2. const httpProxy = require('http-proxy')
  3. const _ = require('lodash')
  4. const log = require('../logger').create('proxy')
  5. function parseProxyConfig (proxies, config) {
  6. proxies = proxies || []
  7. return _.sortBy(_.map(proxies, function (proxyConfiguration, proxyPath) {
  8. if (typeof proxyConfiguration === 'string') {
  9. proxyConfiguration = {target: proxyConfiguration}
  10. }
  11. let proxyUrl = proxyConfiguration.target
  12. const proxyDetails = url.parse(proxyUrl)
  13. let pathname = proxyDetails.pathname
  14. if (proxyPath.endsWith('/') && !proxyUrl.endsWith('/')) {
  15. log.warn(`proxy "${proxyUrl}" normalized to "${proxyUrl}/"`)
  16. proxyUrl += '/'
  17. pathname += '/'
  18. }
  19. if (!proxyPath.endsWith('/') && proxyUrl.endsWith('/')) {
  20. log.warn(`proxy "${proxyPath}" normalized to "${proxyPath}/"`)
  21. proxyPath += '/'
  22. }
  23. if (pathname === '/' && !proxyUrl.endsWith('/')) {
  24. pathname = ''
  25. }
  26. const hostname = proxyDetails.hostname || config.hostname
  27. const protocol = proxyDetails.protocol || config.protocol
  28. const https = proxyDetails.protocol === 'https:'
  29. let port
  30. if (proxyDetails.port) {
  31. port = proxyDetails.port
  32. } else if (proxyDetails.protocol) {
  33. port = https ? '443' : '80'
  34. } else {
  35. port = config.port
  36. }
  37. const changeOrigin = proxyConfiguration.changeOrigin || false
  38. const proxy = httpProxy.createProxyServer({
  39. target: { host: hostname, port, https, protocol },
  40. xfwd: true,
  41. changeOrigin: changeOrigin,
  42. secure: config.proxyValidateSSL
  43. })
  44. ;['proxyReq', 'proxyRes'].forEach(function (name) {
  45. const callback = proxyDetails[name] || config[name]
  46. if (callback) {
  47. proxy.on(name, callback)
  48. }
  49. })
  50. proxy.on('error', function proxyError (err, req, res) {
  51. if (err.code === 'ECONNRESET' && req.socket.destroyed) {
  52. log.debug(`failed to proxy ${req.url} (browser hung up the socket)`)
  53. } else {
  54. log.warn(`failed to proxy ${req.url} (${err.message})`)
  55. }
  56. res.destroy()
  57. })
  58. return { path: proxyPath, baseUrl: pathname, host: hostname, port, https, proxy }
  59. }), 'path').reverse()
  60. }
  61. /**
  62. * Returns a handler which understands the proxies and its redirects, along with the proxy to use
  63. * @param proxies An array of proxy record objects
  64. * @param urlRoot The URL root that karma is mounted on
  65. * @return {Function} handler function
  66. */
  67. function createProxyHandler (proxies, urlRoot) {
  68. if (!proxies.length) {
  69. const nullProxy = (request, response, next) => next()
  70. nullProxy.upgrade = () => {}
  71. return nullProxy
  72. }
  73. function createProxy (request, response, next) {
  74. const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
  75. if (proxyRecord) {
  76. log.debug(`proxying request - ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
  77. request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
  78. proxyRecord.proxy.web(request, response)
  79. } else {
  80. return next()
  81. }
  82. }
  83. createProxy.upgrade = function (request, socket, head) {
  84. // special-case karma's route to avoid upgrading it
  85. if (request.url.startsWith(urlRoot)) {
  86. log.debug(`NOT upgrading proxyWebSocketRequest ${request.url}`)
  87. return
  88. }
  89. const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
  90. if (proxyRecord) {
  91. log.debug(`upgrade proxyWebSocketRequest ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
  92. request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
  93. proxyRecord.proxy.ws(request, socket, head)
  94. }
  95. }
  96. return createProxy
  97. }
  98. exports.create = function (/* config */config, /* config.proxies */proxies) {
  99. return createProxyHandler(parseProxyConfig(proxies, config), config.urlRoot)
  100. }