UNPKG

@nestjs/common

Version:

Decorators, pipes, exceptions and utilities for NestJS applications: @Controller(), @Injectable(), @Body(), ValidationPipe, HttpException and more.

322 lines (321 loc) • 13.1 kB
export const DEFAULT_REDACT_CENSOR = '[REDACTED]'; const CIRCULAR = '[Circular]'; /** * Creates a function that masks properties of logged values. * * - A path without dots (`password`) matches a property with that name at any * depth. * - A dotted path (`user.password`) matches when the last keys leading to a * property are those keys, at any depth. Array indices are not keys, so * `users.password` also matches `{ users: [{ password }] }`. * - Keys are compared case-insensitively. * * Plain objects, arrays, class instances, errors (including `cause`, * `AggregateError#errors` and the `error` and `suppressed` of a * `SuppressedError`), `Map`s, `Set`s, `Headers`, `URLSearchParams`, * `FormData` and `URL`s (their username, password and search params) are * traversed. * Only the objects on the way to a redacted property are copied; the rest is * returned as is, and the input is never mutated. A circular reference is * replaced with `"[Circular]"` (so the objects on the cycle are copied too). An * object that is referenced several times is traversed (and copied) once for * all the references a dotted path can't tell apart. If the value can't be * traversed (for example, a getter throws), the whole value is replaced with * the censor. * * @returns `undefined` when there is nothing to redact. */ export function createRedactor(paths, censor = DEFAULT_REDACT_CENSOR) { const keys = new Set(); const dottedPaths = []; for (const path of paths) { const segments = path .split('.') .map(segment => segment.trim().toLowerCase()) .filter(segment => segment.length > 0); if (segments.length === 1) { keys.add(segments[0]); } else if (segments.length > 1) { dottedPaths.push(segments); } } if (keys.size === 0 && dottedPaths.length === 0) { return undefined; } // How many of the keys leading to an object the dotted paths can look at. const contextLength = Math.max(0, ...dottedPaths.map(segments => segments.length - 1)); // The keys that a dotted path compares with the keys leading to a // property. Any other key is never equal to one of them, so it is kept as // "" (which is never a segment): the cache keys built from the path are // then made of configured keys only, however long the keys of the logged // value are. const parentSegments = new Set(dottedPaths.flatMap(segments => segments.slice(0, -1))); return (value) => { // Lower-cased keys from the root to the value being visited, or "" for a // key that no dotted path goes through. const path = []; // Objects on that path, to detect circular references. const ancestors = []; // What each visited object was replaced with, by the last keys leading to // it (a dotted path can match under some keys and not under others). // Otherwise, an object referenced many times would be traversed, and // copied, once per reference. const visited = new Map(); const isRedacted = (key) => { if (keys.has(key)) { return true; } return dottedPaths.some(segments => { const last = segments.length - 1; if (segments[last] !== key || last > path.length) { return false; } for (let i = 1; i <= last; i++) { if (segments[last - i] !== path[path.length - i]) { return false; } } return true; }); }; // Each call starts with a fresh "path" and "ancestors", so an exception // (caught below) doesn't need to restore them. const visitProperty = (key, propertyValue) => { const normalizedKey = key.toLowerCase(); if (isRedacted(normalizedKey)) { return censor; } if (typeof propertyValue !== 'object' || propertyValue === null) { return propertyValue; } path.push(parentSegments.has(normalizedKey) ? normalizedKey : ''); const redacted = visit(propertyValue); path.pop(); return redacted; }; const visit = (current) => { if (typeof current !== 'object' || current === null) { return current; } if (ancestors.includes(current)) { return CIRCULAR; } const context = contextLength > 0 ? JSON.stringify(path.slice(-contextLength)) : ''; let results = visited.get(context); if (!results) { results = new Map(); visited.set(context, results); } if (results.has(current)) { return results.get(current); } let redacted; ancestors.push(current); if (Array.isArray(current)) { redacted = redactArray(current); } else if (Object.getPrototypeOf(current) === Object.prototype) { redacted = redactObject(current); } else if (current instanceof Map) { redacted = redactMap(current); } else if (current instanceof Set) { redacted = redactSet(current); } else if (current instanceof URL) { redacted = redactUrl(current); } else if (isOpaque(current)) { redacted = current; } else if (getEntryListType(current)) { redacted = redactEntryList(current); } else { redacted = redactObject(current); } ancestors.pop(); results.set(current, redacted); return redacted; }; const redactArray = (array) => { let copy; for (const index of Object.keys(array)) { const item = array[index]; const redacted = visit(item); if (!Object.is(redacted, item)) { copy ??= Object.assign(new Array(array.length), array); copy[index] = redacted; } } return copy ?? array; }; const redactMap = (map) => { let changed = false; const entries = []; for (const [key, entryValue] of map) { const redactedKey = typeof key === 'string' ? key : visit(key); const redactedValue = typeof key === 'string' ? visitProperty(key, entryValue) : visit(entryValue); changed ||= !Object.is(redactedKey, key) || !Object.is(redactedValue, entryValue); entries.push([redactedKey, redactedValue]); } return changed ? new Map(entries) : map; }; const redactSet = (set) => { let changed = false; const values = []; for (const setValue of set) { const redacted = visit(setValue); changed ||= !Object.is(redacted, setValue); values.push(redacted); } return changed ? new Set(values) : set; }; const redactEntryList = (list) => { let changed = false; const entries = []; for (const [key, entryValue] of list) { const redactedValue = visitProperty(key, entryValue); changed ||= !Object.is(redactedValue, entryValue); entries.push([key, redactedValue]); } if (!changed) { return list; } const EntryListType = getEntryListType(list); const copy = new EntryListType(); try { for (const [key, entryValue] of entries) { // A file of a FormData keeps its name, as it is a File. copy.append(key, entryValue); } } catch { // `Headers` only takes Latin-1 values, which the censor may not be // ("••••"), so the entries are printed as a `Map` instead return new Map(entries); } return copy; }; // A URL holds its parts in internal slots, as the entry lists do, so a // copy is built from its href with the redacted parts set again (and // percent-encoded by the URL, as any other text would be). const redactUrl = (url) => { const credentials = ['username', 'password'].filter(key => url[key] !== '' && visitProperty(key, url[key]) !== url[key]); const searchParams = visitProperty('searchParams', url.searchParams); if (credentials.length === 0 && searchParams === url.searchParams) { return url; } const copy = new URL(url.href); for (const key of credentials) { copy[key] = censor; } if (searchParams !== url.searchParams) { copy.search = searchParams.toString(); } return copy; }; const redactObject = (object) => { const source = object; const keysToVisit = Object.keys(source); if (object instanceof Error) { // Non-enumerable, but part of the logged error ("error" and // "suppressed" are those of a SuppressedError). for (const key of ['cause', 'errors', 'error', 'suppressed']) { if (Object.prototype.hasOwnProperty.call(object, key) && !keysToVisit.includes(key)) { keysToVisit.push(key); } } } let changes; for (const key of keysToVisit) { const original = source[key]; const redacted = visitProperty(key, original); if (!Object.is(redacted, original)) { changes ??= new Map(); changes.set(key, redacted); } } if (!changes) { return object; } if (Object.getPrototypeOf(object) === Object.prototype) { const copy = { ...source }; for (const [key, redacted] of changes) { if (key === '__proto__') { // An assignment would call the "__proto__" setter. Object.defineProperty(copy, key, { value: redacted, enumerable: true, writable: true, configurable: true, }); } else { copy[key] = redacted; } } return copy; } // Keeps the prototype and the other properties (including the // non-enumerable "message" and "stack" of errors). const descriptors = Object.getOwnPropertyDescriptors(object); if (object instanceof Error && descriptors.stack?.get) { // V8 may define "stack" as an accessor that only works on the // original error. descriptors.stack = { value: object.stack, enumerable: descriptors.stack.enumerable, writable: true, configurable: true, }; } for (const [key, redacted] of changes) { descriptors[key] = { value: redacted, enumerable: descriptors[key].enumerable, writable: true, configurable: true, }; } return Object.create(Object.getPrototypeOf(object), descriptors); }; try { return visit(value); } catch { return censor; } }; } /** * The classes that hold their entries in internal slots rather than in * properties, so that a copy must be built through their API. They are * printed with their entries, as `Map`s are. */ const ENTRY_LIST_TYPES = [ Headers, URLSearchParams, FormData, ]; function getEntryListType(value) { return ENTRY_LIST_TYPES.find(type => value instanceof type); } /** * Objects whose content isn't made of properties worth traversing. */ function isOpaque(value) { return (value instanceof Date || value instanceof RegExp || value instanceof Promise || value instanceof WeakMap || value instanceof WeakSet || value instanceof ArrayBuffer || ArrayBuffer.isView(value)); }