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: Redact Email Addresses and IPs From Auth Flow Logs (#16994)

Marco Berettaee1d59e59058
diff --git a/api/server/controllers/AuthController.js b/api/server/controllers/AuthController.js
index a261ace60c..3299baa8c7 100644
--- a/api/server/controllers/AuthController.js
+++ b/api/server/controllers/AuthController.js
@@ -17,6 +17,7 @@ const {
getValidOpenIDReuseCredential,
isTokenRetired,
isTwoFactorEnrollmentRequired,
+ getSafeErrorMetadata,
sanitizeUserForAuthResponse,
} = require('@librechat/api');
const {
@@ -78,13 +79,16 @@ const registrationController = async (req, res) => {
try {
await deleteTokens({ token: req.invite.token });
} catch (error) {
- logger.error('[registrationController] Failed to consume invite after registration', error);
+ logger.error(
+ '[registrationController] Failed to consume invite after registration',
+ getSafeErrorMetadata(error),
+ );
}
}
res.status(status).send({ message });
} catch (err) {
- logger.error('[registrationController]', err);
- return res.status(500).json({ message: err.message });
+ logger.error('[registrationController]', getSafeErrorMetadata(err));
+ return res.status(500).json({ message: 'Something went wrong' });
}
};
@@ -288,8 +292,8 @@ const resetPasswordRequestController = async (req, res) => {
return res.status(200).json(resetService);
}
} catch (e) {
- logger.error('[resetPasswordRequestController]', e);
- return res.status(400).json({ message: e.message });
+ logger.error('[resetPasswordRequestController]', getSafeErrorMetadata(e));
+ return res.status(400).json({ message: 'Something went wrong' });
}
};
diff --git a/api/server/controllers/AuthController.spec.js b/api/server/controllers/AuthController.spec.js
index 40fb8d2a0b..ead5410d6a 100644
--- a/api/server/controllers/AuthController.spec.js
+++ b/api/server/controllers/AuthController.spec.js
@@ -143,6 +143,7 @@ const {
refreshController,
registrationController,
resetPasswordController,
+ resetPasswordRequestController,
} = require('./AuthController');
const { getGraphApiToken } = require('~/server/services/GraphTokenService');
const {
@@ -154,6 +155,7 @@ const {
setAuthTokens,
registerUser,
resetPassword,
+ requestPasswordReset,
} = require('~/server/services/AuthService');
const { getOpenIdConfig, getOpenIdEmail } = require('~/strategies');
const {
@@ -2789,6 +2791,32 @@ describe('registrationController - invite consumption', () => {
expect(logger.error).toHaveBeenCalled();
});
+ it('answers an unexpected registration failure generically and logs safe metadata', async () => {
+ registerUser.mockRejectedValue(new Error('smtp rejected [email protected]'));
+ const res = buildRes();
+
+ await registrationController({ body: {}, invite }, res);
+
+ expect(res.status).toHaveBeenCalledWith(500);
+ expect(res.json).toHaveBeenCalledWith({ message: 'Something went wrong' });
+ expect(logger.error).toHaveBeenCalledWith('[registrationController]', { type: 'Error' });
+ expect(JSON.stringify(logger.error.mock.calls)).not.toContain('[email protected]');
+ });
+
+ it('answers a failed password reset request generically and logs safe metadata', async () => {
+ requestPasswordReset.mockRejectedValue(new Error('smtp rejected [email protected]'));
+ const res = buildRes();
+
+ await resetPasswordRequestController({ body: { email: '[email protected]' } }, res);
+
+ expect(res.status).toHaveBeenCalledWith(400);
+ expect(res.json).toHaveBeenCalledWith({ message: 'Something went wrong' });
+ expect(logger.error).toHaveBeenCalledWith('[resetPasswordRequestController]', {
+ type: 'Error',
+ });
+ expect(JSON.stringify(logger.error.mock.calls)).not.toContain('[email protected]');
+ });
+
it('never forwards the creation signal to the client', async () => {
registerUser.mockResolvedValue({ status: 200, message: 'ok', userCreated: true });
const res = buildRes();
diff --git a/api/server/services/AuthService.js b/api/server/services/AuthService.js
index 5c67cb554e..21c7f41cfb 100644
--- a/api/server/services/AuthService.js
+++ b/api/server/services/AuthService.js
@@ -26,6 +26,7 @@ const {
createOpenIDSessionIdentity,
resolveAppConfigForUser,
commitPasswordReset,
+ getSafeErrorMetadata,
} = require('@librechat/api');
const {
findUser,
@@ -288,7 +289,7 @@ const sendVerificationEmail = async (user) => {
expiresIn: 900,
});
- logger.info(`[sendVerificationEmail] Verification link issued. [Email: ${email}]`);
+ logger.info(`[sendVerificationEmail] Verification link issued. [User ID: ${user._id}]`);
};
/**
@@ -307,35 +308,33 @@ const verifyEmail = async (req) => {
try {
decodedEmail = decodeURIComponent(email);
} catch {
- logger.warn(`[verifyEmail] [Invalid email encoding] [Email: ${email}]`);
+ logger.warn('[verifyEmail] [Invalid email encoding]');
return new Error(invalidEmailVerificationMessage);
}
const user = await findUser({ email: decodedEmail }, 'email _id emailVerified');
if (!user) {
- logger.warn(`[verifyEmail] [User not found] [Email: ${decodedEmail}]`);
+ logger.warn('[verifyEmail] [User not found]');
return new Error(invalidEmailVerificationMessage);
}
const emailVerificationData = await findEmailVerificationToken(user);
if (!emailVerificationData) {
- logger.warn(`[verifyEmail] [No email verification data found] [Email: ${decodedEmail}]`);
+ logger.warn(`[verifyEmail] [No email verification data found] [User ID: ${user._id}]`);
return new Error(invalidEmailVerificationMessage);
}
if (!emailVerificationData.token) {
- logger.warn(
- `[verifyEmail] [Email verification token data is invalid] [Email: ${decodedEmail}]`,
- );
+ logger.warn(`[verifyEmail] [Email verification token data is invalid] [User ID: ${user._id}]`);
return new Error(invalidEmailVerificationMessage);
}
const tokenUserId = emailVerificationData.userId?.toString();
const userId = user._id?.toString();
if (!tokenUserId || tokenUserId !== userId) {
- logger.warn(`[verifyEmail] [Email verification token user mismatch] [Email: ${decodedEmail}]`);
+ logger.warn(`[verifyEmail] [Email verification token user mismatch] [User ID: ${user._id}]`);
return new Error(invalidEmailVerificationMessage);
}
@@ -343,26 +342,26 @@ const verifyEmail = async (req) => {
if (!isValid) {
logger.warn(
- `[verifyEmail] [Invalid or expired email verification token] [Email: ${decodedEmail}]`,
+ `[verifyEmail] [Invalid or expired email verification token] [User ID: ${user._id}]`,
);
return new Error(invalidEmailVerificationMessage);
}
if (user.emailVerified) {
await deleteTokens(getEmailVerificationTokenDeleteQuery(emailVerificationData));
- logger.info(`[verifyEmail] Email already verified [Email: ${decodedEmail}]`);
+ logger.info(`[verifyEmail] Email already verified [User ID: ${user._id}]`);
return { message: 'Email verification was successful', status: 'success' };
}
const updatedUser = await updateUser(emailVerificationData.userId, { emailVerified: true });
if (!updatedUser) {
- logger.warn(`[verifyEmail] [User update failed] [Email: ${decodedEmail}]`);
+ logger.warn(`[verifyEmail] [User update failed] [User ID: ${user._id}]`);
return new Error(invalidEmailVerificationMessage);
}
await deleteTokens(getEmailVerificationTokenDeleteQuery(emailVerificationData));
- logger.info(`[verifyEmail] Email verification successful [Email: ${decodedEmail}]`);
+ logger.info(`[verifyEmail] Email verification successful [User ID: ${user._id}]`);
return { message: 'Email verification was successful', status: 'success' };
};
@@ -376,11 +375,10 @@ const registerUser = async (user, additionalData = {}) => {
const result = registerSchema.safeParse(user);
if (!result.success) {
const errorMessage = errorsToString(result.error.errors);
- logger.info(
- 'Route: register - Validation Error',
- { name: 'Request params:', value: user },
- { name: 'Validation error:', value: errorMessage },
- );
+ logger.info('Route: register - Validation Error', {
+ name: 'Validation error:',
+ value: errorMessage,
+ });
return { status: 404, message: errorMessage };
}
@@ -395,18 +393,14 @@ const registerUser = async (user, additionalData = {}) => {
if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) {
const errorMessage =
'The email address provided cannot be used. Please use a different email address.';
- logger.error(`[registerUser] [Registration not allowed] [Email: ${user.email}]`);
+ logger.error('[registerUser] [Registration not allowed]');
return { status: 403, message: errorMessage };
}
const existingUser = await findUser({ email }, 'email _id');
if (existingUser) {
- logger.info(
- 'Register User - Email in use',
- { name: 'Request params:', value: user },
- { name: 'Existing user:', value: existingUser },
- );
+ logger.info(`[registerUser] Email in use [User ID: ${existingUser._id}]`);
// Sleep for 1 second
await new Promise((resolve) => setTimeout(resolve, 1000));
@@ -449,12 +443,19 @@ const registerUser = async (user, additionalData = {}) => {
* without the response body revealing which of the two happened. */
return { status: 200, message: genericVerificationMessage, userCreated: true };
} catch (err) {
- logger.error('[registerUser] Error in registering user:', err);
+ logger.error('[registerUser] Error in registering user:', getSafeErrorMetadata(err));
if (newUserId) {
- const result = await deleteUserById(newUserId);
- logger.warn(
- `[registerUser] [Email: ${email}] [Temporary User deleted: ${JSON.stringify(result)}]`,
- );
+ try {
+ const result = await deleteUserById(newUserId);
+ logger.warn(
+ `[registerUser] [User ID: ${newUserId}] [Temporary User deleted: ${JSON.stringify(result)}]`,
+ );
+ } catch (cleanupError) {
+ logger.error(
+ `[registerUser] [User ID: ${newUserId}] Failed to delete temporary user`,
+ getSafeErrorMetadata(cleanupError),
+ );
+ }
}
return { status: 500, message: 'Something went wrong' };
}
@@ -480,9 +481,7 @@ const requestPasswordReset = async (req) => {
const baseConfig = await getAppConfig({ baseOnly: true });
if (!isEmailDomainAllowed(email, baseConfig?.registration?.allowedDomains)) {
- logger.warn(
- `[requestPasswordReset] Blocked - email domain not allowed [Email: ${email}] [IP: ${req.ip}]`,
- );
+ logger.warn('[requestPasswordReset] Blocked - email domain not allowed');
const error = new Error(ErrorTypes.AUTH_FAILED);
error.code = ErrorTypes.AUTH_FAILED;
error.message = 'Email domain not allowed';
@@ -495,24 +494,25 @@ const requestPasswordReset = async (req) => {
try {
appConfig = await resolveAppConfigForUser(getAppConfig, user);
} catch (err) {
- logger.error('[requestPasswordReset] Failed to resolve tenant config, using base:', err);
+ logger.error(
+ '[requestPasswordReset] Failed to resolve tenant config, using base:',
+ getSafeErrorMetadata(err),
+ );
}
}
if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) {
- logger.warn(
- `[requestPasswordReset] Tenant config blocked domain [Email: ${email}] [IP: ${req.ip}]`,
- );
+ logger.warn('[requestPasswordReset] Tenant config blocked domain');
return {
message: 'If an account with that email exists, a password reset link has been sent to it.',
};
}
const emailEnabled = checkEmailConfig();
- logger.warn(`[requestPasswordReset] [Password reset request initiated] [Email: ${email}]`);
+ logger.warn('[requestPasswordReset] [Password reset request initiated]');
if (!user) {
- logger.warn(`[requestPasswordReset] [No user found] [Email: ${email}] [IP: ${req.ip}]`);
+ logger.warn('[requestPasswordReset] [No user found]');
return {
message: 'If an account with that email exists, a password reset link has been sent to it.',
};
@@ -548,13 +548,9 @@ const requestPasswordReset = async (req) => {
},
template: 'requestPasswordReset.handlebars',
});
- logger.info(
- `[requestPasswordReset] Link emailed. [Email: ${email}] [ID: ${user._id}] [IP: ${req.ip}]`,
- );
+ logger.info(`[requestPasswordReset] Link emailed. [User ID: ${user._id}]`);
} else {
- logger.info(
- `[requestPasswordReset] Link issued. [Email: ${email}] [ID: ${user._id}] [IP: ${req.ip}]`,
- );
+ logger.info(`[requestPasswordReset] Link issued. [User ID: ${user._id}]`);
return { link };
}
@@ -604,7 +600,7 @@ const resetPassword = async (userId, token, password) => {
}
await deleteTokens(getPasswordResetTokenDeleteQuery(passwordResetToken));
- logger.info(`[resetPassword] Password reset successful. [Email: ${user.email}]`);
+ logger.info(`[resetPassword] Password reset successful. [User ID: ${userId}]`);
return { message: 'Password reset was successful' };
};
@@ -968,7 +964,7 @@ const resendVerificationEmail = async (req) => {
const user = await findUser({ email }, 'email _id name');
if (!user) {
- logger.warn(`[resendVerificationEmail] [No user found] [Email: ${email}]`);
+ logger.warn('[resendVerificationEmail] [No user found]');
return { status: 200, message: genericVerificationMessage };
}
@@ -1001,14 +997,17 @@ const resendVerificationEmail = async (req) => {
expiresIn: 900,
});
- logger.info(`[resendVerificationEmail] Verification link issued. [Email: ${user.email}]`);
+ logger.info(`[resendVerificationEmail] Verification link issued. [User ID: ${user._id}]`);
return {
status: 200,
message: genericVerificationMessage,
};
} catch (error) {
- logger.error(`[resendVerificationEmail] Error resending verification email: ${error.message}`);
+ logger.error(
+ '[resendVerificationEmail] Error resending verification email:',
+ getSafeErrorMetadata(error),
+ );
return {
status: 200,
message: genericVerificationMessage,
diff --git a/api/server/services/AuthService.spec.js b/api/server/services/AuthService.spec.js
index 82dcfae4d6..c3c224d99b 100644
--- a/api/server/services/AuthService.spec.js
+++ b/api/server/services/AuthService.spec.js
@@ -27,6 +27,7 @@ jest.mock(
isEnabled: jest.fn((val) => val === 'true' || val === true),
checkEmailConfig: jest.fn(),
isEmailDomainAllowed: jest.fn(),
+ getSafeErrorMetadata: jest.fn((error) => ({ type: error?.name ?? 'UnknownError' })),
math: jest.fn((val, fallback) => (val ? Number(val) : fallback)),
storeOpenIdSession: jest.fn(),
shouldUseSecureCookie,
@@ -143,11 +144,13 @@ let parseCloudFrontCookieScope;
let storeOpenIdSession;
let jwt;
let logger;
+let registerSchema;
let getTenantId;
let findUser;
let findToken;
let createUser;
let updateUser;
+let deleteUserById;
let countUsers;
let getUserById;
let generateToken;
@@ -185,12 +188,14 @@ jest.isolateModules(() => {
storeOpenIdSession,
} = require('@librechat/api'));
jwt = require('jsonwebtoken');
+ ({ registerSchema } = require('~/strategies/validators'));
({ logger, getTenantId } = require('@librechat/data-schemas'));
({
findUser,
findToken,
createUser,
updateUser,
+ deleteUserById,
countUsers,
getUserById,
generateToken,
@@ -689,6 +694,9 @@ describe('setOpenIDAuthTokens', () => {
});
});
+const loggedText = () =>
+ JSON.stringify(['info', 'warn', 'error', 'debug'].map((level) => logger[level].mock.calls));
+
describe('registerUser', () => {
const registrationPayload = {
name: 'Test User',
@@ -765,6 +773,62 @@ describe('registerUser', () => {
}),
);
});
+
+ it('contains a failed cleanup of the temporary user and logs safe metadata only', async () => {
+ checkEmailConfig.mockReturnValue(true);
+ sendEmail.mockRejectedValueOnce(new Error('smtp rejected [email protected]'));
+ deleteUserById.mockRejectedValueOnce(new Error('db failure [email protected]'));
+
+ const result = await registerUser(registrationPayload);
+
+ expect(result).toEqual({ status: 500, message: 'Something went wrong' });
+ expect(loggedText()).not.toContain('[email protected]');
+ });
+
+ it('logs a duplicate registration by id without the body or existing user', async () => {
+ findUser.mockResolvedValue({ _id: 'existing-id', email: '[email protected]' });
+
+ const result = await registerUser({ ...registrationPayload, email: '[email protected]' });
+
+ expect(result.status).toBe(200);
+ expect(createUser).not.toHaveBeenCalled();
+ expect(logger.info.mock.calls).toEqual([
+ ['[registerUser] Email in use [User ID: existing-id]'],
+ ]);
+ const logged = loggedText();
+ for (const secret of [
+ 'testuser',
+ 'Test User',
+ registrationPayload.password,
+ ]) {
+ expect(logged).not.toContain(secret);
+ }
+ });
+
+ it('does not log the registration body on validation failure', async () => {
+ registerSchema.safeParse.mockReturnValueOnce({
+ success: false,
+ error: { errors: [{ path: ['password'], message: 'Password too short' }] },
+ });
+
+ const result = await registerUser({
+ ...registrationPayload,
+ email: '[email protected]',
+ });
+
+ expect(result.status).toBe(404);
+ expect(logger.info).toHaveBeenCalled();
+ const logged = loggedText();
+ for (const secret of [
+ 'testuser',
+ 'Test User',
+ registrationPayload.password,
+ ]) {
+ expect(logged).not.toContain(secret);
+ }
+ });
});
describe('verifyEmail public response handling', () => {
@@ -1188,6 +1252,19 @@ describe('resendVerificationEmail', () => {
jest.clearAllMocks();
});
+ it('logs a failed resend without the error message or address', async () => {
+ findUser.mockResolvedValue({ _id: 'user-fail', email: '[email protected]', name: 'Leaky' });
+ checkEmailConfig.mockReturnValue(true);
+ sendEmail.mockRejectedValueOnce(new Error('rejected [email protected]'));
+
+ await resendVerificationEmail({ body: { email: '[email protected]' } });
+
+ expect(logger.error.mock.calls).toEqual([
+ ['[resendVerificationEmail] Error resending verification email:', { type: 'Error' }],
+ ]);
+ expect(loggedText()).not.toContain('[email protected]');
+ });
+
it('should not delete tokens when no user exists for the email', async () => {
findUser.mockResolvedValue(null);
@@ -1257,7 +1334,8 @@ describe('resendVerificationEmail', () => {
message: 'Please check your email to verify your email address.',
});
expect(logger.error).toHaveBeenCalledWith(
- '[resendVerificationEmail] Error resending verification email: mail transport unavailable',
+ '[resendVerificationEmail] Error resending verification email:',
+ { type: 'Error' },
);
});
});
diff --git a/e2e/specs/mock/scenarios/auth-log-redaction.spec.ts b/e2e/specs/mock/scenarios/auth-log-redaction.spec.ts
new file mode 100644
index 0000000000..bcc94022cf
--- /dev/null
+++ b/e2e/specs/mock/scenarios/auth-log-redaction.spec.ts
@@ -0,0 +1,44 @@
+import { randomUUID } from 'crypto';
+import { expect, test } from '@playwright/test';
+
+const GENERIC_RESET_MESSAGE =
+ 'If an account with that email exists, a password reset link has been sent to it.';
+
+test.describe('auth flows after log redaction', () => {
+ test('an unknown address gets the generic password reset reply @scenario:auth-reset-unknown-email-generic-reply', async ({
+ playwright,
+ baseURL,
+ }) => {
+ const request = await playwright.request.newContext({ baseURL });
+ try {
+ const response = await request.post('/api/auth/requestPasswordReset', {
+ data: { email: `unknown-${randomUUID().slice(0, 8)}@example.com` },
+ });
+ expect(response.status()).toBe(200);
+ expect(await response.json()).toEqual({ message: GENERIC_RESET_MESSAGE });
+ } finally {
+ await request.dispose();
+ }
+ });
+
+ test('an invalid registration is rejected with its validation error @scenario:auth-register-validation-error-reported', async ({
+ playwright,
+ baseURL,
+ }) => {
+ const request = await playwright.request.newContext({ baseURL });
+ try {
+ const response = await request.post('/api/auth/register', {
+ data: {
+ email: `short-${randomUUID().slice(0, 8)}@example.com`,
+ name: 'Short Password',
+ password: 'a',
+ confirm_password: 'a',
+ },
+ });
+ expect(response.ok()).toBeFalsy();
+ expect(await response.text()).toMatch(/password/i);
+ } finally {
+ await request.dispose();
+ }
+ });
+});
diff --git a/packages/api/src/auth/email.ts b/packages/api/src/auth/email.ts
index e990fe5af1..91c5711f48 100644
--- a/packages/api/src/auth/email.ts
+++ b/packages/api/src/auth/email.ts
@@ -2,6 +2,7 @@ import { z } from 'zod';
import { timingSafeEqual } from 'node:crypto';
import { logger, hashToken, getRandomValues, isValidObjectIdString } from '@librechat/data-schemas';
import type { EmailChangeErrorCode, TCustomConfig } from 'librechat-data-provider';
+import { getSafeErrorMetadata } from '../utils/errors';
import { isEmailDomainAllowed } from './domain';
import { isEnabled } from '../utils/common';
@@ -274,7 +275,10 @@ async function sendSecurityNotification(
try {
await deps.sendEmail(data);
} catch (error) {
- logger.error(`[emailChange] Failed to send ${logContext} notification`, error);
+ logger.error(
+ `[emailChange] Failed to send ${logContext} notification`,
+ getSafeErrorMetadata(error),
+ );
}
}
@@ -343,7 +347,7 @@ async function deleteTokensOrLog(
try {
await deps.deleteTokens(query, tenantId);
} catch (error) {
- logger.error(`[emailChange] Failed to clean up ${context}`, error);
+ logger.error(`[emailChange] Failed to clean up ${context}`, getSafeErrorMetadata(error));
}
}
@@ -361,7 +365,7 @@ async function claimTokenIfCurrent(
const { deletedCount } = await deps.deleteTokens(query, tenantId);
return deletedCount ? 'claimed' : 'superseded';
} catch (error) {
- logger.error('[emailChange] Failed to claim the pending token', error);
+ logger.error('[emailChange] Failed to claim the pending token', getSafeErrorMetadata(error));
return 'unavailable';
}
}
@@ -398,7 +402,7 @@ async function restoreClaimedToken(
tenantId,
);
} catch (error) {
- logger.error('[emailChange] Failed to restore the claimed token', error);
+ logger.error('[emailChange] Failed to restore the claimed token', getSafeErrorMetadata(error));
}
}
@@ -444,9 +448,7 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
}
const ip = input.ip ?? 'unknown';
- logger.info(
- `[emailChange] Change requested [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`,
- );
+ logger.info(`[emailChange] Change requested [User ID: ${userId}] [IP: ${ip}]`);
await sendSecurityNotification(
deps,
{
@@ -466,16 +468,12 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
const passwordMatches = await deps.verifyPassword(user, parsed.data.currentPassword);
if (!passwordMatches) {
- logger.warn(
- `[emailChange] Incorrect password [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`,
- );
+ logger.warn(`[emailChange] Incorrect password [User ID: ${userId}] [IP: ${ip}]`);
return result(403, 'Current password is incorrect', 'current_password_invalid');
}
if (!isEmailDomainAllowed(newEmail, input.allowedDomains)) {
- logger.warn(
- `[emailChange] Domain not allowed [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`,
- );
+ logger.warn(`[emailChange] Domain not allowed [User ID: ${userId}] [IP: ${ip}]`);
return result(403, 'Email domain is not allowed', 'email_domain_not_allowed');
}
@@ -491,9 +489,7 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
]);
if (existingUser && userIdOf(existingUser) !== userId) {
- logger.warn(
- `[emailChange] Email already in use [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`,
- );
+ logger.warn(`[emailChange] Email already in use [User ID: ${userId}] [IP: ${ip}]`);
return result(409, 'Email address is already linked to another account', 'email_in_use');
}
@@ -510,9 +506,7 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
/** The re-read above guards delivery: an account change during request validation must not
* produce a verification message whose link can never be used. */
if (!accountMatchesRequest(latestUser, userId, oldEmail, user.password)) {
- logger.warn(
- `[emailChange] Account changed while issuing [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`,
- );
+ logger.warn(`[emailChange] Account changed while issuing [User ID: ${userId}] [IP: ${ip}]`);
return result(409, 'Account was modified during the request', 'account_modified');
}
@@ -532,8 +526,8 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
});
} catch (error) {
logger.error(
- `[emailChange] Verification delivery failed [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`,
- error,
+ `[emailChange] Verification delivery failed [User ID: ${userId}] [IP: ${ip}]`,
+ getSafeErrorMetadata(error),
);
return result(500, 'Failed to send verification email', 'email_delivery_failed');
}
@@ -569,7 +563,7 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
}
if (!replacedToken) {
logger.warn(
- `[emailChange] Competing request completed first [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`,
+ `[emailChange] Competing request completed first [User ID: ${userId}] [IP: ${ip}]`,
);
return result(409, 'Another email change request completed first', 'request_in_progress');
}
@@ -579,15 +573,11 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
const committedUser = await deps.getUserById(input.userId, input.tenantId);
if (!accountMatchesRequest(committedUser, userId, oldEmail, user.password)) {
await deleteTokensOrLog(deps, tokenQuery, user.tenantId, 'token bound to a stale address');
- logger.warn(
- `[emailChange] Account changed while issuing [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`,
- );
+ logger.warn(`[emailChange] Account changed while issuing [User ID: ${userId}] [IP: ${ip}]`);
return result(409, 'Account was modified during the request', 'account_modified');
}
- logger.info(
- `[emailChange] Verification issued [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`,
- );
+ logger.info(`[emailChange] Verification issued [User ID: ${userId}] [IP: ${ip}]`);
return result(200, 'Verification link sent to your new email address');
}
@@ -622,9 +612,7 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
isTokenExpired(emailChangeToken) ||
!(await tokenMatches(token, emailChangeToken.token))
) {
- logger.warn(
- `[emailChange] Invalid confirmation [User ID: ${userId}] [New Email: ${email}] [IP: ${ip}]`,
- );
+ logger.warn(`[emailChange] Invalid confirmation [User ID: ${userId}] [IP: ${ip}]`);
return unresolvedLink();
}
@@ -643,9 +631,7 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
normalizeEmail(emailChangeToken.email ?? '') !== email ||
normalizeEmail(emailChangeToken.identifier ?? '') !== oldEmail
) {
- logger.warn(
- `[emailChange] Stale confirmation [User ID: ${userId}] [New Email: ${email}] [IP: ${ip}]`,
- );
+ logger.warn(`[emailChange] Stale confirmation [User ID: ${userId}] [IP: ${ip}]`);
return unresolvedLink();
}
@@ -660,9 +646,7 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
}
if (!isEmailDomainAllowed(email, policy.allowedDomains)) {
- logger.warn(
- `[emailChange] Domain no longer allowed [User ID: ${userId}] [New Email: ${email}] [IP: ${ip}]`,
- );
+ logger.warn(`[emailChange] Domain no longer allowed [User ID: ${userId}] [IP: ${ip}]`);
return result(403, 'Email domain is not allowed', 'email_domain_not_allowed');
}
@@ -682,15 +666,11 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
tenantId,
);
if (claim === 'unavailable') {
- logger.error(
- `[emailChange] Token claim failed [User ID: ${userId}] [New Email: ${email}] [IP: ${ip}]`,
- );
+ logger.error(`[emailChange] Token claim failed [User ID: ${userId}] [IP: ${ip}]`);
return result(500, 'Failed to change email address');
}
if (claim === 'superseded') {
- logger.warn(
- `[emailChange] Superseded confirmation [User ID: ${userId}] [New Email: ${email}] [IP: ${ip}]`,
- );
+ logger.warn(`[emailChange] Superseded confirmation [User ID: ${userId}] [IP: ${ip}]`);
return result(400, EMAIL_CHANGE_ERROR_MESSAGE, 'invalid_token');
}
@@ -713,8 +693,8 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
return result(409, 'Email address is already linked to another account', 'email_in_use');
}
logger.error(
- `[emailChange] Update failed [User ID: ${userId}] [New Email: ${email}] [IP: ${ip}]`,
- error,
+ `[emailChange] Update failed [User ID: ${userId}] [IP: ${ip}]`,
+ getSafeErrorMetadata(error),
);
await restoreClaimedToken(deps, emailChangeToken, scope, tenantId);
return result(500, 'Failed to change email address');
@@ -778,9 +758,7 @@ export function createEmailChangeService(deps: EmailChangeDeps): {
),
]);
- logger.info(
- `[emailChange] Change completed [User ID: ${userId}] [Old Email: ${oldEmail}] [New Email: ${email}] [IP: ${ip}]`,
- );
+ logger.info(`[emailChange] Change completed [User ID: ${userId}] [IP: ${ip}]`);
return result(200, 'Email address changed successfully');
}
diff --git a/packages/data-schemas/src/methods/token.spec.ts b/packages/data-schemas/src/methods/token.spec.ts
index 0666a7aa56..ff42597ec9 100644
--- a/packages/data-schemas/src/methods/token.spec.ts
+++ b/packages/data-schemas/src/methods/token.spec.ts
@@ -3,6 +3,7 @@ import { MongoMemoryServer } from 'mongodb-memory-server';
import type * as t from '~/types';
import { createTokenModel } from '~/models/token';
import { createTokenMethods } from './token';
+import logger from '~/config/winston';
/** Mocking logger */
jest.mock('~/config/winston', () => ({
@@ -1292,3 +1293,23 @@ describe('Token email normalization', () => {
expect(found).not.toBeNull();
});
});
+
+describe('token method failure logging', () => {
+ it('logs only the error type when a lookup fails and still rethrows', async () => {
+ const failure = new Error('E11000 duplicate key [email protected]');
+ const spy = jest.spyOn(Token, 'findOne').mockImplementationOnce(() => {
+ throw failure;
+ });
+ (logger.debug as jest.Mock).mockClear();
+
+ await expect(methods.findToken({ email: '[email protected]' })).rejects.toBe(failure);
+
+ expect(logger.debug).toHaveBeenCalledWith('An error occurred while finding token', {
+ type: 'Error',
+ });
+ expect(JSON.stringify((logger.debug as jest.Mock).mock.calls)).not.toContain(
+ );
+ spy.mockRestore();
+ });
+});
diff --git a/packages/data-schemas/src/methods/token.ts b/packages/data-schemas/src/methods/token.ts
index db376829cc..316a143d8a 100644
--- a/packages/data-schemas/src/methods/token.ts
+++ b/packages/data-schemas/src/methods/token.ts
@@ -53,7 +53,9 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): {
return await Token.create(newTokenData);
} catch (error) {
- logger.debug('An error occurred while creating token:', error);
+ logger.debug('An error occurred while creating token', {
+ type: error instanceof Error ? error.name : typeof error,
+ });
throw error;
}
}
@@ -102,7 +104,9 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): {
throw error;
}
} catch (error) {
- logger.debug('An error occurred while conditionally replacing token:', error);
+ logger.debug('An error occurred while conditionally replacing token', {
+ type: error instanceof Error ? error.name : typeof error,
+ });
throw error;
}
}
@@ -129,7 +133,9 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): {
return await Token.findOneAndUpdate(dbQuery, dataToUpdate, { new: true });
} catch (error) {
- logger.debug('An error occurred while updating token:', error);
+ logger.debug('An error occurred while updating token', {
+ type: error instanceof Error ? error.name : typeof error,
+ });
throw error;
}
}
@@ -171,7 +177,9 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): {
$and: conditions,
});
} catch (error) {
- logger.debug('An error occurred while deleting tokens:', error);
+ logger.debug('An error occurred while deleting tokens', {
+ type: error instanceof Error ? error.name : typeof error,
+ });
throw error;
}
}
@@ -212,7 +220,9 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): {
return token as IToken | null;
} catch (error) {
- logger.debug('An error occurred while finding token:', error);
+ logger.debug('An error occurred while finding token', {
+ type: error instanceof Error ? error.name : typeof error,
+ });
throw error;
}
}