server.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const {
  2. AUTH_HEADER,
  3. JSON_WEB_TOKEN,
  4. NPM_SECRET,
  5. DEEP_HEADER_AUTHORIZATION,
  6. DEEP_HEADER_SET_COOKIE,
  7. REWRITE_REQUEST,
  8. REWRITE_RESPONSE,
  9. } = require('./matchers')
  10. const {
  11. redactUrlMatcher,
  12. redactUrlPasswordMatcher,
  13. redactMatchers,
  14. } = require('./utils')
  15. const { serializeError } = require('./error')
  16. const { deepMap } = require('./deep-map')
  17. const _redact = redactMatchers(
  18. NPM_SECRET,
  19. AUTH_HEADER,
  20. JSON_WEB_TOKEN,
  21. DEEP_HEADER_AUTHORIZATION,
  22. DEEP_HEADER_SET_COOKIE,
  23. REWRITE_REQUEST,
  24. REWRITE_RESPONSE,
  25. redactUrlMatcher(
  26. redactUrlPasswordMatcher()
  27. )
  28. )
  29. const redact = (input) => deepMap(input, (value, path) => _redact(value, { path }))
  30. /** takes an error returns new error keeping some custom properties */
  31. function redactError (input) {
  32. const { message, ...data } = serializeError(input)
  33. const output = new Error(redact(message))
  34. return Object.assign(output, redact(data))
  35. }
  36. /** runs a function within try / catch and throws error wrapped in redactError */
  37. function redactThrow (func) {
  38. if (typeof func !== 'function') {
  39. throw new Error('redactThrow expects a function')
  40. }
  41. return async (...args) => {
  42. try {
  43. return await func(...args)
  44. } catch (error) {
  45. throw redactError(error)
  46. }
  47. }
  48. }
  49. module.exports = { redact, redactError, redactThrow }