Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🙈 fix: Mask Emails and Drop Personal Identifiers From Logs (#17048)

Marco Berettad0e253043a14
diff --git a/.env.example b/.env.example
index 0c57c87bff..adc737f30b 100644
--- a/.env.example
+++ b/.env.example
@@ -199,6 +199,11 @@ CONSOLE_JSON=false
# Default: 255
# CONSOLE_JSON_STRING_LENGTH=255
+# The number of values (objects, and strings weighted by length) one log record may redact
+# before the rest is replaced, so very wide payloads cannot stall logging.
+# Default: 5000
+# LOG_REDACTION_MAX_NODES=5000
+
#===============#
# Debug Logging #
#===============#
diff --git a/api/server/controllers/AuthController.js b/api/server/controllers/AuthController.js
index c814548472..1238190f15 100644
--- a/api/server/controllers/AuthController.js
+++ b/api/server/controllers/AuthController.js
@@ -471,9 +471,7 @@ const refreshController = async (req, res) => {
openidId: claims.sub,
...(openidIssuer ? { openidIssuer } : {}),
});
- logger.info(
- `[refreshController] Updated user ${user.email} openidId (${reason}): ${user.openidId ?? 'null'} -> ${claims.sub}`,
- );
+ logger.info(`[refreshController] Updated user ${user._id} openidId (${reason})`);
}
if (
diff --git a/api/server/middleware/abortMiddleware.js b/api/server/middleware/abortMiddleware.js
index 52fd6b2857..1dfd994d18 100644
--- a/api/server/middleware/abortMiddleware.js
+++ b/api/server/middleware/abortMiddleware.js
@@ -133,9 +133,7 @@ async function abortMessage(req, res) {
responseMessage,
};
- logger.debug(
- `[abortMessage] ID: ${userId} | ${req.user.email} | Aborted request: ${conversationId}`,
- );
+ logger.debug(`[abortMessage] ID: ${userId} | Aborted request: ${conversationId}`);
if (res.headersSent) {
return sendEvent(res, finalEvent);
diff --git a/api/server/middleware/logHeaders.js b/api/server/middleware/logHeaders.js
index 398542747a..2a9c982813 100644
--- a/api/server/middleware/logHeaders.js
+++ b/api/server/middleware/logHeaders.js
@@ -1,4 +1,5 @@
const { logger } = require('@librechat/data-schemas');
+const { getForwardedHeaders } = require('@librechat/api');
/**
* Middleware to log Forwarded Headers
@@ -10,16 +11,7 @@ const { logger } = require('@librechat/data-schemas');
*/
const logHeaders = (req, res, next) => {
try {
- const forwardedHeaders = {};
- if (req.headers['x-forwarded-for']) {
- forwardedHeaders['x-forwarded-for'] = req.headers['x-forwarded-for'];
- }
- if (req.headers['x-forwarded-host']) {
- forwardedHeaders['x-forwarded-host'] = req.headers['x-forwarded-host'];
- }
- if (req.headers['x-forwarded-proto']) {
- forwardedHeaders['x-forwarded-proto'] = req.headers['x-forwarded-proto'];
- }
+ const forwardedHeaders = getForwardedHeaders(req.headers);
if (Object.keys(forwardedHeaders).length > 0) {
logger.debug('X-Forwarded headers detected in OAuth request:', forwardedHeaders);
}
diff --git a/api/server/services/OboTokenService.js b/api/server/services/OboTokenService.js
index fc1a7a45d9..c3327a743a 100644
--- a/api/server/services/OboTokenService.js
+++ b/api/server/services/OboTokenService.js
@@ -5,6 +5,7 @@ const { CacheKeys } = require('librechat-data-provider');
const {
createOpenIDOboIdentityTuple,
getSkewedTokenCacheTtlMs,
+ getUserLogId,
getTokenExpiresAtMs,
hasUsableTokenExpiry,
normalizeExpiresIn,
@@ -94,6 +95,7 @@ async function delay(ms) {
}
async function performOboExchange({ user, accessToken, scopes, config, tokensCache, cacheKey }) {
+ const userLogId = getUserLogId(user);
const requestGrant = async () =>
client.genericGrantRequest(config, 'urn:ietf:params:oauth:grant-type:jwt-bearer', {
scope: scopes,
@@ -111,7 +113,7 @@ async function performOboExchange({ user, accessToken, scopes, config, tokensCac
}
logger.warn(
- `[OboTokenService] Transient OBO exchange failure for user: ${user.openidId}, retrying once`,
+ `[OboTokenService] Transient OBO exchange failure for user: ${userLogId}, retrying once`,
error,
);
await delay(OBO_RETRY_DELAY_MS);
@@ -141,7 +143,7 @@ async function performOboExchange({ user, accessToken, scopes, config, tokensCac
await tokensCache.set(cacheKey, tokenResponse, getSkewedTokenCacheTtlMs(expiresAt, now));
logger.debug(
- `[OboTokenService] Successfully obtained and cached OBO token for user: ${user.openidId}`,
+ `[OboTokenService] Successfully obtained and cached OBO token for user: ${userLogId}`,
);
return tokenResponse;
}
@@ -168,6 +170,7 @@ async function exchangeOboToken(user, accessToken, scopes, fromCache = true, ide
throw new Error('Access token is required for OBO exchange');
}
+ const userLogId = getUserLogId(user);
if (!scopes) {
throw new Error('Scopes are required for OBO exchange');
}
@@ -192,23 +195,23 @@ async function exchangeOboToken(user, accessToken, scopes, fromCache = true, ide
const cachedToken = await tokensCache.get(cacheKey);
if (cachedToken) {
if (hasUsableTokenExpiry(cachedToken.expires_at)) {
- logger.debug(`[OboTokenService] Using cached token for user: ${user.openidId}`);
+ logger.debug(`[OboTokenService] Using cached token for user: ${userLogId}`);
return cachedToken;
}
logger.debug(
- `[OboTokenService] Ignoring cached OBO token without usable expiry for user: ${user.openidId}`,
+ `[OboTokenService] Ignoring cached OBO token without usable expiry for user: ${userLogId}`,
);
}
const inFlight = inFlightExchanges.get(cacheKey);
if (inFlight) {
- logger.debug(`[OboTokenService] Joining in-flight OBO exchange for user: ${user.openidId}`);
+ logger.debug(`[OboTokenService] Joining in-flight OBO exchange for user: ${userLogId}`);
return inFlight;
}
}
logger.debug(
- `[OboTokenService] Requesting new OBO token for user: ${user.openidId}, scopes: ${scopes}`,
+ `[OboTokenService] Requesting new OBO token for user: ${userLogId}, scopes: ${scopes}`,
);
const exchangePromise = performOboExchange({
diff --git a/api/strategies/ldapStrategy.js b/api/strategies/ldapStrategy.js
index 64bc776bf9..bf3ee10467 100644
--- a/api/strategies/ldapStrategy.js
+++ b/api/strategies/ldapStrategy.js
@@ -130,9 +130,7 @@ const ldapLogin = new LdapStrategy(ldapOptions, async (userinfo, done) => {
// instead of AUTH_FAILED — both deny access.
const baseConfig = await getAppConfig({ baseOnly: true });
if (!isEmailDomainAllowed(mail, baseConfig?.registration?.allowedDomains)) {
- logger.error(
- `[LDAP Strategy] Authentication blocked - email domain not allowed [Email: ${mail}]`,
- );
+ logger.error(`[LDAP Strategy] Authentication blocked - email domain not allowed`);
return done(null, false, { message: 'Email domain not allowed' });
}
@@ -146,9 +144,7 @@ const ldapLogin = new LdapStrategy(ldapOptions, async (userinfo, done) => {
: baseConfig;
if (!isEmailDomainAllowed(mail, appConfig?.registration?.allowedDomains)) {
- logger.error(
- `[LDAP Strategy] Authentication blocked - email domain not allowed [Email: ${mail}]`,
- );
+ logger.error(`[LDAP Strategy] Authentication blocked - email domain not allowed`);
return done(null, false, { message: 'Email domain not allowed' });
}
diff --git a/api/strategies/openidStrategy.js b/api/strategies/openidStrategy.js
index 02c09f11b0..1d56aafb93 100644
--- a/api/strategies/openidStrategy.js
+++ b/api/strategies/openidStrategy.js
@@ -749,11 +749,11 @@ async function processOpenIDAuth(tokenset, existingUsersOnly = false) {
if (adminRoles && (adminRoles === true || adminRoleValues.includes(adminRole))) {
user.role = SystemRoles.ADMIN;
adminRoleGranted = true;
- logger.info(`[openidStrategy] User ${username} is an admin based on role: ${adminRole}`);
+ logger.info(`[openidStrategy] User ${user._id} is an admin based on role: ${adminRole}`);
} else if (user.role === SystemRoles.ADMIN) {
user.role = SystemRoles.USER;
logger.info(
- `[openidStrategy] User ${username} demoted from admin - role no longer present in token`,
+ `[openidStrategy] User ${user._id} demoted from admin - role no longer present in token`,
);
}
}
@@ -829,17 +829,7 @@ async function processOpenIDAuth(tokenset, existingUsersOnly = false) {
tenantId: user.tenantId,
});
- logger.info(
- `[openidStrategy] login success openidId: ${user.openidId} | email: ${user.email} | username: ${user.username} `,
- {
- user: {
- openidId: user.openidId,
- username: user.username,
- email: user.email,
- name: user.name,
- },
- },
- );
+ logger.info(`[openidStrategy] login success for user: ${user._id}`);
return {
...user,
diff --git a/e2e/specs/mock/scenarios/log-email-masking.spec.ts b/e2e/specs/mock/scenarios/log-email-masking.spec.ts
new file mode 100644
index 0000000000..e2e59c5f10
--- /dev/null
+++ b/e2e/specs/mock/scenarios/log-email-masking.spec.ts
@@ -0,0 +1,49 @@
+import { resolve } from 'node:path';
+import { expect, test } from '@playwright/test';
+import { run, repoRoot, inOneProject } from './lint.helpers';
+
+/**
+ * The shared winston logger masks email addresses before any transport writes
+ * them. The probe logs through the real logger and captures what reaches
+ * stdout, which is what the log sink retains.
+ */
+
+const PROBE = `
+process.env.DEBUG_CONSOLE = 'true';
+process.env.CONSOLE_JSON = 'false';
+const { logger } = require('@librechat/data-schemas');
+const chunks = [];
+const write = process.stdout.write.bind(process.stdout);
+process.stdout.write = (chunk) => { chunks.push(String(chunk)); return true; };
+logger.error('login failed for [email protected]');
+logger.error('login failed for josé.müller@exämple.de and 用户@例子.中国');
+setTimeout(() => {
+ process.stdout.write = write;
+ process.stdout.write('RESULT' + JSON.stringify(chunks.join('')));
+ process.exit(0);
+}, 500);
+`;
+
+function probeOutput(): string {
+ const result = run('node', ['-e', PROBE], { cwd: resolve(repoRoot, 'api') });
+ expect(result.status, result.output).toBe(0);
+ return JSON.parse(result.stdout.slice(result.stdout.indexOf('RESULT') + 'RESULT'.length));
+}
+
+test.describe('email masking in logs', () => {
+ test.beforeEach(() => inOneProject());
+
+ test('an email address in a log message is masked @scenario:log-email-masked-in-message', () => {
+ test.setTimeout(120_000);
+ const output = probeOutput();
+ expect(output).toContain('[REDACTED_EMAIL]');
+ expect(output).not.toContain('[email protected]');
+ });
+
+ test('an email address with non-ASCII characters is masked @scenario:log-unicode-email-masked', () => {
+ test.setTimeout(120_000);
+ const output = probeOutput();
+ expect(output).not.toContain('müller@');
+ expect(output).not.toContain('用户@');
+ });
+});
diff --git a/packages/api/src/auth/googleRefresh.ts b/packages/api/src/auth/googleRefresh.ts
index dac9016858..d2ea438bfb 100644
--- a/packages/api/src/auth/googleRefresh.ts
+++ b/packages/api/src/auth/googleRefresh.ts
@@ -218,7 +218,7 @@ async function resolveAdminUser(
});
if (matches.length > 1) {
logger.error('[admin/oauth/refresh] ambiguous googleId match', {
- googleId,
+ matchCount: matches.length,
tenantId: options.tenantId,
});
throw new AdminRefreshError('USER_ID_MISMATCH', 401, 'Ambiguous identity');
diff --git a/packages/api/src/auth/ldap.ts b/packages/api/src/auth/ldap.ts
index e44a235832..678fd658a5 100644
--- a/packages/api/src/auth/ldap.ts
+++ b/packages/api/src/auth/ldap.ts
@@ -22,7 +22,7 @@ export async function findLdapUser({
}): Promise<LoginUserResolution> {
const user = await findUser({ ldapId });
if (user && user.provider !== 'ldap') {
- logger.info(`[ldapStrategy] User ${user.email} already exists with provider ${user.provider}`);
+ logger.info(`[ldapStrategy] User ${user._id} already exists with provider ${user.provider}`);
return { user: null, error: ErrorTypes.AUTH_FAILED };
}
return { user, error: null };
diff --git a/packages/api/src/middleware/error.spec.ts b/packages/api/src/middleware/error.spec.ts
index 59e63d1009..135ff96ea8 100644
--- a/packages/api/src/middleware/error.spec.ts
+++ b/packages/api/src/middleware/error.spec.ts
@@ -105,8 +105,12 @@ describe('ErrorController', () => {
messages: 'An document with that ["email"] already exists.',
fields: '["email"]',
});
- expect(logger.warn).toHaveBeenCalledWith(
- 'Duplicate key error: E11000 duplicate key error collection: test.users index: email_1 dup key: { email: "[email protected]" }',
+ expect(logger.warn).toHaveBeenCalledWith('Duplicate key error', {
+ mongoCode: 11000,
+ fields: ['email'],
+ });
+ expect(JSON.stringify((logger.warn as jest.Mock).mock.calls)).not.toContain(
);
});
@@ -127,9 +131,10 @@ describe('ErrorController', () => {
messages: 'An document with that ["email","username"] already exists.',
fields: '["email","username"]',
});
- expect(logger.warn).toHaveBeenCalledWith(
- 'Duplicate key error: E11000 duplicate key error collection: test.users index: email_1 dup key: { email: "[email protected]" }',
- );
+ expect(logger.warn).toHaveBeenCalledWith('Duplicate key error', {
+ mongoCode: 11000,
+ fields: ['email', 'username'],
+ });
});
it('should handle error with code 11000 as string', () => {
diff --git a/packages/api/src/middleware/error.ts b/packages/api/src/middleware/error.ts
index a3868bae7d..2eb21c2c18 100644
--- a/packages/api/src/middleware/error.ts
+++ b/packages/api/src/middleware/error.ts
@@ -7,7 +7,10 @@ import { buildTenantIsolationErrorLogContext } from './auth';
import { OpenIDReauthRequiredError } from '~/utils/oidc';
const handleDuplicateKeyError = (err: MongoServerError, res: Response) => {
- logger.warn('Duplicate key error: ' + (err.errmsg || err.message));
+ logger.warn('Duplicate key error', {
+ mongoCode: err.code,
+ fields: err.keyValue ? Object.keys(err.keyValue) : [],
+ });
const field = err.keyValue ? `${JSON.stringify(Object.keys(err.keyValue))}` : 'unknown';
const code = 409;
res
diff --git a/packages/api/src/middleware/forwarded.spec.ts b/packages/api/src/middleware/forwarded.spec.ts
new file mode 100644
index 0000000000..34ac0923a5
--- /dev/null
+++ b/packages/api/src/middleware/forwarded.spec.ts
@@ -0,0 +1,20 @@
+import { getForwardedHeaders } from './forwarded';
+
+describe('getForwardedHeaders', () => {
+ it('reports the hop count instead of the forwarded-for addresses', () => {
+ const result = getForwardedHeaders({
+ 'x-forwarded-for': '203.0.113.7, 198.51.100.2',
+ 'x-forwarded-host': 'chat.example.com',
+ 'x-forwarded-proto': 'https',
+ });
+ expect(result).toEqual({
+ 'x-forwarded-for-hops': 2,
+ 'x-forwarded-host': 'chat.example.com',
+ 'x-forwarded-proto': 'https',
+ });
+ });
+
+ it('returns nothing when no forwarded header is present', () => {
+ expect(getForwardedHeaders({})).toEqual({});
+ });
+});
diff --git a/packages/api/src/middleware/forwarded.ts b/packages/api/src/middleware/forwarded.ts
new file mode 100644
index 0000000000..b4b916bec5
--- /dev/null
+++ b/packages/api/src/middleware/forwarded.ts
@@ -0,0 +1,22 @@
+import type { IncomingHttpHeaders } from 'http';
+
+/**
+ * Picks the X-Forwarded headers safe to log. The forwarded-for chain holds client addresses, so only
+ * its hop count is reported.
+ */
+export function getForwardedHeaders(headers: IncomingHttpHeaders): Record<string, string | number> {
+ const forwarded: Record<string, string | number> = {};
+ const forwardedFor = headers['x-forwarded-for'];
+ if (forwardedFor) {
+ forwarded['x-forwarded-for-hops'] = String(forwardedFor).split(',').length;
+ }
+ const host = headers['x-forwarded-host'];
+ if (host) {
+ forwarded['x-forwarded-host'] = String(host);
+ }
+ const proto = headers['x-forwarded-proto'];
+ if (proto) {
+ forwarded['x-forwarded-proto'] = String(proto);
+ }
+ return forwarded;
+}
diff --git a/packages/api/src/middleware/index.ts b/packages/api/src/middleware/index.ts
index 4522e83ba4..82b706028f 100644
--- a/packages/api/src/middleware/index.ts
+++ b/packages/api/src/middleware/index.ts
@@ -26,6 +26,7 @@ export * from './modelBoundContent';
export * from './messageFilterPii';
export * from './messageValidation';
export * from './feedback';
+export * from './forwarded';
export * from './generationRetry';
export * from './code';
export * from './management';
diff --git a/packages/api/src/utils/identity.spec.ts b/packages/api/src/utils/identity.spec.ts
index 761489351b..50968eeb10 100644
--- a/packages/api/src/utils/identity.spec.ts
+++ b/packages/api/src/utils/identity.spec.ts
@@ -1,4 +1,5 @@
import {
+ getUserLogId,
createAuthIdentityContext,
createOpenIDOboIdentityTuple,
createOpenIDSessionIdentity,
@@ -146,3 +147,12 @@ describe('auth identity helpers', () => {
).toBe('tenant-a\x1fissuer-a\x1fsub-a');
});
});
+
+describe('getUserLogId', () => {
+ it('prefers _id, falls back to id, and never throws', () => {
+ expect(getUserLogId({ _id: 'a', id: 'b' })).toBe('a');
+ expect(getUserLogId({ id: 'b' })).toBe('b');
+ expect(getUserLogId({})).toBe('unknown');
+ expect(getUserLogId(undefined)).toBe('unknown');
+ });
+});
diff --git a/packages/api/src/utils/identity.ts b/packages/api/src/utils/identity.ts
index f40928b332..e794a262ff 100644
--- a/packages/api/src/utils/identity.ts
+++ b/packages/api/src/utils/identity.ts
@@ -288,3 +288,9 @@ export function createOpenIDOboIdentityTuple({
export function serializeAuthIdentityTuple(tuple: AuthIdentityTuple): string {
return [tuple.tenantId, tuple.openidIssuer, tuple.subject].join(IDENTITY_PART_SEPARATOR);
}
+
+/** Internal user id for log lines, never an email, name or provider subject. */
+export function getUserLogId(user?: Pick<AuthIdentitySource, 'id' | '_id'> | null): string {
+ const id = user?._id ?? user?.id;
+ return id == null ? 'unknown' : String(id);
+}
diff --git a/packages/data-schemas/src/config/parsers.spec.ts b/packages/data-schemas/src/config/parsers.spec.ts
index fcee84d78a..5b94d43c5d 100644
--- a/packages/data-schemas/src/config/parsers.spec.ts
+++ b/packages/data-schemas/src/config/parsers.spec.ts
@@ -1,5 +1,11 @@
import winston from 'winston';
-import { debugTraverse, jsonTruncateFormat, redactFormat, redactMessage } from './parsers';
+import {
+ debugTraverse,
+ jsonTruncateFormat,
+ redactFormat,
+ redactMessage,
+ stripHeavyErrorFields,
+} from './parsers';
const SPLAT_SYMBOL = Symbol.for('splat');
const MESSAGE_SYMBOL = Symbol.for('message');
@@ -59,6 +65,679 @@ describe('redactMessage', () => {
);
});
+ it('masks email addresses in messages', () => {
+ expect(redactMessage('login for [email protected] | ok')).toBe(
+ 'login for [REDACTED_EMAIL] | ok',
+ );
+ expect(redactMessage('[email protected] and [email protected]')).toBe('[REDACTED_EMAIL] and [REDACTED_EMAIL]');
+ expect(redactMessage('user jö[email protected] ok')).toBe('user [REDACTED_EMAIL] ok');
+ expect(redactMessage('user 用户@例子.公司 ok')).toBe('user [REDACTED_EMAIL] ok');
+ expect(redactMessage('user user@bücher.de ok')).toBe('user [REDACTED_EMAIL] ok');
+ expect(redactMessage('a@b and user@localhost')).toBe('a@b and user@localhost');
+ expect(redactMessage('mention @handle and v1.2.3')).toBe('mention @handle and v1.2.3');
+ });
+
+ it('masks the whole token for apostrophes, long local parts and combining-mark domains', () => {
+ expect(redactMessage("mary.jane'[email protected]")).toBe('[REDACTED_EMAIL]');
+ expect(redactMessage(`${'a'.repeat(100)}@example.com ok`)).toBe('[REDACTED_EMAIL] ok');
+ expect(redactMessage('user@उदाहरण.भारत ok')).toBe('[REDACTED_EMAIL] ok');
+ });
+
+ it('masks address-literal domains without eating the closing bracket of a label', () => {
+ expect(redactMessage('user@[192.0.2.1] ok')).toBe('[REDACTED_EMAIL] ok');
+ expect(redactMessage('[Email: [email protected]]')).toBe('[Email: [REDACTED_EMAIL]]');
+ });
+
+ it('does not let a truncated address slip past the matcher', () => {
+ const lead = `${'x '.repeat(4090)}`;
+ const input = `${lead}[email protected] and more`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).not.toContain('janedoe');
+ expect(out).toContain('truncated');
+ });
+
+ it('keeps both entries when a redacted key collides with an unchanged one, and masks object Map keys', () => {
+ const mapInfo = runRedactFormat({
+ level: 'info',
+ message: 'm',
+ [SPLAT_SYMBOL]: [new Map<unknown, unknown>([[{ contact: '[email protected]' }, 'failed']])],
+ });
+ const [mapOut] = mapInfo[SPLAT_SYMBOL] as Map<unknown, unknown>[];
+ expect(JSON.stringify([...mapOut.keys()])).not.toContain('jane');
+
+ const info = runRedactFormat({
+ level: 'info',
+ message: 'm',
+ [SPLAT_SYMBOL]: [{ '[email protected]': 'a', '[REDACTED_EMAIL]': 'b' }],
+ });
+ const out = JSON.stringify(info[SPLAT_SYMBOL]);
+ expect(out).not.toContain('jane');
+ expect(out).toContain('"a"');
+ expect(out).toContain('"b"');
+ });
+
+ it('masks a quoted address whose space sits on the truncation boundary', () => {
+ const input = `${' '.repeat(8187)}"jane doe"@example.com;${'x'.repeat(2000)}`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).not.toMatch(/jane/);
+ });
+
+ it('masks serialized quoted addresses and many colliding keys in linear time', () => {
+ expect(redactMessage(JSON.stringify({ email: '"jane doe"@example.com' }))).not.toMatch(/jane/);
+ const keys = Object.fromEntries(
+ Array.from({ length: 5000 }, (_, index) => [`u${index}@example.com`, index]),
+ );
+ const started = Date.now();
+ const info = runRedactFormat({ level: 'info', message: 'm', ...keys });
+ expect(Date.now() - started).toBeLessThan(1000);
+ expect(JSON.stringify(info)).not.toContain('example.com');
+ });
+
+ it('masks serialized escaped-quote locals and long-scheme credential URLs', () => {
+ expect(redactMessage(JSON.stringify({ email: '"jane\\"doe"@example.com' }))).not.toMatch(
+ /jane/,
+ );
+ expect(
+ redactMessage('company-specific-connection-protocol://alice:s3cr3t@localhost'),
+ ).not.toContain('s3cr3t');
+ });
+
+ it('redacts every secret shape in long strings, inside and straddling the cap', () => {
+ const secrets = [
+ 'sk-secretcanary123',
+ 'Bearer secretcanary123',
+ 'api_key=secretcanary123',
+ 'Authorization: secretcanary123',
+ 'Cookie: sid=secretcanary123',
+ 'postgresql://user:[email protected]/app',
+ 'eyJsecretcanary.eyJsecretcanary.secretcanary',
+ ];
+ for (const secret of secrets) {
+ for (const offset of [0, 4000, 8100, 8192 - secret.length / 2]) {
+ const input = `${'x '.repeat(Math.floor(offset / 2))}${secret} ${'y '.repeat(3000)}`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).not.toContain('secretcanary');
+ }
+ }
+ });
+
+ it('masks one-character final labels, direct Error stacks and tokens crossing the window edge', () => {
+ expect(redactMessage('[email protected] ok')).toBe('[REDACTED_EMAIL] ok');
+ const error = new Error('failed for [email protected]');
+ void error.stack;
+ const info = runRedactFormat(error as unknown as RedactInfo);
+ expect(String((info as unknown as Error).stack)).not.toContain('jane');
+ const long = `${' '.repeat(8000)}sk-${'a'.repeat(1500)}${' '.repeat(10)}`;
+ const out = String(runRedactFormat({ level: 'info', message: `${long}tail` }).message);
+ expect(out).not.toContain('aaaa');
+ const edge = `${' '.repeat(8100)}postgresql://user:${'p'.repeat(1300)}@host/db end`;
+ expect(String(runRedactFormat({ level: 'info', message: edge }).message)).not.toContain('pppp');
+ });
+
+ it('masks delimiter-bearing identifiers and keeps a complete 8.5k input intact', () => {
+ expect(redactMessage('user(comment)@blocked.example ok')).toBe('[REDACTED_EMAIL] ok');
+ const input = `${'a'.repeat(8500)}`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).toContain('aaaa');
+ });
+
+ it('masks a quoted local part of any length', () => {
+ expect(redactMessage(`"${'a'.repeat(200)}"@blocked.example ok`)).toBe('[REDACTED_EMAIL] ok');
+ });
+
+ it('keeps the uncapped matcher linear on quote and escape floods', () => {
+ for (const input of ['\\"'.repeat(50000), '"\\"'.repeat(30000), '"a'.repeat(50000)]) {
+ const started = Date.now();
+ redactMessage(input);
+ expect(Date.now() - started).toBeLessThan(500);
+ }
+ });
+
+ it('drops an unfinished quoted address that outruns the window', () => {
+ const input = `${' '.repeat(8180)}"jane ${'x'.repeat(2000)}"@example.com tail`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).not.toContain('jane');
+ });
+
+ it('drops a quoted address whose window edge falls on an inner space', () => {
+ const input = `${' '.repeat(8180)}"jane ${'x'.repeat(1030)} doe"@example.com tail`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).not.toContain('jane');
+ });
+
+ it('keeps a completed quoted address redacted when a stray quote precedes the edge', () => {
+ const input = `note: " ${' '.repeat(8172)}"jane doe"@example.com ${'x'.repeat(2000)}`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).not.toContain('jane');
+ });
+
+ it('keeps text after a completed quoted address', () => {
+ const input = `prefix "jane doe"@example.com diagnostic-code ${'x'.repeat(10000)}`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).toContain('diagnostic-code');
+ expect(out).not.toContain('jane');
+ });
+
+ it('has no residual caps and masks credential URIs after scheme punctuation', () => {
+ expect(
+ redactMessage(JSON.stringify({ email: `"${'a'.repeat(65)}"@example.com` })),
+ ).not.toContain('aaaa');
+ expect(redactMessage(`u@[${'a'.repeat(64)}.x] ok`)).toBe('[REDACTED_EMAIL] ok');
+ expect(redactMessage('-redis://:pw0rd@redis:6379')).not.toContain('pw0rd');
+ expect(redactMessage('...postgresql://user:pw0rd@db/database')).not.toContain('pw0rd');
+ for (const input of ['a-'.repeat(50000), '\\"a'.repeat(30000), 'u@['.repeat(30000)]) {
+ const started = Date.now();
+ redactMessage(input);
+ expect(Date.now() - started).toBeLessThan(500);
+ }
+ });
+
+ it('masks empty quoted locals and survives read-only error properties', () => {
+ expect(redactMessage('""@blocked.example ok')).toBe('[REDACTED_EMAIL] ok');
+ class DetailError extends Error {
+ get detail() {
+ return '[email protected]';
+ }
+ }
+ const error = new DetailError('boom');
+ Object.defineProperty(error, 'detail', {
+ enumerable: true,
+ configurable: false,
+ get: () => '[email protected]',
+ });
+ const out = runRedactFormat(error as unknown as RedactInfo) as unknown as { detail: string };
+ expect(out.detail).not.toContain('jane');
+ });
+
+ it('sanitizes a copy when a stack or key cannot be replaced in place', () => {
+ const error = new Error('failed for [email protected]');
+ Object.defineProperty(error, 'stack', { value: 'at [email protected]', writable: false });
+ const out = runRedactFormat(error as unknown as RedactInfo) as unknown as { stack: string };
+ expect(out.stack).not.toContain('jane');
+ const frozen = { level: 'info', message: 'm' } as RedactInfo;
+ Object.defineProperty(frozen, '[email protected]', { value: 1, enumerable: true });
+ expect(JSON.stringify(runRedactFormat(frozen))).not.toContain('jane');
+ });
+
+ it('masks serialized escaped-backslash locals and skips heavy error graphs', () => {
+ expect(redactMessage(JSON.stringify({ email: '"jane\\\\doe"@example.com' }))).not.toContain(
+ 'jane',
+ );
+ let graph: Record<string, unknown> = { leaf: 'x' };
+ for (let depth = 0; depth < 6; depth++) {
+ graph = Object.fromEntries(Array.from({ length: 10 }, (_, index) => [`k${index}`, graph]));
+ }
+ const started = Date.now();
+ runRedactFormat({
+ level: 'error',
+ message: 'm',
+ config: graph,
+ isAxiosError: true,
+ } as RedactInfo);
+ expect(Date.now() - started).toBeLessThan(500);
+ });
+
+ it('masks serialized locals with a lone escaped backslash and stays linear on backslash runs', () => {
+ expect(redactMessage(JSON.stringify({ email: '"jane\\doe"@example.com' }))).not.toContain(
+ 'jane',
+ );
+ for (const input of ['\\"' + '\\'.repeat(60000), '\\"\\\\'.repeat(20000)]) {
+ const started = Date.now();
+ redactMessage(input);
+ expect(Date.now() - started).toBeLessThan(500);
+ }
+ });
+
+ it('redacts compact request info, splat errors and comma-edged URIs', () => {
+ const axiosError = Object.assign(new Error('boom'), {
+ isAxiosError: true,
+ config: { method: 'get', url: 'https://[email protected]/?api_key=secret' },
+ });
+ const wrapped = winston.format.combine(redactFormat(), stripHeavyErrorFields());
+ const out = wrapped.transform(
+ { level: 'error', message: 'm', [SPLAT_SYMBOL]: [axiosError] },
+ {},
+ );
+ expect(JSON.stringify(out)).not.toMatch(/secret|user@example/);
+ const topLevel = wrapped.transform(Object.assign(axiosError, { level: 'error' }) as never, {});
+ expect(JSON.stringify(topLevel)).not.toMatch(/secret|user@example/);
+ const edge = `${' '.repeat(8100)}postgresql://user:${'p'.repeat(1050)},${'q'.repeat(60)}@host/db end`;
+ expect(String(runRedactFormat({ level: 'info', message: edge }).message)).not.toContain('pppp');
+ });
+
+ it('does not clone heavy graphs of splat errors', () => {
+ let graph: Record<string, unknown> = { leaf: 'x' };
+ for (let depth = 0; depth < 6; depth++) {
+ graph = Object.fromEntries(Array.from({ length: 10 }, (_, index) => [`k${index}`, graph]));
+ }
+ const error = Object.assign(new Error('boom'), {
+ isAxiosError: true,
+ config: { method: 'get', url: 'https://example.test/', graph },
+ request: graph,
+ });
+ const started = Date.now();
+ runRedactFormat({ level: 'error', message: 'm', [SPLAT_SYMBOL]: [error] });
+ expect(Date.now() - started).toBeLessThan(500);
+ });
+
+ it('redacts address keys on nested Error objects', () => {
+ const error = Object.assign(new Error('lookup failed'), { '[email protected]': 'missing' });
+ const info = runRedactFormat({ level: 'info', message: 'm', [SPLAT_SYMBOL]: [error] });
+ const [out] = info[SPLAT_SYMBOL] as Array<Record<string, unknown>>;
+ expect(Object.keys(out).join()).not.toContain('jane');
+ expect(out['[REDACTED_EMAIL]']).toBe('missing');
+ });
+
+ it('redacts enumerable getter values on nested Error objects', () => {
+ const error = new Error('boom');
+ Object.defineProperty(error, 'detail', { enumerable: true, get: () => '[email protected]' });
+ const info = runRedactFormat({ level: 'info', message: 'm', [SPLAT_SYMBOL]: [error] });
+ const [out] = info[SPLAT_SYMBOL] as Array<{ detail: string }>;
+ expect(out.detail).not.toContain('jane');
+ });
+
+ it('survives throwing top-level getters and redacts heavy-named fields on plain records', () => {
+ const error = new Error('boom');
+ Object.defineProperty(error, 'detail', {
+ enumerable: true,
+ get: () => {
+ throw new Error('nope');
+ },
+ });
+ expect(() => runRedactFormat(error as unknown as RedactInfo)).not.toThrow();
+ const out = runRedactFormat({
+ level: 'error',
+ message: 'failed',
+ socket: { note: 'Bearer secretcanary' },
+ } as RedactInfo);
+ expect(JSON.stringify(out)).not.toContain('secretcanary');
+ });
+
+ it('drops an unfinished serialized quoted address at the window edge', () => {
+ const input = `${' '.repeat(8170)}${JSON.stringify({ email: `"jane ${'x'.repeat(2000)}"@example.com` })}`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).not.toContain('jane');
+ });
+
+ it('masks JSON control escapes in serialized quoted locals and bounds wide payloads', () => {
+ expect(redactMessage(JSON.stringify({ email: '"jane\tdoe"@example.com' }))).not.toContain(
+ 'jane',
+ );
+ let tree: Record<string, unknown> = { leaf: 'x' };
+ for (let depth = 0; depth < 5; depth++) {
+ tree = Object.fromEntries(Array.from({ length: 8 }, (_, index) => [`k${index}`, tree]));
+ }
+ const started = Date.now();
+ runRedactFormat({
+ level: 'info',
+ message: 'm',
+ a: tree,
+ b: tree,
+ c: { x: tree },
+ } as RedactInfo);
+ expect(Date.now() - started).toBeLessThan(500);
+ });
+
+ it('masks credentials after a scheme of any length', () => {
+ expect(redactMessage(`${'a'.repeat(300)}://alice:secretcanary@localhost`)).not.toContain(
+ 'secretcanary',
+ );
+ });
+
+ it('counts strings against the budget and survives nested throwing getters', () => {
+ const strings = Object.fromEntries(
+ Array.from({ length: 50000 }, (_, index) => [`s${index}`, 'x'.repeat(8000)]),
+ );
+ const started = Date.now();
+ runRedactFormat({ level: 'info', message: 'm', payload: strings } as RedactInfo);
+ expect(Date.now() - started).toBeLessThan(500);
+ const payload = {};
+ Object.defineProperty(payload, 'bad', {
+ enumerable: true,
+ get: () => {
+ throw new Error('nope');
+ },
+ });
+ expect(() =>
+ runRedactFormat({ level: 'info', message: 'm', payload } as RedactInfo),
+ ).not.toThrow();
+ });
+
+ it('rebuilds the record when an accessor ignores writes', () => {
+ const error = new Error('boom');
+ Object.defineProperty(error, 'detail', {
+ enumerable: true,
+ configurable: true,
+ get: () => '[email protected]',
+ set: () => undefined,
+ });
+ const out = runRedactFormat(error as unknown as RedactInfo) as unknown as { detail: string };
+ expect(out.detail).not.toContain('jane');
+ });
+
+ it('rebuilds the record when a stack accessor ignores writes', () => {
+ const error = new Error('boom');
+ Object.defineProperty(error, 'stack', {
+ get: () => 'at [email protected]',
+ set: () => undefined,
+ configurable: true,
+ });
+ const out = runRedactFormat(error as unknown as RedactInfo) as unknown as { stack: string };
+ expect(out.stack).not.toContain('jane');
+ });
+
+ it('survives a throwing stack accessor', () => {
+ const error = new Error('boom');
+ Object.defineProperty(error, 'stack', {
+ get: () => {
+ throw new Error('nope');
+ },
+ configurable: true,
+ });
+ expect(() => runRedactFormat(error as unknown as RedactInfo)).not.toThrow();
+ });
+
+ it('masks serialized locals with an escaped solidus', () => {
+ expect(redactMessage(JSON.stringify({ email: '"a/b"@example.com' }).replace('/', '\\/'))).toBe(
+ '{"email":"[REDACTED_EMAIL]"}',
+ );
+ });
+
+ it('survives a throwing isAxiosError marker', () => {
+ const record = { level: 'info', message: 'm' } as RedactInfo;
+ Object.defineProperty(record, 'isAxiosError', {
+ enumerable: true,
+ get: () => {
+ throw new Error('nope');
+ },
+ });
+ expect(() => runRedactFormat(record)).not.toThrow();
+ });
+
+ it('masks URL-encoded addresses, drops fields past the budget and never keeps raw heavy fields', () => {
+ expect(redactMessage('GET /v1?email=jane%40example.com&x=1')).toBe(
+ 'GET /v1?email=[REDACTED_EMAIL]&x=1',
+ );
+ const started = Date.now();
+ redactMessage('a'.repeat(100000));
+ redactMessage('a%40'.repeat(30000));
+ expect(Date.now() - started).toBeLessThan(500);
+ const wide = Object.fromEntries(
+ Array.from({ length: 20000 }, (_, index) => [`n${index}`, index]),
+ );
+ const out = runRedactFormat({ level: 'info', message: 'm', ...wide } as RedactInfo);
+ expect(Object.keys(out).length).toBeLessThan(6000);
+ const config = {
+ method: 'get',
+ url: 'https://example.test/',
+ headers: { authorization: 'Bearer secretcanary' },
+ };
+ Object.defineProperty(config, 'method', {
+ enumerable: false,
+ get: () => {
+ throw new Error('nope');
+ },
+ });
+ const axiosRecord = {
+ level: 'error',
+ message: 'm',
+ isAxiosError: true,
+ config,
+ request: { a: 1 },
+ };
+ const result = runRedactFormat(axiosRecord as RedactInfo);
+ expect(JSON.stringify(result)).not.toContain('secretcanary');
+ });
+
+ it('redacts encoded address keys and survives throwing nested Axios configs', () => {
+ const out = runRedactFormat({
+ level: 'info',
+ message: 'm',
+ 'jane%40example.com': 1,
+ } as RedactInfo);
+ expect(JSON.stringify(out)).not.toContain('jane');
+ const config = { url: 'https://example.test/' };
+ Object.defineProperty(config, 'method', {
+ enumerable: true,
+ get: () => {
+ throw new Error('nope');
+ },
+ });
+ const error = Object.assign(new Error('boom'), { isAxiosError: true, config });
+ expect(() =>
+ runRedactFormat({ level: 'error', message: 'm', [SPLAT_SYMBOL]: [error] }),
+ ).not.toThrow();
+ });
+
+ it('redacts URL objects in compact request info', () => {
+ const error = Object.assign(new Error('boom'), {
+ isAxiosError: true,
+ config: {
+ method: 'get',
+ url: new URL('https://user:[email protected]/[email protected]'),
+ },
+ });
+ const wrapped = winston.format.combine(redactFormat(), stripHeavyErrorFields());
+ const out = wrapped.transform({ level: 'error', message: 'm', [SPLAT_SYMBOL]: [error] }, {});
+ expect(JSON.stringify(out)).not.toMatch(/secretcanary|jane/);
+ });
+
+ it('masks long encoded addresses linearly and strips serializer hooks', () => {
+ expect(redactMessage(`?e=${'a'.repeat(400)}%40${'b'.repeat(300)}.com&x=1`)).toBe(
+ '?e=[REDACTED_EMAIL]&x=1',
+ );
+ const started = Date.now();
+ redactMessage('a%40'.repeat(50000));
+ redactMessage('a'.repeat(100000));
+ expect(Date.now() - started).toBeLessThan(500);
+ const out = runRedactFormat({
+ level: 'info',
+ message: 'm',
+ payload: { email: '[email protected]', toJSON: () => ({ email: '[email protected]' }) },
+ } as RedactInfo);
+ expect(JSON.stringify(out)).not.toContain('jane');
+ });
+
+ it('strips serializer hooks from Error clones and top-level records', () => {
+ const error = Object.assign(new Error('boom'), {
+ toJSON: () => ({ email: '[email protected]' }),
+ });
+ const info = runRedactFormat({ level: 'info', message: 'm', [SPLAT_SYMBOL]: [error] });
+ expect(JSON.stringify(info[SPLAT_SYMBOL])).not.toContain('jane');
+ const top = runRedactFormat({
+ level: 'info',
+ message: 'm',
+ toJSON: () => '[email protected]',
+ } as RedactInfo);
+ expect(JSON.stringify(top)).not.toContain('jane');
+ });
+
+ it('neutralizes inherited serializer hooks', () => {
+ class Hooked extends Error {
+ toJSON() {
+ return { email: '[email protected]' };
+ }
+ }
+ const direct = runRedactFormat(new Hooked('boom') as unknown as RedactInfo);
+ expect(JSON.stringify(direct)).not.toContain('jane');
+ const nested = runRedactFormat({
+ level: 'info',
+ message: 'm',
+ [SPLAT_SYMBOL]: [new Hooked('x')],
+ });
+ expect(JSON.stringify(nested[SPLAT_SYMBOL])).not.toContain('jane');
+ });
+
+ it('survives a throwing toJSON getter', () => {
+ const record = { level: 'info', message: 'm' } as RedactInfo;
+ Object.defineProperty(record, 'toJSON', {
+ get: () => {
+ throw new Error('nope');
+ },
+ configurable: false,
+ });
+ expect(() => runRedactFormat(record)).not.toThrow();
+ });
+
+ it('replaces function values so their serializers never run', () => {
+ const fn = Object.assign(() => undefined, { toString: () => '[email protected]' });
+ const out = runRedactFormat({ level: 'info', message: fn as unknown as string });
+ expect(String(out.message)).not.toContain('jane');
+ });
+
+ it('masks encoded domain separators', () => {
+ expect(redactMessage('GET /v1?email=jane%40example%2Ecom&x=1')).toBe(
+ 'GET /v1?email=[REDACTED_EMAIL]&x=1',
+ );
+ });
+
+ it('keeps encoded-email matching linear at repeated URL boundaries', () => {
+ const started = Date.now();
+ redactMessage('?a%40'.repeat(30000));
+ redactMessage('&a%40'.repeat(30000));
+ redactMessage('/a%40'.repeat(30000));
+ expect(Date.now() - started).toBeLessThan(500);
+ });
+
+ it('shadows an inherited throwing serializer getter on nested errors', () => {
+ class Throwing extends Error {
+ get toJSON(): never {
+ throw new Error('nope');
+ }
+ }
+ const info = runRedactFormat({
+ level: 'info',
+ message: 'm',
+ [SPLAT_SYMBOL]: [new Throwing('x')],
+ });
+ expect(() => JSON.stringify(info[SPLAT_SYMBOL])).not.toThrow();
+ });
+
+ it('rebuilds records with accessor messages and masks doubly encoded addresses', () => {
+ const record = { level: 'info' } as RedactInfo;
+ Object.defineProperty(record, 'message', {
+ enumerable: true,
+ get: () => '[email protected]',
+ set: () => undefined,
+ });
+ expect(JSON.stringify(runRedactFormat(record))).not.toContain('jane');
+ expect(
+ redactMessage('redirect_uri=https%3A%2F%2Fx%3Femail%3Djane%2540example.com&a=1'),
+ ).not.toContain('jane');
+ });
+
+ it('redacts multiply encoded address keys', () => {
+ const out = runRedactFormat({
+ level: 'info',
+ message: 'm',
+ 'jane%2540example.com': 1,
+ } as RedactInfo);
+ expect(JSON.stringify(out)).not.toContain('jane');
+ });
+
+ it('survives throwing message getters and nested serializer getters', () => {
+ const record = { level: 'info' } as RedactInfo;
+ Object.defineProperty(record, 'message', {
+ enumerable: true,
+ get: () => {
+ throw new Error('nope');
+ },
+ });
+ expect(() => runRedactFormat(record)).not.toThrow();
+ class Nested {
+ get toJSON(): never {
+ throw new Error('nope');
+ }
+ }
+ expect(() =>
+ runRedactFormat({ level: 'info', message: 'm', payload: new Nested() } as RedactInfo),
+ ).not.toThrow();
+ });
+
+ it('survives revoked proxies and redacts the compact request method', () => {
+ const { proxy, revoke } = Proxy.revocable({}, {});
+ revoke();
+ expect(() =>
+ runRedactFormat({ level: 'info', message: 'm', payload: proxy } as RedactInfo),
+ ).not.toThrow();
+ const config = { method: 'Bearer secretcanary', url: 'https://example.test/' };
+ const out = runRedactFormat({
+ level: 'error',
+ message: 'm',
+ isAxiosError: true,
+ config,
+ } as RedactInfo);
+ expect(JSON.stringify(out)).not.toContain('secretcanary');
+ });
+
+ it('stays fast on adversarial 100k inputs for every redaction path', () => {
+ const inputs = [
+ 'a@'.repeat(50000),
+ `a@${'a.'.repeat(50000)}`,
+ '"a@'.repeat(30000),
+ '\\"'.repeat(50000),
+ 'a'.repeat(100000),
+ `${'a'.repeat(100000)}://h`,
+ 'Bearer '.repeat(14000),
+ ];
+ for (const input of inputs) {
+ const started = Date.now();
+ runRedactFormat({ level: 'info', message: input });
+ runRedactFormat({ level: 'info', message: 'm', [input]: 1, nested: { [input]: input } });
+ expect(Date.now() - started).toBeLessThan(1000);
+ }
+ });
+
+ it('keeps redaction of a long run without an address bounded', () => {
+ const started = Date.now();
+ const out = String(
+ runRedactFormat({ level: 'info', message: `${'a'.repeat(100000)}://host` }).message,
+ );
+ expect(Date.now() - started).toBeLessThan(500);
+ expect(out).toContain('truncated');
+ });
+
+ it('masks quoted and bracketed addresses cut right before the at sign or inside the literal', () => {
+ for (const [addr, cut] of [
+ ['"jane doe"@example.com', '"jane doe"'.length],
+ ['jane@[192.0.2.1]', 'jane@['.length],
+ ] as const) {
+ const input = `${' '.repeat(8192 - cut)}${addr} tail`;
+ const out = String(runRedactFormat({ level: 'info', message: input }).message);
+ expect(out).not.toMatch(/jane/);
+ }
+ });
+
+ it('masks quoted local parts', () => {
+ expect(redactMessage('user "jane.doe"@example.com ok')).toBe('user [REDACTED_EMAIL] ok');
+ expect(redactMessage('user "jane\\"doe"@example.com ok')).toBe('user [REDACTED_EMAIL] ok');
+ expect(redactMessage('user "jane doe"@example.com ok')).toBe('user [REDACTED_EMAIL] ok');
+ expect(redactMessage('user customer/[email protected] ok')).toBe(
+ 'user [REDACTED_EMAIL] ok',
+ );
+ });
+
+ it('scans long non-email text in linear time', () => {
+ const inputs = ['_'.repeat(100_000), `${'_'.repeat(50_000)}@${'-'.repeat(50_000)}`];
+ const start = Date.now();
+ for (const input of inputs) {
+ expect(redactMessage(input)).toBe(input);
+ }
+ expect(Date.now() - start).toBeLessThan(1000);
+ });
+
+ it('masks email addresses in metadata values and nested objects', () => {
+ const info = runRedactSplatFormat({
+ level: 'info',
+ message: 'x',
+ [SPLAT_SYMBOL]: [{ user: { contact: '[email protected]' }, list: ['[email protected]'] }],
+ });
+ const [meta] = info[SPLAT_SYMBOL] as Array<{ user: { contact: string }; list: string[] }>;
+ expect(meta.user.contact).toBe('[REDACTED_EMAIL]');
+ expect(meta.list).toEqual(['[REDACTED_EMAIL]']);
+ });
+
it('does not redact ordinary words containing sensitive prefixes', () => {
expect(redactMessage('task-runner failed')).toBe('task-runner failed');
expect(redactMessage('mask-value computed')).toBe('mask-value computed');
@@ -114,6 +793,24 @@ describe('redactMessage', () => {
});
describe('redactFormat', () => {
+ it('masks emails in top-level fields, stack traces and metadata keys', () => {
+ const info = runRedactFormat({
+ level: 'error',
+ message: 'lookup',
+ contact: '[email protected]',
+ stack: 'Error: failed for [email protected]\n at x',
+ token: 'sk-abcdef',
+ '[email protected]': 'missing',
+ nested: { '[email protected]': 1, '[email protected]': 2, other: 3 },
+ });
+ expect(info.contact).toBe('[REDACTED_EMAIL]');
+ expect(info.stack).toBe('Error: failed for [REDACTED_EMAIL]\n at x');
+ expect(info.token).toBe('[REDACTED]');
+ expect(info['[REDACTED_EMAIL]']).toBe('missing');
+ expect(info).not.toHaveProperty(['[email protected]']);
+ expect(info.nested).toEqual({ '[REDACTED_EMAIL]': 1, '[REDACTED_EMAIL]#2': 2, other: 3 });
+ });
+
it.each(['error', 'warn', 'info', 'debug'])('redacts info.message for %s level', (level) => {
const info = runRedactFormat({ level, message: 'Bearer secretvalue' });
expect(info.message).toBe('Bearer [REDACTED]');
diff --git a/packages/data-schemas/src/config/parsers.ts b/packages/data-schemas/src/config/parsers.ts
index 3a2bab5208..671c42fc9a 100644
--- a/packages/data-schemas/src/config/parsers.ts
+++ b/packages/data-schemas/src/config/parsers.ts
@@ -14,6 +14,12 @@ const REDACTED_VALUE = '[REDACTED]';
const REDACTION_TRUNCATED_KEY = '__redaction_truncated__';
const MAX_REDACTION_DEPTH = 8;
const MAX_REDACTION_ENTRIES = 50;
+/**
+ * Objects one log record may visit while redacting, so a broad payload cannot stall the event loop.
+ * Env-only like CONSOLE_JSON_STRING_LENGTH: the logger is built at import, before librechat.yaml loads.
+ */
+const MAX_REDACTION_NODES: number = parseInt(process.env.LOG_REDACTION_MAX_NODES || '', 10) || 5000;
+let redactionNodeBudget = Number.POSITIVE_INFINITY;
const DEFAULT_REDACTION_STRING_LENGTH = 8192;
const MAX_REDACTION_STRING_LENGTH = Math.max(
CONSOLE_JSON_STRING_LENGTH,
@@ -49,9 +55,23 @@ const sensitiveKeys: RegExp[] = [
/(\b)eyJ[a-zA-Z0-9_-]{5,}\.[a-zA-Z0-9_-]{5,}\.[a-zA-Z0-9_-]+/g,
/\b((?:Proxy-)?Authorization:\s*)[^\r\n]+/gi,
/\b((?:Cookie|Set-Cookie):\s*)[^\r\n]+/gi,
- /([a-z][a-z0-9+.-]*:\/\/)[^/\s:@]*:[^/\s@]+(?=@)/gi,
+ /(:\/\/)[^/\s:@]*:[^/\s@]+(?=@)/g,
];
+/**
+ * Matches a whole delimiter-bounded token that holds an address. The lookbehind lets the scan start
+ * only at a token boundary, so long non-email text is scanned once instead of once per character.
+ */
+const EMAIL_PATTERN =
+ /(?:(?<!\\)\\"(?:[^"\\\r\n]|\\{3}"|\\{4}|\\{2}(?!\\)|\\[bfnrt/]|\\u[0-9a-fA-F]{4})*\\"|(?<!\\)"(?:[^"\\\r\n]|\\.)*"|(?<![^\s<>[\],;"])[^\s<>[\],;"]+)@(?:\[[^\]\s@]+\]|[^\s<>[\],;"@]+\.[^\s<>[\],;"@]+)/gu;
+/** Set while redacting splat arguments at levels whose later format strips heavy error fields. */
+let skipHeavyErrorFields = false;
+/** URL-encoded addresses (`user%40host.tld`), anchored at a token start so scans stay linear. */
+const ENCODED_EMAIL_PATTERN =
+ /(?<![^\s<>"&=?/#])(?:(?!%(?:25)*40)[^\s<>"&=?/#])+%(?:25)*40[^\s<>"&=?/#]+(?:\.|%(?:25)*2e)[^\s<>"&=?/#]+/giu;
+const REDACTION_WINDOW_SLACK = 1024;
+const REDACTED_EMAIL_VALUE = '[REDACTED_EMAIL]';
+
const sensitiveMetadataKey =
/^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|password|assertion|client[-_]?assertion|client[-_]?secret|code[-_]?verifier|credential|signature|connection[-_]?string)$/i;
const errorStringProperties = new Set(['name', 'message', 'stack']);
@@ -67,10 +87,10 @@ function redactMessage(str: string, trimLength?: number): string {
return '';
}
- const redacted = sensitiveKeys.reduce(
- (currentMessage, pattern) => currentMessage.replace(pattern, '$1[REDACTED]'),
- str,
- );
+ const redacted = sensitiveKeys
+ .reduce((currentMessage, pattern) => currentMessage.replace(pattern, '$1[REDACTED]'), str)
+ .replace(EMAIL_PATTERN, REDACTED_EMAIL_VALUE)
+ .replace(ENCODED_EMAIL_PATTERN, REDACTED_EMAIL_VALUE);
if (trimLength !== undefined && redacted.length > trimLength) {
return `${redacted.substring(0, trimLength)}...`;
@@ -79,13 +99,57 @@ function redactMessage(str: string, trimLength?: number): string {
return redacted;
}
+/** Whitespace and angle brackets only: commas, quotes and brackets can sit inside one token. */
+const EMAIL_TOKEN_DELIMITER = /[\s<>]/u;
+/** Completed addresses and escaped (serialized) quotes are skipped; only a lone plain quote is counted. */
+const QUOTE_OR_ADDRESS =
+ /\\"(?:[^"\\\r\n]|\\{3}"|\\{4}|\\{2}(?!\\)|\\[bfnrt/]|\\u[0-9a-fA-F]{4})*\\"@|\\"|"(?:[^"\\\r\n]|\\.)*"@|"/gu;
+
+/** Drops a token cut by the window edge: its terminator is unseen, so no pattern could match it. */
+function trimUnfinishedToken(full: string, window: string): string {
+ if (window.length === full.length) {
+ return window;
+ }
+ let end = window.length;
+ if (!EMAIL_TOKEN_DELIMITER.test(full[end])) {
+ while (end > 0 && !EMAIL_TOKEN_DELIMITER.test(window[end - 1])) {
+ end--;
+ }
+ }
+ const trimmed = window.substring(0, end);
+ let quotes = 0;
+ let lastOpen = -1;
+ for (const match of trimmed.matchAll(QUOTE_OR_ADDRESS)) {
+ if (match[0] === '"') {
+ quotes++;
+ lastOpen = match.index;
+ }
+ }
+ /** An odd count of quotes outside completed addresses means the cut fell inside a quoted local. */
+ return quotes % 2 === 1 ? trimmed.substring(0, lastOpen) : trimmed;
+}
+
function redactLogString(str: string): string {
+ /** A string costs one node plus one per 512 scanned characters, so wide payloads stay bounded. */
+ redactionNodeBudget -= 1 + Math.floor(Math.min(str.length, MAX_REDACTION_STRING_LENGTH) / 512);
+ if (redactionNodeBudget < 0) {
+ return REDACTED_VALUE;
+ }
if (str.length <= MAX_REDACTION_STRING_LENGTH) {
return redactMessage(str);
}
- const redacted = redactMessage(str.substring(0, MAX_REDACTION_STRING_LENGTH));
- return `${redacted}... [truncated ${str.length - MAX_REDACTION_STRING_LENGTH} chars]`;
+ /**
+ * Redacts a bounded window past the cutoff before cutting, so an address that straddles the limit
+ * is matched whole. The unfinished token at the window edge is dropped rather than kept unmatched.
+ */
+ const window = trimUnfinishedToken(
+ str,
+ str.substring(0, MAX_REDACTION_STRING_LENGTH + REDACTION_WINDOW_SLACK),
+ );
+ const redacted = redactMessage(window);
+ const kept = redacted.substring(0, MAX_REDACTION_STRING_LENGTH);
+ return `${kept}... [truncated ${str.length - kept.length} chars]`;
}
function isPlainRecord(value: object): value is Record<string, unknown> {
@@ -93,6 +157,25 @@ function isPlainRecord(value: object): value is Record<string, unknown> {
return prototype === Object.prototype || prototype === null;
}
+/** `cursors` remembers the next free suffix per base so many colliding keys stay linear. */
+function redactLogKey(
+ key: string,
+ isUsed: (candidate: string) => boolean,
+ cursors: Map<string, number>,
+): string {
+ const base = /@|%(?:25)*40/i.test(key) ? redactLogString(key) : key;
+ let candidate = base;
+ let suffix = cursors.get(base) ?? 2;
+ while (isUsed(candidate)) {
+ candidate = `${base}#${suffix}`;
+ suffix++;
+ }
+ if (candidate !== base) {
+ cursors.set(base, suffix);
+ }
+ return candidate;
+}
+
function isSensitiveMetadataKey(key: string): boolean {
return sensitiveMetadataKey.test(key);
}
@@ -129,13 +212,14 @@ function defineRedactedDescriptor(
descriptor: PropertyDescriptor,
seen: WeakMap<object, unknown>,
depth: number,
+ targetKey: string | symbol = key,
): void {
if (!('value' in descriptor)) {
- Object.defineProperty(target, key, descriptor);
+ Object.defineProperty(target, targetKey, descriptor);
return;
}
- Object.defineProperty(target, key, {
+ Object.defineProperty(target, targetKey, {
...descriptor,
value:
typeof key === 'string'
@@ -147,20 +231,58 @@ function defineRedactedDescriptor(
function redactErrorValue(error: Error, seen: WeakMap<object, unknown>, depth: number): Error {
const redacted = Object.create(Object.getPrototypeOf(error)) as Error & Record<string, unknown>;
seen.set(error, redacted);
+ const cursors = new Map<string, number>();
+ neutralizeSerializer(redacted);
defineRedactedErrorProperty(redacted, 'name', error.name);
defineRedactedErrorProperty(redacted, 'message', error.message);
defineRedactedErrorProperty(redacted, 'stack', error.stack);
Reflect.ownKeys(error).forEach((key) => {
- if (typeof key === 'string' && errorStringProperties.has(key)) {
+ if (typeof key === 'string' && (errorStringProperties.has(key) || key === 'toJSON')) {
return;
}
- const descriptor = Object.getOwnPropertyDescriptor(error, key);
+ let descriptor = Object.getOwnPropertyDescriptor(error, key);
if (descriptor === undefined) {
return;
}
- defineRedactedDescriptor(redacted, key, descriptor, seen, depth + 1);
+ if (descriptor.enumerable && descriptor.get !== undefined) {
+ /** An enumerable getter is serialized by value, so it is materialized and redacted like data. */
+ try {
+ descriptor = {
+ value: descriptor.get.call(error),
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ };
+ } catch {
+ return;
+ }
+ }
+ if (skipHeavyErrorFields && typeof key === 'string') {
+ const isAxios = readsTrue(error as unknown as Record<string, unknown>, 'isAxiosError');
+ if (isAxios && key === 'config') {
+ const compact = safelyCompact(descriptor.value);
+ if (compact !== undefined) {
+ defineRedactedDescriptor(
+ redacted,
+ key,
+ { ...descriptor, value: compact },
+ seen,
+ depth + 1,
+ );
+ }
+ return;
+ }
+ if (HEAVY_ERROR_KEYS.has(key) || (isAxios && AXIOS_ONLY_HEAVY_KEYS.has(key))) {
+ return;
+ }
+ }
+ const targetKey =
+ typeof key === 'string'
+ ? redactLogKey(key, (c) => Object.prototype.hasOwnProperty.call(redacted, c), cursors)
+ : key;
+ defineRedactedDescriptor(redacted, key, descriptor, seen, depth + 1, targetKey);
});
return redacted;
}
@@ -170,12 +292,12 @@ function isBufferValue(value: object): value is Buffer {
}
function getJsonValue(value: object): unknown {
- const toJSON = (value as { toJSON?: unknown }).toJSON;
- if (typeof toJSON !== 'function') {
- return undefined;
- }
-
try {
+ const toJSON = (value as { toJSON?: unknown }).toJSON;
+ if (typeof toJSON !== 'function') {
+ return undefined;
+ }
+
const jsonValue = toJSON.call(value);
return jsonValue === value ? undefined : jsonValue;
} catch {
@@ -203,6 +325,7 @@ function redactMapValue(
depth: number,
): Map<unknown, unknown> {
const redacted = new Map<unknown, unknown>();
+ const cursors = new Map<string, number>();
seen.set(value, redacted);
let count = 0;
for (const [mapKey, mapValue] of value) {
@@ -210,8 +333,12 @@ function redactMapValue(
redacted.set(REDACTION_TRUNCATED_KEY, 'Additional map entries omitted');
break;
}
+ const safeKey =
+ typeof mapKey === 'string'
+ ? redactLogKey(mapKey, (candidate) => redacted.has(candidate), cursors)
+ : redactLogValue(mapKey, seen, depth + 1);
redacted.set(
- mapKey,
+ safeKey,
typeof mapKey === 'string'
? redactRecordValue(mapKey, mapValue, seen, depth + 1)
: redactLogValue(mapValue, seen, depth + 1),
@@ -240,6 +367,57 @@ function redactSetValue(
return redacted;
}
+/** Shadows an inherited `toJSON` with an inert own property so no hook runs after redaction. */
+function neutralizeSerializer(target: object): boolean {
+ let hooked = true;
+ try {
+ hooked = typeof (target as { toJSON?: unknown }).toJSON === 'function';
+ } catch {
+ /* a throwing getter is treated as a hook and shadowed below */
+ }
+ if (!hooked) {
+ return true;
+ }
+ try {
+ Object.defineProperty(target, 'toJSON', {
+ value: undefined,
+ enumerable: false,
+ configurable: true,
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function safely(read: () => boolean): boolean {
+ try {
+ return read();
+ } catch {
+ return false;
+ }
+}
+
+function safelyCompact(config: unknown): Record<string, unknown> | undefined {
+ try {
+ return compactRequestInfo(config);
+ } catch {
+ return undefined;
+ }
+}
+
+function readsTrue(record: Record<string | symbol, unknown>, key: string): boolean {
+ return safely(() => record[key] === true);
+}
+
+function readField(record: Record<string, unknown>, key: string): unknown {
+ try {
+ return record[key];
+ } catch {
+ return '[Unreadable]';
+ }
+}
+
function redactObjectEntries(
value: object,
seen: WeakMap<object, unknown>,
@@ -247,6 +425,7 @@ function redactObjectEntries(
): Record<string, unknown> | undefined {
const record = value as Record<string, unknown>;
let redacted: Record<string, unknown> | undefined;
+ const cursors = new Map<string, number>();
let count = 0;
for (const key in record) {
@@ -257,11 +436,21 @@ function redactObjectEntries(
redacted = {};
seen.set(value, redacted);
}
+ /** A serialization hook would run after redaction and could re-emit the raw values. */
+ if (key === 'toJSON') {
+ continue;
+ }
if (count >= MAX_REDACTION_ENTRIES) {
redacted[REDACTION_TRUNCATED_KEY] = 'Additional object properties omitted';
break;
}
- redacted[key] = redactRecordValue(key, record[key], seen, depth + 1);
+ redacted[
+ redactLogKey(
+ key,
+ (candidate) => Object.prototype.hasOwnProperty.call(redacted, candidate),
+ cursors,
+ )
+ ] = redactRecordValue(key, readField(record, key), seen, depth + 1);
count += 1;
}
@@ -310,6 +499,11 @@ function redactLogValue(value: unknown, seen = new WeakMap<object, unknown>(), d
return redactLogString(value);
}
+ /** A function's `toString`/`toJSON` would run after redaction, so only a marker is kept. */
+ if (typeof value === 'function') {
+ return '[Function]';
+ }
+
if (value === null || typeof value !== 'object') {
return value;
}
@@ -319,10 +513,19 @@ function redactLogValue(value: unknown, seen = new WeakMap<object, unknown>(), d
return cached;
}
- if (depth >= MAX_REDACTION_DEPTH) {
+ if (depth >= MAX_REDACTION_DEPTH || redactionNodeBudget-- <= 0) {
return REDACTED_VALUE;
}
+ try {
+ return redactObjectValue(value, seen, depth);
+ } catch {
+ /* revoked proxies and throwing traps must not abort the log call */
+ return '[Unreadable]';
+ }
+}
+
+function redactObjectValue(value: object, seen: WeakMap<object, unknown>, depth: number): unknown {
if (Array.isArray(value)) {
const redacted: unknown[] = [];
seen.set(value, redacted);
@@ -347,6 +550,49 @@ function redactLogValue(value: unknown, seen = new WeakMap<object, unknown>(), d
return redactObjectEntries(value, seen, depth) ?? {};
}
+/** Writes a redacted field back; returns false when a read-only property refuses the write. */
+function setLogField(
+ target: Record<string, unknown>,
+ key: string,
+ safeKey: string,
+ value: unknown,
+): boolean {
+ let removed = true;
+ try {
+ if (safeKey !== key) {
+ removed = Reflect.deleteProperty(target, key);
+ }
+ target[safeKey] = value;
+ return removed;
+ } catch {
+ try {
+ Object.defineProperty(target, safeKey, { value, configurable: true, writable: true });
+ } catch {
+ /* handled by the caller through the false return */
+ }
+ return false;
+ }
+}
+
+/** Rebuilds the record as a plain writable copy when some field could not be replaced in place. */
+function sanitizedCopy(
+ info: Record<string | symbol, unknown>,
+ fields: Record<string, unknown>,
+ stack: string | undefined,
+ message: unknown,
+): winston.Logform.TransformableInfo {
+ const copy: Record<string | symbol, unknown> = {};
+ for (const symbol of Object.getOwnPropertySymbols(info)) {
+ copy[symbol] = info[symbol];
+ }
+ copy.level = info.level;
+ copy.message = message;
+ if (stack !== undefined) {
+ copy.stack = stack;
+ }
+ return Object.assign(copy, fields) as winston.Logform.TransformableInfo;
+}
+
/**
* Redacts sensitive information from log messages at every level.
* Note: Intentionally mutates the object.
@@ -356,9 +602,52 @@ function redactLogValue(value: unknown, seen = new WeakMap<object, unknown>(), d
const redactFormat: winston.Logform.FormatWrap = winston.format(
(info: winston.Logform.TransformableInfo) => {
const infoRecord = info as Record<string | symbol, unknown>;
+ const stripsHeavyFields = info.level === 'error' || info.level === 'warn';
+ const outerBudget = redactionNodeBudget;
+ redactionNodeBudget = MAX_REDACTION_NODES;
+ const topSeen = new WeakMap<object, unknown>();
+ const skipsHeavyTopLevel = stripsHeavyFields && safely(() => isErrorLike(info));
+
+ let redactedMessage: unknown;
+ let replaceFailed = false;
+ let rawMessage: unknown;
+ try {
+ rawMessage = info.message;
+ } catch {
+ rawMessage = '[Unreadable]';
+ replaceFailed = true;
+ }
+ if (rawMessage !== undefined) {
+ redactedMessage = redactLogValue(rawMessage);
+ if (Object.getOwnPropertyDescriptor(info, 'message')?.get !== undefined) {
+ replaceFailed = true;
+ }
+ try {
+ info.message = redactedMessage as string;
+ } catch {
+ replaceFailed = true;
+ }
+ }
- if (info.message !== undefined) {
- info.message = redactLogValue(info.message);
+ /** A direct `logger.error(error)` makes `info` the Error, whose stack is non-enumerable. */
+ let redactedStack: string | undefined;
+ let rawStack: unknown;
+ try {
+ rawStack = infoRecord.stack;
+ } catch {
+ rawStack = undefined;
+ replaceFailed = true;
+ }
+ if (typeof rawStack === 'string') {
+ redactedStack = redactLogString(rawStack);
+ if (Object.getOwnPropertyDescriptor(info, 'stack')?.get !== undefined) {
+ replaceFailed = true;
+ }
+ try {
+ infoRecord.stack = redactedStack;
+ } catch {
+ replaceFailed = true;
+ }
}
const symbolValue = infoRecord[MESSAGE_SYMBOL];
@@ -367,9 +656,81 @@ const redactFormat: winston.Logform.FormatWrap = winston.format(
}
if (infoRecord[SPLAT_SYMBOL] !== undefined) {
- infoRecord[SPLAT_SYMBOL] = redactLogValue(infoRecord[SPLAT_SYMBOL]);
+ skipHeavyErrorFields = stripsHeavyFields;
+ try {
+ infoRecord[SPLAT_SYMBOL] = redactLogValue(infoRecord[SPLAT_SYMBOL]);
+ } finally {
+ skipHeavyErrorFields = false;
+ }
+ }
+
+ const cursors = new Map<string, number>();
+ const fields: Record<string, unknown> = {};
+ const isAxios = readsTrue(infoRecord, 'isAxiosError');
+ for (const key of Object.keys(info)) {
+ if (key === 'message' || key === 'level') {
+ continue;
+ }
+ if (key === 'toJSON') {
+ if (!Reflect.deleteProperty(info, key)) {
+ replaceFailed = true;
+ }
+ continue;
+ }
+ /** Past the budget, further top-level fields are dropped rather than scanned. */
+ if (redactionNodeBudget-- <= 0) {
+ if (!Reflect.deleteProperty(info, key)) {
+ replaceFailed = true;
+ }
+ continue;
+ }
+ /**
+ * `stripHeavyErrorFields` drops these later. Cloning the graph here would only burn time, and
+ * leaving the raw value would depend on that later pass succeeding, so the field is replaced
+ * by its redacted compact form (or removed) now.
+ */
+ if (
+ skipsHeavyTopLevel &&
+ (HEAVY_ERROR_KEYS.has(key) || (isAxios && AXIOS_ONLY_HEAVY_KEYS.has(key)))
+ ) {
+ const compact =
+ isAxios && key === 'config' ? safelyCompact(readField(infoRecord, key)) : undefined;
+ if (compact !== undefined) {
+ fields[key] = compact;
+ if (!setLogField(infoRecord, key, key, compact)) {
+ replaceFailed = true;
+ }
+ } else if (!Reflect.deleteProperty(info, key)) {
+ replaceFailed = true;
+ }
+ continue;
+ }
+ /** An accessor keeps serving its original value after assignment, so the record is rebuilt. */
+ if (Object.getOwnPropertyDescriptor(info, key)?.get !== undefined) {
+ replaceFailed = true;
+ }
+ let raw: unknown;
+ try {
+ raw = infoRecord[key];
+ } catch {
+ raw = '[Unreadable]';
+ }
+ const value = redactRecordValue(key, raw, topSeen, 0);
+ const safeKey = redactLogKey(
+ key,
+ (candidate) => candidate !== key && Object.prototype.hasOwnProperty.call(info, candidate),
+ cursors,
+ );
+ fields[safeKey] = value;
+ if (!setLogField(infoRecord, key, safeKey, value)) {
+ replaceFailed = true;
+ }
+ }
+ redactionNodeBudget = outerBudget;
+ if (!neutralizeSerializer(info)) {
+ replaceFailed = true;
}
- return info;
+ return replaceFailed ? sanitizedCopy(infoRecord, fields, redactedStack, redactedMessage) : info;
},
);
@@ -531,7 +892,7 @@ const compactRequestInfo = (config: unknown): { method?: unknown; url?: unknown
if (method === undefined && url === undefined) {
return undefined;
}
- return { method, url };
+ return { method: redactLogValue(method), url: redactLogValue(url) };
};
const compactResponse = (response: unknown): Record<string, unknown> | undefined => {
@@ -700,4 +1061,11 @@ const jsonTruncateFormat: winston.Logform.FormatWrap = winston.format(
},
);
-export { redactFormat, redactMessage, debugTraverse, jsonTruncateFormat, stripHeavyErrorFields };
+export {
+ redactFormat,
+ redactMessage,
+ redactLogString,
+ debugTraverse,
+ jsonTruncateFormat,
+ stripHeavyErrorFields,
+};
diff --git a/packages/data-schemas/src/config/winston.ts b/packages/data-schemas/src/config/winston.ts
index 05bbc7afc7..0d117bdaf2 100644
--- a/packages/data-schemas/src/config/winston.ts
+++ b/packages/data-schemas/src/config/winston.ts
@@ -3,6 +3,7 @@ import 'winston-daily-rotate-file';
import {
redactFormat,
redactMessage,
+ redactLogString,
debugTraverse,
jsonTruncateFormat,
stripHeavyErrorFields,
@@ -20,7 +21,13 @@ const useDebugLogging = typeof DEBUG_LOGGING === 'string' && DEBUG_LOGGING.toLow
const useFileLogging = typeof LOG_TO_FILE !== 'string' || LOG_TO_FILE.toLowerCase() !== 'false';
-const requestContextFormat = winston.format(attachRequestContext);
+const requestContextFormat = winston.format((info) => {
+ const withContext = attachRequestContext(info);
+ if (typeof withContext.request_path === 'string') {
+ withContext.request_path = redactLogString(withContext.request_path);
+ }
+ return withContext;
+});
winston.addColors({
info: 'green',