generated from 47ng/typescript-library-starter
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
50 lines (47 loc) · 1.43 KB
/
index.ts
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
/**
* Build a RegExp matching the values of secure environment variables.
*
* @param secureEnv A list of environment variable names to redact
* @param env Where to read the values from (defaults to process.env)
*/
export function build(
secureEnv: string[],
env: NodeJS.ProcessEnv = process.env
): RegExp {
const unified = Object.keys(env)
.filter(env => secureEnv.includes(env))
.map(envName => {
const value = env[envName]
// Ignore JSON values that are too generic (might erase other fields)
if (!value || ['true', 'false', 'null'].includes(value)) {
return null
}
const escapedValue = value
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d')
return `(${escapedValue})`
})
.filter(x => !!x)
.join('|')
if (unified === '') {
// Use negated negative lookahead to never match anything
// https://stackoverflow.com/questions/1723182/a-regex-that-will-never-be-matched-by-anything
return new RegExp(/(?!)/, 'g')
}
return new RegExp(unified, 'g')
}
// --
/**
* Redact a string based on a built RegExp (from redactEnv.build).
*
* @param input The input string to redact
* @param regexp A RegExp built by redactEnv.build
* @param replace What to replace redacted text with (defaults to '\[secure\]')
*/
export function redact(
input: string,
regexp: RegExp,
replace: string = '[secure]'
) {
return input.replace(regexp, replace)
}