server.js 1.3 KB

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