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