minor internal refactors
[squeep-authentication-module] / lib / common.js
1 'use strict';
2
3 const { common } = require('@squeep/api-dingus');
4
5
6 /**
7 * Recursively freeze an object.
8 * @param {object} o object to freeze
9 * @returns {object} frozen object
10 */
11 const freezeDeep = (o) => {
12 Object.freeze(o);
13 Object.getOwnPropertyNames(o).forEach((prop) => {
14 if (Object.hasOwn(o, prop)
15 && ['object', 'function'].includes(typeof o[prop]) // eslint-disable-line security/detect-object-injection
16 && !Object.isFrozen(o[prop])) { // eslint-disable-line security/detect-object-injection
17 return freezeDeep(o[prop]); // eslint-disable-line security/detect-object-injection
18 }
19 });
20 return o;
21 };
22
23 /**
24 * Return a new object duplicating `o`, without the properties specified.
25 * @param {object} o source object
26 * @param {string[]} props list of property names to omit
27 * @returns {object} pruned object
28 */
29 const omit = (o, props) => {
30 return Object.fromEntries(Object.entries(o).filter(([k]) => !props.includes(k)));
31 };
32
33 /**
34 * Helper to log mystery-box statistics.
35 * @param {object} logger logger
36 * @param {Function} logger.debug log debug
37 * @param {string} scope scope
38 * @returns {Function} stats log decorator
39 */
40 const mysteryBoxLogger = (logger, scope) => {
41 return (s) => {
42 logger.debug(scope, `${s.packageName}@${s.packageVersion}:${s.method}`, omit(s, [
43 'packageName',
44 'packageVersion',
45 'method',
46 ]));
47 };
48 };
49
50 /**
51 * Hide sensitive part of an Authorization header.
52 * @param {string} authHeader header value
53 * @returns {string} scrubbed header value
54 */
55 const obscureAuthorizationHeader = (authHeader) => {
56 if (!authHeader) {
57 return authHeader;
58 }
59 const space = authHeader.indexOf(' ');
60 // This blurs entire string if no space found, because -1.
61 return authHeader.slice(0, space + 1) + '*'.repeat(authHeader.length - (space + 1));
62 };
63
64 module.exports = Object.assign(Object.create(common), {
65 freezeDeep,
66 mysteryBoxLogger,
67 obscureAuthorizationHeader,
68 omit,
69 });