From 4ffe3825ecc5dcc1e7738e08dd3936b1be46ea5b Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Wed, 23 Sep 2026 10:47:30 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=A7=20feat:=20add=20email=20address=20?= =?UTF-8?q?change=20(#14597)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 9ff251dd96b350105b46185715a897cc1d4c30cf) Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/14597 --- .env.example | 5 + .github/workflows/playwright-mock.yml | 21 +- api/server/controllers/UserController.js | 64 +- api/server/controllers/UserController.spec.js | 89 ++ .../__tests__/UserController.mcpOAuth.spec.js | 5 + .../controllers/__tests__/deleteUser.spec.js | 5 + .../__tests__/maybeUninstallOAuthMCP.spec.js | 5 + api/server/middleware/config/app.js | 18 +- api/server/middleware/index.js | 2 + .../middleware/limiters/emailChangeLimiter.js | 40 + .../emailChangeSubmissionIpLimiter.js | 45 + .../limiters/emailChangeSubmissionLimiter.js | 39 + .../emailChangeSubmissionLimiter.test.js | 36 + api/server/middleware/limiters/index.js | 6 + api/server/routes/__tests__/config.spec.js | 22 + api/server/routes/config.js | 13 +- api/server/routes/user.js | 19 + .../routes/user.verify-ratelimit.test.js | 50 + api/server/services/AuthService.js | 25 +- api/server/services/AuthService.spec.js | 158 +-- .../emails/emailChangeAttempt.handlebars | 42 + .../utils/emails/emailChanged.handlebars | 44 + .../utils/emails/verifyEmailChange.handlebars | 46 + client/src/components/Auth/VerifyEmail.tsx | 129 +- .../Auth/__tests__/LoginForm.spec.tsx | 1 + .../Auth/__tests__/VerifyEmail.spec.tsx | 117 ++ .../Nav/Settings/__tests__/Sidebar.spec.tsx | 2 + .../Nav/Settings/__tests__/registry.spec.ts | 29 + .../src/components/Nav/Settings/context.tsx | 6 + .../src/components/Nav/Settings/registry.tsx | 10 + client/src/components/Nav/Settings/types.ts | 2 + .../Nav/SettingsTabs/Account/ChangeEmail.tsx | 159 +++ .../Account/__tests__/ChangeEmail.spec.tsx | 58 + client/src/data-provider/Auth/mutations.ts | 23 + client/src/locales/en/translation.json | 23 + client/src/utils/errors.ts | 8 + e2e/README.md | 17 + e2e/playwright.config.email.ts | 77 ++ e2e/setup/authenticate.ts | 12 +- e2e/setup/cleanupUser.ts | 12 +- e2e/setup/global-setup.email.ts | 75 ++ e2e/setup/global-teardown.email.ts | 15 + e2e/setup/mailbox-server.js | 229 ++++ e2e/setup/mailbox.ts | 76 ++ e2e/setup/users.email.ts | 21 + e2e/specs/email/email-change-disabled.spec.ts | 51 + e2e/specs/email/email-change.spec.ts | 101 ++ .../scenarios/email-change-gating.spec.ts | 136 ++ librechat.example.yaml | 17 + package.json | 2 + packages/api/src/app/limits.ts | 2 + packages/api/src/app/service.ts | 13 + packages/api/src/auth/email.spec.ts | 1145 +++++++++++++++++ packages/api/src/auth/email.ts | 788 ++++++++++++ .../api/src/auth/emailChangeStore.spec.ts | 261 ++++ packages/api/src/auth/emailChangeStore.ts | 221 ++++ packages/api/src/auth/index.ts | 3 + packages/api/src/auth/passwordReset.spec.ts | 203 +++ packages/api/src/auth/passwordReset.ts | 119 ++ ...ectionFactory.oauthSdk.integration.test.ts | 8 + .../__tests__/MCPConnectionFactory.test.ts | 25 + .../mcp/__tests__/MCPOAuthTokenExpiry.test.ts | 2 + packages/data-provider/src/api-endpoints.ts | 4 + packages/data-provider/src/config.ts | 29 + packages/data-provider/src/data-service.ts | 12 + packages/data-provider/src/types.ts | 30 + packages/data-schemas/src/app/service.ts | 2 + .../data-schemas/src/methods/token.spec.ts | 106 +- packages/data-schemas/src/methods/token.ts | 83 ++ .../src/methods/user.methods.spec.ts | 23 + packages/data-schemas/src/methods/user.ts | 24 +- packages/data-schemas/src/schema/token.ts | 4 + packages/data-schemas/src/schema/user.ts | 5 + packages/data-schemas/src/types/app.ts | 2 + packages/data-schemas/src/types/token.ts | 4 + packages/data-schemas/src/types/user.ts | 1 + 76 files changed, 5173 insertions(+), 153 deletions(-) create mode 100644 api/server/middleware/limiters/emailChangeLimiter.js create mode 100644 api/server/middleware/limiters/emailChangeSubmissionIpLimiter.js create mode 100644 api/server/middleware/limiters/emailChangeSubmissionLimiter.js create mode 100644 api/server/middleware/limiters/emailChangeSubmissionLimiter.test.js create mode 100644 api/server/utils/emails/emailChangeAttempt.handlebars create mode 100644 api/server/utils/emails/emailChanged.handlebars create mode 100644 api/server/utils/emails/verifyEmailChange.handlebars create mode 100644 client/src/components/Auth/__tests__/VerifyEmail.spec.tsx create mode 100644 client/src/components/Nav/SettingsTabs/Account/ChangeEmail.tsx create mode 100644 client/src/components/Nav/SettingsTabs/Account/__tests__/ChangeEmail.spec.tsx create mode 100644 e2e/playwright.config.email.ts create mode 100644 e2e/setup/global-setup.email.ts create mode 100644 e2e/setup/global-teardown.email.ts create mode 100644 e2e/setup/mailbox-server.js create mode 100644 e2e/setup/mailbox.ts create mode 100644 e2e/setup/users.email.ts create mode 100644 e2e/specs/email/email-change-disabled.spec.ts create mode 100644 e2e/specs/email/email-change.spec.ts create mode 100644 e2e/specs/mock/scenarios/email-change-gating.spec.ts create mode 100644 packages/api/src/auth/email.spec.ts create mode 100644 packages/api/src/auth/email.ts create mode 100644 packages/api/src/auth/emailChangeStore.spec.ts create mode 100644 packages/api/src/auth/emailChangeStore.ts create mode 100644 packages/api/src/auth/passwordReset.spec.ts create mode 100644 packages/api/src/auth/passwordReset.ts diff --git a/.env.example b/.env.example index 05c8baeadf..922fd6e8e4 100644 --- a/.env.example +++ b/.env.example @@ -892,6 +892,11 @@ ALLOW_SOCIAL_LOGIN=false ALLOW_SOCIAL_REGISTRATION=false ALLOW_PASSWORD_RESET=false # ALLOW_ACCOUNT_DELETION=true # note: enabled by default if omitted/commented out +# ALLOW_EMAIL_CHANGE=true # note: enabled by default if omitted/commented out +# `emailChange` in librechat.yaml takes precedence over this, and also sets the link lifetime. +# Multi-node rollouts: keep this false until every node runs this version or newer. Older +# nodes issue and accept password reset links that carry no address binding, so one held by +# a previous address owner can outlive the change and reset the renamed account. ALLOW_UNVERIFIED_EMAIL_LOGIN=true SESSION_EXPIRY=1000 * 60 * 15 diff --git a/.github/workflows/playwright-mock.yml b/.github/workflows/playwright-mock.yml index 9713220892..aa56ad71d3 100644 --- a/.github/workflows/playwright-mock.yml +++ b/.github/workflows/playwright-mock.yml @@ -70,7 +70,7 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha }} CHANGED: ${{ github.event.pull_request.changed_files }} E2E_SKIP_ARMED: ${{ vars.CODEGRAPH_E2E_SKIP }} - FULL_INCLUDE: '{"include":[{"name":"memory, shard 1/6","stream_store":"memory","redis_image":"","suite":"full","shard":"1/6","artifact":"memory-1-of-6"},{"name":"memory, shard 2/6","stream_store":"memory","redis_image":"","suite":"full","shard":"2/6","artifact":"memory-2-of-6"},{"name":"memory, shard 3/6","stream_store":"memory","redis_image":"","suite":"full","shard":"3/6","artifact":"memory-3-of-6"},{"name":"memory, shard 4/6","stream_store":"memory","redis_image":"","suite":"full","shard":"4/6","artifact":"memory-4-of-6"},{"name":"memory, shard 5/6","stream_store":"memory","redis_image":"","suite":"full","shard":"5/6","artifact":"memory-5-of-6"},{"name":"memory, shard 6/6","stream_store":"memory","redis_image":"","suite":"full","shard":"6/6","artifact":"memory-6-of-6"},{"name":"redis transport, shard 1/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"1/2","artifact":"redis-transport-1-of-2"},{"name":"redis transport, shard 2/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"2/2","artifact":"redis-transport-2-of-2"}]}' + FULL_INCLUDE: '{"include":[{"name":"memory, shard 1/3","stream_store":"memory","redis_image":"","suite":"full","shard":"1/3","artifact":"memory-1-of-3","email_change":"true"},{"name":"memory, shard 2/3","stream_store":"memory","redis_image":"","suite":"full","shard":"2/3","artifact":"memory-2-of-3"},{"name":"memory, shard 3/3","stream_store":"memory","redis_image":"","suite":"full","shard":"3/3","artifact":"memory-3-of-3"},{"name":"redis transport","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"","artifact":"redis-transport"}]}' run: | set +e note() { echo "$1" >> "$GITHUB_STEP_SUMMARY"; } @@ -176,9 +176,9 @@ jobs: ${{ (github.event_name == 'pull_request' && needs.codegraph_select.outputs.e2e_include != '' && fromJSON(needs.codegraph_select.outputs.e2e_include)) || - ((github.event_name == 'pull_request' || inputs.coverage == 'pr') && - fromJSON('{"include":[{"name":"memory, shard 1/6","stream_store":"memory","redis_image":"","suite":"full","shard":"1/6","artifact":"memory-1-of-6"},{"name":"memory, shard 2/6","stream_store":"memory","redis_image":"","suite":"full","shard":"2/6","artifact":"memory-2-of-6"},{"name":"memory, shard 3/6","stream_store":"memory","redis_image":"","suite":"full","shard":"3/6","artifact":"memory-3-of-6"},{"name":"memory, shard 4/6","stream_store":"memory","redis_image":"","suite":"full","shard":"4/6","artifact":"memory-4-of-6"},{"name":"memory, shard 5/6","stream_store":"memory","redis_image":"","suite":"full","shard":"5/6","artifact":"memory-5-of-6"},{"name":"memory, shard 6/6","stream_store":"memory","redis_image":"","suite":"full","shard":"6/6","artifact":"memory-6-of-6"},{"name":"redis transport, shard 1/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"1/2","artifact":"redis-transport-1-of-2"},{"name":"redis transport, shard 2/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"2/2","artifact":"redis-transport-2-of-2"}]}')) || - fromJSON('{"include":[{"name":"memory, shard 1/2","stream_store":"memory","redis_image":"","suite":"full","shard":"1/2","artifact":"memory-1-of-2"},{"name":"memory, shard 2/2","stream_store":"memory","redis_image":"","suite":"full","shard":"2/2","artifact":"memory-2-of-2"},{"name":"redis, shard 1/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"full","shard":"1/2","artifact":"redis-1-of-2"},{"name":"redis, shard 2/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"full","shard":"2/2","artifact":"redis-2-of-2"}]}') + (github.event_name == 'pull_request' && + fromJSON('{"include":[{"name":"memory, shard 1/3","stream_store":"memory","redis_image":"","suite":"full","shard":"1/3","artifact":"memory-1-of-3","email_change":"true"},{"name":"memory, shard 2/3","stream_store":"memory","redis_image":"","suite":"full","shard":"2/3","artifact":"memory-2-of-3"},{"name":"memory, shard 3/3","stream_store":"memory","redis_image":"","suite":"full","shard":"3/3","artifact":"memory-3-of-3"},{"name":"redis transport","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"","artifact":"redis-transport"}]}')) || + fromJSON('{"include":[{"name":"memory, shard 1/2","stream_store":"memory","redis_image":"","suite":"full","shard":"1/2","artifact":"memory-1-of-2","email_change":"true"},{"name":"memory, shard 2/2","stream_store":"memory","redis_image":"","suite":"full","shard":"2/2","artifact":"memory-2-of-2"},{"name":"redis, shard 1/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"full","shard":"1/2","artifact":"redis-1-of-2"},{"name":"redis, shard 2/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"full","shard":"2/2","artifact":"redis-2-of-2"}]}') }} services: redis: @@ -372,6 +372,19 @@ jobs: env: CI: 'true' + - name: Run registered-email change e2e + if: matrix.email_change == 'true' + run: npx playwright test --config=e2e/playwright.config.email.ts + env: + CI: 'true' + + - name: Run disabled registered-email change e2e + if: matrix.email_change == 'true' + run: npx playwright test --config=e2e/playwright.config.email.ts + env: + CI: 'true' + E2E_ALLOW_EMAIL_CHANGE: 'false' + - name: Upload Playwright HTML report if: ${{ !cancelled() }} uses: actions/upload-artifact@v6 diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.js index ca96b88e7a..2df1017a9a 100644 --- a/api/server/controllers/UserController.js +++ b/api/server/controllers/UserController.js @@ -1,8 +1,14 @@ +const bcrypt = require('bcryptjs'); const mongoose = require('mongoose'); -const { logger } = require('@librechat/data-schemas'); +const { logger, runAsSystem, tenantStorage } = require('@librechat/data-schemas'); const { getNewS3URL, needsRefresh, + comparePassword, + checkEmailConfig, + createEmailChangeService, + createEmailChangeDeps, + resolveEmailChangeSettings, GenerationJobManager, getAppConfigOptionsFromUser, normalizeHttpError, @@ -40,8 +46,30 @@ const { quiesceUserSchedules, restoreUserSchedulesFromDeletion, } = require('~/server/services/Schedules'); +const { sendEmail } = require('~/server/utils'); const db = require('~/models'); +const emailChangeService = createEmailChangeService( + createEmailChangeDeps({ + store: { + findUser: db.findUser, + getUserById: db.getUserById, + updateUser: db.updateUser, + findToken: db.findToken, + replaceTokenIfCurrent: db.replaceTokenIfCurrent, + deleteTokens: db.deleteTokens, + }, + withTenant: (tenantId, operation) => + tenantId ? tenantStorage.run({ tenantId }, operation) : runAsSystem(operation), + comparePassword: (user, password) => + comparePassword(user, password, { compare: bcrypt.compare }), + sendEmail, + getAppConfig, + clientDomain: process.env.DOMAIN_CLIENT ?? 'http://localhost:3080', + appName: process.env.APP_TITLE || 'LibreChat', + }), +); + const PUBLIC_USER_RESPONSE_FIELDS = [ '_id', 'id', @@ -630,12 +658,46 @@ const resendVerificationController = async (req, res) => { } }; +const requestEmailChangeController = async (req, res) => { + try { + const userId = req.user?._id?.toString?.() ?? req.user?.id?.toString?.(); + if (!userId) { + return res.status(401).json({ message: 'Unauthorized' }); + } + const result = await emailChangeService.requestEmailChange({ + body: req.body, + userId, + tenantId: req.user?.tenantId, + allowedDomains: req.config?.registration?.allowedDomains, + settings: resolveEmailChangeSettings(req.config?.emailChange), + emailEnabled: checkEmailConfig(), + ip: req.ip, + }); + return res.status(result.status).json({ message: result.message, code: result.code }); + } catch (error) { + logger.error('[requestEmailChangeController]', error); + return res.status(500).json({ message: 'Something went wrong.' }); + } +}; + +const confirmEmailChangeController = async (req, res) => { + try { + const result = await emailChangeService.confirmEmailChange({ body: req.body, ip: req.ip }); + return res.status(result.status).json({ message: result.message, code: result.code }); + } catch (error) { + logger.error('[confirmEmailChangeController]', error); + return res.status(500).json({ message: 'Something went wrong.' }); + } +}; + module.exports = { getUserController, getTermsStatusController, acceptTermsController, deleteUserController, verifyEmailController, + requestEmailChangeController, + confirmEmailChangeController, updateUserPluginsController, resendVerificationController, deleteUserMcpServers, diff --git a/api/server/controllers/UserController.spec.js b/api/server/controllers/UserController.spec.js index aecc5bc218..0912feca0e 100644 --- a/api/server/controllers/UserController.spec.js +++ b/api/server/controllers/UserController.spec.js @@ -22,6 +22,11 @@ const mockRestoreUserSchedules = jest.fn().mockResolvedValue(undefined); const mockGetWebSearchInstallEntries = jest.fn(); const mockInvalidateCodeEnvironmentConfigCache = jest.fn().mockResolvedValue(undefined); const mockRevokeUserCodeEnvironmentWorkers = jest.fn().mockResolvedValue(0); +const mockEmailChangeService = { + requestEmailChange: jest.fn(), + confirmEmailChange: jest.fn(), +}; +const mockCreateEmailChangeService = jest.fn(() => mockEmailChangeService); jest.mock('@librechat/data-schemas', () => { const actual = jest.requireActual('@librechat/data-schemas'); @@ -68,6 +73,7 @@ jest.mock('~/models', () => { updateUser: jest.fn(), acceptTerms: jest.fn(), getUserById: jest.fn().mockResolvedValue(null), + findUser: jest.fn().mockResolvedValue(null), findToken: jest.fn(), getFiles: jest.fn().mockResolvedValue([]), removeUserFromAllGroups: jest.fn().mockImplementation(async (userId) => { @@ -97,6 +103,7 @@ jest.mock('sharp', () => jest.mock('@librechat/api', () => ({ ...jest.requireActual('@librechat/api'), + createEmailChangeService: (...args) => mockCreateEmailChangeService(...args), needsRefresh: jest.fn(), getNewS3URL: jest.fn(), getWebSearchInstallEntries: (...args) => mockGetWebSearchInstallEntries(...args), @@ -178,6 +185,7 @@ const { } = require('./UserController'); const { Group } = require('~/db/models'); const { + findUser, deleteConvos, acceptTerms, deleteUserById, @@ -279,6 +287,87 @@ describe('updateUserPluginsController', () => { }); }); +describe('emailChangeService dependencies', () => { + const emailChangeDeps = mockCreateEmailChangeService.mock.calls[0][0]; + + beforeEach(() => { + jest.clearAllMocks(); + findUser.mockResolvedValue(null); + }); + + it('constrains tenant-less email conflict checks to default-tenant users', async () => { + await emailChangeDeps.findUserByEmail('new@example.com'); + + expect(findUser).toHaveBeenCalledWith( + { + email: 'new@example.com', + $or: [{ tenantId: { $exists: false } }, { tenantId: null }], + }, + 'email _id tenantId', + ); + }); + + it('rechecks the domain policy against the full principal config, not the base config', async () => { + const { getAppConfig } = require('~/server/services/Config'); + getAppConfig.mockResolvedValue({ registration: { allowedDomains: ['allowed.com'] } }); + + const policy = await emailChangeDeps.resolvePolicy({ + _id: '507f1f77bcf86cd799439011', + role: 'USER', + idOnTheSource: 'source-id', + }); + + expect(policy.allowedDomains).toEqual(['allowed.com']); + expect(getAppConfig).toHaveBeenCalledWith( + expect.objectContaining({ userId: '507f1f77bcf86cd799439011', role: 'USER' }), + ); + expect(getAppConfig).not.toHaveBeenCalledWith(expect.objectContaining({ baseOnly: true })); + }); + + it('resolves a tenant-less domain policy outside the cross-tenant system context', async () => { + const { getAppConfig } = require('~/server/services/Config'); + const { getTenantId, SYSTEM_TENANT_ID } = require('@librechat/data-schemas'); + let observedTenant = 'unset'; + getAppConfig.mockImplementation(async () => { + observedTenant = getTenantId(); + return { registration: { allowedDomains: ['allowed.com'] } }; + }); + + await emailChangeDeps.resolvePolicy({ + _id: '507f1f77bcf86cd799439011', + role: 'USER', + }); + + expect(observedTenant).not.toBe(SYSTEM_TENANT_ID); + expect(getAppConfig).toHaveBeenCalledWith(expect.objectContaining({ tenantId: undefined })); + }); + + it('keeps the domain policy of a tenant user scoped to their own tenant', async () => { + const { getAppConfig } = require('~/server/services/Config'); + const { getTenantId } = require('@librechat/data-schemas'); + let observedTenant = 'unset'; + getAppConfig.mockImplementation(async () => { + observedTenant = getTenantId(); + return { registration: { allowedDomains: ['tenant.com'] } }; + }); + + await emailChangeDeps.resolvePolicy({ + _id: '507f1f77bcf86cd799439011', + role: 'USER', + tenantId: 'tenant-a', + }); + + expect(observedTenant).toBe('tenant-a'); + expect(getAppConfig).toHaveBeenCalledWith(expect.objectContaining({ tenantId: 'tenant-a' })); + }); + + afterEach(() => { + const { getAppConfig } = require('~/server/services/Config'); + getAppConfig.mockReset(); + getAppConfig.mockResolvedValue({}); + }); +}); + describe('verifyEmailController', () => { const mockRes = { status: jest.fn().mockReturnThis(), diff --git a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js index a7676324cf..26cbc25df1 100644 --- a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js +++ b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js @@ -26,6 +26,11 @@ jest.mock('librechat-data-provider', () => ({ jest.mock('@librechat/api', () => ({ ...jest.requireActual('@librechat/api'), + createEmailChangeService: jest.fn(() => ({ + requestEmailChange: jest.fn(), + confirmEmailChange: jest.fn(), + })), + createEmailChangeDeps: jest.fn(() => ({})), MCPOAuthHandler: { generateFlowId: jest.fn((userId, serverName, tenantId) => { const flowId = `${userId}:${serverName}`; diff --git a/api/server/controllers/__tests__/deleteUser.spec.js b/api/server/controllers/__tests__/deleteUser.spec.js index f625311d49..0294b05bb5 100644 --- a/api/server/controllers/__tests__/deleteUser.spec.js +++ b/api/server/controllers/__tests__/deleteUser.spec.js @@ -48,6 +48,11 @@ jest.mock('librechat-data-provider', () => ({ })); jest.mock('@librechat/api', () => ({ + createEmailChangeService: jest.fn(() => ({ + requestEmailChange: jest.fn(), + confirmEmailChange: jest.fn(), + })), + createEmailChangeDeps: jest.fn(() => ({})), MCPOAuthHandler: {}, MCPTokenStorage: {}, normalizeHttpError: jest.fn(), diff --git a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js index defbca7f9d..53c36b7719 100644 --- a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js +++ b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js @@ -31,6 +31,11 @@ jest.mock('@librechat/data-schemas', () => ({ jest.mock('@librechat/api', () => { return { ...jest.requireActual('@librechat/api'), + createEmailChangeService: jest.fn(() => ({ + requestEmailChange: jest.fn(), + confirmEmailChange: jest.fn(), + })), + createEmailChangeDeps: jest.fn(() => ({})), MCPOAuthHandler: { revokeOAuthToken: (...args) => mockRevokeOAuthToken(...args), deleteFlowAndStateMapping: (...args) => mockDeleteFlowAndStateMapping(...args), diff --git a/api/server/middleware/config/app.js b/api/server/middleware/config/app.js index 3768089b24..6b7a969bed 100644 --- a/api/server/middleware/config/app.js +++ b/api/server/middleware/config/app.js @@ -1,5 +1,5 @@ const { logger } = require('@librechat/data-schemas'); -const { getAppConfigOptionsFromUser } = require('@librechat/api'); +const { getAppConfigOptionsFromUser, resolveStrictAppConfig } = require('@librechat/api'); const { getAppConfig } = require('~/server/services/Config'); const configMiddleware = async (req, res, next) => { @@ -24,4 +24,20 @@ const configMiddleware = async (req, res, next) => { } }; +/** The same resolution, without the fallback; `resolveStrictAppConfig` owns that choice. */ +const strictConfigMiddleware = async (req, res, next) => { + try { + req.config = await resolveStrictAppConfig(getAppConfig, req.user); + next(); + } catch (error) { + logger.error('Strict config middleware error:', { + error: error.message, + userRole: req.user?.role, + path: req.path, + }); + next(error); + } +}; + module.exports = configMiddleware; +module.exports.strictConfigMiddleware = strictConfigMiddleware; diff --git a/api/server/middleware/index.js b/api/server/middleware/index.js index 814baf075b..852b23b7f6 100644 --- a/api/server/middleware/index.js +++ b/api/server/middleware/index.js @@ -21,6 +21,7 @@ const checkInviteUser = require('./checkInviteUser'); const requireJwtAuth = require('./requireJwtAuth'); const { requireRumProxyAuth } = require('./requireJwtAuth'); const configMiddleware = require('./config/app'); +const { strictConfigMiddleware } = require('./config/app'); const validateModel = require('./validateModel'); const moderateText = require('./moderateText'); const logHeaders = require('./logHeaders'); @@ -55,6 +56,7 @@ module.exports = { requireSameOrigin, canDeleteAccount, configMiddleware, + strictConfigMiddleware, checkDomainAllowed, validateMessageReq, canReadActiveJobConversation, diff --git a/api/server/middleware/limiters/emailChangeLimiter.js b/api/server/middleware/limiters/emailChangeLimiter.js new file mode 100644 index 0000000000..ff7dff5bf9 --- /dev/null +++ b/api/server/middleware/limiters/emailChangeLimiter.js @@ -0,0 +1,40 @@ +const rateLimit = require('express-rate-limit'); +const { ViolationTypes } = require('librechat-data-provider'); +const { limiterCache, removePorts } = require('@librechat/api'); +const { logViolation } = require('~/cache'); + +const { + EMAIL_CHANGE_USER_WINDOW = 2, + EMAIL_CHANGE_USER_MAX = 3, + EMAIL_CHANGE_VIOLATION_SCORE: score, +} = process.env; +const windowMs = EMAIL_CHANGE_USER_WINDOW * 60 * 1000; +const max = EMAIL_CHANGE_USER_MAX; +const windowInMinutes = windowMs / 60000; +const message = `Too many attempts, please try again after ${windowInMinutes} minute(s)`; + +const handler = async (req, res) => { + const type = ViolationTypes.VERIFY_EMAIL_LIMIT; + const errorMessage = { + type, + max, + windowInMinutes, + }; + + await logViolation(req, res, type, errorMessage, score); + return res.status(429).json({ message }); +}; + +const limiterOptions = { + windowMs, + max, + handler, + /** Keyed per account so users sharing an egress address cannot exhaust each + * other's budget; falls back to the address only for unauthenticated calls. */ + keyGenerator: (req) => req.user?.id ?? removePorts(req), + store: limiterCache('email_change_limiter'), +}; + +const emailChangeLimiter = rateLimit(limiterOptions); + +module.exports = emailChangeLimiter; diff --git a/api/server/middleware/limiters/emailChangeSubmissionIpLimiter.js b/api/server/middleware/limiters/emailChangeSubmissionIpLimiter.js new file mode 100644 index 0000000000..59d3610ead --- /dev/null +++ b/api/server/middleware/limiters/emailChangeSubmissionIpLimiter.js @@ -0,0 +1,45 @@ +const rateLimit = require('express-rate-limit'); +const { ViolationTypes } = require('librechat-data-provider'); +const { limiterCache, removePorts } = require('@librechat/api'); +const { logViolation } = require('~/cache'); + +/** + * Confirmation is unauthenticated and `emailChangeSubmissionLimiter` keys on the + * caller-supplied `userId`, so rotating that id yields a fresh bucket per request. + * This layer bounds the whole source address, keeping the per-user limiter's + * isolation without letting one client issue unbounded token lookups. + */ +const { + EMAIL_CHANGE_CONFIRM_IP_WINDOW = 2, + EMAIL_CHANGE_CONFIRM_IP_MAX = 20, + EMAIL_CHANGE_SUBMISSION_IP_VIOLATION_SCORE: score, +} = process.env; +const windowMs = EMAIL_CHANGE_CONFIRM_IP_WINDOW * 60 * 1000; +const max = EMAIL_CHANGE_CONFIRM_IP_MAX; +const windowInMinutes = windowMs / 60000; +const message = `Too many attempts, please try again after ${windowInMinutes} minute(s)`; + +const handler = async (req, res) => { + const type = ViolationTypes.VERIFY_EMAIL_LIMIT; + const errorMessage = { + type, + max, + windowInMinutes, + limiter: 'submission_ip', + }; + + await logViolation(req, res, type, errorMessage, score); + return res.status(429).json({ message }); +}; + +const limiterOptions = { + windowMs, + max, + handler, + keyGenerator: removePorts, + store: limiterCache('email_change_submission_ip_limiter'), +}; + +const emailChangeSubmissionIpLimiter = rateLimit(limiterOptions); + +module.exports = emailChangeSubmissionIpLimiter; diff --git a/api/server/middleware/limiters/emailChangeSubmissionLimiter.js b/api/server/middleware/limiters/emailChangeSubmissionLimiter.js new file mode 100644 index 0000000000..0c23fcb913 --- /dev/null +++ b/api/server/middleware/limiters/emailChangeSubmissionLimiter.js @@ -0,0 +1,39 @@ +const rateLimit = require('express-rate-limit'); +const { ViolationTypes } = require('librechat-data-provider'); +const { limiterCache, removePorts, emailChangeSubmissionKey } = require('@librechat/api'); +const { logViolation } = require('~/cache'); + +const { + EMAIL_CHANGE_CONFIRM_USER_WINDOW = process.env.VERIFY_EMAIL_WINDOW ?? 2, + EMAIL_CHANGE_CONFIRM_USER_MAX = process.env.VERIFY_EMAIL_MAX ?? 2, + VERIFY_EMAIL_SUBMISSION_VIOLATION_SCORE: score, +} = process.env; +const windowMs = EMAIL_CHANGE_CONFIRM_USER_WINDOW * 60 * 1000; +const max = EMAIL_CHANGE_CONFIRM_USER_MAX; +const windowInMinutes = windowMs / 60000; +const message = `Too many attempts, please try again after ${windowInMinutes} minute(s)`; + +const handler = async (req, res) => { + const type = ViolationTypes.VERIFY_EMAIL_LIMIT; + const errorMessage = { + type, + max, + windowInMinutes, + limiter: 'submission', + }; + + await logViolation(req, res, type, errorMessage, score); + return res.status(429).json({ message }); +}; + +const limiterOptions = { + windowMs, + max, + handler, + keyGenerator: (req) => emailChangeSubmissionKey(removePorts(req) ?? 'unknown', req.body?.userId), + store: limiterCache('email_change_submission_limiter'), +}; + +const emailChangeSubmissionLimiter = rateLimit(limiterOptions); + +module.exports = emailChangeSubmissionLimiter; diff --git a/api/server/middleware/limiters/emailChangeSubmissionLimiter.test.js b/api/server/middleware/limiters/emailChangeSubmissionLimiter.test.js new file mode 100644 index 0000000000..2bdd2b1028 --- /dev/null +++ b/api/server/middleware/limiters/emailChangeSubmissionLimiter.test.js @@ -0,0 +1,36 @@ +const mockRateLimit = jest.fn((options) => options); +const mockLimiterCache = jest.fn((name) => ({ name })); + +jest.mock('express-rate-limit', () => mockRateLimit); +jest.mock('@librechat/api', () => ({ + limiterCache: mockLimiterCache, + removePorts: (req) => req.ip, + /** The key policy lives in packages/api and is covered by its own tests; here it records + * what this file feeds it, which is the wiring this file owns. */ + emailChangeSubmissionKey: (ip, submittedUserId) => `ip:${ip}:user:${String(submittedUserId)}`, +})); +jest.mock('~/cache', () => ({ logViolation: jest.fn() })); + +const limiter = require('./emailChangeSubmissionLimiter'); + +describe('emailChangeSubmissionLimiter', () => { + it('keys the allowance on the caller address and the submitted account', () => { + expect( + limiter.keyGenerator({ ip: '203.0.113.10', body: { userId: '507f1f77bcf86cd799439011' } }), + ).toBe('ip:203.0.113.10:user:507f1f77bcf86cd799439011'); + }); + + it('falls back to an unknown address when the request carries none', () => { + expect(limiter.keyGenerator({ body: { userId: '507f1f77bcf86cd799439011' } })).toBe( + 'ip:unknown:user:507f1f77bcf86cd799439011', + ); + }); + + it('passes a missing body through to the policy rather than throwing', () => { + expect(limiter.keyGenerator({ ip: '203.0.113.10' })).toBe('ip:203.0.113.10:user:undefined'); + }); + + it('uses a store isolated from ordinary email verification', () => { + expect(limiter.store).toEqual({ name: 'email_change_submission_limiter' }); + }); +}); diff --git a/api/server/middleware/limiters/index.js b/api/server/middleware/limiters/index.js index 2ad2b14564..317278fe51 100644 --- a/api/server/middleware/limiters/index.js +++ b/api/server/middleware/limiters/index.js @@ -11,6 +11,9 @@ const toolCallLimiter = require('./toolCallLimiter'); const messageLimiters = require('./messageLimiters'); const promptUsageLimiter = require('./promptUsageLimiter'); const verifyEmailLimiter = require('./verifyEmailLimiter'); +const emailChangeLimiter = require('./emailChangeLimiter'); +const emailChangeSubmissionLimiter = require('./emailChangeSubmissionLimiter'); +const emailChangeSubmissionIpLimiter = require('./emailChangeSubmissionIpLimiter'); const resetPasswordLimiter = require('./resetPasswordLimiter'); const twoFactorTempLimiter = require('./twoFactorTempLimiter'); const verifyEmailSubmissionLimiter = require('./verifyEmailSubmissionLimiter'); @@ -29,6 +32,9 @@ module.exports = { createTTSLimiters, createSTTLimiters, verifyEmailLimiter, + emailChangeLimiter, + emailChangeSubmissionLimiter, + emailChangeSubmissionIpLimiter, resetPasswordLimiter, verifyEmailSubmissionLimiter, resetPasswordSubmissionLimiter, diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js index 82c714873b..8a55fc4f2c 100644 --- a/api/server/routes/__tests__/config.spec.js +++ b/api/server/routes/__tests__/config.spec.js @@ -103,6 +103,7 @@ afterEach(() => { delete process.env.SAML_CERT; delete process.env.SAML_SESSION_SECRET; delete process.env.ALLOW_ACCOUNT_DELETION; + delete process.env.ALLOW_EMAIL_CHANGE; delete process.env.ADMIN_PANEL_URL; delete process.env.ENABLE_INSIGHTS; delete process.env.ANALYTICS_GTM_ID; @@ -197,6 +198,7 @@ describe('GET /api/config', () => { expect(response.body).not.toHaveProperty('analyticsGtmId'); expect(response.body).not.toHaveProperty('openidReuseTokens'); expect(response.body).not.toHaveProperty('allowAccountDeletion'); + expect(response.body).not.toHaveProperty('allowEmailChange'); expect(response.body).not.toHaveProperty('customFooter'); expect(response.body).not.toHaveProperty('adminPanelURL'); }); @@ -219,6 +221,7 @@ describe('GET /api/config', () => { expect(response.body).not.toHaveProperty('staticBundlerURL'); expect(response.body).not.toHaveProperty('helpAndFaqURL'); expect(response.body).not.toHaveProperty('allowAccountDeletion'); + expect(response.body).not.toHaveProperty('allowEmailChange'); }); it('should include socialLogins and turnstile from base config', async () => { @@ -695,6 +698,25 @@ describe('GET /api/config', () => { expect(mockHasCapability).toHaveBeenCalled(); }); + it('should enable email changes by default for authenticated users', async () => { + mockGetAppConfig.mockResolvedValue(baseAppConfig); + const app = createApp(mockUser); + + const response = await request(app).get('/api/config'); + + expect(response.body.allowEmailChange).toBe(true); + }); + + it('should disable email changes when ALLOW_EMAIL_CHANGE is false', async () => { + process.env.ALLOW_EMAIL_CHANGE = 'false'; + mockGetAppConfig.mockResolvedValue(baseAppConfig); + const app = createApp(mockUser); + + const response = await request(app).get('/api/config'); + + expect(response.body.allowEmailChange).toBe(false); + }); + it('should override allowAccountDeletion to true for users with ACCESS_ADMIN capability', async () => { process.env.ALLOW_ACCOUNT_DELETION = 'false'; mockGetAppConfig.mockResolvedValue(baseAppConfig); diff --git a/api/server/routes/config.js b/api/server/routes/config.js index d3e3682ab4..7cb97fdef9 100644 --- a/api/server/routes/config.js +++ b/api/server/routes/config.js @@ -1,6 +1,8 @@ const express = require('express'); const { isEnabled, + resolveEmailChangeSettings, + checkEmailConfig, isLangfuseConnectionAvailable, isLangfuseFanoutEnabled, getBalanceConfig, @@ -94,11 +96,7 @@ function buildPreLoginPayload() { emailLoginEnabled, registrationEnabled: !ldap?.enabled && isEnabled(process.env.ALLOW_REGISTRATION), socialLoginEnabled: isEnabled(process.env.ALLOW_SOCIAL_LOGIN), - emailEnabled: - (!!process.env.EMAIL_SERVICE || !!process.env.EMAIL_HOST) && - !!process.env.EMAIL_USERNAME && - !!process.env.EMAIL_PASSWORD && - !!process.env.EMAIL_FROM, + emailEnabled: checkEmailConfig(), passwordResetEnabled, }; @@ -138,7 +136,7 @@ function buildPublicSharePayload() { * openid token-reuse marker) and are not needed on the pre-login screens, so they * are not exposed to unauthenticated callers. */ -function buildPostLoginPayload() { +function buildPostLoginPayload(appConfig) { /** @type {Partial} */ const payload = { showBirthdayIcon: @@ -153,6 +151,7 @@ function buildPostLoginPayload() { allowAccountDeletion: process.env.ALLOW_ACCOUNT_DELETION === undefined || isEnabled(process.env.ALLOW_ACCOUNT_DELETION), + allowEmailChange: resolveEmailChangeSettings(appConfig?.emailChange).enabled, }; return payload; @@ -293,7 +292,7 @@ router.get('/', async function (req, res) { const payload = { ...preLoginPayload, ...publicSharePayload, - ...buildPostLoginPayload(), + ...buildPostLoginPayload(appConfig), sharedLinksSnapshotFilesEnabled: sharedLinksEnabled && isFileSnapshotEnabled(appConfig), socialLogins: appConfig?.registration?.socialLogins ?? defaultSocialLogins, interface: appConfig?.interfaceConfig, diff --git a/api/server/routes/user.js b/api/server/routes/user.js index 4107e410c7..c736976238 100644 --- a/api/server/routes/user.js +++ b/api/server/routes/user.js @@ -6,13 +6,19 @@ const { getTermsStatusController, acceptTermsController, verifyEmailController, + requestEmailChangeController, + confirmEmailChangeController, deleteUserController, getUserController, } = require('~/server/controllers/UserController'); const { verifyEmailLimiter, + emailChangeLimiter, + emailChangeSubmissionLimiter, + emailChangeSubmissionIpLimiter, verifyEmailSubmissionLimiter, configMiddleware, + strictConfigMiddleware, canDeleteAccount, requireJwtAuth, } = require('~/server/middleware'); @@ -33,6 +39,19 @@ router.get('/terms', requireJwtAuth, getTermsStatusController); router.post('/terms/accept', requireJwtAuth, acceptTermsController); router.post('/plugins', requireJwtAuth, updateUserPluginsController); router.delete('/delete', requireJwtAuth, canDeleteAccount, configMiddleware, deleteUserController); +router.post( + '/email/change', + requireJwtAuth, + emailChangeLimiter, + strictConfigMiddleware, + requestEmailChangeController, +); +router.post( + '/email/verify', + emailChangeSubmissionIpLimiter, + emailChangeSubmissionLimiter, + confirmEmailChangeController, +); router.post('/verify', verifyEmailSubmissionLimiter, verifyEmailController); router.post('/verify/resend', verifyEmailLimiter, resendVerificationController); diff --git a/api/server/routes/user.verify-ratelimit.test.js b/api/server/routes/user.verify-ratelimit.test.js index c61ade5720..5e4d1a365f 100644 --- a/api/server/routes/user.verify-ratelimit.test.js +++ b/api/server/routes/user.verify-ratelimit.test.js @@ -2,13 +2,18 @@ const express = require('express'); const request = require('supertest'); const mockVerifyEmailSubmissionLimiter = jest.fn((req, res, next) => next()); +const mockEmailChangeSubmissionLimiter = jest.fn((req, res, next) => next()); +const mockEmailChangeSubmissionIpLimiter = jest.fn((req, res, next) => next()); const mockVerifyEmailController = jest.fn((req, res) => res.status(204).end()); +const mockConfirmEmailChangeController = jest.fn((req, res) => res.status(204).end()); jest.mock('~/server/controllers/UserController', () => ({ getUserController: jest.fn((req, res) => res.status(204).end()), deleteUserController: jest.fn((req, res) => res.status(204).end()), acceptTermsController: jest.fn((req, res) => res.status(204).end()), verifyEmailController: (...args) => mockVerifyEmailController(...args), + requestEmailChangeController: jest.fn((req, res) => res.status(204).end()), + confirmEmailChangeController: (...args) => mockConfirmEmailChangeController(...args), getTermsStatusController: jest.fn((req, res) => res.status(204).end()), updateUserPluginsController: jest.fn((req, res) => res.status(204).end()), resendVerificationController: jest.fn((req, res) => res.status(204).end()), @@ -20,7 +25,11 @@ jest.mock('~/server/middleware', () => { requireJwtAuth: pass, canDeleteAccount: pass, configMiddleware: pass, + strictConfigMiddleware: pass, verifyEmailLimiter: pass, + emailChangeLimiter: pass, + emailChangeSubmissionLimiter: (...args) => mockEmailChangeSubmissionLimiter(...args), + emailChangeSubmissionIpLimiter: (...args) => mockEmailChangeSubmissionIpLimiter(...args), verifyEmailSubmissionLimiter: (...args) => mockVerifyEmailSubmissionLimiter(...args), }; }); @@ -38,7 +47,10 @@ describe('POST /api/user/verify rate limiting', () => { beforeEach(() => { jest.clearAllMocks(); mockVerifyEmailSubmissionLimiter.mockImplementation((req, res, next) => next()); + mockEmailChangeSubmissionLimiter.mockImplementation((req, res, next) => next()); + mockEmailChangeSubmissionIpLimiter.mockImplementation((req, res, next) => next()); mockVerifyEmailController.mockImplementation((req, res) => res.status(204).end()); + mockConfirmEmailChangeController.mockImplementation((req, res) => res.status(204).end()); app = express(); app.use(express.json()); @@ -68,4 +80,42 @@ describe('POST /api/user/verify rate limiting', () => { expect(response.body).toEqual({ message: 'Too many verification attempts' }); expect(mockVerifyEmailController).not.toHaveBeenCalled(); }); + + it('limits email change confirmation before checking the token', async () => { + await request(app).post('/api/user/email/verify').send({ token: 'token' }).expect(204); + + expect(mockEmailChangeSubmissionLimiter).toHaveBeenCalledTimes(1); + expect(mockVerifyEmailSubmissionLimiter).not.toHaveBeenCalled(); + expect(mockConfirmEmailChangeController).toHaveBeenCalledTimes(1); + expect(mockEmailChangeSubmissionLimiter.mock.invocationCallOrder[0]).toBeLessThan( + mockConfirmEmailChangeController.mock.invocationCallOrder[0], + ); + }); + + it('caps confirmation per source address before the caller-keyed limiter', async () => { + await request(app) + .post('/api/user/email/verify') + .send({ userId: 'a'.repeat(24), token: 'token' }) + .expect(204); + + expect(mockEmailChangeSubmissionIpLimiter).toHaveBeenCalledTimes(1); + expect(mockEmailChangeSubmissionIpLimiter.mock.invocationCallOrder[0]).toBeLessThan( + mockEmailChangeSubmissionLimiter.mock.invocationCallOrder[0], + ); + }); + + it('rejects rotated user ids once the source address cap is reached', async () => { + mockEmailChangeSubmissionIpLimiter.mockImplementation((req, res) => + res.status(429).json({ message: 'Too many attempts' }), + ); + + const response = await request(app) + .post('/api/user/email/verify') + .send({ userId: 'b'.repeat(24), token: 'token' }) + .expect(429); + + expect(response.body).toEqual({ message: 'Too many attempts' }); + expect(mockEmailChangeSubmissionLimiter).not.toHaveBeenCalled(); + expect(mockConfirmEmailChangeController).not.toHaveBeenCalled(); + }); }); diff --git a/api/server/services/AuthService.js b/api/server/services/AuthService.js index 24d26b895d..5c67cb554e 100644 --- a/api/server/services/AuthService.js +++ b/api/server/services/AuthService.js @@ -25,6 +25,7 @@ const { normalizeExpiresIn, createOpenIDSessionIdentity, resolveAppConfigForUser, + commitPasswordReset, } = require('@librechat/api'); const { findUser, @@ -526,6 +527,7 @@ const requestPasswordReset = async (req) => { await createToken({ userId: user._id, + email: user.email.toLowerCase(), type: AuthTokenTypes.PASSWORD_RESET, token: hash, createdAt: Date.now(), @@ -570,20 +572,23 @@ const requestPasswordReset = async (req) => { * @returns */ const resetPassword = async (userId, token, password) => { - const passwordResetToken = await findPasswordResetToken(userId); + const outcome = await commitPasswordReset( + { + findResetToken: findPasswordResetToken, + getUserById, + updateUser, + deleteTokens, + compareToken: (candidate, storedHash) => bcrypt.compareSync(candidate, storedHash), + hashPassword: (plain) => bcrypt.hashSync(plain, 10), + }, + { userId, token, password }, + ); - if (!passwordResetToken) { + if (!outcome.ok) { return new Error('Invalid or expired password reset token'); } - const isValid = bcrypt.compareSync(token, passwordResetToken.token); - - if (!isValid) { - return new Error('Invalid or expired password reset token'); - } - - const hash = bcrypt.hashSync(password, 10); - const user = await updateUser(userId, { password: hash }); + const { user, resetToken: passwordResetToken } = outcome; if (checkEmailConfig()) { await sendEmail({ diff --git a/api/server/services/AuthService.spec.js b/api/server/services/AuthService.spec.js index f9e239fef8..1a5bac88fb 100644 --- a/api/server/services/AuthService.spec.js +++ b/api/server/services/AuthService.spec.js @@ -60,6 +60,7 @@ jest.mock( : undefined; }, resolveAppConfigForUser: jest.fn(async (_getAppConfig, _user) => ({})), + commitPasswordReset: jest.fn(), createOpenIDSessionIdentity: jest.fn( ({ user, userId, openidSubject, tenantId, openidIssuer }) => { const normalize = (value) => { @@ -167,12 +168,14 @@ let resendVerificationEmail; let setAuthTokens; let setCloudFrontAuthCookies; let verifyEmail; +let commitPasswordReset; jest.isolateModules(() => { ({ checkEmailConfig, isEmailDomainAllowed, resolveAppConfigForUser, + commitPasswordReset, setRefreshTokenCookie, setOpenIDMarkerCookies, setCloudFrontCookies, @@ -949,6 +952,7 @@ describe('requestPasswordReset', () => { expect(createToken).toHaveBeenCalledWith( expect.objectContaining({ userId: user._id, + email: user.email, type: 'password_reset', }), ); @@ -956,114 +960,122 @@ describe('requestPasswordReset', () => { }); describe('resetPassword', () => { + /** The reset policy itself (address binding, the compare-and-set, the email change + * sweep) lives in `@librechat/api` and is covered by passwordReset.spec.ts. What + * remains here is this file's wiring: which token lookup it injects, and which token + * it deletes once the policy has committed. The double runs the injected lookup so + * that wiring is still exercised, and decides nothing else. */ + const resolvedUser = { email: 'user@example.com' }; + beforeEach(() => { jest.clearAllMocks(); checkEmailConfig.mockReturnValue(false); + commitPasswordReset.mockImplementation(async (deps, { userId }) => { + const resetToken = await deps.findResetToken(userId); + return resetToken ? { ok: true, user: resolvedUser, resetToken } : { ok: false }; + }); }); - it('should only accept password reset tokens for password reset', async () => { - const verificationHash = bcrypt.hashSync('verification-token', 10); - findToken.mockImplementation(async (query) => { - if (query.type === 'password_reset') { - return null; - } - if (query.type === null && query.email === null && query.identifier === null) { - return null; - } - return { token: verificationHash, userId: 'user-reset', email: 'user@example.com' }; - }); - updateUser.mockResolvedValue({ email: 'user@example.com' }); + it('looks for a typed reset token before the untyped legacy shape', async () => { + findToken.mockResolvedValue(null); - const result = await resetPassword('user-reset', 'verification-token', 'new-password'); + const result = await resetPassword('user-reset', 'reset-token', 'new-password'); expect(result).toBeInstanceOf(Error); - expect(findToken).toHaveBeenCalledWith( - { - userId: 'user-reset', - type: 'password_reset', - }, + expect(findToken).toHaveBeenNthCalledWith( + 1, + { userId: 'user-reset', type: 'password_reset' }, { sort: { createdAt: -1 } }, ); - expect(findToken).toHaveBeenCalledWith( - { - userId: 'user-reset', - email: null, - identifier: null, - type: null, - }, + expect(findToken).toHaveBeenNthCalledWith( + 2, + { userId: 'user-reset', email: null, identifier: null, type: null }, { sort: { createdAt: -1 } }, ); - expect(updateUser).not.toHaveBeenCalled(); expect(deleteTokens).not.toHaveBeenCalled(); }); - it('should delete only the used password reset token after a successful reset', async () => { - const resetHash = bcrypt.hashSync('reset-token', 10); + it('hands the policy the database and password surfaces it needs', async () => { findToken.mockResolvedValue({ - token: resetHash, + token: 'reset-hash', userId: 'user-reset', type: 'password_reset', }); - updateUser.mockResolvedValue({ email: 'user@example.com' }); + + await resetPassword('user-reset', 'reset-token', 'new-password'); + + expect(commitPasswordReset).toHaveBeenCalledWith( + expect.objectContaining({ + findResetToken: expect.any(Function), + getUserById: expect.any(Function), + updateUser: expect.any(Function), + deleteTokens: expect.any(Function), + compareToken: expect.any(Function), + hashPassword: expect.any(Function), + }), + { userId: 'user-reset', token: 'reset-token', password: 'new-password' }, + ); + }); + + it('deletes only the typed reset token the policy consumed', async () => { + findToken.mockResolvedValue({ + token: 'reset-hash', + userId: 'user-reset', + email: 'user@example.com', + type: 'password_reset', + }); const result = await resetPassword('user-reset', 'reset-token', 'new-password'); expect(result).toEqual({ message: 'Password reset was successful' }); - expect(findToken).toHaveBeenCalledWith( - { - userId: 'user-reset', - type: 'password_reset', - }, - { sort: { createdAt: -1 } }, - ); - expect(deleteTokens).toHaveBeenCalledWith({ - token: resetHash, - type: 'password_reset', - }); + expect(deleteTokens).toHaveBeenCalledWith({ token: 'reset-hash', type: 'password_reset' }); }); - it('should accept legacy reset tokens without affecting verification-shaped tokens', async () => { - const legacyResetHash = bcrypt.hashSync('legacy-reset-token', 10); - findToken.mockImplementation(async (query) => { - if (query.type === 'password_reset') { - return null; - } - if (query.type === null && query.email === null && query.identifier === null) { - return { - token: legacyResetHash, - userId: 'user-reset', - }; - } - return null; - }); - updateUser.mockResolvedValue({ email: 'user@example.com' }); + it('deletes an untyped legacy token by its exact stored shape', async () => { + findToken.mockImplementation(async (query) => + query.type === 'password_reset' + ? null + : { token: 'legacy-hash', userId: 'user-reset', email: null, identifier: null, type: null }, + ); const result = await resetPassword('user-reset', 'legacy-reset-token', 'new-password'); expect(result).toEqual({ message: 'Password reset was successful' }); - expect(findToken).toHaveBeenCalledWith( - { - userId: 'user-reset', - type: 'password_reset', - }, - { sort: { createdAt: -1 } }, - ); - expect(findToken).toHaveBeenCalledWith( - { - userId: 'user-reset', - email: null, - identifier: null, - type: null, - }, - { sort: { createdAt: -1 } }, - ); expect(deleteTokens).toHaveBeenCalledWith({ - token: legacyResetHash, + token: 'legacy-hash', email: null, identifier: null, type: null, }); }); + + it('returns the generic error and touches nothing when the policy refuses', async () => { + findToken.mockResolvedValue(null); + + const result = await resetPassword('user-reset', 'reset-token', 'new-password'); + + expect(result).toBeInstanceOf(Error); + expect(sendEmail).not.toHaveBeenCalled(); + expect(deleteTokens).not.toHaveBeenCalled(); + }); + + it('notifies the account once the reset has committed', async () => { + checkEmailConfig.mockReturnValue(true); + findToken.mockResolvedValue({ + token: 'reset-hash', + userId: 'user-reset', + type: 'password_reset', + }); + + await resetPassword('user-reset', 'reset-token', 'new-password'); + + expect(sendEmail).toHaveBeenCalledWith( + expect.objectContaining({ + email: 'user@example.com', + template: 'passwordReset.handlebars', + }), + ); + }); }); describe('verifyEmail', () => { diff --git a/api/server/utils/emails/emailChangeAttempt.handlebars b/api/server/utils/emails/emailChangeAttempt.handlebars new file mode 100644 index 0000000000..6582ba668a --- /dev/null +++ b/api/server/utils/emails/emailChangeAttempt.handlebars @@ -0,0 +1,42 @@ + + + + + Email change requested + + + + + + +
+ + + + +
+

Email change requested

+

Hello {{name}},

+

+ A request was made to change the email address on your + {{appName}} + account to + {{newEmail}}. +

+

Time: + {{requestedAt}}
IP address: + {{ip}}

+

+ If you did not make this request, change your password immediately and contact + your administrator. +

+
+
+ + \ No newline at end of file diff --git a/api/server/utils/emails/emailChanged.handlebars b/api/server/utils/emails/emailChanged.handlebars new file mode 100644 index 0000000000..8c16a0cf72 --- /dev/null +++ b/api/server/utils/emails/emailChanged.handlebars @@ -0,0 +1,44 @@ + + + + + Email address changed + + + + + + +
+ + + + +
+

Email address changed

+

Hello {{name}},

+

The email address for your {{appName}} account was changed successfully.

+

+ Previous email: + {{oldEmail}}
+ New email: + {{newEmail}}
+ Time: + {{changedAt}}
+ IP address: + {{ip}} +

+

+ If you did not make this change, contact your administrator immediately and secure + your account. +

+
+
+ + \ No newline at end of file diff --git a/api/server/utils/emails/verifyEmailChange.handlebars b/api/server/utils/emails/verifyEmailChange.handlebars new file mode 100644 index 0000000000..0572fc488c --- /dev/null +++ b/api/server/utils/emails/verifyEmailChange.handlebars @@ -0,0 +1,46 @@ + + + + + Verify your new email address + + + + + + +
+ + + + +
+

Verify your new email address

+

Hello {{name}},

+

+ Confirm + {{newEmail}} + as the new email address for your + {{appName}} + account. This link expires in {{linkLifetime}}. +

+

+ Verify new email +

+

If you did not request this change, you can ignore this email.

+

© + {{year}} + {{appName}}

+
+
+ + \ No newline at end of file diff --git a/client/src/components/Auth/VerifyEmail.tsx b/client/src/components/Auth/VerifyEmail.tsx index bba11455a7..e21bfeaeaa 100644 --- a/client/src/components/Auth/VerifyEmail.tsx +++ b/client/src/components/Auth/VerifyEmail.tsx @@ -1,7 +1,13 @@ import { useState, useEffect, useMemo, useCallback } from 'react'; import { useSearchParams, useNavigate } from 'react-router-dom'; import { Button, Spinner, ThemeSelector } from '@librechat/client'; -import { useVerifyEmailMutation, useResendVerificationEmail } from '~/data-provider'; +import type { EmailChangeErrorCode } from 'librechat-data-provider'; +import { + useVerifyEmailMutation, + useResendVerificationEmail, + useConfirmEmailChangeMutation, +} from '~/data-provider'; +import { getResponseErrorCode } from '~/utils'; import { useLocalize } from '~/hooks'; function RequestPasswordReset() { @@ -9,12 +15,14 @@ function RequestPasswordReset() { const localize = useLocalize(); const [params] = useSearchParams(); - const [countdown, setCountdown] = useState(3); + const [countdown, setCountdown] = useState(0); const [headerText, setHeaderText] = useState(''); const [showResendLink, setShowResendLink] = useState(false); const [verificationStatus, setVerificationStatus] = useState(false); const token = useMemo(() => params.get('token') || '', [params]); const email = useMemo(() => params.get('email') || '', [params]); + const userId = useMemo(() => params.get('userId') || '', [params]); + const isEmailChange = useMemo(() => params.get('type') === 'email-change', [params]); const countdownRedirect = useCallback(() => { setCountdown(3); @@ -43,6 +51,24 @@ function RequestPasswordReset() { }, }); + const confirmEmailChangeMutation = useConfirmEmailChangeMutation({ + onSuccess: () => { + setHeaderText(localize('com_auth_email_change_success') + ' ๐ŸŽ‰'); + setVerificationStatus(true); + countdownRedirect(); + }, + onError: (error) => { + const code = getResponseErrorCode(error); + const messageKey = + code === 'email_in_use' + ? 'com_ui_email_change_error_in_use' + : 'com_auth_email_change_failed'; + setHeaderText(localize(messageKey) + ' ๐Ÿ˜ข'); + setShowResendLink(false); + setVerificationStatus(true); + }, + }); + const resendEmailMutation = useResendVerificationEmail({ onSuccess: () => { setHeaderText(localize('com_auth_email_resent_success') + ' ๐Ÿ“ง'); @@ -59,11 +85,17 @@ function RequestPasswordReset() { }; useEffect(() => { - if (verificationStatus || verifyEmailMutation.isLoading) { + if ( + verificationStatus || + verifyEmailMutation.isLoading || + confirmEmailChangeMutation.isLoading + ) { return; } - if (token && email) { + if (isEmailChange && token && email && userId) { + confirmEmailChangeMutation.mutate({ email, token, userId }); + } else if (!isEmailChange && token && email) { verifyEmailMutation.mutate({ email, token }); } else { if (email) { @@ -71,53 +103,66 @@ function RequestPasswordReset() { } else { setHeaderText(localize('com_auth_email_verification_invalid') + ' ๐Ÿคจ'); } - setShowResendLink(true); + setShowResendLink(!isEmailChange); setVerificationStatus(true); } - }, [token, email, verificationStatus, verifyEmailMutation, localize]); + }, [ + token, + email, + userId, + isEmailChange, + verificationStatus, + verifyEmailMutation, + confirmEmailChangeMutation, + localize, + ]); - const VerificationSuccess = () => ( -
-

{headerText}

- {countdown > 0 && ( -

- {localize('com_auth_email_verification_redirecting', { 0: countdown.toString() })} -

- )} - {showResendLink && countdown === 0 && ( -

- {localize('com_auth_email_verification_resend_prompt')} - -

- )} -
- ); - - const VerificationInProgress = () => ( -
-

- {localize('com_auth_email_verification_in_progress')} -

-
- -
-
- ); + const statusText = verificationStatus + ? headerText + : localize( + isEmailChange + ? 'com_auth_email_change_verification_in_progress' + : 'com_auth_email_verification_in_progress', + ); return (
- {verificationStatus ? : } +
+

+ {statusText} +

+ {!verificationStatus && ( +
+ +
+ )} + {verificationStatus && countdown > 0 && ( +

+ {localize('com_auth_email_verification_redirecting', { 0: countdown.toString() })} +

+ )} + {verificationStatus && showResendLink && countdown === 0 && ( +

+ {localize('com_auth_email_verification_resend_prompt')} + +

+ )} +
); } diff --git a/client/src/components/Auth/__tests__/LoginForm.spec.tsx b/client/src/components/Auth/__tests__/LoginForm.spec.tsx index a818402350..f1c6e1d54c 100644 --- a/client/src/components/Auth/__tests__/LoginForm.spec.tsx +++ b/client/src/components/Auth/__tests__/LoginForm.spec.tsx @@ -40,6 +40,7 @@ const mockStartupConfig: TStartupConfig = { sharedLinksEnabled: true, publicSharedLinksEnabled: true, allowAccountDeletion: true, + allowEmailChange: true, }; const setup = ({ diff --git a/client/src/components/Auth/__tests__/VerifyEmail.spec.tsx b/client/src/components/Auth/__tests__/VerifyEmail.spec.tsx new file mode 100644 index 0000000000..2714067cd1 --- /dev/null +++ b/client/src/components/Auth/__tests__/VerifyEmail.spec.tsx @@ -0,0 +1,117 @@ +import { MemoryRouter } from 'react-router-dom'; +import { render, screen } from '@testing-library/react'; +import type { TConfirmEmailChange } from 'librechat-data-provider'; +import VerifyEmail from '~/components/Auth/VerifyEmail'; +import * as dataProvider from '~/data-provider'; + +jest.mock('@librechat/client', () => ({ + Spinner: () => null, + ThemeSelector: () => null, +})); + +jest.mock('~/data-provider', () => ({ + useVerifyEmailMutation: jest.fn(), + useResendVerificationEmail: jest.fn(), + useConfirmEmailChangeMutation: jest.fn(), +})); + +const mockUseVerifyEmailMutation = jest.mocked(dataProvider.useVerifyEmailMutation); +const mockUseResendVerificationEmail = jest.mocked(dataProvider.useResendVerificationEmail); +const mockUseConfirmEmailChangeMutation = jest.mocked(dataProvider.useConfirmEmailChangeMutation); + +const idleMutationState = () => ({ + context: undefined, + data: undefined, + error: null, + failureCount: 0, + failureReason: null, + isError: false as const, + isIdle: true as const, + isLoading: false as const, + isPaused: false, + isSuccess: false as const, + status: 'idle' as const, + variables: undefined, + reset: jest.fn(), +}); + +describe('VerifyEmail', () => { + beforeEach(() => { + mockUseVerifyEmailMutation.mockReturnValue({ + ...idleMutationState(), + mutate: jest.fn(), + mutateAsync: jest.fn(), + }); + mockUseResendVerificationEmail.mockReturnValue({ + ...idleMutationState(), + mutate: jest.fn(), + mutateAsync: jest.fn(), + }); + mockUseConfirmEmailChangeMutation.mockImplementation((options) => ({ + ...idleMutationState(), + mutate: jest.fn((variables: TConfirmEmailChange) => { + options?.onError?.({ response: { data: { code: 'invalid_token' } } }, variables, undefined); + }), + mutateAsync: jest.fn(), + })); + }); + + it('does not show a redirect countdown after email-change verification fails', async () => { + render( + + + , + ); + + expect( + await screen.findByRole('heading', { name: 'Email change verification failed ๐Ÿ˜ข' }), + ).toBeInTheDocument(); + expect(screen.queryByText(/Redirecting in/i)).not.toBeInTheDocument(); + }); + + it('announces the email-change verification result in a live region', async () => { + render( + + + , + ); + + const heading = await screen.findByRole('heading', { + name: 'Email change verification failed ๐Ÿ˜ข', + }); + expect(heading).toHaveAttribute('aria-live', 'polite'); + expect(heading).toHaveAttribute('aria-atomic', 'true'); + }); + + it('renders the same live status heading while verification is still pending', () => { + mockUseConfirmEmailChangeMutation.mockReturnValue({ + ...idleMutationState(), + mutate: jest.fn(), + mutateAsync: jest.fn(), + }); + + render( + + + , + ); + + const heading = screen.getByRole('heading', { + name: 'Verifying your new email address, please wait', + }); + expect(heading).toHaveAttribute('aria-live', 'polite'); + expect(heading).toHaveAttribute('aria-atomic', 'true'); + }); +}); diff --git a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx index 8272fe91d7..b05254326c 100644 --- a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx +++ b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx @@ -15,6 +15,8 @@ const ctx: SettingsContextValue = { hasMultiConvo: false, hasPrompts: false, isLocalProvider: true, + emailEnabled: true, + allowEmailChange: true, twoFactorEnabled: false, allowAccountDeletion: true, aboutEnabled: false, diff --git a/client/src/components/Nav/Settings/__tests__/registry.spec.ts b/client/src/components/Nav/Settings/__tests__/registry.spec.ts index d277ebfe44..59240449bd 100644 --- a/client/src/components/Nav/Settings/__tests__/registry.spec.ts +++ b/client/src/components/Nav/Settings/__tests__/registry.spec.ts @@ -17,6 +17,8 @@ const settingsContext: SettingsContextValue = { hasMultiConvo: false, hasPrompts: false, isLocalProvider: true, + emailEnabled: true, + allowEmailChange: true, twoFactorEnabled: false, allowAccountDeletion: true, aboutEnabled: false, @@ -100,4 +102,31 @@ describe('settings registry', () => { expect(entry?.show?.({ ...settingsContext, hasStatefulCodeSessions: false })).toBe(false); }); }); + + describe('email change visibility', () => { + const emailChangeEntry = registry.find((entry) => entry.id === 'changeEmail'); + + it('places email changes in the Account profile section', () => { + expect(emailChangeEntry).toMatchObject({ + tab: SettingsTabValues.ACCOUNT, + section: 'profile', + }); + }); + + it('shows email changes for local accounts when email delivery is configured', () => { + expect(emailChangeEntry?.show?.(settingsContext)).toBe(true); + }); + + it('hides email changes for federated accounts', () => { + expect(emailChangeEntry?.show?.({ ...settingsContext, isLocalProvider: false })).toBe(false); + }); + + it('hides email changes when email delivery is unavailable', () => { + expect(emailChangeEntry?.show?.({ ...settingsContext, emailEnabled: false })).toBe(false); + }); + + it('hides email changes when administrators disable them', () => { + expect(emailChangeEntry?.show?.({ ...settingsContext, allowEmailChange: false })).toBe(false); + }); + }); }); diff --git a/client/src/components/Nav/Settings/context.tsx b/client/src/components/Nav/Settings/context.tsx index bb725d3c79..6a54bdc58d 100644 --- a/client/src/components/Nav/Settings/context.tsx +++ b/client/src/components/Nav/Settings/context.tsx @@ -31,6 +31,8 @@ export function useSettingsContext(): SettingsContextValue { const langfuseConnectionAccess = startupConfig?.langfuseConnectionAccess === true; const adminPanelURL = startupConfig?.adminPanelURL ?? ''; const isLocalProvider = user?.provider === 'local'; + const emailEnabled = startupConfig?.emailEnabled === true; + const allowEmailChange = startupConfig?.allowEmailChange === true; const twoFactorEnabled = user?.twoFactorEnabled === true; const allowAccountDeletion = startupConfig?.allowAccountDeletion !== false; const aboutEnabled = startupConfig?.interface?.buildInfo !== false; @@ -53,6 +55,8 @@ export function useSettingsContext(): SettingsContextValue { hasMultiConvo: hasMultiConvoBool, hasPrompts: hasPromptsBool, isLocalProvider, + emailEnabled, + allowEmailChange, twoFactorEnabled, allowAccountDeletion, aboutEnabled, @@ -70,6 +74,8 @@ export function useSettingsContext(): SettingsContextValue { hasMultiConvoBool, hasPromptsBool, isLocalProvider, + emailEnabled, + allowEmailChange, twoFactorEnabled, allowAccountDeletion, aboutEnabled, diff --git a/client/src/components/Nav/Settings/registry.tsx b/client/src/components/Nav/Settings/registry.tsx index ba831ccbd2..1e2b14df0d 100644 --- a/client/src/components/Nav/Settings/registry.tsx +++ b/client/src/components/Nav/Settings/registry.tsx @@ -37,6 +37,7 @@ import ChatDirection from '../SettingsTabs/Chat/ChatDirection'; import { DeleteCache } from '../SettingsTabs/Data/DeleteCache'; import { ManageFiles } from '../SettingsTabs/Data/ManageFiles'; import { smoothStreamingAtom } from '~/store/smoothStreaming'; +import ChangeEmail from '../SettingsTabs/Account/ChangeEmail'; import { RevokeKeys } from '../SettingsTabs/Data/RevokeKeys'; import { ClearChats } from '../SettingsTabs/Data/ClearChats'; import { TokenCredits, AutoRefill } from './BillingControls'; @@ -709,6 +710,15 @@ export const registry: SettingEntry[] = [ labelKey: 'com_ui_settings_label_avatar', Component: Avatar, }, + { + id: 'changeEmail', + tab: ACCOUNT, + section: 'profile', + labelKey: 'com_ui_settings_label_change_email', + keywords: ['email', 'address', 'account'], + show: (ctx) => ctx.isLocalProvider && ctx.emailEnabled && ctx.allowEmailChange, + Component: ChangeEmail, + }, // Account ยท Security { id: 'twoFactor', diff --git a/client/src/components/Nav/Settings/types.ts b/client/src/components/Nav/Settings/types.ts index faf1c6b124..3f981ae924 100644 --- a/client/src/components/Nav/Settings/types.ts +++ b/client/src/components/Nav/Settings/types.ts @@ -47,6 +47,8 @@ export interface SettingsContextValue { hasMultiConvo: boolean; hasPrompts: boolean; isLocalProvider: boolean; + emailEnabled: boolean; + allowEmailChange: boolean; twoFactorEnabled: boolean; allowAccountDeletion: boolean; aboutEnabled: boolean; diff --git a/client/src/components/Nav/SettingsTabs/Account/ChangeEmail.tsx b/client/src/components/Nav/SettingsTabs/Account/ChangeEmail.tsx new file mode 100644 index 0000000000..d1c385ab54 --- /dev/null +++ b/client/src/components/Nav/SettingsTabs/Account/ChangeEmail.tsx @@ -0,0 +1,159 @@ +import { useState } from 'react'; +import { + Button, + Input, + Label, + OGDialog, + OGDialogClose, + OGDialogContent, + OGDialogDescription, + OGDialogFooter, + OGDialogHeader, + OGDialogTitle, + OGDialogTrigger, + SecretInput, + Spinner, + useToastContext, +} from '@librechat/client'; +import type { EmailChangeErrorCode } from 'librechat-data-provider'; +import type { FormEvent } from 'react'; +import type { TranslationKeys } from '~/hooks'; +import { useRequestEmailChangeMutation } from '~/data-provider'; +import { useAuthContext, useLocalize } from '~/hooks'; +import { getResponseErrorCode } from '~/utils'; + +const errorKeys: Partial> = { + current_password_invalid: 'com_ui_email_change_error_password', + email_change_disabled: 'com_ui_email_change_error_disabled', + email_delivery_failed: 'com_ui_email_change_error_delivery', + email_domain_not_allowed: 'com_ui_email_change_error_domain', + email_in_use: 'com_ui_email_change_error_in_use', + email_service_unavailable: 'com_ui_email_change_error_unavailable', + invalid_request: 'com_ui_email_change_error_invalid', + local_account_required: 'com_ui_email_change_error_local', + request_in_progress: 'com_ui_email_change_error_in_progress', + same_email: 'com_ui_email_change_error_same', +}; + +export default function ChangeEmail() { + const localize = useLocalize(); + const { user } = useAuthContext(); + const { showToast } = useToastContext(); + const [isOpen, setIsOpen] = useState(false); + const [newEmail, setNewEmail] = useState(''); + const [currentPassword, setCurrentPassword] = useState(''); + const [errorKey, setErrorKey] = useState(); + const mutation = useRequestEmailChangeMutation({ + onSuccess: () => { + showToast({ message: localize('com_ui_email_change_verification_sent') }); + setIsOpen(false); + setNewEmail(''); + setCurrentPassword(''); + setErrorKey(undefined); + }, + onError: (error) => { + const code = getResponseErrorCode(error); + setErrorKey((code ? errorKeys[code] : undefined) ?? 'com_ui_email_change_error_unexpected'); + }, + }); + + const handleOpenChange = (open: boolean) => { + setIsOpen(open); + setErrorKey(undefined); + if (!open) { + setNewEmail(''); + setCurrentPassword(''); + } + }; + + const handleSubmit = (event: FormEvent) => { + event.preventDefault(); + setErrorKey(undefined); + if (newEmail.trim().toLowerCase() === user?.email.trim().toLowerCase()) { + setErrorKey('com_ui_email_change_error_same'); + return; + } + mutation.mutate({ newEmail, currentPassword }); + }; + + return ( + +
+
+ +

{user?.email}

+
+ + + +
+ + + {localize('com_ui_email_change_title')} + {localize('com_ui_email_change_description')} + +
+
+ + setNewEmail(event.target.value)} + disabled={mutation.isLoading} + required + /> +
+
+ + setCurrentPassword(event.target.value)} + disabled={mutation.isLoading} + required + /> +
+ {errorKey && ( + + )} +
+ + + + + + +
+
+ ); +} diff --git a/client/src/components/Nav/SettingsTabs/Account/__tests__/ChangeEmail.spec.tsx b/client/src/components/Nav/SettingsTabs/Account/__tests__/ChangeEmail.spec.tsx new file mode 100644 index 0000000000..5b1f6a89c6 --- /dev/null +++ b/client/src/components/Nav/SettingsTabs/Account/__tests__/ChangeEmail.spec.tsx @@ -0,0 +1,58 @@ +import userEvent from '@testing-library/user-event'; +import { render, screen, waitFor } from '@testing-library/react'; +import ChangeEmail from '../ChangeEmail'; + +const mockShowToast = jest.fn(); +const mockMutate = jest.fn(); +let mockIsLoading = false; + +jest.mock('@librechat/client', () => { + const actual = jest.requireActual('@librechat/client'); + return { + ...actual, + useToastContext: () => ({ showToast: mockShowToast }), + }; +}); + +jest.mock('~/hooks', () => ({ + useLocalize: () => (key: string) => key, + useAuthContext: () => ({ user: { email: 'old@example.com' } }), +})); + +jest.mock('~/data-provider', () => ({ + useRequestEmailChangeMutation: () => ({ mutate: mockMutate, isLoading: mockIsLoading }), +})); + +describe('ChangeEmail', () => { + beforeEach(() => { + mockIsLoading = false; + }); + + async function openDialog() { + const user = userEvent.setup(); + const view = render(); + await user.click(screen.getByRole('button', { name: 'com_ui_email_change_title' })); + expect(await screen.findByRole('dialog')).toBeInTheDocument(); + return { user, view }; + } + + it('keeps the cancel control usable while the request is pending', async () => { + const { view } = await openDialog(); + + mockIsLoading = true; + view.rerender(); + + expect(screen.getByRole('button', { name: 'com_ui_cancel' })).toBeEnabled(); + }); + + it('still dismisses on Escape while the request is pending', async () => { + const { user, view } = await openDialog(); + + mockIsLoading = true; + view.rerender(); + + await user.keyboard('{Escape}'); + + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + }); +}); diff --git a/client/src/data-provider/Auth/mutations.ts b/client/src/data-provider/Auth/mutations.ts index 66db9bb23f..205f028b8a 100644 --- a/client/src/data-provider/Auth/mutations.ts +++ b/client/src/data-provider/Auth/mutations.ts @@ -129,6 +129,29 @@ export const useUpdateUserPreferencesMutation = ( ); }; +export const useRequestEmailChangeMutation = ( + options?: t.MutationOptions, +): UseMutationResult => { + return useMutation({ + mutationFn: (payload: t.TRequestEmailChange) => dataService.requestEmailChange(payload), + ...(options ?? {}), + }); +}; + +export const useConfirmEmailChangeMutation = ( + options?: t.MutationOptions, +): UseMutationResult => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (payload: t.TConfirmEmailChange) => dataService.confirmEmailChange(payload), + ...(options ?? {}), + onSuccess: (...args) => { + queryClient.invalidateQueries([QueryKeys.user]); + options?.onSuccess?.(...args); + }, + }); +}; + export const useEnableTwoFactorMutation = (): UseMutationResult< t.TEnable2FAResponse, unknown, diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index 16402b1a68..4ebd5b733e 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -298,6 +298,9 @@ "com_auth_email_resend_link": "Resend Email", "com_auth_email_resent_failed": "Failed to resend verification email", "com_auth_email_resent_success": "Verification email resent successfully", + "com_auth_email_change_failed": "Email change verification failed", + "com_auth_email_change_success": "Email address changed successfully", + "com_auth_email_change_verification_in_progress": "Verifying your new email address, please wait", "com_auth_email_verification_failed": "Email verification failed", "com_auth_email_verification_failed_token_missing": "Verification failed, token missing", "com_auth_email_verification_in_progress": "Verifying your email, please wait", @@ -2302,6 +2305,26 @@ "com_ui_settings_label_archive_all_chats": "Archive all chats", "com_ui_settings_label_auto_refill": "Auto-refill", "com_ui_settings_label_avatar": "Avatar", + "com_ui_settings_label_change_email": "Email address", + "com_ui_email_change_button": "Change", + "com_ui_email_change_current_password": "Current password", + "com_ui_email_change_description": "Enter a new email address and your current password. The change is completed only after you open the verification link sent to the new address.", + "com_ui_email_change_error_delivery": "The verification email could not be sent. Please try again.", + "com_ui_email_change_error_disabled": "Email changes are disabled by the administrator.", + "com_ui_email_change_error_domain": "That email domain is not allowed.", + "com_ui_email_change_error_in_progress": "Another email change request completed first. Please use its verification email or try again.", + "com_ui_email_change_error_in_use": "That email address is already linked to another account.", + "com_ui_email_change_error_invalid": "Enter a valid email address and your current password.", + "com_ui_email_change_error_local": "Email changes are only available for local accounts.", + "com_ui_email_change_error_password": "Your current password is incorrect.", + "com_ui_email_change_error_same": "The new email address must be different from your current email.", + "com_ui_email_change_error_unavailable": "Email delivery is not configured for this server.", + "com_ui_email_change_error_unexpected": "The email change request failed. Please try again.", + "com_ui_email_change_new_email": "New email address", + "com_ui_email_change_send_verification": "Send verification link", + "com_ui_email_change_sending_verification": "Sending verification link", + "com_ui_email_change_title": "Change email address", + "com_ui_email_change_verification_sent": "Check your new email address for a verification link.", "com_ui_settings_label_backup_codes": "Backup codes", "com_ui_settings_label_clear_chats": "Delete all chats", "com_ui_settings_label_conversation_mode": "Conversation mode", diff --git a/client/src/utils/errors.ts b/client/src/utils/errors.ts index 62beaa6079..b27eae6056 100644 --- a/client/src/utils/errors.ts +++ b/client/src/utils/errors.ts @@ -43,3 +43,11 @@ export const getCodeWorkspaceErrorReason = ( const reason = data != null && typeof data === 'object' && 'reason' in data ? data.reason : null; return isCodeWorkspaceSelectionErrorReason(reason) ? reason : undefined; }; + +export const getResponseErrorCode = (error: unknown): TCode | undefined => { + if (!axios.isAxiosError<{ code?: string }>(error)) { + return undefined; + } + const code = error.response?.data?.code; + return typeof code === 'string' ? (code as TCode) : undefined; +}; diff --git a/e2e/README.md b/e2e/README.md index a948857794..94c11f7ab8 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -36,6 +36,23 @@ authenticated shell, sends one real prompt, reloads the resulting conversation, the conversation created by that run through LibreChat's authenticated API. Keep deterministic provider behavior and destructive database fixtures in the mock profile instead. +## Email Delivery + +The registered-email flow has a dedicated profile because enabling SMTP changes registration into a verification-required workflow. It starts a disposable local SMTP mailbox, verifies the setup account from the delivered message, and then tests the Settings โ†’ Account email change, verification link, notifications to both addresses, and login with the new address: + +```sh +npm run e2e:email-change +``` + +The disabled-mode profile verifies that `ALLOW_EMAIL_CHANGE=false` hides the Account control, +rejects both request and confirmation endpoints, and sends no email: + +```sh +npm run e2e:email-change:disabled +``` + +Override `E2E_SMTP_PORT` or `E2E_MAILBOX_PORT` if ports 1025 or 8025 are already in use. The mailbox binds only to `127.0.0.1` and is discarded with the test process. + ## Stream Stores and Shards The mock profile uses the in-memory generation stream store by default. To exercise the same browser scenarios through a real Redis job store and pub/sub transport, start Redis on port 6379 and run: diff --git a/e2e/playwright.config.email.ts b/e2e/playwright.config.email.ts new file mode 100644 index 0000000000..1f0fbca8a3 --- /dev/null +++ b/e2e/playwright.config.email.ts @@ -0,0 +1,77 @@ +import { defineConfig } from '@playwright/test'; +import path from 'path'; +import mockConfig from './playwright.config.mock'; + +const rootPath = path.resolve(__dirname, '..'); +const mailboxServerPath = path.resolve(rootPath, 'e2e/setup/mailbox-server.js'); +const emailChangeDisabled = process.env.E2E_ALLOW_EMAIL_CHANGE === 'false'; +const profileSuffix = emailChangeDisabled ? '-disabled' : ''; +const reportPath = path.resolve(rootPath, `e2e/playwright-report/email-change${profileSuffix}`); +const SMTP_PORT = process.env.E2E_SMTP_PORT ?? '1025'; +const MAILBOX_PORT = process.env.E2E_MAILBOX_PORT ?? '8025'; +const MAILBOX_URL = `http://127.0.0.1:${MAILBOX_PORT}`; + +const emailEnv: Record = { + EMAIL_HOST: '127.0.0.1', + EMAIL_PORT: SMTP_PORT, + EMAIL_FROM: 'noreply@librechat.test', + EMAIL_FROM_NAME: 'LibreChat E2E', + EMAIL_SERVICE: '', + EMAIL_ENCRYPTION: '', + EMAIL_USERNAME: '', + EMAIL_PASSWORD: '', + MAILGUN_API_KEY: '', + MAILGUN_DOMAIN: '', + ALLOW_EMAIL_CHANGE: emailChangeDisabled ? 'false' : 'true', + E2E_MAILBOX_URL: MAILBOX_URL, +}; + +/** The global setup and the mailbox helpers read these from this process. */ +Object.assign(process.env, emailEnv); + +if (!Array.isArray(mockConfig.webServer)) { + throw new Error('The email E2E profile requires the mock profile web servers'); +} +/** + * The mock profile snapshots `process.env` into each server's `env` while this + * module is still importing it, which is before the assignment above runs. The + * app would then start with no mail delivery configured and registration would + * silently verify the account instead of sending a link, so merge the mail + * settings into the inherited entries rather than relying on that ordering. + */ +const mockWebServers = mockConfig.webServer.map((server) => ({ + ...server, + env: { ...(server.env ?? process.env), ...emailEnv }, +})); + +export default defineConfig({ + ...mockConfig, + globalSetup: require.resolve('./setup/global-setup.email'), + globalTeardown: require.resolve('./setup/global-teardown.email'), + testDir: 'specs/email/', + testMatch: emailChangeDisabled ? 'email-change-disabled.spec.ts' : 'email-change.spec.ts', + outputDir: `specs/.test-results/email-change${profileSuffix}`, + fullyParallel: false, + workers: 1, + reporter: [['html', { outputFolder: reportPath, open: 'never' }], ['list']], + use: { + ...mockConfig.use, + storageState: path.resolve(rootPath, `e2e/.generated/storageState.email${profileSuffix}.json`), + }, + webServer: [ + { + command: `node ${mailboxServerPath}`, + cwd: rootPath, + env: { + ...process.env, + E2E_SMTP_PORT: SMTP_PORT, + E2E_MAILBOX_PORT: MAILBOX_PORT, + }, + url: `${MAILBOX_URL}/health`, + stdout: 'pipe', + timeout: 60_000, + reuseExistingServer: false, + }, + ...mockWebServers, + ], +}); diff --git a/e2e/setup/authenticate.ts b/e2e/setup/authenticate.ts index 0d637c400c..3e5d4276a2 100644 --- a/e2e/setup/authenticate.ts +++ b/e2e/setup/authenticate.ts @@ -8,8 +8,7 @@ dotenv.config(); const timeout = Number(process.env.E2E_AUTH_TIMEOUT ?? 15000); const chromiumChannel = process.env.E2E_CHROMIUM_CHANNEL || undefined; -async function register(page: Page, user: User) { - await page.getByRole('link', { name: 'Sign up' }).click(); +export async function submitRegistration(page: Page, user: User) { await page.getByLabel('Full name').click(); await page.getByLabel('Full name').fill(user.name); await page.getByLabel('Email').click(); @@ -22,6 +21,11 @@ async function register(page: Page, user: User) { await page.getByLabel('Submit registration').click(); } +export async function register(page: Page, user: User) { + await page.getByRole('link', { name: 'Sign up' }).click(); + await submitRegistration(page, user); +} + async function registrationErrorIsVisible(page: Page) { return page .getByTestId('registration-error') @@ -29,13 +33,13 @@ async function registrationErrorIsVisible(page: Page) { .catch(() => false); } -async function login(page: Page, user: User) { +export async function login(page: Page, user: User) { await page.getByLabel('Email').fill(user.email); await page.getByLabel('Password').fill(user.password); await page.getByTestId('login-button').click(); } -function appURL(baseURL: string, pathname = '') { +export function appURL(baseURL: string, pathname = '') { const normalizedBaseURL = baseURL.endsWith('/') ? baseURL : `${baseURL}/`; return new URL(pathname.replace(/^\/+/, ''), normalizedBaseURL).toString(); } diff --git a/e2e/setup/cleanupUser.ts b/e2e/setup/cleanupUser.ts index 3101d60850..e15b16a0f1 100644 --- a/e2e/setup/cleanupUser.ts +++ b/e2e/setup/cleanupUser.ts @@ -2,6 +2,7 @@ import path from 'path'; import { applyRuntimeEnv } from './runtimeEnv'; type TUser = { email: string; password: string }; +type DatabaseConnection = { connection: { close: () => Promise } }; /** * Registers the backend's `~` alias in this process. Playwright's require hook only @@ -37,9 +38,10 @@ export default async function cleanupUser(user: TUser) { /* eslint-enable @typescript-eslint/no-require-imports */ const { email } = user; + let db: DatabaseConnection | undefined; try { console.log('๐Ÿค–: global teardown has been started'); - const db = await connectDb(); + db = await connectDb(); console.log('๐Ÿค–: โœ… Connected to Database'); const foundUser = await findUser({ email }); @@ -84,10 +86,14 @@ export default async function cleanupUser(user: TUser) { await User.deleteMany({ _id: userId }); console.log('๐Ÿค–: โœ… Deleted user from Database'); - - await db.connection.close(); } catch (error) { console.error('Error:', error); + } finally { + try { + await db?.connection.close(); + } catch (error) { + console.error('Error closing database connection:', error); + } } } diff --git a/e2e/setup/global-setup.email.ts b/e2e/setup/global-setup.email.ts new file mode 100644 index 0000000000..e0c262c60c --- /dev/null +++ b/e2e/setup/global-setup.email.ts @@ -0,0 +1,75 @@ +import { chromium } from '@playwright/test'; +import type { FullConfig } from '@playwright/test'; +import cleanupUser from './cleanupUser'; +import { appURL, login, submitRegistration } from './authenticate'; +import { clearMailbox, getVerificationURL, waitForMessage } from './mailbox'; +import { getEmailChangeTarget, getEmailChangeUser } from './users.email'; + +const timeout = Number(process.env.E2E_AUTH_TIMEOUT ?? 15_000); +const chromiumChannel = process.env.E2E_CHROMIUM_CHANNEL || undefined; + +async function globalSetup(config: FullConfig) { + const user = getEmailChangeUser(); + await cleanupUser({ email: getEmailChangeTarget(), password: user.password }); + await cleanupUser(user); + await clearMailbox(); + + const { baseURL, storageState } = config.projects[0].use; + if (typeof baseURL !== 'string' || typeof storageState !== 'string') { + throw new Error('Email E2E setup requires string baseURL and storageState values'); + } + + const browser = await chromium.launch({ + headless: config.projects[0].use.headless ?? true, + ...(chromiumChannel ? { channel: chromiumChannel } : {}), + }); + try { + const page = await browser.newPage(); + const pageErrors: string[] = []; + const failedResponses: string[] = []; + page.on('pageerror', (error) => pageErrors.push(error.message)); + page.on('response', (response) => { + if (response.status() >= 400) { + failedResponses.push(`${response.status()} ${response.url()}`); + } + }); + await page.goto(appURL(baseURL, 'register'), { timeout }); + try { + await page.getByLabel('Full name').waitFor({ timeout }); + } catch (error) { + const body = (await page.locator('body').innerText()).slice(0, 2000); + throw new Error( + `Registration form did not render at ${page.url()}\nPage errors: ${pageErrors.join(' | ') || 'none'}\nFailed responses: ${failedResponses.join(' | ') || 'none'}\nBody: ${body || '(empty)'}`, + { cause: error }, + ); + } + const registrationResponsePromise = page.waitForResponse( + (response) => + response.request().method() === 'POST' && + new URL(response.url()).pathname === '/api/auth/register', + ); + await submitRegistration(page, user); + const registrationResponse = await registrationResponsePromise; + if (!registrationResponse.ok()) { + throw new Error( + `Registration failed with ${registrationResponse.status()}: ${await registrationResponse.text()}`, + ); + } + + const verificationEmail = await waitForMessage({ + to: user.email, + subject: 'Verify your email', + }); + await page.goto(getVerificationURL(verificationEmail, baseURL), { timeout }); + await page.getByRole('heading', { name: /Email verified successfully/ }).waitFor({ timeout }); + + await page.goto(appURL(baseURL, 'login'), { timeout }); + await login(page, user); + await page.waitForURL(appURL(baseURL, 'c/new'), { timeout }); + await page.context().storageState({ path: storageState }); + } finally { + await browser.close(); + } +} + +export default globalSetup; diff --git a/e2e/setup/global-teardown.email.ts b/e2e/setup/global-teardown.email.ts new file mode 100644 index 0000000000..5740b7be6a --- /dev/null +++ b/e2e/setup/global-teardown.email.ts @@ -0,0 +1,15 @@ +import cleanupUser from './cleanupUser'; +import { getEmailChangeTarget, getEmailChangeUser } from './users.email'; + +async function globalTeardown() { + const user = getEmailChangeUser(); + for (const email of [getEmailChangeTarget(), user.email]) { + try { + await cleanupUser({ email, password: user.password }); + } catch (error) { + console.error('Error:', error); + } + } +} + +export default globalTeardown; diff --git a/e2e/setup/mailbox-server.js b/e2e/setup/mailbox-server.js new file mode 100644 index 0000000000..1c166b5513 --- /dev/null +++ b/e2e/setup/mailbox-server.js @@ -0,0 +1,229 @@ +const http = require('http'); +const net = require('net'); + +const SMTP_PORT = Number(process.env.E2E_SMTP_PORT ?? 1025); +const HTTP_PORT = Number(process.env.E2E_MAILBOX_PORT ?? 8025); +const MAX_MESSAGE_BYTES = 5 * 1024 * 1024; + +const messages = []; +let nextId = 1; + +function decodeQuotedPrintable(value) { + return value + .replace(/=\r?\n/g, '') + .replace(/=([0-9A-F]{2})/gi, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16))); +} + +function decodeBody(raw, headers) { + const encoding = headers.get('content-transfer-encoding')?.toLowerCase(); + if (encoding === 'base64') { + return Buffer.from(raw.replace(/\s/g, ''), 'base64').toString('utf8'); + } + if (encoding === 'quoted-printable') { + return decodeQuotedPrintable(raw); + } + return raw; +} + +function decodeHtmlEntities(value) { + const namedEntities = { + amp: '&', + apos: "'", + gt: '>', + lt: '<', + quot: '"', + }; + return value + .replace(/&#x([0-9A-F]+);/gi, (_match, hex) => String.fromCodePoint(Number.parseInt(hex, 16))) + .replace(/&#(\d+);/g, (_match, decimal) => String.fromCodePoint(Number.parseInt(decimal, 10))) + .replace(/&(amp|apos|gt|lt|quot);/g, (_match, name) => namedEntities[name]); +} + +function parseMessage(raw, envelope) { + const separator = raw.search(/\r?\n\r?\n/); + const rawHeaders = separator === -1 ? raw : raw.slice(0, separator); + const rawBody = separator === -1 ? '' : raw.slice(separator).replace(/^\r?\n\r?\n/, ''); + const headers = new Map(); + + for (const line of rawHeaders.replace(/\r?\n[ \t]+/g, ' ').split(/\r?\n/)) { + const colon = line.indexOf(':'); + if (colon > 0) { + headers.set(line.slice(0, colon).toLowerCase(), line.slice(colon + 1).trim()); + } + } + + const body = decodeBody(rawBody, headers); + const urls = (body.match(/https?:\/\/[^\s"'<>]+/g) ?? []).map(decodeHtmlEntities); + + return { + id: nextId++, + from: envelope.from, + to: [...envelope.to], + subject: headers.get('subject') ?? '', + body, + urls, + }; +} + +function createSmtpServer() { + return net.createServer((socket) => { + let buffer = ''; + let dataLines = []; + let dataBytes = 0; + let readingData = false; + let envelope = { from: '', to: [] }; + + const reply = (line) => socket.write(`${line}\r\n`); + const resetEnvelope = () => { + envelope = { from: '', to: [] }; + dataLines = []; + dataBytes = 0; + readingData = false; + }; + + const handleCommand = (line) => { + const [command = ''] = line.trim().split(/\s+/, 1); + const upperCommand = command.toUpperCase(); + + if (upperCommand === 'EHLO') { + socket.write('250-localhost\r\n250-PIPELINING\r\n250-8BITMIME\r\n250 SMTPUTF8\r\n'); + return; + } + if (upperCommand === 'HELO') { + reply('250 localhost'); + return; + } + if (upperCommand === 'MAIL') { + const match = line.match(/^MAIL FROM:\s*\s]+)>?/i); + if (!match) { + reply('501 Invalid sender'); + return; + } + envelope.from = match[1]; + reply('250 Sender accepted'); + return; + } + if (upperCommand === 'RCPT') { + const match = line.match(/^RCPT TO:\s*\s]+)>?/i); + if (!match) { + reply('501 Invalid recipient'); + return; + } + envelope.to.push(match[1].toLowerCase()); + reply('250 Recipient accepted'); + return; + } + if (upperCommand === 'DATA') { + if (!envelope.from || envelope.to.length === 0) { + reply('503 MAIL FROM and RCPT TO required'); + return; + } + readingData = true; + reply('354 End data with .'); + return; + } + if (upperCommand === 'RSET') { + resetEnvelope(); + reply('250 Reset'); + return; + } + if (upperCommand === 'NOOP') { + reply('250 OK'); + return; + } + if (upperCommand === 'QUIT') { + reply('221 Bye'); + socket.end(); + return; + } + reply('502 Command not implemented'); + }; + + const handleLine = (line) => { + if (!readingData) { + handleCommand(line); + return; + } + if (line === '.') { + messages.push(parseMessage(dataLines.join('\r\n'), envelope)); + resetEnvelope(); + reply('250 Message accepted'); + return; + } + + const unstuffed = line.startsWith('..') ? line.slice(1) : line; + dataBytes += Buffer.byteLength(unstuffed) + 2; + if (dataBytes > MAX_MESSAGE_BYTES) { + resetEnvelope(); + reply('552 Message too large'); + return; + } + dataLines.push(unstuffed); + }; + + socket.setEncoding('utf8'); + socket.setTimeout(30_000, () => socket.destroy()); + socket.on('error', () => socket.destroy()); + socket.on('data', (chunk) => { + buffer += chunk; + let newline = buffer.indexOf('\n'); + while (newline !== -1) { + const line = buffer.slice(0, newline).replace(/\r$/, ''); + buffer = buffer.slice(newline + 1); + handleLine(line); + newline = buffer.indexOf('\n'); + } + }); + reply('220 localhost ESMTP LibreChat E2E mailbox'); + }); +} + +function sendJson(response, status, body) { + response.writeHead(status, { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', + }); + response.end(JSON.stringify(body)); +} + +function createHttpServer() { + return http.createServer((request, response) => { + const url = new URL(request.url ?? '/', `http://127.0.0.1:${HTTP_PORT}`); + if (request.method === 'GET' && url.pathname === '/health') { + sendJson(response, 200, { ok: true }); + return; + } + if (request.method === 'DELETE' && url.pathname === '/messages') { + messages.length = 0; + nextId = 1; + sendJson(response, 200, { ok: true }); + return; + } + if (request.method === 'GET' && url.pathname === '/messages') { + const to = url.searchParams.get('to')?.toLowerCase(); + const subject = url.searchParams.get('subject'); + const matches = messages.filter( + (message) => (!to || message.to.includes(to)) && (!subject || message.subject === subject), + ); + sendJson(response, 200, { messages: matches }); + return; + } + sendJson(response, 404, { error: 'Not found' }); + }); +} + +const smtpServer = createSmtpServer(); +const httpServer = createHttpServer(); + +smtpServer.listen(SMTP_PORT, '127.0.0.1', () => { + httpServer.listen(HTTP_PORT, '127.0.0.1', () => { + console.log(`[e2e] Mailbox listening on SMTP ${SMTP_PORT} and HTTP ${HTTP_PORT}`); + }); +}); + +function shutdown() { + httpServer.close(() => smtpServer.close()); +} + +process.once('SIGINT', shutdown); +process.once('SIGTERM', shutdown); diff --git a/e2e/setup/mailbox.ts b/e2e/setup/mailbox.ts new file mode 100644 index 0000000000..4e45be4eca --- /dev/null +++ b/e2e/setup/mailbox.ts @@ -0,0 +1,76 @@ +const DEFAULT_MAILBOX_URL = 'http://127.0.0.1:8025'; + +export interface MailboxMessage { + id: number; + from: string; + to: string[]; + subject: string; + body: string; + urls: string[]; +} + +interface MailboxResponse { + messages: MailboxMessage[]; +} + +interface MessageFilter { + to: string; + subject: string; +} + +function mailboxURL(pathname: string): URL { + return new URL(pathname, process.env.E2E_MAILBOX_URL ?? DEFAULT_MAILBOX_URL); +} + +async function readMessages(url: URL): Promise { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`Failed to read E2E mailbox: ${response.status} ${await response.text()}`); + } + return ((await response.json()) as MailboxResponse).messages; +} + +export async function clearMailbox(): Promise { + const response = await fetch(mailboxURL('/messages'), { method: 'DELETE' }); + if (!response.ok) { + throw new Error(`Failed to clear E2E mailbox: ${response.status} ${await response.text()}`); + } +} + +async function findMessages(filter: MessageFilter): Promise { + const url = mailboxURL('/messages'); + url.searchParams.set('to', filter.to); + url.searchParams.set('subject', filter.subject); + return readMessages(url); +} + +export async function getMailboxMessages(): Promise { + return readMessages(mailboxURL('/messages')); +} + +export async function waitForMessage( + filter: MessageFilter, + timeout = 15_000, +): Promise { + const deadline = Date.now() + timeout; + while (Date.now() < deadline) { + const [message] = await findMessages(filter); + if (message) { + return message; + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error(`Timed out waiting for email "${filter.subject}" to ${filter.to}`); +} + +export function getVerificationURL(message: MailboxMessage, baseURL: string): string { + const expectedOrigin = new URL(baseURL).origin; + const verificationURL = message.urls.find((candidate) => { + const url = new URL(candidate); + return url.origin === expectedOrigin && url.pathname === '/verify'; + }); + if (!verificationURL) { + throw new Error(`No verification URL found in email "${message.subject}"`); + } + return verificationURL; +} diff --git a/e2e/setup/users.email.ts b/e2e/setup/users.email.ts new file mode 100644 index 0000000000..e1fa7b03e5 --- /dev/null +++ b/e2e/setup/users.email.ts @@ -0,0 +1,21 @@ +import type { User } from '../types'; + +const DEFAULT_EMAIL_CHANGE_USER: User = { + email: 'email-change-user@example.com', + name: 'Email Change User', + password: 'securepassword789', +}; + +const DEFAULT_NEW_EMAIL = 'email-change-user-updated@example.com'; + +export function getEmailChangeUser(): User { + return { + email: process.env.E2E_EMAIL_CHANGE_USER_EMAIL ?? DEFAULT_EMAIL_CHANGE_USER.email, + name: process.env.E2E_EMAIL_CHANGE_USER_NAME ?? DEFAULT_EMAIL_CHANGE_USER.name, + password: process.env.E2E_EMAIL_CHANGE_USER_PASSWORD ?? DEFAULT_EMAIL_CHANGE_USER.password, + }; +} + +export function getEmailChangeTarget(): string { + return process.env.E2E_EMAIL_CHANGE_TARGET ?? DEFAULT_NEW_EMAIL; +} diff --git a/e2e/specs/email/email-change-disabled.spec.ts b/e2e/specs/email/email-change-disabled.spec.ts new file mode 100644 index 0000000000..78c75faae3 --- /dev/null +++ b/e2e/specs/email/email-change-disabled.spec.ts @@ -0,0 +1,51 @@ +import { expect, test } from '@playwright/test'; +import { clearMailbox, getMailboxMessages } from '../../setup/mailbox'; +import { getEmailChangeTarget, getEmailChangeUser } from '../../setup/users.email'; + +test.describe('account settings ยท disabled registered-email changes', () => { + test('hides the control and rejects both backend operations without sending mail', async ({ + page, + }) => { + const user = getEmailChangeUser(); + const newEmail = getEmailChangeTarget(); + const refreshResponse = await page.request.post('/api/auth/refresh'); + expect(refreshResponse.status()).toBe(200); + const { token } = (await refreshResponse.json()) as { token: string }; + const headers = { Authorization: `Bearer ${token}` }; + + const configResponse = await page.request.get('/api/config', { headers }); + expect(configResponse.status()).toBe(200); + expect((await configResponse.json()).allowEmailChange).toBe(false); + + await page.goto('/c/new'); + await page.getByTestId('nav-user').click(); + await page.getByRole('menuitem', { name: 'Settings' }).click(); + await page.getByRole('tab', { name: 'Account' }).click(); + await expect( + page.getByRole('tabpanel', { name: 'Account' }).getByRole('button', { + name: 'Change email address', + }), + ).toHaveCount(0); + + await clearMailbox(); + + const requestResponse = await page.request.post('/api/user/email/change', { + headers, + data: { currentPassword: user.password, newEmail }, + }); + expect(requestResponse.status()).toBe(403); + expect(await requestResponse.json()).toMatchObject({ code: 'email_change_disabled' }); + + const confirmationResponse = await page.request.post('/api/user/email/verify', { + data: { + email: newEmail, + token: 'unused-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + expect(confirmationResponse.status()).toBe(403); + expect(await confirmationResponse.json()).toMatchObject({ code: 'email_change_disabled' }); + + expect(await getMailboxMessages()).toEqual([]); + }); +}); diff --git a/e2e/specs/email/email-change.spec.ts b/e2e/specs/email/email-change.spec.ts new file mode 100644 index 0000000000..16139822a2 --- /dev/null +++ b/e2e/specs/email/email-change.spec.ts @@ -0,0 +1,101 @@ +import { expect, test } from '@playwright/test'; +import AxeBuilder from '@axe-core/playwright'; +import { clearMailbox, getVerificationURL, waitForMessage } from '../../setup/mailbox'; +import { getEmailChangeTarget, getEmailChangeUser } from '../../setup/users.email'; + +test.describe('account settings ยท registered email', () => { + test('changes a verified email through the delivered link and notifies both addresses', async ({ + page, + baseURL, + }) => { + test.setTimeout(60_000); + if (!baseURL) { + throw new Error('Email change E2E test requires a baseURL'); + } + + const user = getEmailChangeUser(); + const newEmail = getEmailChangeTarget(); + await clearMailbox(); + + await page.goto('/c/new'); + await page.getByTestId('nav-user').click(); + await page.getByRole('menuitem', { name: 'Settings' }).click(); + await page.getByRole('tab', { name: 'Account' }).click(); + await page + .getByRole('tabpanel', { name: 'Account' }) + .getByRole('button', { name: 'Change email address' }) + .click(); + + const accessibilityScan = await new AxeBuilder({ page }) + .include('#change-email-dialog') + .analyze(); + expect(accessibilityScan.violations).toEqual([]); + + await page.getByLabel('New email address').fill(newEmail); + const currentPasswordInput = page.getByLabel('Current password'); + await expect(currentPasswordInput).toHaveAttribute('type', 'password'); + const showSecretButton = page.getByRole('button', { name: 'Show secret' }); + await showSecretButton.focus(); + await page.keyboard.press('Enter'); + await expect(currentPasswordInput).toHaveAttribute('type', 'text'); + const hideSecretButton = page.getByRole('button', { name: 'Hide secret' }); + await hideSecretButton.focus(); + await page.keyboard.press('Enter'); + await expect(currentPasswordInput).toHaveAttribute('type', 'password'); + await currentPasswordInput.fill(user.password); + const responsePromise = page.waitForResponse( + (response) => + response.request().method() === 'POST' && + new URL(response.url()).pathname === '/api/user/email/change', + ); + await page.getByRole('button', { name: 'Send verification link' }).click(); + const response = await responsePromise; + expect(response.status()).toBe(200); + await expect( + page.getByText('Check your new email address for a verification link.', { exact: true }), + ).toBeVisible(); + + const attemptEmail = await waitForMessage({ + to: user.email, + subject: 'Email change requested', + }); + expect(attemptEmail.body).toContain(newEmail); + expect(attemptEmail.body).toContain('IP address:'); + + const verificationEmail = await waitForMessage({ + to: newEmail, + subject: 'Verify your new email address', + }); + const verificationURL = getVerificationURL(verificationEmail, baseURL); + expect(new URL(verificationURL).searchParams.get('type')).toBe('email-change'); + + await page.goto(verificationURL); + await expect( + page.getByRole('heading', { name: /Email address changed successfully/ }), + ).toBeVisible(); + + const [oldConfirmation, newConfirmation] = await Promise.all([ + waitForMessage({ to: user.email, subject: 'Your email address was changed' }), + waitForMessage({ to: newEmail, subject: 'Your email address was changed' }), + ]); + for (const confirmation of [oldConfirmation, newConfirmation]) { + expect(confirmation.body).toContain(user.email); + expect(confirmation.body).toContain(newEmail); + expect(confirmation.body).toContain('IP address:'); + } + + await page.context().clearCookies(); + await page.goto('/login'); + await page.getByLabel('Email').fill(newEmail); + await page.getByLabel('Password').fill(user.password); + await page.getByTestId('login-button').click(); + await expect(page).toHaveURL(/\/c\/new$/); + + await page.getByTestId('nav-user').click(); + await page.getByRole('menuitem', { name: 'Settings' }).click(); + await page.getByRole('tab', { name: 'Account' }).click(); + await expect( + page.getByRole('tabpanel', { name: 'Account' }).getByText(newEmail, { exact: true }), + ).toBeVisible(); + }); +}); diff --git a/e2e/specs/mock/scenarios/email-change-gating.spec.ts b/e2e/specs/mock/scenarios/email-change-gating.spec.ts new file mode 100644 index 0000000000..01a2a80bef --- /dev/null +++ b/e2e/specs/mock/scenarios/email-change-gating.spec.ts @@ -0,0 +1,136 @@ +import { expect, test } from '@playwright/test'; +import type { Page } from '@playwright/test'; +import { getE2EUser } from '../../../setup/user'; + +/** + * Changing the registered address is offered only where it can actually + * complete: a local account, on a deployment that can deliver mail, with the + * operator's switch left on. Each of those three is a separate gate, and the + * two that live in the served startup config are what an operator turns off. + * + * The end-to-end delivery flow needs an SMTP mailbox and runs in the dedicated + * email profile (`npm run e2e:email-change`). What belongs here is the gating + * either side of it: the control appears when it can work, disappears when the + * operator disables it, and a deployment that cannot send mail refuses the + * request instead of leaving the account half-changed. The confirmation page is + * the other half of that boundary, since its link arrives from outside the app + * and a stale or forged one must not move an address. + * + * The settings dialog scenarios pin the desktop viewport the same way the other + * settings-modal scenarios do; the confirmation page runs at every viewport. + */ + +const user = getE2EUser(); + +type StartupConfigOverrides = { + emailEnabled?: boolean; + allowEmailChange?: boolean; +}; + +/** Serve the deployment's startup config with these flags, leaving the rest of + * the harness config as every other spec reads it. */ +async function withStartupConfig(page: Page, overrides: StartupConfigOverrides) { + await page.route('**/api/config', async (route) => { + const response = await route.fetch(); + const config = await response.json(); + await route.fulfill({ response, json: { ...config, ...overrides } }); + }); +} + +async function openAccountTab(page: Page) { + await page.goto('/c/new', { timeout: 15000 }); + await page.getByTestId('nav-user').click(); + await page.getByRole('menuitem', { name: 'Settings' }).click(); + await page.getByRole('tab', { name: 'Account' }).click(); +} + +const changeEmailButton = (page: Page) => + page.getByRole('button', { name: 'Change email address' }); + +test.describe('account settings ยท registered email gating', () => { + test.describe('settings dialog', () => { + test.use({ viewport: { width: 1280, height: 800 } }); + + test('a local account is offered the change when delivery is configured @scenario:email-change-offered-to-a-local-account', async ({ + page, + }) => { + test.setTimeout(90000); + await withStartupConfig(page, { emailEnabled: true, allowEmailChange: true }); + + await openAccountTab(page); + + await expect(changeEmailButton(page)).toBeVisible({ timeout: 15000 }); + await changeEmailButton(page).click(); + + const dialog = page.getByRole('dialog', { name: 'Change email address' }); + await expect(dialog).toBeVisible({ timeout: 10000 }); + await expect(dialog.getByLabel('New email address')).toBeVisible(); + await expect(dialog.getByLabel('Current password')).toBeVisible(); + /** Nothing is sent until both fields carry a value. */ + await expect(dialog.getByRole('button', { name: 'Send verification link' })).toBeDisabled(); + }); + + test('the operator can take the change off the Account tab @scenario:email-change-hidden-when-the-operator-disables-it', async ({ + page, + }) => { + test.setTimeout(90000); + await withStartupConfig(page, { emailEnabled: true, allowEmailChange: false }); + + await openAccountTab(page); + + /** The tab itself renders, so an empty assertion cannot pass by accident. */ + await expect(page.getByRole('button', { name: 'Delete account' })).toBeVisible({ + timeout: 15000, + }); + await expect(changeEmailButton(page)).toHaveCount(0); + }); + + test('a deployment without mail delivery refuses the request @scenario:email-change-refused-without-email-delivery', async ({ + page, + }) => { + test.setTimeout(90000); + /** The client is told delivery works; the server this runs against has no + * SMTP, which is the mismatch an operator hits after removing it. */ + await withStartupConfig(page, { emailEnabled: true, allowEmailChange: true }); + + await openAccountTab(page); + await changeEmailButton(page).click(); + + const dialog = page.getByRole('dialog', { name: 'Change email address' }); + await expect(dialog).toBeVisible({ timeout: 10000 }); + await dialog.getByLabel('New email address').fill('moved@example.com'); + await dialog.getByLabel('Current password').fill(user.password); + await dialog.getByRole('button', { name: 'Send verification link' }).click(); + + await expect(dialog.getByRole('alert')).toHaveText( + 'Email delivery is not configured for this server.', + { timeout: 15000 }, + ); + /** The dialog stays open and the account never adopts the new address. */ + await expect(dialog).toBeVisible(); + await dialog.getByRole('button', { name: 'Cancel' }).click(); + await expect(dialog).toBeHidden(); + await expect(page.getByText('moved@example.com')).toHaveCount(0); + }); + }); + + test('a confirmation link the server does not recognise changes nothing @scenario:email-change-link-with-an-unknown-token-is-refused', async ({ + page, + }) => { + test.setTimeout(90000); + const query = new URLSearchParams({ + type: 'email-change', + userId: '000000000000000000000000', + email: 'moved@example.com', + token: 'not-a-real-token', + }); + + await page.goto(`/verify?${query.toString()}`, { timeout: 15000 }); + + await expect(page.getByText('Email change verification failed')).toBeVisible({ + timeout: 20000, + }); + /** A refused link is not an invitation to request a new verification mail. */ + await expect(page.getByRole('button', { name: 'Resend Email' })).toHaveCount(0); + }); +}); diff --git a/librechat.example.yaml b/librechat.example.yaml index 8d0f893c9b..edccfcd874 100644 --- a/librechat.example.yaml +++ b/librechat.example.yaml @@ -348,6 +348,12 @@ interface: # size: "normal" # Options: "normal", "compact", "flexible", or "invisible" # Example Registration Object Structure (optional) +# Changing the registered email address from Settings > Account. +# Omitted, these fall back to ALLOW_EMAIL_CHANGE and a 15-minute link. +# emailChange: +# enabled: true +# tokenTTLSeconds: 900 + registration: socialLogins: ['github', 'google', 'discord', 'openid', 'facebook', 'apple', 'saml'] # allowedDomains: @@ -445,6 +451,17 @@ registration: # ipWindowInMinutes: 60 # Rate limit window for conversation imports per IP # userMax: 50 # userWindowInMinutes: 60 # Rate limit window for conversation imports per user +# # Asking for a change of the registered email, per authenticated user. +# emailChange: +# userMax: 3 +# userWindowInMinutes: 2 +# # Opening a verification link. The endpoint is unauthenticated, so the source +# # address is bounded as well as the account the link names. +# emailChangeConfirm: +# ipMax: 20 +# ipWindowInMinutes: 2 +# userMax: 2 +# userWindowInMinutes: 2 # Agent Actions domain restrictions (OpenAPI spec validation) # SECURITY: If not configured, SSRF targets are blocked (localhost, private IPs, .internal/.local TLDs). diff --git a/package.json b/package.json index acd6b8c8d9..c5281b2b1d 100644 --- a/package.json +++ b/package.json @@ -72,6 +72,8 @@ "e2e:a11y": "npm run e2e:prepare && playwright test --config=e2e/playwright.config.a11y.ts --headed", "e2e:ci": "npm run e2e:prepare && playwright test --config=e2e/playwright.config.ts", "e2e:mock": "npm run e2e:prepare && playwright test --config=e2e/playwright.config.mock.ts", + "e2e:email-change": "npm run e2e:prepare && playwright test --config=e2e/playwright.config.email.ts", + "e2e:email-change:disabled": "npm run e2e:prepare && cross-env E2E_ALLOW_EMAIL_CHANGE=false playwright test --config=e2e/playwright.config.email.ts", "e2e:mock:redis": "npm run e2e:prepare && cross-env E2E_STREAM_STORE=redis playwright test --config=e2e/playwright.config.mock.ts", "e2e:mock:redis:transport": "npm run e2e:prepare && cross-env E2E_STREAM_STORE=redis playwright test --config=e2e/playwright.config.redis.ts", "e2e:benchmark:agents": "npm run e2e:prepare && playwright test --config=e2e/playwright.config.benchmark.ts agent-startup.latency.spec.ts", diff --git a/packages/api/src/app/limits.ts b/packages/api/src/app/limits.ts index 809c47d8f2..d50fd6fc84 100644 --- a/packages/api/src/app/limits.ts +++ b/packages/api/src/app/limits.ts @@ -16,6 +16,8 @@ export const handleRateLimits = (rateLimits?: TCustomConfig['rateLimits']): void conversationsImport: RateLimitPrefix.IMPORT, tts: RateLimitPrefix.TTS, stt: RateLimitPrefix.STT, + emailChange: RateLimitPrefix.EMAIL_CHANGE, + emailChangeConfirm: RateLimitPrefix.EMAIL_CHANGE_CONFIRM, }; Object.entries(rateLimitKeys).forEach(([key, prefix]) => { diff --git a/packages/api/src/app/service.ts b/packages/api/src/app/service.ts index 44a4750bd3..069bc766b5 100644 --- a/packages/api/src/app/service.ts +++ b/packages/api/src/app/service.ts @@ -244,6 +244,19 @@ export function getAppConfigOptionsFromUser( }; } +/** + * A route that decides policy from the resolved configuration must not be handed the base + * configuration when principal or override resolution fails, because the base can be broader + * than the scope that should have decided. The caller supplies the reader, so the selection + * of that policy lives here rather than in the middleware that assigns the result. + */ +export function resolveStrictAppConfig( + getAppConfig: (options: GetAppConfigOptions) => Promise, + user?: AppConfigUserLike | null, +): Promise { + return getAppConfig({ ...getAppConfigOptionsFromUser(user), failClosed: true }); +} + // โ”€โ”€ Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ let _strictOverride: boolean | undefined; diff --git a/packages/api/src/auth/email.spec.ts b/packages/api/src/auth/email.spec.ts new file mode 100644 index 0000000000..dc28670227 --- /dev/null +++ b/packages/api/src/auth/email.spec.ts @@ -0,0 +1,1145 @@ +import { hashToken } from '@librechat/data-schemas'; +import type { TokenQuery } from '@librechat/data-schemas'; +import { + EMAIL_CHANGE_TOKEN_TYPE, + createEmailChangeService, + emailChangeSubmissionKey, + type EmailChangeDeps, + type EmailChangeToken, + type EmailChangeUser, +} from './email'; + +const user: EmailChangeUser = { + _id: '507f1f77bcf86cd799439011', + email: 'old@example.com', + name: 'Test User', + password: 'password-hash', + provider: 'local', + tenantId: 'tenant-1', +}; + +function createDeps(overrides: Partial = {}) { + const deps: EmailChangeDeps = { + findUserByEmail: jest.fn().mockResolvedValue(null), + getUserById: jest.fn().mockResolvedValue(user), + updateUser: jest.fn().mockResolvedValue({ ...user, email: 'new@example.com' }), + findToken: jest.fn().mockResolvedValue(null), + replaceTokenIfCurrent: jest.fn().mockResolvedValue(true), + deleteTokens: jest.fn().mockResolvedValue({ deletedCount: 1 }), + verifyPassword: jest.fn().mockResolvedValue(true), + resolvePolicy: jest.fn().mockResolvedValue({ + settings: { enabled: true, tokenTTLSeconds: 900 }, + allowedDomains: null, + }), + sendEmail: jest.fn().mockResolvedValue(undefined), + resolveSettings: jest.fn().mockResolvedValue({ enabled: true, tokenTTLSeconds: 900 }), + clientDomain: 'https://chat.example.com/', + appName: 'LibreChat', + ...overrides, + }; + return { deps, service: createEmailChangeService(deps) }; +} + +const DEFAULT_SETTINGS = { enabled: true, tokenTTLSeconds: 900 }; + +describe('emailChangeSubmissionKey', () => { + it('isolates confirmation attempts by address and by account', () => { + const first = emailChangeSubmissionKey('203.0.113.10', '507f1f77bcf86cd799439011'); + const second = emailChangeSubmissionKey('203.0.113.10', '507f1f77bcf86cd799439012'); + + expect(first).toBe('ip:203.0.113.10:user:507f1f77bcf86cd799439011'); + expect(first).not.toBe(second); + }); + + it('collapses ids that cannot name an account into one bucket', () => { + /** Otherwise a caller mints a fresh allowance by varying an id it invented. */ + expect(emailChangeSubmissionKey('203.0.113.10', 'not-an-id')).toBe( + 'ip:203.0.113.10:user:invalid', + ); + expect(emailChangeSubmissionKey('203.0.113.10', undefined)).toBe( + 'ip:203.0.113.10:user:invalid', + ); + expect(emailChangeSubmissionKey('203.0.113.10', { toString: () => 'x' })).toBe( + 'ip:203.0.113.10:user:invalid', + ); + }); + + it('normalizes the case of an id so one account is one bucket', () => { + expect(emailChangeSubmissionKey('203.0.113.10', '507F1F77BCF86CD799439011')).toBe( + 'ip:203.0.113.10:user:507f1f77bcf86cd799439011', + ); + }); +}); + +describe('email change service', () => { + describe('requestEmailChange', () => { + it('rejects requests when email changes are disabled', async () => { + const { deps, service } = createDeps({}); + + const response = await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'new@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: { enabled: false, tokenTTLSeconds: 900 }, + emailEnabled: true, + }); + + expect(response).toEqual({ + status: 403, + message: 'Email changes are disabled', + code: 'email_change_disabled', + }); + expect(deps.getUserById).not.toHaveBeenCalled(); + expect(deps.sendEmail).not.toHaveBeenCalled(); + }); + + it('verifies the password, records the IP, alerts the old address, and verifies the new one', async () => { + const { deps, service } = createDeps(); + + const response = await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: ' New@Example.com ' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + allowedDomains: ['example.com'], + settings: DEFAULT_SETTINGS, + emailEnabled: true, + ip: '203.0.113.8', + }); + + expect(response).toEqual({ + status: 200, + message: 'Verification link sent to your new email address', + }); + expect(deps.verifyPassword).toHaveBeenCalledWith(user, 'correct-password'); + expect(deps.replaceTokenIfCurrent).toHaveBeenCalledWith( + 'email_change:507f1f77bcf86cd799439011', + null, + expect.objectContaining({ + userId: '507f1f77bcf86cd799439011', + email: 'new@example.com', + scope: 'email_change:507f1f77bcf86cd799439011', + identifier: 'old@example.com', + type: EMAIL_CHANGE_TOKEN_TYPE, + expiresIn: 900, + metadata: { + requestIp: '203.0.113.8', + passwordFingerprint: expect.any(String), + }, + }), + 'tenant-1', + ); + expect(deps.sendEmail).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ + email: 'old@example.com', + template: 'emailChangeAttempt.handlebars', + }), + ); + expect(deps.sendEmail).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + email: 'new@example.com', + template: 'verifyEmailChange.handlebars', + payload: expect.objectContaining({ + verificationLink: expect.stringMatching( + /^https:\/\/chat\.example\.com\/verify\?type=email-change&userId=507f1f77bcf86cd799439011&email=new%40example\.com&token=/, + ), + linkLifetime: '15 minutes', + }), + }), + ); + }); + + it('never says a link lasts longer than it does', async () => { + const { deps, service } = createDeps(); + + await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'new@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + /** Ninety minutes is not two hours; rounding up would outlive the token. */ + settings: { enabled: true, tokenTTLSeconds: 5400 }, + emailEnabled: true, + }); + + expect(deps.sendEmail).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + template: 'verifyEmailChange.handlebars', + payload: expect.objectContaining({ linkLifetime: '90 minutes' }), + }), + ); + }); + + it('states the lifetime the link was actually issued with', async () => { + const { deps, service } = createDeps(); + + await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'new@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: { enabled: true, tokenTTLSeconds: 3600 }, + emailEnabled: true, + }); + + expect(deps.replaceTokenIfCurrent).toHaveBeenCalledWith( + expect.any(String), + null, + expect.objectContaining({ expiresIn: 3600 }), + expect.anything(), + ); + expect(deps.sendEmail).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + template: 'verifyEmailChange.handlebars', + payload: expect.objectContaining({ linkLifetime: '1 hour' }), + }), + ); + }); + + it('stores the link when the observed token expires away during delivery', async () => { + /** The expiry monitor can sweep an already-expired token while the message is in + * flight; the recipient holds a live link, so the request must not report a race. */ + const swept = { token: 'expired-token' }; + const findToken: EmailChangeDeps['findToken'] = jest.fn(async () => ({ + userId: '507f1f77bcf86cd799439011', + email: 'stale@example.com', + token: swept.token, + })); + const replaceTokenIfCurrent: EmailChangeDeps['replaceTokenIfCurrent'] = jest.fn( + async (_scope, expectedToken) => expectedToken === null, + ); + const { deps, service } = createDeps({ findToken, replaceTokenIfCurrent }); + + const response = await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'new@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + }); + + expect(response).toMatchObject({ status: 200 }); + expect(deps.replaceTokenIfCurrent).toHaveBeenNthCalledWith( + 1, + expect.any(String), + 'expired-token', + expect.anything(), + expect.anything(), + ); + expect(deps.replaceTokenIfCurrent).toHaveBeenNthCalledWith( + 2, + expect.any(String), + null, + expect.anything(), + expect.anything(), + ); + }); + + it('still reports a race when another request holds the scope', async () => { + const findToken: EmailChangeDeps['findToken'] = jest.fn(async () => ({ + userId: '507f1f77bcf86cd799439011', + email: 'stale@example.com', + token: 'observed-token', + })); + /** A competitor replaced the scoped token, so neither the observed hash nor an empty + * scope is available to claim. */ + const replaceTokenIfCurrent: EmailChangeDeps['replaceTokenIfCurrent'] = jest.fn( + async () => false, + ); + const { deps, service } = createDeps({ findToken, replaceTokenIfCurrent }); + + const response = await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'new@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + }); + + expect(response).toMatchObject({ status: 409, code: 'request_in_progress' }); + expect(deps.replaceTokenIfCurrent).toHaveBeenCalledTimes(2); + }); + + it('notifies the old address but does not disclose conflicts until the password is valid', async () => { + const { deps, service } = createDeps({ + verifyPassword: jest.fn().mockResolvedValue(false), + findUserByEmail: jest.fn().mockResolvedValue({ ...user, _id: '507f1f77bcf86cd799439012' }), + }); + + const response = await service.requestEmailChange({ + body: { currentPassword: 'wrong-password', newEmail: 'taken@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + ip: '203.0.113.9', + }); + + expect(response).toMatchObject({ status: 403, code: 'current_password_invalid' }); + expect(deps.sendEmail).toHaveBeenCalledTimes(1); + expect(deps.findUserByEmail).not.toHaveBeenCalled(); + expect(deps.replaceTokenIfCurrent).not.toHaveBeenCalled(); + }); + + it('returns an explicit conflict when the verified new address belongs to another account', async () => { + const { deps, service } = createDeps({ + findUserByEmail: jest.fn().mockResolvedValue({ + ...user, + _id: '507f1f77bcf86cd799439012', + email: 'taken@example.com', + }), + }); + + const response = await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'taken@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + }); + + expect(response).toMatchObject({ status: 409, code: 'email_in_use' }); + expect(deps.replaceTokenIfCurrent).not.toHaveBeenCalled(); + }); + + it('does not issue a link when a concurrent confirmation moves the account', async () => { + const { deps, service } = createDeps({ + getUserById: jest + .fn() + .mockResolvedValueOnce(user) + .mockResolvedValueOnce({ ...user, email: 'confirmed@example.com' }), + }); + + const response = await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'new@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + }); + + expect(response).toMatchObject({ status: 409, code: 'account_modified' }); + expect(deps.replaceTokenIfCurrent).not.toHaveBeenCalled(); + expect(deps.deleteTokens).not.toHaveBeenCalled(); + expect(deps.sendEmail).not.toHaveBeenCalledWith( + expect.objectContaining({ template: 'verifyEmailChange.handlebars' }), + ); + }); + + it('does not replace the pending token if verification delivery fails', async () => { + const sendEmail = jest + .fn() + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(new Error('SMTP unavailable')); + const { deps, service } = createDeps({ sendEmail }); + + const response = await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'new@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + }); + + expect(response).toMatchObject({ status: 500, code: 'email_delivery_failed' }); + expect(deps.replaceTokenIfCurrent).not.toHaveBeenCalled(); + expect(deps.deleteTokens).not.toHaveBeenCalled(); + }); + + it('preserves a successful overlapping request when the replacing delivery fails', async () => { + type StoredToken = Pick< + Parameters[2], + 'email' | 'token' + >; + let storedToken: StoredToken | undefined = { + email: 'existing@example.com', + token: 'existing-token', + }; + const findToken: EmailChangeDeps['findToken'] = jest.fn(async () => + storedToken + ? { + userId: '507f1f77bcf86cd799439011', + email: storedToken.email, + token: storedToken.token, + } + : null, + ); + const replaceTokenIfCurrent: EmailChangeDeps['replaceTokenIfCurrent'] = jest.fn( + async (_scope, expectedToken, data) => { + if ((storedToken?.token ?? null) !== expectedToken) { + return false; + } + storedToken = { email: data.email, token: data.token }; + return true; + }, + ); + const deleteTokens: EmailChangeDeps['deleteTokens'] = jest.fn(async (query) => { + if (storedToken?.token === query.token) { + storedToken = undefined; + } + return { deletedCount: 1 }; + }); + let markFirstDeliveryStarted: () => void = () => undefined; + const firstDeliveryStarted = new Promise((resolve) => { + markFirstDeliveryStarted = resolve; + }); + let completeFirstDelivery: () => void = () => undefined; + const firstDelivery = new Promise((resolve) => { + completeFirstDelivery = resolve; + }); + const sendEmail: EmailChangeDeps['sendEmail'] = jest.fn((data) => { + if (data.template !== 'verifyEmailChange.handlebars') { + return Promise.resolve(); + } + if (data.email === 'first@example.com') { + markFirstDeliveryStarted(); + return firstDelivery; + } + return Promise.reject(new Error('SMTP unavailable')); + }); + const { service } = createDeps({ + findToken, + replaceTokenIfCurrent, + deleteTokens, + sendEmail, + }); + + const firstRequest = service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'first@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + }); + await firstDeliveryStarted; + + const secondResponse = await service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'second@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + }); + + expect(secondResponse).toMatchObject({ status: 500, code: 'email_delivery_failed' }); + expect(storedToken).toEqual({ + email: 'existing@example.com', + token: 'existing-token', + }); + + completeFirstDelivery(); + await expect(firstRequest).resolves.toMatchObject({ status: 200 }); + expect(storedToken).toEqual({ + email: 'first@example.com', + token: expect.any(String), + }); + }); + + it('returns success only for the token that wins an overlapping replacement', async () => { + type StoredToken = { email?: string; token: string }; + let storedToken: StoredToken | undefined; + let releaseReads: () => void = () => undefined; + const bothPredecessorsRead = new Promise((resolve) => { + releaseReads = resolve; + }); + let reads = 0; + const findToken: EmailChangeDeps['findToken'] = jest.fn(async () => { + const snapshot = storedToken; + reads += 1; + if (reads === 2) { + releaseReads(); + } + await bothPredecessorsRead; + return snapshot + ? { + userId: '507f1f77bcf86cd799439011', + email: snapshot.email, + token: snapshot.token, + } + : null; + }); + const replaceTokenIfCurrent: EmailChangeDeps['replaceTokenIfCurrent'] = jest.fn( + async (_scope, expectedToken, data) => { + if ((storedToken?.token ?? null) !== expectedToken) { + return false; + } + storedToken = { email: data.email, token: data.token }; + return true; + }, + ); + const { service } = createDeps({ + findToken, + replaceTokenIfCurrent, + }); + + const responses = await Promise.all([ + service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'first@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + }), + service.requestEmailChange({ + body: { currentPassword: 'correct-password', newEmail: 'second@example.com' }, + userId: '507f1f77bcf86cd799439011', + tenantId: 'tenant-1', + settings: DEFAULT_SETTINGS, + emailEnabled: true, + }), + ]); + + expect( + responses.map(({ status, code }) => ({ status, code })).sort((a, b) => a.status - b.status), + ).toEqual([ + { status: 200, code: undefined }, + { status: 409, code: 'request_in_progress' }, + ]); + const winningEmail = responses[0].status === 200 ? 'first@example.com' : 'second@example.com'; + expect(storedToken).toEqual({ email: winningEmail, token: expect.any(String) }); + }); + }); + + describe('confirmEmailChange', () => { + async function pendingToken(): Promise { + return { + userId: '507f1f77bcf86cd799439011', + email: 'new@example.com', + scope: 'email_change:507f1f77bcf86cd799439011', + identifier: 'old@example.com', + token: await hashToken('raw-token'), + expiresAt: new Date(Date.now() + 60_000), + metadata: new Map([['passwordFingerprint', await hashToken(user.password!)]]), + tenantId: 'tenant-1', + }; + } + + it('rejects a pending confirmation the owner scope has since disabled', async () => { + /** The deployment still allows changes; the tenant, role, group or user that owns the + * link does not, and that is the scope the link was issued under. */ + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + resolvePolicy: jest.fn().mockResolvedValue({ + settings: { enabled: false, tokenTTLSeconds: 900 }, + allowedDomains: null, + }), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 403, code: 'email_change_disabled' }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('reports an unavailable endpoint, not a bad token, when a link names no owner', async () => { + /** I3: a deployment that disabled changes answers for a link there is no owner to ask, + * so the confirmation endpoint stays visibly unavailable rather than reporting on the + * token a caller supplied. */ + const { deps, service } = createDeps({ + resolveSettings: jest.fn().mockResolvedValue({ enabled: false, tokenTTLSeconds: 900 }), + findToken: jest.fn().mockResolvedValue(null), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'unused-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toEqual({ + status: 403, + message: 'Email changes are disabled', + code: 'email_change_disabled', + }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('still reports an invalid token when the deployment allows changes', async () => { + const { service } = createDeps({ findToken: jest.fn().mockResolvedValue(null) }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'unused-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 400, code: 'invalid_token' }); + }); + + it('confirms a link an override enabled even when the deployment default is off', async () => { + /** Issuance read the requesting user's effective configuration, so a link exists only + * because that scope allowed it; a second read of the deployment default would refuse + * a link the account can legitimately complete. */ + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + resolvePolicy: jest.fn().mockResolvedValue({ + settings: { enabled: true, tokenTTLSeconds: 900 }, + allowedDomains: null, + }), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 200 }); + expect(deps.updateUser).toHaveBeenCalled(); + }); + + it('rejects malformed user IDs before querying the database', async () => { + const { deps, service } = createDeps(); + + const response = await service.confirmEmailChange({ + body: { email: 'new@example.com', token: 'raw-token', userId: 'not-an-object-id' }, + }); + + expect(response).toMatchObject({ status: 400, code: 'invalid_token' }); + expect(deps.findToken).not.toHaveBeenCalled(); + }); + + it('consumes the token, changes the verified email, and confirms to both addresses', async () => { + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'NEW@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + ip: '198.51.100.4', + }); + + expect(response).toEqual({ status: 200, message: 'Email address changed successfully' }); + expect(deps.deleteTokens).toHaveBeenCalledWith( + expect.objectContaining({ + userId: '507f1f77bcf86cd799439011', + type: EMAIL_CHANGE_TOKEN_TYPE, + }), + 'tenant-1', + ); + expect(deps.updateUser).toHaveBeenCalledWith( + '507f1f77bcf86cd799439011', + { email: 'new@example.com', emailVerified: true, emailChangedAt: expect.any(Date) }, + { email: 'old@example.com', password: 'password-hash', provider: 'local' }, + 'tenant-1', + ); + expect(deps.sendEmail).toHaveBeenCalledTimes(2); + expect(deps.sendEmail).toHaveBeenCalledWith( + expect.objectContaining({ + email: 'old@example.com', + template: 'emailChanged.handlebars', + }), + ); + expect(deps.sendEmail).toHaveBeenCalledWith( + expect.objectContaining({ + email: 'new@example.com', + template: 'emailChanged.handlebars', + }), + ); + }); + + it('revokes leftover reset tokens only after the commit', async () => { + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 200 }); + const deleteMock = deps.deleteTokens as jest.Mock; + const updateOrder = (deps.updateUser as jest.Mock).mock.invocationCallOrder[0]; + const resetCleanups = deleteMock.mock.calls + .map((call, index) => ({ + query: call[0] as TokenQuery, + order: deleteMock.mock.invocationCallOrder[index], + })) + .filter(({ query }) => query.type === 'password_reset'); + expect(resetCleanups.map(({ query }) => query.email).sort()).toEqual([ + null, + 'old@example.com', + ]); + expect(resetCleanups.every(({ order }) => order > updateOrder)).toBe(true); + }); + + it('leaves an email change token issued after the commit intact', async () => { + const pending = await pendingToken(); + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(pending), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 200 }); + const emailChangeDeletes = (deps.deleteTokens as jest.Mock).mock.calls.filter( + ([query]) => query.type === EMAIL_CHANGE_TOKEN_TYPE, + ); + expect(emailChangeDeletes).toHaveLength(1); + expect(emailChangeDeletes[0][0]).toMatchObject({ + scope: pending.scope, + token: pending.token, + }); + }); + + it('leaves a reset issued for the committed address intact', async () => { + const resetTokens: Array = ['old@example.com']; + const deleteTokens: EmailChangeDeps['deleteTokens'] = jest.fn(async (query: TokenQuery) => { + if (query.type !== 'password_reset') { + return { deletedCount: 1 }; + } + const before = resetTokens.length; + for (let index = resetTokens.length - 1; index >= 0; index--) { + if (query.email === undefined || resetTokens[index] === query.email) { + resetTokens.splice(index, 1); + } + } + return { deletedCount: before - resetTokens.length }; + }); + /** Stands in for another replica observing the committed address and issuing a + * correctly bound reset before this request's post-commit sweep reaches Mongo. */ + const updateUser: EmailChangeDeps['updateUser'] = jest.fn(async () => { + resetTokens.push('new@example.com'); + return { ...user, email: 'new@example.com' }; + }); + const { service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + deleteTokens, + updateUser, + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 200 }); + expect(resetTokens).toEqual(['new@example.com']); + }); + + it('leaves the link usable when the update fails transiently', async () => { + const pending = await pendingToken(); + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(pending), + updateUser: jest.fn().mockRejectedValue(new Error('connection reset')), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 500 }); + const emailChangeDeletes = (deps.deleteTokens as jest.Mock).mock.calls.filter( + ([query]) => query.type === EMAIL_CHANGE_TOKEN_TYPE, + ); + expect(emailChangeDeletes).toHaveLength(1); + expect(emailChangeDeletes[0][0]).toMatchObject({ + scope: pending.scope, + token: pending.token, + }); + expect(deps.replaceTokenIfCurrent).toHaveBeenCalledWith( + pending.scope, + null, + expect.objectContaining({ + scope: pending.scope, + token: pending.token, + type: EMAIL_CHANGE_TOKEN_TYPE, + email: 'new@example.com', + identifier: 'old@example.com', + }), + 'tenant-1', + ); + expect( + (deps.deleteTokens as jest.Mock).mock.calls.some( + ([query]) => query.type === 'password_reset' || query.type == null, + ), + ).toBe(false); + }); + + it('leaves an existing password reset intact when the update fails transiently', async () => { + const resetTokens = ['pending-reset']; + const deleteTokens = jest.fn(async (query: TokenQuery) => { + if (query.type === 'password_reset' || query.type == null) { + const deletedCount = resetTokens.length; + resetTokens.length = 0; + return { deletedCount }; + } + return { deletedCount: 1 }; + }); + const { service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + deleteTokens: deleteTokens as EmailChangeDeps['deleteTokens'], + updateUser: jest.fn().mockRejectedValue(new Error('connection reset')), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 500 }); + expect(resetTokens).toEqual(['pending-reset']); + }); + + it('refuses a confirmation superseded mid-flight and leaves the newer link intact', async () => { + const pending = await pendingToken(); + const supersedingToken = await hashToken('superseding-token'); + let storedToken: string | null = pending.token; + const deleteTokens = jest.fn(async (query: TokenQuery) => { + if (query.type !== EMAIL_CHANGE_TOKEN_TYPE) { + return { deletedCount: 0 }; + } + if (query.token !== undefined && query.token !== storedToken) { + return { deletedCount: 0 }; + } + const deletedCount = storedToken === null ? 0 : 1; + storedToken = null; + return { deletedCount }; + }); + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(pending), + /** A second request replaces the scoped token after this confirmation read it. */ + findUserByEmail: jest.fn(async () => { + storedToken = supersedingToken; + return null; + }), + deleteTokens: deleteTokens as EmailChangeDeps['deleteTokens'], + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 400, code: 'invalid_token' }); + expect(deps.updateUser).not.toHaveBeenCalled(); + expect(storedToken).toBe(supersedingToken); + }); + + it('leaves password resets alone when the confirmation is superseded', async () => { + const pending = await pendingToken(); + const supersedingToken = await hashToken('superseding-token'); + let storedToken: string | null = pending.token; + const resetTokens = ['pending-reset']; + const deleteTokens = jest.fn(async (query: TokenQuery) => { + if (query.type === 'password_reset') { + const deletedCount = resetTokens.length; + resetTokens.length = 0; + return { deletedCount }; + } + if (query.type !== EMAIL_CHANGE_TOKEN_TYPE) { + return { deletedCount: 0 }; + } + if (query.token !== undefined && query.token !== storedToken) { + return { deletedCount: 0 }; + } + const deletedCount = storedToken === null ? 0 : 1; + storedToken = null; + return { deletedCount }; + }); + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(pending), + /** A second request replaces the scoped token after this confirmation read it. */ + findUserByEmail: jest.fn(async () => { + storedToken = supersedingToken; + return null; + }), + deleteTokens: deleteTokens as EmailChangeDeps['deleteTokens'], + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 400, code: 'invalid_token' }); + expect(deps.updateUser).not.toHaveBeenCalled(); + expect(resetTokens).toEqual(['pending-reset']); + }); + + it('reports a failed claim as a server error instead of an invalid link', async () => { + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + deleteTokens: jest.fn(async (query: TokenQuery) => { + if (query.token !== undefined) { + throw new Error('token store unavailable'); + } + return { deletedCount: 1 }; + }) as EmailChangeDeps['deleteTokens'], + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toEqual({ status: 500, message: 'Failed to change email address' }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('rejects confirmation when the allowlist stopped permitting the pending address', async () => { + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + resolvePolicy: jest.fn().mockResolvedValue({ + settings: { enabled: true, tokenTTLSeconds: 900 }, + allowedDomains: ['allowed.com'], + }), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 403, code: 'email_domain_not_allowed' }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('rejects confirmation when the account moved to a federated provider', async () => { + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + getUserById: jest.fn().mockResolvedValue({ ...user, provider: 'openid' }), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 400, code: 'invalid_token' }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('rejects an invalid token without updating the user', async () => { + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'wrong-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 400, code: 'invalid_token' }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('rejects an expired token even before the TTL cleanup removes it', async () => { + const token = await pendingToken(); + token.expiresAt = new Date(Date.now() - 1); + const { deps, service } = createDeps({ findToken: jest.fn().mockResolvedValue(token) }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 400, code: 'invalid_token' }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('rejects a stale token after the account email has changed', async () => { + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + getUserById: jest.fn().mockResolvedValue({ ...user, email: 'other@example.com' }), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 400, code: 'invalid_token' }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('rejects a pending token after the account password has changed', async () => { + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + getUserById: jest.fn().mockResolvedValue({ ...user, password: 'new-password-hash' }), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 400, code: 'invalid_token' }); + expect(deps.deleteTokens).not.toHaveBeenCalled(); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('allows only one competing confirmation to update the original account state', async () => { + const firstToken = { + ...(await pendingToken()), + email: 'first@example.com', + token: await hashToken('first-token'), + }; + const secondToken = { + ...(await pendingToken()), + email: 'second@example.com', + token: await hashToken('second-token'), + }; + let accountEmail = user.email; + let updateCallCount = 0; + let releaseUpdates: (() => void) | undefined; + const updatesReady = new Promise((resolve) => { + releaseUpdates = resolve; + }); + const updateUser = jest.fn( + async ( + _userId: string, + update: { email: string; emailVerified: boolean }, + expected: { email: string; password: string }, + ) => { + updateCallCount += 1; + if (updateCallCount === 2) { + releaseUpdates?.(); + } + await updatesReady; + if (expected?.email !== accountEmail || expected?.password !== user.password) { + return null; + } + accountEmail = update.email; + return { ...user, ...update }; + }, + ); + const { service } = createDeps({ + findToken: jest.fn(async ({ email }) => + email === firstToken.email ? firstToken : secondToken, + ), + getUserById: jest.fn().mockResolvedValue(user), + updateUser: updateUser as EmailChangeDeps['updateUser'], + }); + + const responses = await Promise.all([ + service.confirmEmailChange({ + body: { + email: 'first@example.com', + token: 'first-token', + userId: '507f1f77bcf86cd799439011', + }, + }), + service.confirmEmailChange({ + body: { + email: 'second@example.com', + token: 'second-token', + userId: '507f1f77bcf86cd799439011', + }, + }), + ]); + + expect(responses.map(({ status }) => status).sort()).toEqual([200, 400]); + expect(['first@example.com', 'second@example.com']).toContain(accountEmail); + }); + + it('still succeeds and sends confirmations when post-commit cleanup fails', async () => { + const deleteTokens = jest + .fn() + .mockResolvedValueOnce({ deletedCount: 1 }) + .mockResolvedValueOnce({ deletedCount: 1 }) + .mockResolvedValueOnce({ deletedCount: 1 }) + .mockRejectedValueOnce(new Error('cleanup unavailable')); + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + deleteTokens, + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toEqual({ status: 200, message: 'Email address changed successfully' }); + expect(deps.updateUser).toHaveBeenCalledTimes(1); + expect(deps.sendEmail).toHaveBeenCalledTimes(2); + }); + + it('surfaces a uniqueness race during the final update', async () => { + const duplicateError = Object.assign(new Error('duplicate key'), { code: 11000 }); + const { deps, service } = createDeps({ + findToken: jest.fn().mockResolvedValue(await pendingToken()), + updateUser: jest.fn().mockRejectedValue(duplicateError), + }); + + const response = await service.confirmEmailChange({ + body: { + email: 'new@example.com', + token: 'raw-token', + userId: '507f1f77bcf86cd799439011', + }, + }); + + expect(response).toMatchObject({ status: 409, code: 'email_in_use' }); + expect(deps.sendEmail).not.toHaveBeenCalled(); + expect(deps.replaceTokenIfCurrent).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/api/src/auth/email.ts b/packages/api/src/auth/email.ts new file mode 100644 index 0000000000..e990fe5af1 --- /dev/null +++ b/packages/api/src/auth/email.ts @@ -0,0 +1,788 @@ +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 { isEmailDomainAllowed } from './domain'; +import { isEnabled } from '../utils/common'; + +export type { EmailChangeErrorCode } from 'librechat-data-provider'; + +export const EMAIL_CHANGE_TOKEN_TYPE = 'email_change'; +const PASSWORD_RESET_TOKEN_TYPE = 'password_reset'; + +export function isEmailChangeAllowed( + value: string | undefined = process.env.ALLOW_EMAIL_CHANGE, +): boolean { + return value === undefined || isEnabled(value); +} + +/** + * yaml wins over the environment, which wins over the documented default, so a deployment + * that sets neither keeps exactly the behavior it has today. + */ +export function resolveEmailChangeSettings( + config?: TCustomConfig['emailChange'], + env: NodeJS.ProcessEnv = process.env, +): EmailChangeSettings { + return { + enabled: config?.enabled ?? isEmailChangeAllowed(env.ALLOW_EMAIL_CHANGE), + tokenTTLSeconds: config?.tokenTTLSeconds ?? DEFAULT_EMAIL_CHANGE_TOKEN_TTL_SECONDS, + }; +} + +export const DEFAULT_EMAIL_CHANGE_TOKEN_TTL_SECONDS: number = 15 * 60; + +const SUBMITTED_ID_PATTERN = /^[a-f\d]{24}$/i; + +/** + * The confirmation endpoint is unauthenticated, so its per-submission allowance is keyed on + * the address the request came from together with the account it names. The submitted id is + * untrusted: one that cannot identify an account collapses to a single bucket, so a caller + * cannot mint a fresh allowance per malformed value. + */ +export function emailChangeSubmissionKey(ip: string, submittedUserId: unknown): string { + const userId = + typeof submittedUserId === 'string' && SUBMITTED_ID_PATTERN.test(submittedUserId) + ? submittedUserId.toLowerCase() + : 'invalid'; + return `ip:${ip}:user:${userId}`; +} +const EMAIL_CHANGE_ERROR_MESSAGE = 'Invalid or expired email change request'; + +const requestSchema = z.object({ + currentPassword: z.string().min(1).max(128), + newEmail: z + .string() + .trim() + .email() + .max(254) + .transform((email) => email.toLowerCase()), +}); + +const confirmSchema = z.object({ + email: z + .string() + .trim() + .email() + .max(254) + .transform((email) => email.toLowerCase()), + token: z.string().min(1), + userId: z.string().refine(isValidObjectIdString), +}); + +/** + * The service speaks in plain records so a caller can implement it without Mongoose. The + * adapter that owns the database is the one that turns documents into these. + */ +export interface EmailChangeUser { + _id?: string; + id?: string; + email: string; + name?: string; + username?: string; + password?: string; + provider?: string; + role?: string; + tenantId?: string; + /** Null is a resolved answer, absent is unknown; principal resolution distinguishes them. */ + idOnTheSource?: string | null; +} + +/** `lean()` yields a Map for a Mongoose map field, so reads tolerate either shape. */ +export type EmailChangeTokenMetadata = + | { requestIp?: string; passwordFingerprint?: string } + | Map; + +export interface EmailChangeToken { + userId: string; + token: string; + email?: string; + scope?: string; + identifier?: string; + expiresAt?: Date | string; + metadata?: EmailChangeTokenMetadata; + tenantId?: string; +} + +/** `null` matches a stored field that is absent, which is how legacy reset tokens are found. */ +export interface EmailChangeTokenQuery { + userId?: string; + email?: string | null; + identifier?: string | null; + type?: string | null; + scope?: string; + token?: string; +} + +export interface EmailChangeTokenData { + userId: string; + email: string; + scope: string; + identifier: string; + type: string; + token: string; + expiresIn: number; + metadata?: EmailChangeTokenMetadata; +} + +/** What an operator may set, resolved once per call from yaml, then env, then the default. */ +export interface EmailChangeSettings { + enabled: boolean; + tokenTTLSeconds: number; +} + +/** The effective policy for one account, read in that account's own principal scope. */ +export interface EmailChangePolicy { + settings: EmailChangeSettings; + allowedDomains?: string[] | null; +} + +interface EmailData { + email: string; + subject: string; + payload: Record; + template: string; +} + +export interface EmailChangeDeps { + findUserByEmail: (email: string, tenantId?: string) => Promise; + getUserById: (userId: string, tenantId?: string) => Promise; + updateUser: ( + userId: string, + update: Pick & { emailVerified: boolean; emailChangedAt: Date }, + expectedState: Pick, + tenantId?: string, + ) => Promise; + findToken: (query: EmailChangeTokenQuery, tenantId?: string) => Promise; + replaceTokenIfCurrent: ( + scope: string, + expectedToken: string | null, + data: EmailChangeTokenData, + tenantId?: string, + ) => Promise; + deleteTokens: ( + query: EmailChangeTokenQuery, + tenantId?: string, + ) => Promise<{ deletedCount?: number }>; + verifyPassword: (user: EmailChangeUser, password: string) => Promise; + /** The token owner's effective policy, so confirmation honors the scope that issued the + * link: neither an address the allowlist stopped permitting, nor a change a tenant, role, + * group, or user override has since disabled. */ + resolvePolicy: (user: EmailChangeUser) => Promise; + sendEmail: (data: EmailData) => Promise; + /** The deployment default, which answers only for a link that resolves to no owner: a + * disabled deployment reports an unavailable endpoint rather than an invalid token. It + * never decides a link that does resolve; `resolvePolicy` owns that. */ + resolveSettings: () => Promise; + clientDomain: string; + appName: string; +} + +export interface EmailChangeResult { + status: number; + message: string; + code?: EmailChangeErrorCode; +} + +export interface RequestEmailChangeInput { + body: { + currentPassword?: string; + newEmail?: string; + }; + userId: string; + tenantId?: string; + allowedDomains?: string[] | null; + emailEnabled: boolean; + /** Resolved from the effective config the request already loaded. */ + settings: EmailChangeSettings; + ip?: string; +} + +export interface ConfirmEmailChangeInput { + body: { + email?: string; + token?: string; + userId?: string; + }; + ip?: string; +} + +function result(status: number, message: string, code?: EmailChangeErrorCode): EmailChangeResult { + return { status, message, ...(code ? { code } : {}) }; +} + +function normalizeEmail(email: string): string { + return email.trim().toLowerCase(); +} + +function userIdOf(user: EmailChangeUser): string | undefined { + const userId = user._id ?? user.id; + return userId?.toString(); +} + +function accountMatchesRequest( + user: EmailChangeUser | null, + userId: string, + email: string, + password: string, +): boolean { + return ( + !!user && + userIdOf(user) === userId && + user.provider === 'local' && + user.password === password && + normalizeEmail(user.email) === email + ); +} + +function displayName(user: EmailChangeUser): string { + return user.name || user.username || user.email; +} + +/** + * The template promises a lifetime, so it has to be the one the token was issued with, and + * never a longer one: rounding 90 minutes up to "2 hours" would keep claiming a link is + * valid half an hour after it expired. Only a whole number of hours is said in hours. + */ +function formatLifetime(seconds: number): string { + const minutes = Math.floor(seconds / 60); + if (minutes < 60 || minutes % 60 !== 0) { + return `${minutes} minute${minutes === 1 ? '' : 's'}`; + } + const hours = minutes / 60; + return `${hours} hour${hours === 1 ? '' : 's'}`; +} + +function formatTimestamp(): string { + return new Date().toISOString(); +} + +async function tokenMatches(candidate: string, storedHash: string): Promise { + const candidateHash = await hashToken(candidate); + const candidateBuffer = Buffer.from(candidateHash, 'hex'); + const storedBuffer = Buffer.from(storedHash, 'hex'); + return ( + candidateBuffer.length === storedBuffer.length && timingSafeEqual(candidateBuffer, storedBuffer) + ); +} + +async function sendSecurityNotification( + deps: EmailChangeDeps, + data: EmailData, + logContext: string, +): Promise { + try { + await deps.sendEmail(data); + } catch (error) { + logger.error(`[emailChange] Failed to send ${logContext} notification`, error); + } +} + +function verificationLink( + deps: EmailChangeDeps, + userId: string, + email: string, + token: string, +): string { + const query = new URLSearchParams({ + type: 'email-change', + userId, + email, + token, + }); + return `${deps.clientDomain.replace(/\/$/, '')}/verify?${query.toString()}`; +} + +function emailChangeTokenScope(userId: string): string { + return `${EMAIL_CHANGE_TOKEN_TYPE}:${userId}`; +} + +function isDuplicateKeyError(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + 'code' in error && + (error as { code?: number }).code === 11000 + ); +} + +function expiryOf(token: EmailChangeToken): number | null { + if (!token.expiresAt) { + return null; + } + const expiresAt = new Date(token.expiresAt).getTime(); + return Number.isFinite(expiresAt) ? expiresAt : null; +} + +function isTokenExpired(token: EmailChangeToken): boolean { + const expiresAt = expiryOf(token); + return expiresAt === null || expiresAt <= Date.now(); +} + +function remainingLifetimeSeconds(token: EmailChangeToken): number { + const expiresAt = expiryOf(token); + return expiresAt === null ? 0 : Math.floor((expiresAt - Date.now()) / 1000); +} + +function tokenMetadataValue( + token: EmailChangeToken, + key: 'requestIp' | 'passwordFingerprint', +): unknown { + if (token.metadata instanceof Map) { + return token.metadata.get(key); + } + return token.metadata?.[key]; +} + +async function deleteTokensOrLog( + deps: EmailChangeDeps, + query: EmailChangeTokenQuery, + tenantId: string | undefined, + context: string, +): Promise { + try { + await deps.deleteTokens(query, tenantId); + } catch (error) { + logger.error(`[emailChange] Failed to clean up ${context}`, error); + } +} + +type TokenClaim = 'claimed' | 'superseded' | 'unavailable'; + +/** Consumes the pending token only while the stored hash still matches the presented link, + * so a confirmation that a newer request superseded finds nothing to claim. A failed delete + * is reported separately because it must not be read as a superseded link. */ +async function claimTokenIfCurrent( + deps: EmailChangeDeps, + query: EmailChangeTokenQuery, + tenantId: string | undefined, +): Promise { + try { + const { deletedCount } = await deps.deleteTokens(query, tenantId); + return deletedCount ? 'claimed' : 'superseded'; + } catch (error) { + logger.error('[emailChange] Failed to claim the pending token', error); + return 'unavailable'; + } +} + +/** Reinstates a claimed token so a transient commit failure leaves the link usable. The + * conditional insert is a no-op once a newer request owns the scope, and an elapsed + * lifetime is left consumed rather than revived. */ +async function restoreClaimedToken( + deps: EmailChangeDeps, + token: EmailChangeToken, + scope: string, + tenantId: string | undefined, +): Promise { + const expiresIn = remainingLifetimeSeconds(token); + const { email, identifier } = token; + /** A pending change always carries both; without them there is no link to reinstate. */ + if (expiresIn <= 0 || !email || !identifier) { + return; + } + try { + await deps.replaceTokenIfCurrent( + scope, + null, + { + userId: token.userId, + email, + scope, + identifier, + type: EMAIL_CHANGE_TOKEN_TYPE, + token: token.token, + expiresIn, + metadata: token.metadata, + }, + tenantId, + ); + } catch (error) { + logger.error('[emailChange] Failed to restore the claimed token', error); + } +} + +export function createEmailChangeService(deps: EmailChangeDeps): { + requestEmailChange: (input: RequestEmailChangeInput) => Promise; + confirmEmailChange: (input: ConfirmEmailChangeInput) => Promise; +} { + async function requestEmailChange(input: RequestEmailChangeInput): Promise { + const { settings } = input; + if (!settings.enabled) { + logger.warn( + `[emailChange] Rejected disabled request [User ID: ${input.userId}] [IP: ${input.ip ?? 'unknown'}]`, + ); + return result(403, 'Email changes are disabled', 'email_change_disabled'); + } + + const parsed = requestSchema.safeParse(input.body); + if (!parsed.success) { + return result(400, 'A valid new email and current password are required', 'invalid_request'); + } + + if (!input.emailEnabled) { + return result(503, 'Email delivery is not configured', 'email_service_unavailable'); + } + + const user = await deps.getUserById(input.userId, input.tenantId); + const userId = user ? userIdOf(user) : undefined; + if (!user || !userId || user.provider !== 'local' || !user.password) { + logger.warn( + `[emailChange] Rejected non-local account request [User ID: ${input.userId}] [IP: ${input.ip ?? 'unknown'}]`, + ); + return result( + 403, + 'Email changes are only available for local accounts', + 'local_account_required', + ); + } + + const oldEmail = normalizeEmail(user.email); + const newEmail = parsed.data.newEmail; + if (newEmail === oldEmail) { + return result(400, 'New email must be different from the current email', 'same_email'); + } + + const ip = input.ip ?? 'unknown'; + logger.info( + `[emailChange] Change requested [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`, + ); + await sendSecurityNotification( + deps, + { + email: oldEmail, + subject: 'Email change requested', + payload: { + appName: deps.appName, + name: displayName(user), + newEmail, + ip, + requestedAt: formatTimestamp(), + }, + template: 'emailChangeAttempt.handlebars', + }, + 'email change attempt', + ); + + const passwordMatches = await deps.verifyPassword(user, parsed.data.currentPassword); + if (!passwordMatches) { + logger.warn( + `[emailChange] Incorrect password [User ID: ${userId}] [New Email: ${newEmail}] [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}]`, + ); + return result(403, 'Email domain is not allowed', 'email_domain_not_allowed'); + } + + const tokenScope = emailChangeTokenScope(userId); + /** Nothing here depends on another's result and all three stay scoped to the requesting + * user's tenant, so issuance makes one round trip instead of three before delivery. The + * results are still validated in the order they were, and none of them is acted on until + * the check that owns it passes. */ + const [existingUser, previousToken, latestUser] = await Promise.all([ + deps.findUserByEmail(newEmail, user.tenantId), + deps.findToken({ scope: tokenScope }, user.tenantId), + deps.getUserById(input.userId, input.tenantId), + ]); + + if (existingUser && userIdOf(existingUser) !== userId) { + logger.warn( + `[emailChange] Email already in use [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`, + ); + return result(409, 'Email address is already linked to another account', 'email_in_use'); + } + + const rawToken = await getRandomValues(32); + const tokenHash = await hashToken(rawToken); + const passwordFingerprint = await hashToken(user.password); + const tokenQuery = { + userId, + email: newEmail, + type: EMAIL_CHANGE_TOKEN_TYPE, + token: tokenHash, + }; + + /** 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}]`, + ); + return result(409, 'Account was modified during the request', 'account_modified'); + } + + try { + await deps.sendEmail({ + email: newEmail, + subject: 'Verify your new email address', + payload: { + appName: deps.appName, + name: displayName(user), + newEmail, + verificationLink: verificationLink(deps, userId, newEmail, rawToken), + linkLifetime: formatLifetime(settings.tokenTTLSeconds), + year: new Date().getFullYear().toString(), + }, + template: 'verifyEmailChange.handlebars', + }); + } catch (error) { + logger.error( + `[emailChange] Verification delivery failed [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`, + error, + ); + return result(500, 'Failed to send verification email', 'email_delivery_failed'); + } + + const replacement = { + userId, + email: newEmail, + scope: tokenScope, + identifier: oldEmail, + type: EMAIL_CHANGE_TOKEN_TYPE, + token: tokenHash, + expiresIn: settings.tokenTTLSeconds, + metadata: { requestIp: ip, passwordFingerprint }, + }; + let replacedToken = await deps.replaceTokenIfCurrent( + tokenScope, + previousToken?.token ?? null, + replacement, + user.tenantId, + ); + /** The observed token can be swept by the expiry monitor while the message is in flight, + * and a compare-and-set against a hash that no longer exists cannot tell that apart from + * a competitor. The empty expectation answers it atomically: the scoped index admits the + * insert only while nothing holds the scope, so a real competitor still refuses it and a + * delivered link is not reported as a losing race. */ + if (!replacedToken && previousToken) { + replacedToken = await deps.replaceTokenIfCurrent( + tokenScope, + null, + replacement, + user.tenantId, + ); + } + if (!replacedToken) { + logger.warn( + `[emailChange] Competing request completed first [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`, + ); + return result(409, 'Another email change request completed first', 'request_in_progress'); + } + + /** Re-read after replacement: the prior token remains valid during delivery, so a + * confirmation can move the account before the new token becomes active. */ + 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}]`, + ); + return result(409, 'Account was modified during the request', 'account_modified'); + } + + logger.info( + `[emailChange] Verification issued [User ID: ${userId}] [New Email: ${newEmail}] [IP: ${ip}]`, + ); + return result(200, 'Verification link sent to your new email address'); + } + + /** A link that names no owner has no policy to consult, so the deployment answers for it: + * an operator who turned changes off gets an unavailable endpoint rather than a report + * about the token. A link that does resolve is decided by its owner's policy alone. */ + async function unresolvedLink(): Promise { + if (!(await deps.resolveSettings()).enabled) { + return result(403, 'Email changes are disabled', 'email_change_disabled'); + } + return result(400, EMAIL_CHANGE_ERROR_MESSAGE, 'invalid_token'); + } + + /** Issuance answers from the requesting user's effective configuration, so confirmation has + * to answer from the same scope or a tenant, role, group, or user override that enables + * changes would offer a link the deployment default then refuses. The toggle that decides a + * real link is therefore read once, below, after the link names its owner. */ + async function confirmEmailChange(input: ConfirmEmailChangeInput): Promise { + const parsed = confirmSchema.safeParse(input.body); + if (!parsed.success) { + return unresolvedLink(); + } + + const { email, token, userId } = parsed.data; + const ip = input.ip ?? 'unknown'; + const scope = emailChangeTokenScope(userId); + const tokenQuery = { userId, email, type: EMAIL_CHANGE_TOKEN_TYPE, scope }; + const emailChangeToken = await deps.findToken(tokenQuery); + + if ( + !emailChangeToken || + isTokenExpired(emailChangeToken) || + !(await tokenMatches(token, emailChangeToken.token)) + ) { + logger.warn( + `[emailChange] Invalid confirmation [User ID: ${userId}] [New Email: ${email}] [IP: ${ip}]`, + ); + return unresolvedLink(); + } + + const tenantId = emailChangeToken.tenantId; + const user = await deps.getUserById(userId, tenantId); + const oldEmail = user ? normalizeEmail(user.email) : ''; + const passwordFingerprint = tokenMetadataValue(emailChangeToken, 'passwordFingerprint'); + if ( + !user || + userIdOf(user) !== userId || + user.provider !== 'local' || + !user.password || + typeof passwordFingerprint !== 'string' || + !(await tokenMatches(user.password, passwordFingerprint)) || + emailChangeToken.scope !== scope || + normalizeEmail(emailChangeToken.email ?? '') !== email || + normalizeEmail(emailChangeToken.identifier ?? '') !== oldEmail + ) { + logger.warn( + `[emailChange] Stale confirmation [User ID: ${userId}] [New Email: ${email}] [IP: ${ip}]`, + ); + return unresolvedLink(); + } + + /** The policy of the account the link names, which is the scope that issued it: a + * deployment default reaches this through the same read when nothing overrides it. */ + const policy = await deps.resolvePolicy(user); + if (!policy.settings.enabled) { + logger.warn( + `[emailChange] Rejected disabled confirmation for its owner [User ID: ${userId}] [IP: ${ip}]`, + ); + return result(403, 'Email changes are disabled', 'email_change_disabled'); + } + + if (!isEmailDomainAllowed(email, policy.allowedDomains)) { + logger.warn( + `[emailChange] Domain no longer allowed [User ID: ${userId}] [New Email: ${email}] [IP: ${ip}]`, + ); + return result(403, 'Email domain is not allowed', 'email_domain_not_allowed'); + } + + const existingUser = await deps.findUserByEmail(email, tenantId); + if (existingUser && userIdOf(existingUser) !== userId) { + return result(409, 'Email address is already linked to another account', 'email_in_use'); + } + + /** Claiming the exact hash that was presented binds the commit to this link: a request + * that replaced the scoped token between the lookup and here leaves nothing to claim, + * so a superseded address can no longer overwrite the one the user was last sent. + * Reset tokens stay untouched until after the commit so a failed update cannot revoke + * an unrelated password-reset link. */ + const claim = await claimTokenIfCurrent( + deps, + { ...tokenQuery, token: emailChangeToken.token }, + tenantId, + ); + if (claim === 'unavailable') { + logger.error( + `[emailChange] Token claim failed [User ID: ${userId}] [New Email: ${email}] [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}]`, + ); + return result(400, EMAIL_CHANGE_ERROR_MESSAGE, 'invalid_token'); + } + + /** The compare-and-set remains the commit point and the single-use guard: a competing + * confirmation cannot match `oldEmail` twice. The claimed token is put back when the + * update fails transiently, so the link stays replayable. Reset tokens are not touched + * here: a failed commit must leave the account's existing reset flow intact. */ + try { + const updatedUser = await deps.updateUser( + userId, + { email, emailVerified: true, emailChangedAt: new Date() }, + { email: oldEmail, password: user.password, provider: 'local' }, + tenantId, + ); + if (!updatedUser) { + return result(400, EMAIL_CHANGE_ERROR_MESSAGE, 'invalid_token'); + } + } catch (error) { + if (isDuplicateKeyError(error)) { + 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, + ); + await restoreClaimedToken(deps, emailChangeToken, scope, tenantId); + return result(500, 'Failed to change email address'); + } + + /** After the commit only. Restricted to the address that moved, address-less typed + * tokens, and untyped legacy tokens, so a reset another replica issued for the + * committed address is not revoked with them. `resetPassword` also refuses those + * leftovers via the address binding and `emailChangedAt` checks. No email change + * token is swept here: the claim above already consumed the one this link + * presented, and the scope is unique per user, so anything under it now belongs + * to a request that started after the commit and still has a live link. */ + await Promise.all([ + deleteTokensOrLog( + deps, + { userId, email: oldEmail, type: PASSWORD_RESET_TOKEN_TYPE }, + tenantId, + 'password reset tokens bound to the previous address', + ), + deleteTokensOrLog( + deps, + { userId, email: null, type: PASSWORD_RESET_TOKEN_TYPE }, + tenantId, + 'address-less password reset tokens issued during the change', + ), + deleteTokensOrLog( + deps, + { userId, email: null, identifier: null, type: null }, + tenantId, + 'untyped legacy reset tokens issued before the change', + ), + ]); + const confirmationPayload = { + appName: deps.appName, + name: displayName(user), + oldEmail, + newEmail: email, + ip, + changedAt: formatTimestamp(), + }; + await Promise.all([ + sendSecurityNotification( + deps, + { + email: oldEmail, + subject: 'Your email address was changed', + payload: confirmationPayload, + template: 'emailChanged.handlebars', + }, + 'old-address confirmation', + ), + sendSecurityNotification( + deps, + { + email, + subject: 'Your email address was changed', + payload: confirmationPayload, + template: 'emailChanged.handlebars', + }, + 'new-address confirmation', + ), + ]); + + logger.info( + `[emailChange] Change completed [User ID: ${userId}] [Old Email: ${oldEmail}] [New Email: ${email}] [IP: ${ip}]`, + ); + return result(200, 'Email address changed successfully'); + } + + return { requestEmailChange, confirmEmailChange }; +} diff --git a/packages/api/src/auth/emailChangeStore.spec.ts b/packages/api/src/auth/emailChangeStore.spec.ts new file mode 100644 index 0000000000..d4e29128dd --- /dev/null +++ b/packages/api/src/auth/emailChangeStore.spec.ts @@ -0,0 +1,261 @@ +import { Types } from 'mongoose'; +import type { AppConfig } from '@librechat/data-schemas'; +import type { EmailChangeRuntime, EmailChangeStore } from './emailChangeStore'; +import { createEmailChangeDeps } from './emailChangeStore'; +import { resolveEmailChangeSettings } from './email'; + +function createStore(overrides: Partial = {}): jest.Mocked { + return { + findUser: jest.fn().mockResolvedValue(null), + getUserById: jest.fn().mockResolvedValue(null), + updateUser: jest.fn().mockResolvedValue(null), + findToken: jest.fn().mockResolvedValue(null), + replaceTokenIfCurrent: jest.fn().mockResolvedValue(true), + deleteTokens: jest.fn().mockResolvedValue({ deletedCount: 1 }), + ...overrides, + } as jest.Mocked; +} + +/** A jest.fn cannot satisfy the generic runner, so the spy records beside a typed one. */ +function createTenantRunner(): { + scopes: Array; + withTenant: EmailChangeRuntime['withTenant']; +} { + const scopes: Array = []; + return { + scopes, + withTenant: (tenantId, operation) => { + scopes.push(tenantId); + return operation(); + }, + }; +} + +function createRuntime(overrides: Partial = {}): EmailChangeRuntime { + return { + store: createStore(), + withTenant: (_tenantId, operation) => operation(), + comparePassword: jest.fn().mockResolvedValue(true), + sendEmail: jest.fn().mockResolvedValue(undefined), + getAppConfig: jest.fn().mockResolvedValue({ config: {} } as AppConfig), + clientDomain: 'https://chat.example.com', + appName: 'LibreChat', + ...overrides, + }; +} + +describe('createEmailChangeDeps', () => { + describe('tenant scoping', () => { + it('scopes a tenant-less identity lookup so another tenant cannot answer it', async () => { + const store = createStore(); + const deps = createEmailChangeDeps(createRuntime({ store })); + + await deps.findUserByEmail('moved@example.com'); + + expect(store.findUser).toHaveBeenCalledWith( + { + email: 'moved@example.com', + $or: [{ tenantId: { $exists: false } }, { tenantId: null }], + }, + expect.any(String), + ); + }); + + it('lets the tenant context carry the scope when there is one', async () => { + const store = createStore(); + const { scopes, withTenant } = createTenantRunner(); + const deps = createEmailChangeDeps(createRuntime({ store, withTenant })); + + await deps.findUserByEmail('moved@example.com', 'tenant-a'); + + expect(store.findUser).toHaveBeenCalledWith( + { email: 'moved@example.com' }, + expect.any(String), + ); + expect(scopes).toEqual(['tenant-a']); + }); + + it('runs every read through the tenant runner', async () => { + const { scopes, withTenant } = createTenantRunner(); + const deps = createEmailChangeDeps(createRuntime({ withTenant })); + + await deps.getUserById('user-1', 'tenant-a'); + await deps.findToken({ scope: 'email_change:user-1' }, 'tenant-a'); + await deps.deleteTokens({ userId: 'user-1' }, 'tenant-a'); + + expect(scopes).toEqual(['tenant-a', 'tenant-a', 'tenant-a']); + }); + }); + + describe('narrowing stored documents', () => { + it('hands the service plain string ids', async () => { + const _id = new Types.ObjectId(); + const tenantId = new Types.ObjectId(); + const store = createStore({ + getUserById: jest.fn().mockResolvedValue({ + _id, + tenantId, + email: 'current@example.com', + provider: 'local', + password: 'hashed', + }), + }); + const deps = createEmailChangeDeps(createRuntime({ store })); + + const user = await deps.getUserById('user-1'); + + expect(user).toMatchObject({ + _id: _id.toString(), + id: undefined, + email: 'current@example.com', + name: undefined, + username: undefined, + password: 'hashed', + provider: 'local', + role: undefined, + tenantId: tenantId.toString(), + }); + }); + + it('keeps the source identity the lookup already resolved', async () => { + const store = createStore({ + getUserById: jest + .fn() + .mockResolvedValue({ _id: 'user-1', email: 'current@example.com', idOnTheSource: null }), + }); + const deps = createEmailChangeDeps(createRuntime({ store })); + + /** Null is an answer; dropping it would send principal resolution back to the database. */ + await expect(deps.getUserById('user-1')).resolves.toMatchObject({ idOnTheSource: null }); + }); + + it('leaves the source identity absent when the record has none', async () => { + const store = createStore({ + getUserById: jest.fn().mockResolvedValue({ _id: 'user-1', email: 'current@example.com' }), + }); + const deps = createEmailChangeDeps(createRuntime({ store })); + + const user = await deps.getUserById('user-1'); + + expect(user && 'idOnTheSource' in user).toBe(false); + }); + + it('treats a document without an address as no user', async () => { + const store = createStore({ getUserById: jest.fn().mockResolvedValue({ _id: 'user-1' }) }); + const deps = createEmailChangeDeps(createRuntime({ store })); + + await expect(deps.getUserById('user-1')).resolves.toBeNull(); + }); + + it('treats a token without its hash as no token', async () => { + const store = createStore({ + findToken: jest.fn().mockResolvedValue({ userId: new Types.ObjectId() }), + }); + const deps = createEmailChangeDeps(createRuntime({ store })); + + await expect(deps.findToken({ scope: 'email_change:user-1' })).resolves.toBeNull(); + }); + + it('reads the newest token for a scope', async () => { + const store = createStore(); + const deps = createEmailChangeDeps(createRuntime({ store })); + + await deps.findToken({ scope: 'email_change:user-1' }); + + expect(store.findToken).toHaveBeenCalledWith( + { scope: 'email_change:user-1' }, + { sort: { createdAt: -1 } }, + ); + }); + }); + + describe('confirmation-time policy', () => { + const owner = { + _id: 'user-1', + email: 'current@example.com', + role: 'USER', + tenantId: 'tenant-a', + }; + + it('prefers the yaml section over the environment', async () => { + const getAppConfig = jest + .fn() + .mockResolvedValue({ config: {}, emailChange: { enabled: false } } as AppConfig); + const deps = createEmailChangeDeps(createRuntime({ getAppConfig })); + + await expect(deps.resolvePolicy(owner)).resolves.toMatchObject({ + settings: { enabled: false }, + }); + }); + + it('reads the merged field, not the base yaml a scoped override supersedes', async () => { + /** Overrides are merged onto the AppConfig root; the section retained under `config` + * is the unmerged base, so reading it would ignore a tenant that disabled changes. */ + const getAppConfig = jest + .fn() + .mockResolvedValue({ config: { emailChange: { enabled: false } } } as AppConfig); + const deps = createEmailChangeDeps(createRuntime({ getAppConfig })); + + await expect(deps.resolvePolicy(owner)).resolves.toMatchObject({ + settings: { enabled: true }, + }); + }); + + it('resolves the allowlist against the principal scope of that user', async () => { + const getAppConfig = jest.fn().mockResolvedValue({ + config: {}, + registration: { allowedDomains: ['allowed.example.com'] }, + } as AppConfig); + const deps = createEmailChangeDeps(createRuntime({ getAppConfig })); + + await expect(deps.resolvePolicy(owner)).resolves.toMatchObject({ + allowedDomains: ['allowed.example.com'], + }); + expect(getAppConfig).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-1', role: 'USER', tenantId: 'tenant-a' }), + ); + }); + + it('answers with the setting that scope resolves, not the deployment default', async () => { + /** A link issued while the tenant allowed changes must not confirm after it stopped. */ + const getAppConfig = jest + .fn() + .mockResolvedValue({ config: {}, emailChange: { enabled: false } } as AppConfig); + const deps = createEmailChangeDeps(createRuntime({ getAppConfig })); + + await expect(deps.resolvePolicy(owner)).resolves.toMatchObject({ + settings: { enabled: false }, + }); + }); + + it('reads that scope fail-closed', async () => { + const getAppConfig = jest.fn().mockResolvedValue({ config: {} } as AppConfig); + const deps = createEmailChangeDeps(createRuntime({ getAppConfig })); + + await deps.resolvePolicy(owner); + + expect(getAppConfig).toHaveBeenCalledWith(expect.objectContaining({ failClosed: true })); + }); + }); +}); + +describe('resolveEmailChangeSettings', () => { + it('is enabled with the documented lifetime when nothing is configured', () => { + expect(resolveEmailChangeSettings(undefined, {})).toEqual({ + enabled: true, + tokenTTLSeconds: 900, + }); + }); + + it('honors the environment when there is no yaml section', () => { + expect(resolveEmailChangeSettings(undefined, { ALLOW_EMAIL_CHANGE: 'false' })).toMatchObject({ + enabled: false, + }); + }); + + it('lets yaml override the environment', () => { + expect( + resolveEmailChangeSettings({ enabled: true }, { ALLOW_EMAIL_CHANGE: 'false' }), + ).toMatchObject({ enabled: true }); + }); +}); diff --git a/packages/api/src/auth/emailChangeStore.ts b/packages/api/src/auth/emailChangeStore.ts new file mode 100644 index 0000000000..27a6a8d46e --- /dev/null +++ b/packages/api/src/auth/emailChangeStore.ts @@ -0,0 +1,221 @@ +import type { AppConfig } from '@librechat/data-schemas'; +import type { + EmailChangeDeps, + EmailChangeSettings, + EmailChangeToken, + EmailChangeTokenData, + EmailChangeTokenMetadata, + EmailChangeTokenQuery, + EmailChangeUser, +} from './email'; +import type { GetAppConfigOptions } from '~/app/service'; +import { getAppConfigOptionsFromUser } from '~/app/service'; +import { resolveEmailChangeSettings } from './email'; + +/** A stored id is an ObjectId in production and a string in tests; both stringify. */ +type Identifier = string | { toString(): string }; + +/** What the database hands back, before it is narrowed to the service's plain records. */ +interface StoredUser { + _id?: Identifier; + id?: Identifier; + email?: string; + name?: string; + username?: string; + password?: string; + provider?: string; + role?: string; + tenantId?: Identifier; + idOnTheSource?: string | null; +} + +interface StoredToken { + userId?: Identifier; + token?: string; + email?: string; + scope?: string; + identifier?: string; + expiresAt?: Date | string; + metadata?: EmailChangeTokenMetadata; + tenantId?: Identifier; +} + +interface StoredUserQuery { + email: string; + $or?: Array<{ tenantId: { $exists: boolean } | null }>; +} + +interface UserCommit { + email: string; + emailVerified: boolean; + emailChangedAt: Date; +} + +interface UserExpectation { + email?: string; + password?: string; + provider?: string; +} + +/** The database surface the change needs, as the application's models already expose it. */ +export interface EmailChangeStore { + findUser: (query: StoredUserQuery, select: string) => Promise; + getUserById: (userId: string, select: string) => Promise; + updateUser: ( + userId: string, + update: UserCommit, + expectedState: UserExpectation, + ) => Promise; + findToken: ( + query: EmailChangeTokenQuery, + options: { sort: { createdAt: -1 } }, + ) => Promise; + replaceTokenIfCurrent: ( + scope: string, + expectedToken: string | null, + data: EmailChangeTokenData, + ) => Promise; + deleteTokens: (query: EmailChangeTokenQuery) => Promise<{ deletedCount?: number }>; +} + +/** Everything else the adapter needs from the host application. */ +export interface EmailChangeRuntime { + store: EmailChangeStore; + /** Runs an operation inside a tenant's context, or in the system one when there is none. */ + withTenant: (tenantId: string | undefined, operation: () => Promise) => Promise; + comparePassword: (user: EmailChangeUser, password: string) => Promise; + sendEmail: (data: { + email: string; + subject: string; + payload: Record; + template: string; + }) => Promise; + getAppConfig: (options: GetAppConfigOptions) => Promise; + clientDomain: string; + appName: string; +} + +const USER_FIELDS = 'email _id name username provider role tenantId idOnTheSource +password'; +const IDENTITY_FIELDS = 'email _id tenantId'; + +function identifier(value?: Identifier): string | undefined { + return value?.toString(); +} + +function toUser(stored: StoredUser | null): EmailChangeUser | null { + if (!stored?.email) { + return null; + } + return { + _id: identifier(stored._id), + id: identifier(stored.id), + email: stored.email, + name: stored.name, + username: stored.username, + password: stored.password, + provider: stored.provider, + role: stored.role, + tenantId: identifier(stored.tenantId), + /** Carried through so principal resolution does not re-read the user we just loaded; + * an explicit `null` is a resolved answer and must survive, unlike an absent field. */ + ...(Object.prototype.hasOwnProperty.call(stored, 'idOnTheSource') + ? { idOnTheSource: stored.idOnTheSource ?? null } + : {}), + }; +} + +function toToken(stored: StoredToken | null): EmailChangeToken | null { + const userId = identifier(stored?.userId); + if (!stored || !userId || !stored.token) { + return null; + } + return { + userId, + token: stored.token, + email: stored.email, + scope: stored.scope, + identifier: stored.identifier, + expiresAt: stored.expiresAt, + metadata: stored.metadata, + tenantId: identifier(stored.tenantId), + }; +} + +/** + * A tenant-less lookup must not match another tenant's account, which a bare `email` query + * would: the system context suppresses tenant filtering, so the scope has to be stated. + */ +function identityQuery(email: string, tenantId?: string): StoredUserQuery { + if (tenantId) { + return { email }; + } + return { email, $or: [{ tenantId: { $exists: false } }, { tenantId: null }] }; +} + +/** + * Builds the service's dependencies from the application's database and mail surfaces. The + * tenant scoping, the identity query and the policy resolution below are authorization + * behavior, so they live here rather than in the route that calls the service. + */ +export function createEmailChangeDeps(runtime: EmailChangeRuntime): EmailChangeDeps { + const { store, withTenant } = runtime; + + /** + * Confirmation is unauthenticated and so has no request config. Resolving the same full + * principal scope issuance used keeps a role, group, or user override of + * `registration.allowedDomains` enforced here too. Deliberately not `withTenant`: a + * tenant-less user would fall back to the system context, which suppresses tenant + * filtering, so another tenant's override of a shared principal such as the `USER` role + * would decide this policy. + */ + const resolveAppConfig = (user: EmailChangeUser): Promise => { + const options = getAppConfigOptionsFromUser( + { + id: user._id ?? user.id, + role: user.role, + tenantId: user.tenantId, + idOnTheSource: user.idOnTheSource, + }, + undefined, + ); + /** A transient principal or override failure must not fall back to a base allowlist + * that is broader than the scoped one, which would commit an address policy forbids. */ + const read = () => runtime.getAppConfig({ ...options, failClosed: true }); + return user.tenantId ? withTenant(user.tenantId, read) : read(); + }; + + return { + findUserByEmail: (email, tenantId) => + withTenant(tenantId, async () => + toUser(await store.findUser(identityQuery(email, tenantId), IDENTITY_FIELDS)), + ), + getUserById: (userId, tenantId) => + withTenant(tenantId, async () => toUser(await store.getUserById(userId, USER_FIELDS))), + updateUser: (userId, update, expectedState, tenantId) => + withTenant(tenantId, async () => + toUser(await store.updateUser(userId, update, expectedState)), + ), + findToken: (query, tenantId) => + withTenant(tenantId, async () => + toToken(await store.findToken(query, { sort: { createdAt: -1 } })), + ), + replaceTokenIfCurrent: (scope, expectedToken, data, tenantId) => + withTenant(tenantId, () => store.replaceTokenIfCurrent(scope, expectedToken, data)), + deleteTokens: (query, tenantId) => withTenant(tenantId, () => store.deleteTokens(query)), + verifyPassword: runtime.comparePassword, + resolvePolicy: async (user) => { + const appConfig = await resolveAppConfig(user); + return { + settings: resolveEmailChangeSettings(appConfig?.emailChange), + allowedDomains: appConfig?.registration?.allowedDomains, + }; + }, + sendEmail: runtime.sendEmail, + resolveSettings: async (): Promise => { + const appConfig = await runtime.getAppConfig({ failClosed: true }); + return resolveEmailChangeSettings(appConfig?.emailChange); + }, + clientDomain: runtime.clientDomain, + appName: runtime.appName, + }; +} diff --git a/packages/api/src/auth/index.ts b/packages/api/src/auth/index.ts index f6e8956439..3d0dd70279 100644 --- a/packages/api/src/auth/index.ts +++ b/packages/api/src/auth/index.ts @@ -11,5 +11,8 @@ export * from './invite'; export * from './codeapi'; export * from './openidRoleSync'; export * from './userDocCache'; +export * from './email'; +export * from './emailChangeStore'; +export * from './passwordReset'; export * from './reuse'; export * from './openid/index'; diff --git a/packages/api/src/auth/passwordReset.spec.ts b/packages/api/src/auth/passwordReset.spec.ts new file mode 100644 index 0000000000..cd137f88b9 --- /dev/null +++ b/packages/api/src/auth/passwordReset.spec.ts @@ -0,0 +1,203 @@ +import type { PasswordResetDeps, PasswordResetToken, PasswordResetUser } from './passwordReset'; +import { commitPasswordReset, resetTokenBindsToAccount } from './passwordReset'; + +const RESET_HASH = 'hashed-reset-token'; + +function createDeps(overrides: Partial = {}): jest.Mocked { + return { + findResetToken: jest.fn().mockResolvedValue(null), + getUserById: jest.fn().mockResolvedValue(null), + updateUser: jest.fn().mockResolvedValue({ email: 'user@example.com' }), + deleteTokens: jest.fn().mockResolvedValue({ deletedCount: 1 }), + compareToken: jest.fn((candidate: string) => candidate === 'reset-token'), + hashPassword: jest.fn(() => 'hashed-password'), + ...overrides, + } as jest.Mocked; +} + +function typedToken(overrides: Partial = {}): PasswordResetToken { + return { token: RESET_HASH, email: 'user@example.com', type: 'password_reset', ...overrides }; +} + +function legacyToken(): PasswordResetToken { + return { token: RESET_HASH, email: null, type: null }; +} + +function account(overrides: Partial = {}): PasswordResetUser { + return { _id: 'user-reset', email: 'user@example.com', ...overrides }; +} + +const input = { userId: 'user-reset', token: 'reset-token', password: 'new-password' }; + +describe('commitPasswordReset', () => { + it('reads the token and the account together', async () => { + /** Both depend only on the supplied id, and neither is acted on before its own check. */ + const order: string[] = []; + const deps = createDeps({ + findResetToken: jest.fn(async () => { + order.push('token:start'); + await Promise.resolve(); + order.push('token:end'); + return typedToken(); + }), + getUserById: jest.fn(async () => { + order.push('user:start'); + return account(); + }), + }); + + await commitPasswordReset(deps, input); + + expect(order.slice(0, 2)).toEqual(['token:start', 'user:start']); + }); + + it('refuses when no reset token exists', async () => { + const deps = createDeps(); + + await expect(commitPasswordReset(deps, input)).resolves.toEqual({ ok: false }); + expect(deps.updateUser).not.toHaveBeenCalled(); + expect(deps.deleteTokens).not.toHaveBeenCalled(); + }); + + it('refuses a token whose secret does not match', async () => { + const deps = createDeps({ findResetToken: jest.fn().mockResolvedValue(typedToken()) }); + + await expect(commitPasswordReset(deps, { ...input, token: 'wrong-token' })).resolves.toEqual({ + ok: false, + }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('commits against the address the account holds now', async () => { + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(typedToken()), + getUserById: jest.fn().mockResolvedValue(account()), + }); + + await expect(commitPasswordReset(deps, input)).resolves.toMatchObject({ ok: true }); + expect(deps.updateUser).toHaveBeenCalledWith( + 'user-reset', + { password: 'hashed-password' }, + { email: 'user@example.com' }, + ); + }); + + it('accepts a typed token issued before addresses were bound', async () => { + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(typedToken({ email: undefined })), + getUserById: jest.fn().mockResolvedValue(account()), + }); + + await expect(commitPasswordReset(deps, input)).resolves.toMatchObject({ ok: true }); + }); + + it('refuses a typed token issued to a previous address', async () => { + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(typedToken({ email: 'old@example.com' })), + getUserById: jest.fn().mockResolvedValue(account({ email: 'new@example.com' })), + }); + + await expect(commitPasswordReset(deps, input)).resolves.toEqual({ ok: false }); + expect(deps.updateUser).not.toHaveBeenCalled(); + expect(deps.deleteTokens).not.toHaveBeenCalled(); + }); + + it('refuses an address-less token once the account has moved', async () => { + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(typedToken({ email: undefined })), + getUserById: jest + .fn() + .mockResolvedValue(account({ email: 'new@example.com', emailChangedAt: new Date() })), + }); + + await expect(commitPasswordReset(deps, input)).resolves.toEqual({ ok: false }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('accepts an untyped legacy token for an account that never moved', async () => { + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(legacyToken()), + getUserById: jest.fn().mockResolvedValue(account()), + }); + + await expect(commitPasswordReset(deps, input)).resolves.toMatchObject({ ok: true }); + }); + + it('refuses an untyped legacy token once the account has moved', async () => { + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(legacyToken()), + getUserById: jest + .fn() + .mockResolvedValue(account({ email: 'new@example.com', emailChangedAt: new Date() })), + }); + + await expect(commitPasswordReset(deps, input)).resolves.toEqual({ ok: false }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('refuses when the account cannot be read', async () => { + const deps = createDeps({ findResetToken: jest.fn().mockResolvedValue(typedToken()) }); + + await expect(commitPasswordReset(deps, input)).resolves.toEqual({ ok: false }); + expect(deps.updateUser).not.toHaveBeenCalled(); + }); + + it('refuses when the compare-and-set finds the address already moved', async () => { + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(typedToken()), + getUserById: jest.fn().mockResolvedValue(account()), + updateUser: jest.fn().mockResolvedValue(null), + }); + + await expect(commitPasswordReset(deps, input)).resolves.toEqual({ ok: false }); + expect(deps.deleteTokens).not.toHaveBeenCalled(); + }); + + it('revokes pending email changes once the password is committed', async () => { + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(typedToken()), + getUserById: jest.fn().mockResolvedValue(account()), + }); + + await commitPasswordReset(deps, input); + + expect(deps.deleteTokens).toHaveBeenCalledWith({ + userId: 'user-reset', + type: 'email_change', + }); + }); + + it('still reports success when the email change sweep fails', async () => { + /** The password is already committed; a failed cleanup must not hand the caller an + * error that invites a retry against a token this reset consumed. */ + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(typedToken()), + getUserById: jest.fn().mockResolvedValue(account()), + deleteTokens: jest.fn().mockRejectedValue(new Error('mongo unavailable')), + }); + + await expect(commitPasswordReset(deps, input)).resolves.toMatchObject({ ok: true }); + }); + + it('returns the token it consumed so the caller can delete exactly that one', async () => { + const resetToken = typedToken(); + const deps = createDeps({ + findResetToken: jest.fn().mockResolvedValue(resetToken), + getUserById: jest.fn().mockResolvedValue(account()), + }); + + await expect(commitPasswordReset(deps, input)).resolves.toMatchObject({ resetToken }); + }); +}); + +describe('resetTokenBindsToAccount', () => { + it('compares addresses without regard to case', () => { + expect(resetTokenBindsToAccount(typedToken({ email: 'User@Example.com' }), account())).toBe( + true, + ); + }); + + it('refuses when there is no account', () => { + expect(resetTokenBindsToAccount(typedToken(), null)).toBe(false); + }); +}); diff --git a/packages/api/src/auth/passwordReset.ts b/packages/api/src/auth/passwordReset.ts new file mode 100644 index 0000000000..79df6c1211 --- /dev/null +++ b/packages/api/src/auth/passwordReset.ts @@ -0,0 +1,119 @@ +import { logger } from '@librechat/data-schemas'; +import { EMAIL_CHANGE_TOKEN_TYPE } from './email'; + +/** The stored reset token, in both the typed shape and the untyped legacy one. */ +export interface PasswordResetToken { + token: string; + email?: string | null; + type?: string | null; +} + +export interface PasswordResetUser { + _id?: string; + email: string; + name?: string; + username?: string; + /** Set when a confirmed email change commits; absent on documents written before it. */ + emailChangedAt?: Date | string | null; +} + +export interface PasswordResetDeps { + findResetToken: (userId: string) => Promise; + getUserById: (userId: string, select: string) => Promise; + updateUser: ( + userId: string, + update: { password: string }, + expectedState: { email: string }, + ) => Promise; + deleteTokens: (query: { userId: string; type: string }) => Promise; + compareToken: (candidate: string, storedHash: string) => boolean; + hashPassword: (password: string) => string; +} + +export interface PasswordResetInput { + userId: string; + token: string; + password: string; +} + +export type PasswordResetOutcome = + | { ok: true; user: PasswordResetUser; resetToken: PasswordResetToken } + | { ok: false }; + +export const PASSWORD_RESET_USER_FIELDS: string = 'email _id name username emailChangedAt'; + +/** + * Keyed on the token's address binding rather than its type, so the untyped legacy shape + * a fallback lookup returns is covered too. Address-less tokens stay usable so links from + * a not-yet-upgraded node keep working, but never for an account whose address has moved: + * they cannot be attributed to the current address and would otherwise outlive the change. + */ +export function resetTokenBindsToAccount( + resetToken: PasswordResetToken, + user: PasswordResetUser | null, +): boolean { + if (!user) { + return false; + } + if (resetToken.email) { + return resetToken.email.toLowerCase() === user.email.toLowerCase(); + } + return user.emailChangedAt == null; +} + +/** + * Revokes the email changes a reset supersedes. Called immediately after the commit rather + * than after the notification: the delete is not scoped to the password the pending token + * was bound to, so every moment it is deferred is a moment an email change request can + * issue a link against the new password and have it revoked here. Confirmation refuses + * tokens bound to the old password independently, by re-checking the stored hash. + */ +export async function clearPendingEmailChanges( + deps: Pick, + userId: string, +): Promise { + try { + await deps.deleteTokens({ userId, type: EMAIL_CHANGE_TOKEN_TYPE }); + } catch (error) { + logger.error('[resetPassword] Failed to clean up pending email changes', error); + } +} + +/** + * Validates a reset link against the account it names and commits the new password, so the + * address binding, the compare-and-set and the email change sweep stay one operation. + * + * The token and the account are read together: both depend only on the supplied id, neither + * is acted on until the validation that owns it passes, and nothing is returned to the + * caller until the whole check does. + */ +export async function commitPasswordReset( + deps: PasswordResetDeps, + input: PasswordResetInput, +): Promise { + const [resetToken, account] = await Promise.all([ + deps.findResetToken(input.userId), + deps.getUserById(input.userId, PASSWORD_RESET_USER_FIELDS), + ]); + + if (!resetToken || !deps.compareToken(input.token, resetToken.token)) { + return { ok: false }; + } + + if (!resetTokenBindsToAccount(resetToken, account) || !account) { + return { ok: false }; + } + + const user = await deps.updateUser( + input.userId, + { password: deps.hashPassword(input.password) }, + { email: account.email }, + ); + if (!user) { + return { ok: false }; + } + + await clearPendingEmailChanges(deps, input.userId); + + return { ok: true, user, resetToken }; +} diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts index 64b398b4ab..aa0748c383 100644 --- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts +++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts @@ -302,6 +302,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', ( const tokenMethods = { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }; @@ -522,6 +523,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', ( tokenMethods: { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }, @@ -566,6 +568,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', ( tokenMethods: { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }, @@ -607,6 +610,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', ( const tokenMethods = { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }; @@ -694,6 +698,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', ( const tokenMethods = { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }; @@ -783,6 +788,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', ( const tokenMethods = { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }; @@ -876,6 +882,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', ( tokenMethods: { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }, @@ -922,6 +929,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', ( tokenMethods: { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }, diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts index 2e70d1a82b..0be1f5967f 100644 --- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts +++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.test.ts @@ -249,6 +249,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -715,6 +716,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: undefined as unknown as TokenMethods['findToken'], createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -749,6 +751,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -1019,6 +1022,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -1088,6 +1092,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -1151,6 +1156,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -1234,6 +1240,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -1330,6 +1337,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -2305,6 +2313,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -2503,6 +2512,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -2711,6 +2721,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -2823,6 +2834,7 @@ describe('MCPConnectionFactory', () => { const tokenMethods = { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }; @@ -3399,6 +3411,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -3532,6 +3545,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -3636,6 +3650,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -3656,6 +3671,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -5336,6 +5352,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -6244,6 +6261,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -6288,6 +6306,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -6331,6 +6350,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -6366,6 +6386,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -6395,6 +6416,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -6454,6 +6476,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -6501,6 +6524,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, @@ -6557,6 +6581,7 @@ describe('MCPConnectionFactory', () => { tokenMethods: { findToken: jest.fn(), createToken: jest.fn(), + replaceTokenIfCurrent: jest.fn(), updateToken: jest.fn(), deleteTokens: jest.fn(), }, diff --git a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts index 375cae3fc5..001ab42f62 100644 --- a/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts +++ b/packages/api/src/mcp/__tests__/MCPOAuthTokenExpiry.test.ts @@ -536,6 +536,7 @@ describe('MCP OAuth Token Expiry Scenarios', () => { tokenMethods: { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }, @@ -651,6 +652,7 @@ describe('MCP OAuth Token Expiry Scenarios', () => { tokenMethods: { findToken: tokenStore.findToken, createToken: tokenStore.createToken, + replaceTokenIfCurrent: jest.fn(), updateToken: tokenStore.updateToken, deleteTokens: tokenStore.deleteTokens, }, diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts index bee6c01bad..5f4adc5593 100644 --- a/packages/data-provider/src/api-endpoints.ts +++ b/packages/data-provider/src/api-endpoints.ts @@ -213,6 +213,10 @@ export const resetPassword = () => `${BASE_URL}/api/auth/resetPassword`; export const verifyEmail = () => `${BASE_URL}/api/user/verify`; +export const requestEmailChange = () => `${BASE_URL}/api/user/email/change`; + +export const confirmEmailChange = () => `${BASE_URL}/api/user/email/verify`; + // Auth page URLs (for client-side navigation and redirects) export const loginPage = () => `${BASE_URL}/login`; export const registerPage = () => `${BASE_URL}/register`; diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index e658ac5ff7..ab9ffab513 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -2069,6 +2069,8 @@ export enum RateLimitPrefix { IMPORT = 'IMPORT', TTS = 'TTS', STT = 'STT', + EMAIL_CHANGE = 'EMAIL_CHANGE', + EMAIL_CHANGE_CONFIRM = 'EMAIL_CHANGE_CONFIRM', } export const rateLimitSchema = z.object({ @@ -2116,6 +2118,22 @@ export const rateLimitSchema = z.object({ userWindowInMinutes: z.number().optional(), }) .optional(), + /** Requesting a change of the registered email; keyed by the authenticated user. */ + emailChange: z + .object({ + userMax: z.number().optional(), + userWindowInMinutes: z.number().optional(), + }) + .optional(), + /** Confirming one; the endpoint is unauthenticated, so the source address is bounded too. */ + emailChangeConfirm: z + .object({ + ipMax: z.number().optional(), + ipWindowInMinutes: z.number().optional(), + userMax: z.number().optional(), + userWindowInMinutes: z.number().optional(), + }) + .optional(), }); export enum EImageOutputType { @@ -2583,6 +2601,7 @@ export type TStartupConfig = { socialLoginEnabled: boolean; passwordResetEnabled: boolean; emailEnabled: boolean; + allowEmailChange: boolean; showBirthdayIcon: boolean; helpAndFaqURL: string; /** Admin panel link, only present for users with admin access */ @@ -3242,6 +3261,16 @@ export const configSchema = z.object({ openidDiscovery: openIdDiscoverySchema.partial().optional(), }) .default({ socialLogins: defaultSocialLogins }), + /** Changing the registered email address. An unset field falls back to its env var, then the + * documented default, so an existing deployment keeps the behavior it has today. */ + emailChange: z + .object({ + /** `ALLOW_EMAIL_CHANGE` when unset; enabled when neither is given. */ + enabled: z.boolean().optional(), + /** Lifetime of a verification link. */ + tokenTTLSeconds: z.number().int().min(60).max(86_400).optional(), + }) + .optional(), balance: balanceSchema.optional(), transactions: transactionsSchema.optional(), speech: z diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts index 8447883e0f..df56867589 100644 --- a/packages/data-provider/src/data-service.ts +++ b/packages/data-provider/src/data-service.ts @@ -329,6 +329,18 @@ export const verifyEmail = (payload: t.TVerifyEmail): Promise => { + return request.post(endpoints.requestEmailChange(), payload); +}; + +export const confirmEmailChange = ( + payload: t.TConfirmEmailChange, +): Promise => { + return request.post(endpoints.confirmEmailChange(), payload); +}; + export const resendVerificationEmail = ( payload: t.TResendVerificationEmail, ): Promise => { diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts index 681188237e..2f3cba38ab 100644 --- a/packages/data-provider/src/types.ts +++ b/packages/data-provider/src/types.ts @@ -814,6 +814,36 @@ export type TVerifyEmail = { export type TResendVerificationEmail = Omit; +export type EmailChangeErrorCode = + | 'account_modified' + | 'current_password_invalid' + | 'email_change_disabled' + | 'email_delivery_failed' + | 'email_domain_not_allowed' + | 'email_in_use' + | 'email_service_unavailable' + | 'invalid_request' + | 'invalid_token' + | 'local_account_required' + | 'request_in_progress' + | 'same_email'; + +export type TRequestEmailChange = { + currentPassword: string; + newEmail: string; +}; + +export type TConfirmEmailChange = { + email: string; + token: string; + userId: string; +}; + +export type TEmailChangeResponse = { + message: string; + code?: EmailChangeErrorCode; +}; + export type TRefreshTokenResponse = { token: string; user: TUser; diff --git a/packages/data-schemas/src/app/service.ts b/packages/data-schemas/src/app/service.ts index e762d1620e..63c7b15850 100644 --- a/packages/data-schemas/src/app/service.ts +++ b/packages/data-schemas/src/app/service.ts @@ -163,6 +163,7 @@ export const AppService = async (params?: { const mcpSettings = config.mcpSettings || null; const actions = config.actions; const registration = config.registration ?? configDefaults.registration; + const emailChange = config.emailChange; const interfaceConfig = await loadDefaultInterface({ config, configDefaults }); const turnstileConfig = loadTurnstileConfig(config, configDefaults); const speech = config.speech; @@ -183,6 +184,7 @@ export const AppService = async (params?: { mcpSettings, fileStrategy, registration, + emailChange, transactions, filteredTools, includedTools, diff --git a/packages/data-schemas/src/methods/token.spec.ts b/packages/data-schemas/src/methods/token.spec.ts index 5661aca552..0666a7aa56 100644 --- a/packages/data-schemas/src/methods/token.spec.ts +++ b/packages/data-schemas/src/methods/token.spec.ts @@ -1,12 +1,13 @@ import mongoose from 'mongoose'; import { MongoMemoryServer } from 'mongodb-memory-server'; import type * as t from '~/types'; +import { createTokenModel } from '~/models/token'; import { createTokenMethods } from './token'; -import tokenSchema from '~/schema/token'; /** Mocking logger */ jest.mock('~/config/winston', () => ({ error: jest.fn(), + warn: jest.fn(), info: jest.fn(), debug: jest.fn(), })); @@ -21,7 +22,7 @@ beforeAll(async () => { await mongoose.connect(mongoUri); /** Register models */ - Token = mongoose.models.Token || mongoose.model('Token', tokenSchema); + Token = createTokenModel(mongoose); /** Initialize methods */ methods = createTokenMethods(mongoose); @@ -34,6 +35,7 @@ afterAll(async () => { beforeEach(async () => { await mongoose.connection.dropDatabase(); + methods = createTokenMethods(mongoose); }); describe('Token Methods - Detailed Tests', () => { @@ -533,6 +535,106 @@ describe('Token Methods - Detailed Tests', () => { }); }); + describe('replaceTokenIfCurrent', () => { + test('allows only one concurrent insert into an empty scope', async () => { + const userId = new mongoose.Types.ObjectId(); + const scope = `email_change:${userId.toString()}`; + const candidates = [ + { + userId, + type: 'email_change', + email: 'first@example.com', + token: 'first-token', + expiresIn: 900, + }, + { + userId, + type: 'email_change', + email: 'second@example.com', + token: 'second-token', + expiresIn: 900, + }, + ]; + + const results = await Promise.all( + candidates.map((candidate) => methods.replaceTokenIfCurrent(scope, null, candidate)), + ); + + expect([...results].sort()).toEqual([false, true]); + const winner = candidates[results.indexOf(true)]; + const pending = await Token.findOne({ scope }).lean(); + expect(pending?.token).toBe(winner.token); + expect(pending?.email).toBe(winner.email); + expect(await Token.countDocuments({ scope })).toBe(1); + }); + + test('allows only one concurrent replacement of the observed token', async () => { + const userId = new mongoose.Types.ObjectId(); + const scope = `email_change:${userId.toString()}`; + await methods.replaceTokenIfCurrent(scope, null, { + userId, + type: 'email_change', + email: 'existing@example.com', + token: 'existing-token', + expiresIn: 900, + }); + + const candidates = [ + { + userId, + type: 'email_change', + email: 'first@example.com', + token: 'first-token', + expiresIn: 900, + }, + { + userId, + type: 'email_change', + email: 'second@example.com', + token: 'second-token', + expiresIn: 900, + }, + ]; + const results = await Promise.all( + candidates.map((candidate) => + methods.replaceTokenIfCurrent(scope, 'existing-token', candidate), + ), + ); + + expect([...results].sort()).toEqual([false, true]); + const winner = candidates[results.indexOf(true)]; + const pending = await Token.findOne({ scope }).lean(); + expect(pending?.token).toBe(winner.token); + expect(pending?.email).toBe(winner.email); + }); + + test('preserves the current token when the expected token is stale', async () => { + const userId = new mongoose.Types.ObjectId(); + const scope = `email_change:${userId.toString()}`; + await methods.replaceTokenIfCurrent(scope, null, { + userId, + type: 'email_change', + email: 'current@example.com', + token: 'current-token', + expiresIn: 900, + }); + + await expect( + methods.replaceTokenIfCurrent(scope, 'stale-token', { + userId, + type: 'email_change', + email: 'replacement@example.com', + token: 'replacement-token', + expiresIn: 900, + }), + ).resolves.toBe(false); + + const pending = await Token.findOne({ scope }).lean(); + expect(pending?.token).toBe('current-token'); + expect(pending?.email).toBe('current@example.com'); + }); + }); + describe('deleteTokens', () => { let user1Id: mongoose.Types.ObjectId; let user2Id: mongoose.Types.ObjectId; diff --git a/packages/data-schemas/src/methods/token.ts b/packages/data-schemas/src/methods/token.ts index cbf640fcf8..db376829cc 100644 --- a/packages/data-schemas/src/methods/token.ts +++ b/packages/data-schemas/src/methods/token.ts @@ -1,14 +1,41 @@ import type { QueryOptions } from 'mongoose'; import { IToken, TokenCreateData, TokenQuery, TokenUpdateData, TokenDeleteResult } from '~/types'; +import { createIndexesWithRetry } from '~/utils/retry'; import logger from '~/config/winston'; +function isDuplicateKeyError(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + 'code' in error && + (error as { code?: number }).code === 11000 + ); +} + // Factory function that takes mongoose instance and returns the methods export function createTokenMethods(mongoose: typeof import('mongoose')): { findToken: (query: TokenQuery, options?: QueryOptions) => Promise; createToken: (tokenData: TokenCreateData) => Promise; + replaceTokenIfCurrent: ( + scope: string, + expectedToken: string | null, + tokenData: TokenCreateData, + ) => Promise; updateToken: (query: TokenQuery, updateData: TokenUpdateData) => Promise; deleteTokens: (query: TokenQuery) => Promise; } { + let indexPromise: Promise | null = null; + + function ensureIndexes(): Promise { + if (!indexPromise) { + indexPromise = createIndexesWithRetry(mongoose.models.Token).catch((error: unknown) => { + indexPromise = null; + throw error; + }); + } + return indexPromise; + } + /** * Creates a new Token instance. */ @@ -31,6 +58,55 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): { } } + /** + * Atomically replaces the scoped token only when it still matches the token + * observed by the caller. A null expectation succeeds only when the scope is absent. + */ + async function replaceTokenIfCurrent( + scope: string, + expectedToken: string | null, + tokenData: TokenCreateData, + ): Promise { + try { + const Token = mongoose.models.Token; + await ensureIndexes(); + const currentTime = new Date(); + const { expiresIn, ...storedTokenData } = tokenData; + const replacement = { + ...storedTokenData, + scope, + createdAt: currentTime, + expiresAt: new Date(currentTime.getTime() + expiresIn * 1000), + }; + const query = { + scope, + token: expectedToken ?? tokenData.token, + }; + + try { + const replacedToken = await Token.findOneAndUpdate( + query, + expectedToken === null ? { $setOnInsert: replacement } : { $set: replacement }, + { + new: true, + upsert: expectedToken === null, + runValidators: true, + setDefaultsOnInsert: true, + }, + ); + return replacedToken !== null; + } catch (error) { + if (isDuplicateKeyError(error)) { + return false; + } + throw error; + } + } catch (error) { + logger.debug('An error occurred while conditionally replacing token:', error); + throw error; + } + } + /** * Updates a Token document that matches the provided query. */ @@ -77,6 +153,9 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): { if (query.type !== undefined) { conditions.push({ type: query.type }); } + if (query.scope !== undefined) { + conditions.push({ scope: query.scope }); + } if (query.identifier !== undefined) { conditions.push({ identifier: query.identifier }); } @@ -119,6 +198,9 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): { if (query.type !== undefined) { conditions.push({ type: query.type }); } + if (query.scope !== undefined) { + conditions.push({ scope: query.scope }); + } if (query.identifier !== undefined) { conditions.push({ identifier: query.identifier }); } @@ -139,6 +221,7 @@ export function createTokenMethods(mongoose: typeof import('mongoose')): { return { findToken, createToken, + replaceTokenIfCurrent, updateToken, deleteTokens, }; diff --git a/packages/data-schemas/src/methods/user.methods.spec.ts b/packages/data-schemas/src/methods/user.methods.spec.ts index e7e0378e4e..6ef431153f 100644 --- a/packages/data-schemas/src/methods/user.methods.spec.ts +++ b/packages/data-schemas/src/methods/user.methods.spec.ts @@ -393,6 +393,29 @@ describe('User Methods - Database Tests', () => { expect(updated?.expiresAt).toBeUndefined(); }); + test('should update only when the expected account state still matches', async () => { + const user = await User.create({ + name: 'Conditional User', + email: 'original@example.com', + password: 'original-password-hash', + provider: 'local', + }); + + const staleUpdate = await methods.updateUser( + user._id?.toString() ?? '', + { email: 'stale@example.com' }, + { email: 'different@example.com', password: 'original-password-hash' }, + ); + const currentUpdate = await methods.updateUser( + user._id?.toString() ?? '', + { email: 'current@example.com' }, + { email: 'original@example.com', password: 'original-password-hash' }, + ); + + expect(staleUpdate).toBeNull(); + expect(currentUpdate?.email).toBe('current@example.com'); + }); + test('should invalidate cached auth user documents on update', async () => { enableAuthUserDocCache(); const user = await User.create({ diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.ts index 0d633b2054..5e59490ed5 100644 --- a/packages/data-schemas/src/methods/user.ts +++ b/packages/data-schemas/src/methods/user.ts @@ -49,7 +49,11 @@ export function createUserMethods( disableTTL?: boolean, returnUser?: boolean, ) => Promise>; - updateUser: (userId: string, updateData: Partial) => Promise; + updateUser: ( + userId: string, + updateData: Partial, + expectedState?: FilterQuery, + ) => Promise; claimSamlIdentity: ( userId: string, samlId: string, @@ -304,16 +308,24 @@ export function createUserMethods( /** * Update a user with new data without overwriting existing properties. */ - async function updateUser(userId: string, updateData: Partial): Promise { + async function updateUser( + userId: string, + updateData: Partial, + expectedState: FilterQuery = {}, + ): Promise { const User = mongoose.models.User; const updateOperation = { $set: updateData, $unset: { expiresAt: '' }, // Remove the expiresAt field to prevent TTL }; - const updated = await User.findByIdAndUpdate(userId, updateOperation, { - new: true, - runValidators: true, - }).lean(); + const updated = await User.findOneAndUpdate( + { ...expectedState, _id: userId }, + updateOperation, + { + new: true, + runValidators: true, + }, + ).lean(); await invalidateAuthUserDocCache(userId); return updated; } diff --git a/packages/data-schemas/src/schema/token.ts b/packages/data-schemas/src/schema/token.ts index a9dac9c6fe..9333e45cce 100644 --- a/packages/data-schemas/src/schema/token.ts +++ b/packages/data-schemas/src/schema/token.ts @@ -20,6 +20,9 @@ const tokenSchema: Schema = new Schema({ type: { type: String, }, + scope: { + type: String, + }, identifier: { type: String, }, @@ -47,6 +50,7 @@ const tokenSchema: Schema = new Schema({ }); tokenSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 }); +tokenSchema.index({ scope: 1 }, { unique: true, sparse: true, name: 'unique_token_scope' }); tokenSchema.index({ userId: 1, type: 1, identifier: 1, tenantId: 1 }); export default tokenSchema; diff --git a/packages/data-schemas/src/schema/user.ts b/packages/data-schemas/src/schema/user.ts index 3e97b548aa..68efec7cc7 100644 --- a/packages/data-schemas/src/schema/user.ts +++ b/packages/data-schemas/src/schema/user.ts @@ -45,6 +45,11 @@ const userSchema: Schema = new Schema( required: true, default: false, }, + /** Set when a confirmed email change commits; password resets use it to refuse + * address-less legacy tokens that a mixed-version deployment could still mint. */ + emailChangedAt: { + type: Date, + }, password: { type: String, trim: true, diff --git a/packages/data-schemas/src/types/app.ts b/packages/data-schemas/src/types/app.ts index df2a4b6054..95770d4fcb 100644 --- a/packages/data-schemas/src/types/app.ts +++ b/packages/data-schemas/src/types/app.ts @@ -80,6 +80,8 @@ export interface AppConfig { cloudfront?: CloudFrontConfig; /** Registration configurations */ registration?: TCustomConfig['registration']; + /** Changing the registered email address */ + emailChange?: TCustomConfig['emailChange']; /** Actions configurations */ actions?: TCustomConfig['actions']; /** Admin-filtered tools */ diff --git a/packages/data-schemas/src/types/token.ts b/packages/data-schemas/src/types/token.ts index 7385da6a32..c31d1a52b8 100644 --- a/packages/data-schemas/src/types/token.ts +++ b/packages/data-schemas/src/types/token.ts @@ -4,6 +4,7 @@ export interface IToken extends Document { userId: Types.ObjectId; email?: string; type?: string; + scope?: string; identifier?: string; token: string; createdAt: Date; @@ -16,6 +17,7 @@ export interface TokenCreateData { userId: Types.ObjectId | string; email?: string; type?: string; + scope?: string; identifier?: string; token: string; expiresIn: number; @@ -27,6 +29,7 @@ export interface TokenQuery { token?: string; email?: string | null; type?: string | null; + scope?: string; identifier?: string | RegExp | null; /** Internal optimistic-concurrency selector for OAuth token record generations. */ metadataCredentialSetId?: string | null; @@ -35,6 +38,7 @@ export interface TokenQuery { export interface TokenUpdateData { email?: string; type?: string; + scope?: string; identifier?: string; token?: string; expiresAt?: Date; diff --git a/packages/data-schemas/src/types/user.ts b/packages/data-schemas/src/types/user.ts index aba23077f6..62cc0f3565 100644 --- a/packages/data-schemas/src/types/user.ts +++ b/packages/data-schemas/src/types/user.ts @@ -20,6 +20,7 @@ export interface IUser extends Document { username?: string; email: string; emailVerified: boolean; + emailChangedAt?: Date; password?: string; avatar?: string; provider: string;