index.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. const matchers = require('./matchers')
  2. const { redactUrlPassword } = require('./utils')
  3. const REPLACE = '***'
  4. const redact = (value) => {
  5. if (typeof value !== 'string' || !value) {
  6. return value
  7. }
  8. return redactUrlPassword(value, REPLACE)
  9. .replace(matchers.NPM_SECRET.pattern, `npm_${REPLACE}`)
  10. .replace(matchers.UUID.pattern, REPLACE)
  11. }
  12. // split on \s|= similar to how nopt parses options
  13. const splitAndRedact = (str) => {
  14. // stateful regex, don't move out of this scope
  15. const splitChars = /[\s=]/g
  16. let match = null
  17. let result = ''
  18. let index = 0
  19. while (match = splitChars.exec(str)) {
  20. result += redact(str.slice(index, match.index)) + match[0]
  21. index = splitChars.lastIndex
  22. }
  23. return result + redact(str.slice(index))
  24. }
  25. // replaces auth info in an array of arguments or in a strings
  26. const redactLog = (arg) => {
  27. if (typeof arg === 'string') {
  28. return splitAndRedact(arg)
  29. } else if (Array.isArray(arg)) {
  30. return arg.map((a) => typeof a === 'string' ? splitAndRedact(a) : a)
  31. }
  32. return arg
  33. }
  34. module.exports = {
  35. redact,
  36. redactLog,
  37. }