bump package version to 3.0.3
[squeep-logger-json-console] / lib / json-replacers.js
1 'use strict';
2
3 /**
4 * Here are some replacers for rendering peculiar entities as JSON suitable for logging.
5 */
6
7 const http = require('node:http');
8
9 /**
10 * Convert any Error to a plain Object.
11 * @param {String} _key
12 * @param {*} value
13 * @returns {Object}
14 */
15 function replacerError(_key, value) {
16 if (value instanceof Error) {
17 const newValue = {};
18 Object.getOwnPropertyNames(value).forEach((propertyName) => newValue[propertyName] = value[propertyName]); // eslint-disable-line security/detect-object-injection
19 value = newValue;
20 }
21 return value;
22 }
23
24
25 /**
26 * Convert any BigInt type to a String.
27 * @param {String} _key
28 * @param {*} value
29 * @returns {String}
30 */
31 function replacerBigInt(_key, value) {
32 if (typeof value === 'bigint') {
33 value = value.toString();
34 }
35 return value;
36 }
37
38
39 /**
40 * Convert any IncomingMessage to a subset Object.
41 * Also sanitizes any Authorization header. We do this here rather than
42 * in sanitization stage so that we do not have to rely on a set path to
43 * this object.
44 * @param {String} _key
45 * @param {*} value
46 * @returns {Object}
47 */
48 function replacerHttpIncomingMessage(_key, value) {
49 if (value instanceof http.IncomingMessage) {
50 const newValue = {};
51 [
52 'method',
53 'url',
54 'httpVersion',
55 'headers',
56 'trailers',
57 ].forEach((property) => newValue[property] = value[property]); // eslint-disable-line security/detect-object-injection
58
59 if (newValue.headers && 'authorization' in newValue.headers) {
60 const authHeader = newValue.headers.authorization;
61 const spaceIndex = authHeader.indexOf(' ');
62 // This blurs entire auth string if no space found, because -1 from indexOf.
63 const blurredAuthHeader = authHeader.slice(0, spaceIndex + 1) + '*'.repeat(authHeader.length - (spaceIndex + 1));
64 // New headers object, as we change it.
65 newValue.headers = {
66 ...newValue.headers,
67 authorization: blurredAuthHeader,
68 };
69 }
70 value = newValue;
71 }
72 return value;
73 }
74
75
76 /**
77 * Convert any ServerResponse or OutgoingMessage to a subset Object.
78 * @param {String} _key
79 * @param {*} value
80 * @returns {Object}
81 */
82 function replacerHttpServerResponse(_key, value) {
83 if (value instanceof http.OutgoingMessage || value instanceof http.ServerResponse) {
84 const newValue = {};
85 [
86 'statusCode',
87 'statusMessage',
88 ].forEach((property) => newValue[property] = value[property]); // eslint-disable-line security/detect-object-injection
89 newValue.headers = value.getHeaders();
90 value = newValue;
91 }
92 return value;
93 }
94
95
96 module.exports = {
97 replacerBigInt,
98 replacerError,
99 replacerHttpIncomingMessage,
100 replacerHttpServerResponse,
101 };