utils.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. const {
  2. URL_MATCHER,
  3. TYPE_URL,
  4. TYPE_REGEX,
  5. TYPE_PATH,
  6. } = require('./matchers')
  7. /**
  8. * creates a string of asterisks,
  9. * this forces a minimum asterisk for security purposes
  10. */
  11. const asterisk = (length = 0) => {
  12. length = typeof length === 'string' ? length.length : length
  13. if (length < 8) {
  14. return '*'.repeat(8)
  15. }
  16. return '*'.repeat(length)
  17. }
  18. /**
  19. * escapes all special regex chars
  20. * @see https://stackoverflow.com/a/9310752
  21. * @see https://github.com/tc39/proposal-regex-escaping
  22. */
  23. const escapeRegExp = (text) => {
  24. return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, `\\$&`)
  25. }
  26. /**
  27. * provieds a regex "or" of the url versions of a string
  28. */
  29. const urlEncodeRegexGroup = (value) => {
  30. const decoded = decodeURIComponent(value)
  31. const encoded = encodeURIComponent(value)
  32. const union = [...new Set([encoded, decoded, value])].map(escapeRegExp).join('|')
  33. return union
  34. }
  35. /**
  36. * a tagged template literal that returns a regex ensures all variables are excaped
  37. */
  38. const urlEncodeRegexTag = (strings, ...values) => {
  39. let pattern = ''
  40. for (let i = 0; i < values.length; i++) {
  41. pattern += strings[i] + `(${urlEncodeRegexGroup(values[i])})`
  42. }
  43. pattern += strings[strings.length - 1]
  44. return new RegExp(pattern)
  45. }
  46. /**
  47. * creates a matcher for redacting url hostname
  48. */
  49. const redactUrlHostnameMatcher = ({ hostname, replacement } = {}) => ({
  50. type: TYPE_URL,
  51. predicate: ({ url }) => url.hostname === hostname,
  52. pattern: ({ url }) => {
  53. return urlEncodeRegexTag`(^${url.protocol}//${url.username}:.+@)?${url.hostname}`
  54. },
  55. replacement: `$1${replacement || asterisk()}`,
  56. })
  57. /**
  58. * creates a matcher for redacting url search / query parameter values
  59. */
  60. const redactUrlSearchParamsMatcher = ({ param, replacement } = {}) => ({
  61. type: TYPE_URL,
  62. predicate: ({ url }) => url.searchParams.has(param),
  63. pattern: ({ url }) => urlEncodeRegexTag`(${param}=)${url.searchParams.get(param)}`,
  64. replacement: `$1${replacement || asterisk()}`,
  65. })
  66. /** creates a matcher for redacting the url password */
  67. const redactUrlPasswordMatcher = ({ replacement } = {}) => ({
  68. type: TYPE_URL,
  69. predicate: ({ url }) => url.password,
  70. pattern: ({ url }) => urlEncodeRegexTag`(^${url.protocol}//${url.username}:)${url.password}`,
  71. replacement: `$1${replacement || asterisk()}`,
  72. })
  73. const redactUrlReplacement = (...matchers) => (subValue) => {
  74. try {
  75. const url = new URL(subValue)
  76. return redactMatchers(...matchers)(subValue, { url })
  77. } catch (err) {
  78. return subValue
  79. }
  80. }
  81. /**
  82. * creates a matcher / submatcher for urls, this function allows you to first
  83. * collect all urls within a larger string and then pass those urls to a
  84. * submatcher
  85. *
  86. * @example
  87. * console.log("this will first match all urls, then pass those urls to the password patcher")
  88. * redactMatchers(redactUrlMatcher(redactUrlPasswordMatcher()))
  89. *
  90. * @example
  91. * console.log(
  92. * "this will assume you are passing in a string that is a url, and will redact the password"
  93. * )
  94. * redactMatchers(redactUrlPasswordMatcher())
  95. *
  96. */
  97. const redactUrlMatcher = (...matchers) => {
  98. return {
  99. ...URL_MATCHER,
  100. replacement: redactUrlReplacement(...matchers),
  101. }
  102. }
  103. const matcherFunctions = {
  104. [TYPE_REGEX]: (matcher) => (value) => {
  105. if (typeof value === 'string') {
  106. value = value.replace(matcher.pattern, matcher.replacement)
  107. }
  108. return value
  109. },
  110. [TYPE_URL]: (matcher) => (value, ctx) => {
  111. if (typeof value === 'string') {
  112. try {
  113. const url = ctx?.url || new URL(value)
  114. const { predicate, pattern } = matcher
  115. const predicateValue = predicate({ url })
  116. if (predicateValue) {
  117. value = value.replace(pattern({ url }), matcher.replacement)
  118. }
  119. } catch (_e) {
  120. return value
  121. }
  122. }
  123. return value
  124. },
  125. [TYPE_PATH]: (matcher) => (value, ctx) => {
  126. const rawPath = ctx?.path
  127. const path = rawPath.join('.').toLowerCase()
  128. const { predicate, replacement } = matcher
  129. const replace = typeof replacement === 'function' ? replacement : () => replacement
  130. const shouldRun = predicate({ rawPath, path })
  131. if (shouldRun) {
  132. value = replace(value, { rawPath, path })
  133. }
  134. return value
  135. },
  136. }
  137. /** converts a matcher to a function */
  138. const redactMatcher = (matcher) => {
  139. return matcherFunctions[matcher.type](matcher)
  140. }
  141. /** converts a series of matchers to a function */
  142. const redactMatchers = (...matchers) => (value, ctx) => {
  143. const flatMatchers = matchers.flat()
  144. return flatMatchers.reduce((result, matcher) => {
  145. const fn = (typeof matcher === 'function') ? matcher : redactMatcher(matcher)
  146. return fn(result, ctx)
  147. }, value)
  148. }
  149. /**
  150. * replacement handler, keeping $1 (if it exists) and replacing the
  151. * rest of the string with asterisks, maintaining string length
  152. */
  153. const redactDynamicReplacement = () => (value, start) => {
  154. if (typeof start === 'number') {
  155. return asterisk(value)
  156. }
  157. return start + asterisk(value.substring(start.length).length)
  158. }
  159. /**
  160. * replacement handler, keeping $1 (if it exists) and replacing the
  161. * rest of the string with a fixed number of asterisks
  162. */
  163. const redactFixedReplacement = (length) => (_value, start) => {
  164. if (typeof start === 'number') {
  165. return asterisk(length)
  166. }
  167. return start + asterisk(length)
  168. }
  169. const redactUrlPassword = (value, replacement) => {
  170. return redactMatchers(redactUrlPasswordMatcher({ replacement }))(value)
  171. }
  172. module.exports = {
  173. asterisk,
  174. escapeRegExp,
  175. urlEncodeRegexGroup,
  176. urlEncodeRegexTag,
  177. redactUrlHostnameMatcher,
  178. redactUrlSearchParamsMatcher,
  179. redactUrlPasswordMatcher,
  180. redactUrlMatcher,
  181. redactUrlReplacement,
  182. redactDynamicReplacement,
  183. redactFixedReplacement,
  184. redactMatchers,
  185. redactUrlPassword,
  186. }