index.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. 'use strict'
  2. //Parse method copied from https://github.com/brianc/node-postgres
  3. //Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com)
  4. //MIT License
  5. //parses a connection string
  6. function parse(str, options = {}) {
  7. //unix socket
  8. if (str.charAt(0) === '/') {
  9. const config = str.split(' ')
  10. return { host: config[0], database: config[1] }
  11. }
  12. // Check for empty host in URL
  13. const config = {}
  14. let result
  15. let dummyHost = false
  16. if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) {
  17. // Ensure spaces are encoded as %20
  18. str = encodeURI(str).replace(/%25(\d\d)/g, '%$1')
  19. }
  20. try {
  21. try {
  22. result = new URL(str, 'postgres://base')
  23. } catch (e) {
  24. // The URL is invalid so try again with a dummy host
  25. result = new URL(str.replace('@/', '@___DUMMY___/'), 'postgres://base')
  26. dummyHost = true
  27. }
  28. } catch (err) {
  29. // Remove the input from the error message to avoid leaking sensitive information
  30. err.input && (err.input = '*****REDACTED*****')
  31. }
  32. // We'd like to use Object.fromEntries() here but Node.js 10 does not support it
  33. for (const entry of result.searchParams.entries()) {
  34. config[entry[0]] = entry[1]
  35. }
  36. config.user = config.user || decodeURIComponent(result.username)
  37. config.password = config.password || decodeURIComponent(result.password)
  38. if (result.protocol == 'socket:') {
  39. config.host = decodeURI(result.pathname)
  40. config.database = result.searchParams.get('db')
  41. config.client_encoding = result.searchParams.get('encoding')
  42. return config
  43. }
  44. const hostname = dummyHost ? '' : result.hostname
  45. if (!config.host) {
  46. // Only set the host if there is no equivalent query param.
  47. config.host = decodeURIComponent(hostname)
  48. } else if (hostname && /^%2f/i.test(hostname)) {
  49. // Only prepend the hostname to the pathname if it is not a URL encoded Unix socket host.
  50. result.pathname = hostname + result.pathname
  51. }
  52. if (!config.port) {
  53. // Only set the port if there is no equivalent query param.
  54. config.port = result.port
  55. }
  56. const pathname = result.pathname.slice(1) || null
  57. config.database = pathname ? decodeURI(pathname) : null
  58. if (config.ssl === 'true' || config.ssl === '1') {
  59. config.ssl = true
  60. }
  61. if (config.ssl === '0') {
  62. config.ssl = false
  63. }
  64. if (config.sslcert || config.sslkey || config.sslrootcert || config.sslmode) {
  65. config.ssl = {}
  66. }
  67. // Only try to load fs if we expect to read from the disk
  68. const fs = config.sslcert || config.sslkey || config.sslrootcert ? require('fs') : null
  69. if (config.sslcert) {
  70. config.ssl.cert = fs.readFileSync(config.sslcert).toString()
  71. }
  72. if (config.sslkey) {
  73. config.ssl.key = fs.readFileSync(config.sslkey).toString()
  74. }
  75. if (config.sslrootcert) {
  76. config.ssl.ca = fs.readFileSync(config.sslrootcert).toString()
  77. }
  78. if (options.useLibpqCompat && config.uselibpqcompat) {
  79. throw new Error('Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.')
  80. }
  81. if (config.uselibpqcompat === 'true' || options.useLibpqCompat) {
  82. switch (config.sslmode) {
  83. case 'disable': {
  84. config.ssl = false
  85. break
  86. }
  87. case 'prefer': {
  88. config.ssl.rejectUnauthorized = false
  89. break
  90. }
  91. case 'require': {
  92. if (config.sslrootcert) {
  93. // If a root CA is specified, behavior of `sslmode=require` will be the same as that of `verify-ca`
  94. config.ssl.checkServerIdentity = function () {}
  95. } else {
  96. config.ssl.rejectUnauthorized = false
  97. }
  98. break
  99. }
  100. case 'verify-ca': {
  101. if (!config.ssl.ca) {
  102. throw new Error(
  103. 'SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.'
  104. )
  105. }
  106. config.ssl.checkServerIdentity = function () {}
  107. break
  108. }
  109. case 'verify-full': {
  110. break
  111. }
  112. }
  113. } else {
  114. switch (config.sslmode) {
  115. case 'disable': {
  116. config.ssl = false
  117. break
  118. }
  119. case 'prefer':
  120. case 'require':
  121. case 'verify-ca':
  122. case 'verify-full': {
  123. break
  124. }
  125. case 'no-verify': {
  126. config.ssl.rejectUnauthorized = false
  127. break
  128. }
  129. }
  130. }
  131. return config
  132. }
  133. // convert pg-connection-string ssl config to a ClientConfig.ConnectionOptions
  134. function toConnectionOptions(sslConfig) {
  135. const connectionOptions = Object.entries(sslConfig).reduce((c, [key, value]) => {
  136. // we explicitly check for undefined and null instead of `if (value)` because some
  137. // options accept falsy values. Example: `ssl.rejectUnauthorized = false`
  138. if (value !== undefined && value !== null) {
  139. c[key] = value
  140. }
  141. return c
  142. }, {})
  143. return connectionOptions
  144. }
  145. // convert pg-connection-string config to a ClientConfig
  146. function toClientConfig(config) {
  147. const poolConfig = Object.entries(config).reduce((c, [key, value]) => {
  148. if (key === 'ssl') {
  149. const sslConfig = value
  150. if (typeof sslConfig === 'boolean') {
  151. c[key] = sslConfig
  152. }
  153. if (typeof sslConfig === 'object') {
  154. c[key] = toConnectionOptions(sslConfig)
  155. }
  156. } else if (value !== undefined && value !== null) {
  157. if (key === 'port') {
  158. // when port is not specified, it is converted into an empty string
  159. // we want to avoid NaN or empty string as a values in ClientConfig
  160. if (value !== '') {
  161. const v = parseInt(value, 10)
  162. if (isNaN(v)) {
  163. throw new Error(`Invalid ${key}: ${value}`)
  164. }
  165. c[key] = v
  166. }
  167. } else {
  168. c[key] = value
  169. }
  170. }
  171. return c
  172. }, {})
  173. return poolConfig
  174. }
  175. // parses a connection string into ClientConfig
  176. function parseIntoClientConfig(str) {
  177. return toClientConfig(parse(str))
  178. }
  179. module.exports = parse
  180. parse.parse = parse
  181. parse.toClientConfig = toClientConfig
  182. parse.parseIntoClientConfig = parseIntoClientConfig