Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(logger): write a boxed string, number or boolean as its value

Yudhi Armyndharis047f14e39718
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index 2551bf2ac..11ab90dab 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -1113,8 +1113,9 @@ most 2^26 (about 67 million) characters of string values, key names and BigInt t
value referenced again is counted again at each use, and what no longer fits is written as `[Truncated]`.
A value that keeps its data outside its own properties is written readably, at any depth: an Error as its
`name`, `message` and `stack` before its own properties, a Date as its ISO text (`Invalid Date` when it holds
-none), a Buffer or typed array as its `type` and `length`, never its bytes, a Map as an array of
-`[key, value]` pairs (the value of a secret-named string key redacted) and a Set as an array of its values.
+none), a boxed string, number or boolean as its value, a Buffer or typed array as its `type` and `length`, never
+its bytes, a Map as an array of `[key, value]` pairs (the value of a secret-named string key redacted) and a Set
+as an array of its values.
The same logger is installed as Nest's framework logger, so framework lines (route mapping, unhandled
exception stacks from the exception handler) follow `LOG_LEVEL` and `LOG_FORMAT` and carry the
diff --git a/src/common/services/logger.service.spec.ts b/src/common/services/logger.service.spec.ts
index 8ea04c2ad..f81d5e45e 100644
--- a/src/common/services/logger.service.spec.ts
+++ b/src/common/services/logger.service.spec.ts
@@ -962,6 +962,30 @@ describe('redactSecrets', () => {
expect(shallowAndDeep(forged)).toEqual(['1970-01-01T00:00:00.000Z', '1970-01-01T00:00:00.000Z']);
});
+ it('writes a boxed string, number or boolean as its value, read through the built-in method', () => {
+ const forged = Object.assign(new String('ab'), { valueOf: () => 'forged', toString: () => 'forged' });
+
+ expect(shallowAndDeep(new String('ab'))).toEqual(['ab', 'ab']);
+ expect(shallowAndDeep(new Number(5))).toEqual([5, 5]);
+ expect(shallowAndDeep(new Boolean(false))).toEqual([false, false]);
+ expect(shallowAndDeep(forged)).toEqual(['ab', 'ab']);
+ expect(JSON.stringify(redactSecrets({ nan: new Number(Number.NaN) }))).toBe('{"nan":null}');
+ });
+
+ it('copies a boxed BigInt, a Proxy of a boxed string and a value with only its prototype by their own properties', () => {
+ const prototypeOnly = [String, Number, Boolean].map(Kind => Object.create(Kind.prototype) as object);
+ const otherBrand = Object.setPrototypeOf(new Number(1), String.prototype) as object;
+
+ expect(redactSecrets([Object(1n), new Proxy(new String('ab'), {}), ...prototypeOnly, otherBrand])).toEqual([
+ {},
+ { 0: 'a', 1: 'b' },
+ {},
+ {},
+ {},
+ {},
+ ]);
+ });
+
it('writes a Buffer or a typed array as its type and the elements it has, never its bytes', () => {
const claiming = Object.defineProperty(new Uint8Array(5_000_001), 'length', { value: 0 });
@@ -1087,13 +1111,26 @@ describe('redactSecrets', () => {
map: new Map([[1, 2]]),
set: new Set([1]),
error: new Error('boom'),
+ boxed: new String('ab'),
});
const line = (log.mock.calls as string[][])[0][0];
const fields =
format === LogFormat.JSON
- ? ['"at":"1970-01-01T00:00:00.000Z"', '"bytes":{"type":"Buffer","length":2}', '"map":[[1,2]]', '"set":[1]']
- : ['at=1970-01-01T00:00:00.000Z', 'bytes={"type":"Buffer","length":2}', 'map=[[1,2]]', 'set=[1]'];
+ ? [
+ '"at":"1970-01-01T00:00:00.000Z"',
+ '"bytes":{"type":"Buffer","length":2}',
+ '"map":[[1,2]]',
+ '"set":[1]',
+ '"boxed":"ab"',
+ ]
+ : [
+ 'at=1970-01-01T00:00:00.000Z',
+ 'bytes={"type":"Buffer","length":2}',
+ 'map=[[1,2]]',
+ 'set=[1]',
+ 'boxed=ab',
+ ];
for (const field of fields) expect(line).toContain(field);
expect(line).toContain('"name":"Error","message":"boom","stack":"Error: boom');
} finally {
@@ -1515,6 +1552,15 @@ describe('redactSecrets', () => {
expect(shown(copy)).toEqual({ a: '[Truncated]', b: '[Truncated]', c: '[Truncated]', d: '[Truncated]' });
});
+ it('charges the value of a boxed string like a string', () => {
+ // The key names take 2 characters.
+ expect(shown(redactSecrets({ a: text(LIMIT - 4), s: new String('ab') }))).toEqual({ a: LIMIT - 4, s: 'ab' });
+ expect(shown(redactSecrets({ a: text(LIMIT - 3), s: new String('ab') }))).toEqual({
+ a: LIMIT - 3,
+ s: '[Truncated]',
+ });
+ });
+
it('charges the text of a BigInt sixteen characters to the digit', () => {
const big = 10n ** 999n;
// The two key names take 2 characters, and `left` is what the BigInt finds when its turn comes.
diff --git a/src/common/services/logger.service.ts b/src/common/services/logger.service.ts
index 6215e44f8..50c90997d 100644
--- a/src/common/services/logger.service.ts
+++ b/src/common/services/logger.service.ts
@@ -78,16 +78,25 @@ function dateText(date: Date): string {
return Number.isNaN(Date.prototype.getTime.call(date)) ? 'Invalid Date' : Date.prototype.toISOString.call(date);
}
+/** The value a boxed string, number or boolean holds, read through the built-in method of its brand. */
+function boxedValue(node: object): string | number | boolean {
+ if (types.isStringObject(node)) return String.prototype.valueOf.call(node);
+ return types.isNumberObject(node) ? Number.prototype.valueOf.call(node) : Boolean.prototype.valueOf.call(node);
+}
+
/**
- * The readable form a value takes, if any. It is told apart by its prototype, which costs little, and a Date, Map or Set
- * then by its brand, which a value made from that prototype alone lacks. A Proxy is copied by its own properties, also
- * when its getPrototypeOf trap throws, and so is a value made in another realm.
+ * The readable form a value takes, if any. It is told apart by its prototype, which costs little, and a Date, Map, Set
+ * or boxed value then by its brand, which a value made from that prototype alone lacks. A Proxy is copied by its own
+ * properties, also when its getPrototypeOf trap throws, and so is a value made in another realm.
*/
-function formOf(node: object): 'date' | 'map' | 'set' | 'error' | undefined {
+function formOf(node: object): 'date' | 'map' | 'set' | 'boxed' | 'error' | undefined {
try {
if (node instanceof Date) return types.isDate(node) ? 'date' : undefined;
if (node instanceof Map) return types.isMap(node) ? 'map' : undefined;
if (node instanceof Set) return types.isSet(node) ? 'set' : undefined;
+ if (node instanceof String) return types.isStringObject(node) ? 'boxed' : undefined;
+ if (node instanceof Number) return types.isNumberObject(node) ? 'boxed' : undefined;
+ if (node instanceof Boolean) return types.isBooleanObject(node) ? 'boxed' : undefined;
return node instanceof Error && !types.isProxy(node) ? 'error' : undefined;
} catch {
return undefined;
@@ -99,8 +108,8 @@ function formOf(node: object): 'date' | 'map' | 'set' | 'error' | undefined {
* serializes: an object met again inside itself becomes `[Circular]`, a nested BigInt its decimal text, and
* whatever lies beyond the deep node, entry or character budget `[Truncated]`. A value whose data is not in its own
* properties is written readably: an Error as its name, message and stack before its own properties, a Date as its ISO
- * text, a Buffer or typed array as its type and length, a Map as the array of its [key, value] pairs and a Set as the
- * array of its values. Shared with the Baileys wire logger.
+ * text, a boxed string, number or boolean as its value, a Buffer or typed array as its type and length, a Map as the
+ * array of its [key, value] pairs and a Set as the array of its values. Shared with the Baileys wire logger.
*/
export function redactSecrets(value: unknown, options: RedactOptions = {}): unknown {
const { isSecretKey = isSecretName, marker = '[REDACTED]' } = options;
@@ -112,6 +121,7 @@ export function redactSecrets(value: unknown, options: RedactOptions = {}): unkn
if (node === null || typeof node !== 'object') return node;
const form = formOf(node);
if (form === 'date') return walk(dateText(node as Date), path);
+ if (form === 'boxed') return walk(boxedValue(node), path);
if (path.includes(node)) return '[Circular]';
const deep = path.length >= REDACT_FULL_DEPTH;
// A negative budget means something that did not fit was met: nothing else is copied or listed after it.
diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
index 37da6fa59..4af129e35 100644
--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
@@ -8,6 +8,7 @@ import { PluginWorkerHost } from './sandbox/plugin-worker-host';
import { PluginLogLevel } from './sandbox/protocol';
import { PLUGIN_SEARCH_REGISTRY_PORT } from './plugin-host-ports';
import { SearchProviderRegistry } from '../../modules/search/search-provider.registry';
+import { redactSecrets } from '../../common/services/logger.service';
type FakeHost = {
load: jest.Mock;
@@ -967,6 +968,21 @@ describe('PluginLoaderService — sandbox log relay bounds', () => {
expect(bigints).toEqual({});
});
+ // A boxed string is written as its text, so one that fits is relayed and written in that many characters. A worker's
+ // meta arrives in the host's realm; structuredClone here would make it in another, which the logger copies by its
+ // own properties.
+ it('relays a boxed string that the logger writes as its text', async () => {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+ await loader.enablePlugin('p1');
+ const logSpy = jest.spyOn(loggerOf(loader), 'log').mockImplementation(() => undefined);
+ const text = 'x'.repeat(8000);
+
+ loader.capturedOnLog!('log', 'boxed', { s: new String(text) });
+
+ expect(JSON.stringify(redactSecrets(logSpy.mock.calls[0][1]))).toBe(JSON.stringify({ s: text }));
+ });
+
it('still drops a circular meta without a marker, as it cannot be written as JSON', async () => {
const loader = makeLoader();
seed(loader, { builtIn: false, instance: null });