Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧿 fix: Bind Login Flows to the Browser That Started Them (#15880)
Danny Avila9cf33cc8be60
diff --git a/api/server/experimental.js b/api/server/experimental.jsindex d0173bd728..ab4c6d0628 100644--- a/api/server/experimental.js+++ b/api/server/experimental.js@@ -628,7 +628,7 @@ if (cluster.isMaster) {}if (isEnabled(ALLOW_SOCIAL_LOGIN)) {- await configureSocialLogins(app);+ await configureSocialLogins(app, appConfig);}app.use(capabilityContextMiddleware);diff --git a/api/server/index.js b/api/server/index.jsindex 73ce8e45d7..a7ae9a6fa6 100644--- a/api/server/index.js+++ b/api/server/index.js@@ -373,7 +373,7 @@ const startServer = async () => {}if (isEnabled(ALLOW_SOCIAL_LOGIN)) {- await configureSocialLogins(app);+ await configureSocialLogins(app, appConfig);}/* Per-request capability cache — must be registered before any route that calls hasCapability */diff --git a/api/server/index.spec.js b/api/server/index.spec.jsindex 9949b5e0bc..b113ab1b97 100644--- a/api/server/index.spec.js+++ b/api/server/index.spec.js@@ -133,6 +133,21 @@ describe('Startup readiness wiring', () => {).toHaveLength(1);});+ it('configures social logins with the app config loaded at startup in both server entries', () => {+ const experimental = fs.readFileSync(path.join(__dirname, 'experimental.js'), 'utf8');++ for (const [name, contents] of [+ ['index.js', source],+ ['experimental.js', experimental],+ ]) {+ const appConfigIndex = contents.indexOf('const appConfig = await getAppConfig(');+ const socialLoginsIndex = contents.indexOf('await configureSocialLogins(app, appConfig);');++ expect([name, appConfigIndex > -1]).toEqual([name, true]);+ expect([name, socialLoginsIndex > appConfigIndex]).toEqual([name, true]);+ }+ });+it('awaits the shared Redis client before startup cache access', () => {const redisReadyIndex = source.indexOf('await waitForKeyvRedisClient();');const connectDbIndex = source.indexOf('await connectDb();');diff --git a/api/server/middleware/index.js b/api/server/middleware/index.jsindex 8f39ea1ee8..814baf075b 100644--- a/api/server/middleware/index.js+++ b/api/server/middleware/index.js@@ -11,6 +11,7 @@ const {} = require('./messageValidation');const checkDomainAllowed = require('./checkDomainAllowed');const { markOAuthNavigation } = require('./oauthNavigation');+const requireSameOrigin = require('./requireSameOrigin');const requireLocalAuth = require('./requireLocalAuth');const canDeleteAccount = require('./canDeleteAccount');const accessResources = require('./accessResources');@@ -51,6 +52,7 @@ module.exports = {checkInviteUser,requireLdapAuth,requireLocalAuth,+ requireSameOrigin,canDeleteAccount,configMiddleware,checkDomainAllowed,diff --git a/api/server/middleware/requireSameOrigin.js b/api/server/middleware/requireSameOrigin.jsnew file mode 100644index 0000000000..815063a9b5--- /dev/null+++ b/api/server/middleware/requireSameOrigin.js@@ -0,0 +1,9 @@+const { createSameOriginGuard } = require('@librechat/api');++module.exports = createSameOriginGuard({+ trustedOrigins: [+ process.env.DOMAIN_CLIENT,+ process.env.DOMAIN_SERVER,+ process.env.ADMIN_PANEL_URL,+ ],+});diff --git a/api/server/routes/admin/auth.js b/api/server/routes/admin/auth.jsindex fbc53c0907..2af6f90367 100644--- a/api/server/routes/admin/auth.js+++ b/api/server/routes/admin/auth.js@@ -156,6 +156,7 @@ function buildGoogleAdminRefreshDeps(sessionExpiry) {router.post('/login/local',middleware.logHeaders,+ middleware.requireSameOrigin,middleware.loginLimiter,middleware.checkBan,middleware.validateEmailLogin,diff --git a/api/server/routes/admin/auth.refresh.test.js b/api/server/routes/admin/auth.refresh.test.jsindex 3539c2d285..c6e0287054 100644--- a/api/server/routes/admin/auth.refresh.test.js+++ b/api/server/routes/admin/auth.refresh.test.js@@ -98,6 +98,7 @@ jest.mock('~/strategies', () => ({jest.mock('~/server/middleware', () => ({logHeaders: jest.fn((req, res, next) => next()),+ requireSameOrigin: jest.fn((req, res, next) => next()),loginLimiter: jest.fn((req, res, next) => next()),checkBan: jest.fn((req, res, next) => next()),validateEmailLogin: jest.fn((req, res, next) => next()),@@ -606,6 +607,33 @@ describe('admin local login route', () => {);});+ it('rejects cross-site submissions before rate limiting or local auth', async () => {+ const response = await request(app).post('/api/admin/login/local').send({+ email: '[email protected]',+ password: 'password',+ });++ expect(response.status).toBe(200);+ expect(middleware.requireSameOrigin).toHaveBeenCalledTimes(1);+ expect(middleware.requireSameOrigin.mock.invocationCallOrder[0]).toBeLessThan(+ middleware.loginLimiter.mock.invocationCallOrder[0],+ );++ jest.clearAllMocks();+ middleware.requireSameOrigin.mockImplementationOnce((req, res) =>+ res.status(403).json({ message: 'Cross-site request rejected' }),+ );++ const rejected = await request(app).post('/api/admin/login/local').send({+ email: '[email protected]',+ password: 'password',+ });++ expect(rejected.status).toBe(403);+ expect(middleware.loginLimiter).not.toHaveBeenCalled();+ expect(middleware.requireLocalAuth).not.toHaveBeenCalled();+ });+it('stops before local auth when the email login gate rejects the request', async () => {middleware.validateEmailLogin.mockImplementationOnce((req, res) =>res.status(403).json({ message: 'Email login is not allowed.' }),diff --git a/api/server/routes/auth.2fa-ratelimit.test.js b/api/server/routes/auth.2fa-ratelimit.test.jsindex 4867f78afe..c352fd64bf 100644--- a/api/server/routes/auth.2fa-ratelimit.test.js+++ b/api/server/routes/auth.2fa-ratelimit.test.js@@ -52,6 +52,7 @@ jest.mock('~/server/middleware', () => {const pass = (req, res, next) => next();return {logHeaders: pass,+ requireSameOrigin: pass,loginLimiter: pass,setTwoFactorTempUser: (...args) => mockSetTwoFactorTempUser(...args),twoFactorTempLimiter: (...args) => mockTwoFactorTempLimiter(...args),diff --git a/api/server/routes/auth.cloudfront.test.js b/api/server/routes/auth.cloudfront.test.jsindex 56f2acf06f..ed7803d573 100644--- a/api/server/routes/auth.cloudfront.test.js+++ b/api/server/routes/auth.cloudfront.test.js@@ -49,6 +49,7 @@ jest.mock('~/server/middleware', () => {const pass = (req, res, next) => next();return {logHeaders: pass,+ requireSameOrigin: pass,loginLimiter: pass,setTwoFactorTempUser: pass,twoFactorTempLimiter: pass,diff --git a/api/server/routes/auth.cross-site.test.js b/api/server/routes/auth.cross-site.test.jsnew file mode 100644index 0000000000..0613d66adb--- /dev/null+++ b/api/server/routes/auth.cross-site.test.js@@ -0,0 +1,188 @@+const express = require('express');+const request = require('supertest');+const { ErrorTypes } = require('librechat-data-provider');++const mockLoginLimiter = jest.fn((req, res, next) => next());+const mockRequireLocalAuth = jest.fn((req, res, next) => next());+const mockSetTwoFactorTempUser = jest.fn((req, res, next) => next());+const mockLoginController = jest.fn((req, res) => res.status(204).end());+const mockVerify2FAWithTempToken = jest.fn((req, res) => res.status(204).end());++jest.mock('@librechat/data-schemas', () => ({+ ...jest.requireActual('@librechat/data-schemas'),+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}));++jest.mock('@librechat/api', () => ({+ ...jest.requireActual('@librechat/api'),+ createSetBalanceConfig: jest.fn(() => (req, res, next) => next()),+}));++jest.mock('~/server/controllers/AuthController', () => ({+ refreshController: jest.fn((req, res) => res.status(204).end()),+ registrationController: jest.fn((req, res) => res.status(204).end()),+ resetPasswordController: jest.fn((req, res) => res.status(204).end()),+ resetPasswordRequestController: jest.fn((req, res) => res.status(204).end()),+ graphTokenController: jest.fn((req, res) => res.status(204).end()),+}));++jest.mock('~/server/controllers/TwoFactorController', () => ({+ enable2FA: jest.fn((req, res) => res.status(204).end()),+ verify2FA: jest.fn((req, res) => res.status(204).end()),+ confirm2FA: jest.fn((req, res) => res.status(204).end()),+ disable2FA: jest.fn((req, res) => res.status(204).end()),+ regenerateBackupCodes: jest.fn((req, res) => res.status(204).end()),+}));++jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({+ verify2FAWithTempToken: (...args) => mockVerify2FAWithTempToken(...args),+}));++jest.mock('~/server/controllers/auth/LogoutController', () => ({+ logoutController: jest.fn((req, res) => res.status(204).end()),+}));++jest.mock('~/server/controllers/auth/LoginController', () => ({+ loginController: (...args) => mockLoginController(...args),+}));++jest.mock('~/models', () => ({+ findBalanceByUser: jest.fn(),+ upsertBalanceFields: jest.fn(),+}));++jest.mock('~/server/services/Config', () => ({+ getAppConfig: jest.fn(),+}));++jest.mock('~/server/middleware', () => {+ const pass = (req, res, next) => next();+ return {+ logHeaders: pass,+ requireSameOrigin: jest.requireActual('~/server/middleware/requireSameOrigin'),+ loginLimiter: (...args) => mockLoginLimiter(...args),+ setTwoFactorTempUser: (...args) => mockSetTwoFactorTempUser(...args),+ twoFactorTempLimiter: pass,+ checkBan: pass,+ validateEmailLogin: pass,+ requireLocalAuth: (...args) => mockRequireLocalAuth(...args),+ requireLdapAuth: (...args) => mockRequireLocalAuth(...args),+ registerLimiter: pass,+ checkInviteUser: pass,+ validateRegistration: pass,+ resetPasswordLimiter: pass,+ resetPasswordSubmissionLimiter: pass,+ validatePasswordReset: pass,+ requireJwtAuth: pass,+ };+});++const ORIGINAL_ENV = process.env;+const APP_ORIGIN = 'https://chat.example.com';+const OTHER_ORIGIN = 'https://other-site.example.net';+const ADMIN_PANEL_ORIGIN = 'https://admin.example.com';++describe('local login endpoints reject cross-site submissions', () => {+ let app;++ beforeAll(() => {+ process.env = {+ ...ORIGINAL_ENV,+ DOMAIN_CLIENT: APP_ORIGIN,+ DOMAIN_SERVER: APP_ORIGIN,+ ADMIN_PANEL_URL: `${ADMIN_PANEL_ORIGIN}/`,+ };+ app = express();+ app.use(express.json());+ app.use(express.urlencoded({ extended: true }));+ app.use('/api/auth', require('./auth'));+ });++ afterAll(() => {+ process.env = ORIGINAL_ENV;+ });++ beforeEach(() => {+ jest.clearAllMocks();+ });++ it('rejects a login form submitted from another site before authenticating', async () => {+ const response = await request(app)+ .post('/api/auth/login')+ .set('Host', 'chat.example.com')+ .set('Sec-Fetch-Site', 'cross-site')+ .set('Origin', OTHER_ORIGIN)+ .type('form')+ .send({ email: '[email protected]', password: 'other-password' })+ .expect(403);++ expect(response.body).toEqual({+ message: 'Cross-site request rejected',+ code: ErrorTypes.AUTH_CROSS_ORIGIN,+ });+ expect(response.headers['set-cookie']).toBeUndefined();+ expect(mockLoginLimiter).not.toHaveBeenCalled();+ expect(mockRequireLocalAuth).not.toHaveBeenCalled();+ expect(mockLoginController).not.toHaveBeenCalled();+ });++ it('rejects a cross-site temp-token 2FA submission before verifying it', async () => {+ await request(app)+ .post('/api/auth/2fa/verify-temp')+ .set('Host', 'chat.example.com')+ .set('Sec-Fetch-Site', 'cross-site')+ .set('Origin', OTHER_ORIGIN)+ .type('form')+ .send({ tempToken: 'other-temp-token', token: '123456' })+ .expect(403);++ expect(mockSetTwoFactorTempUser).not.toHaveBeenCalled();+ expect(mockVerify2FAWithTempToken).not.toHaveBeenCalled();+ });++ it('accepts the login form the app submits from its own origin', async () => {+ await request(app)+ .post('/api/auth/login')+ .set('Host', 'chat.example.com')+ .set('Sec-Fetch-Site', 'same-origin')+ .set('Origin', APP_ORIGIN)+ .send({ email: '[email protected]', password: 'password' })+ .expect(204);++ expect(mockRequireLocalAuth).toHaveBeenCalledTimes(1);+ expect(mockLoginController).toHaveBeenCalledTimes(1);+ });++ it('accepts a 2FA submission from the configured client origin', async () => {+ await request(app)+ .post('/api/auth/2fa/verify-temp')+ .set('Host', 'api.example.com')+ .set('Sec-Fetch-Site', 'same-site')+ .set('Origin', APP_ORIGIN)+ .send({ tempToken: 'temp-token', token: '123456' })+ .expect(204);++ expect(mockVerify2FAWithTempToken).toHaveBeenCalledTimes(1);+ });++ it('accepts a login posted from the configured admin panel origin', async () => {+ await request(app)+ .post('/api/auth/login')+ .set('Host', 'chat.example.com')+ .set('Sec-Fetch-Site', 'same-site')+ .set('Origin', ADMIN_PANEL_ORIGIN)+ .send({ email: '[email protected]', password: 'password' })+ .expect(204);++ expect(mockLoginController).toHaveBeenCalledTimes(1);+ });++ it('accepts a server-side client that sends no browser headers', async () => {+ await request(app)+ .post('/api/auth/login')+ .send({ email: '[email protected]', password: 'password' })+ .expect(204);++ expect(mockLoginController).toHaveBeenCalledTimes(1);+ });+});diff --git a/api/server/routes/auth.js b/api/server/routes/auth.jsindex 6c942dff7b..99a2094492 100644--- a/api/server/routes/auth.js+++ b/api/server/routes/auth.js@@ -43,6 +43,7 @@ router.post('/logout', middleware.requireJwtAuth, logoutController);router.post('/login',middleware.logHeaders,+ middleware.requireSameOrigin,middleware.loginLimiter,middleware.checkBan,middleware.validateEmailLogin,@@ -91,6 +92,7 @@ router.post('/2fa/enable', middleware.requireJwtAuth, enable2FA);router.post('/2fa/verify', middleware.requireJwtAuth, verify2FA);router.post('/2fa/verify-temp',+ middleware.requireSameOrigin,middleware.setTwoFactorTempUser,middleware.twoFactorTempLimiter,middleware.checkBan,diff --git a/api/server/routes/auth.reset-password-ratelimit.test.js b/api/server/routes/auth.reset-password-ratelimit.test.jsindex 7d49576d7c..5aeebef408 100644--- a/api/server/routes/auth.reset-password-ratelimit.test.js+++ b/api/server/routes/auth.reset-password-ratelimit.test.js@@ -52,6 +52,7 @@ jest.mock('~/server/middleware', () => {const pass = (req, res, next) => next();return {logHeaders: pass,+ requireSameOrigin: pass,loginLimiter: pass,setTwoFactorTempUser: pass,twoFactorTempLimiter: pass,diff --git a/api/server/routes/oauth.js b/api/server/routes/oauth.jsindex 2d87bb43a0..710fac1c63 100644--- a/api/server/routes/oauth.js+++ b/api/server/routes/oauth.js@@ -81,7 +81,6 @@ router.get('/google/callback',passport.authenticate('google', {failureRedirect: `${domains.client}/oauth/error`,- failureMessage: true,session: false,scope: ['openid', 'profile', 'email'],}),@@ -106,7 +105,6 @@ router.get('/facebook/callback',passport.authenticate('facebook', {failureRedirect: `${domains.client}/oauth/error`,- failureMessage: true,session: false,scope: ['public_profile'],profileFields: ['id', 'email', 'name'],@@ -149,7 +147,6 @@ router.get('/github/callback',passport.authenticate('github', {failureRedirect: `${domains.client}/oauth/error`,- failureMessage: true,session: false,scope: ['user:email', 'read:user'],}),@@ -173,7 +170,6 @@ router.get('/discord/callback',passport.authenticate('discord', {failureRedirect: `${domains.client}/oauth/error`,- failureMessage: true,session: false,scope: ['identify', 'email'],}),@@ -196,7 +192,6 @@ router.post('/apple/callback',passport.authenticate('apple', {failureRedirect: `${domains.client}/oauth/error`,- failureMessage: true,session: false,}),setBalanceConfig,diff --git a/api/server/routes/oauth.state.test.js b/api/server/routes/oauth.state.test.jsnew file mode 100644index 0000000000..2f44059870--- /dev/null+++ b/api/server/routes/oauth.state.test.js@@ -0,0 +1,363 @@+const express = require('express');+const request = require('supertest');+const passport = require('passport');+const cookieParser = require('cookie-parser');++jest.mock('@librechat/data-schemas', () => ({+ ...jest.requireActual('@librechat/data-schemas'),+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}));++jest.mock('~/server/services/Config', () => ({+ getAppConfig: jest.fn().mockResolvedValue({}),+}));++jest.mock('~/models', () => ({+ findUser: jest.fn(),+ updateUser: jest.fn(),+ findBalanceByUser: jest.fn(),+ upsertBalanceFields: jest.fn(),+}));++jest.mock('~/strategies/process', () => ({+ createSocialUser: jest.fn(),+ handleExistingUser: jest.fn().mockResolvedValue(undefined),+}));++jest.mock('~/server/middleware', () => ({+ logHeaders: (req, res, next) => next(),+ loginLimiter: (req, res, next) => next(),+ markOAuthNavigation: (req, res, next) => next(),+ checkDomainAllowed: (req, res, next) => next(),+}));++jest.mock('~/server/controllers/auth/oauth', () => ({+ createOAuthHandler: () => (req, res) => res.status(200).json({ userId: req.user._id }),+}));++const ORIGINAL_ENV = process.env;+const APP_URL = 'https://chat.example.com';++/** Splits a `Set-Cookie` header into its name, value and lower-cased attributes. */+function parseSetCookie(header) {+ const [pair, ...attributes] = header.split(';').map((part) => part.trim());+ const separator = pair.indexOf('=');+ return {+ name: pair.slice(0, separator),+ value: decodeURIComponent(pair.slice(separator + 1)),+ attributes: attributes.map((attribute) => attribute.toLowerCase()),+ };+}++function getStateCookie(response, provider) {+ const headers = response.headers['set-cookie'] ?? [];+ return headers+ .map(parseSetCookie)+ .find(({ name }) => name.startsWith(`__Host-oauth_state_${provider}.`));+}++/** The `name=value` pair a browser sends back for a cookie the server set. */+const asCookie = ({ name, value }) => `${name}=${value}`;++const stateLocation = (response) => new URL(response.headers.location).searchParams.get('state');+const BINDING_PATTERN = /^[A-Za-z0-9_-]{43}$/;++describe('OAuth login state binding', () => {+ let app;+ let github;+ let apple;+ let findUser;++ beforeAll(() => {+ process.env = {+ ...ORIGINAL_ENV,+ DOMAIN_CLIENT: APP_URL,+ DOMAIN_SERVER: APP_URL,+ GITHUB_CLIENT_ID: 'github-client',+ GITHUB_CLIENT_SECRET: 'github-secret',+ GITHUB_CALLBACK_URL: '/oauth/github/callback',+ APPLE_CLIENT_ID: 'apple-client',+ APPLE_TEAM_ID: 'apple-team',+ APPLE_KEY_ID: 'apple-key',+ APPLE_PRIVATE_KEY_PATH: '/nonexistent/apple.p8',+ APPLE_CALLBACK_URL: '/oauth/apple/callback',+ };++ const githubStrategy = require('~/strategies/githubStrategy');+ const appleStrategy = require('~/strategies/appleStrategy');+ ({ findUser } = require('~/models'));++ const stateOptions = { secret: 'jwt-secret', secureCookie: true };+ github = githubStrategy(stateOptions);+ apple = appleStrategy(stateOptions);+ passport.use(github);+ passport.use(apple);++ app = express();+ app.use(express.urlencoded({ extended: true }));+ app.use(cookieParser());+ app.use(passport.initialize());+ app.use('/oauth', require('./oauth'));+ app.use((err, req, res, _next) => res.status(500).json({ message: err.message }));+ });++ afterAll(() => {+ passport.unuse('github');+ passport.unuse('apple');+ process.env = ORIGINAL_ENV;+ });++ beforeEach(() => {+ jest.clearAllMocks();+ github._oauth2.getOAuthAccessToken = jest.fn((code, params, callback) =>+ callback(null, 'provider-access-token', 'provider-refresh-token', {}),+ );+ github.userProfile = jest.fn((accessToken, done) =>+ done(null, {+ id: '42',+ username: 'user',+ displayName: 'User',+ emails: [{ value: '[email protected]', verified: true }],+ photos: [{ value: 'https://avatars.example.com/42' }],+ }),+ );+ apple._oauth2.getOAuthAccessToken = jest.fn((code, params, callback) =>+ callback(new Error('token exchange reached')),+ );+ findUser.mockResolvedValue({+ _id: 'user-1',+ provider: 'github',+ githubId: '42',+ email: '[email protected]',+ });+ });++ describe('GitHub', () => {+ it('signs the authorization state for a host-only binding cookie', async () => {+ const response = await request(app).get('/oauth/github').expect(302);++ const location = new URL(response.headers.location);+ const cookie = getStateCookie(response, 'github');++ expect(location.origin).toBe('https://github.com');+ expect(location.searchParams.get('state')).toBeTruthy();+ expect(cookie.value).toMatch(BINDING_PATTERN);+ expect(location.searchParams.get('state')).not.toContain(cookie.value);+ expect(cookie.attributes).toEqual(+ expect.arrayContaining(['httponly', 'secure', 'samesite=lax', 'path=/']),+ );+ expect(cookie.attributes).toContain('max-age=600');+ });++ it('issues a fresh state for every authorization request', async () => {+ const first = await request(app).get('/oauth/github').expect(302);+ const second = await request(app).get('/oauth/github').expect(302);++ expect(stateLocation(first)).not.toBe(stateLocation(second));+ });++ it('rejects a callback link from a browser that never started the flow', async () => {+ const otherFlow = await request(app).get('/oauth/github').expect(302);+ const otherState = new URL(otherFlow.headers.location).searchParams.get('state');++ const response = await request(app)+ .get('/oauth/github/callback')+ .query({ code: 'unrelated-code', state: otherState })+ .expect(302);++ expect(response.headers.location).toBe(`${APP_URL}/oauth/error`);+ expect(github._oauth2.getOAuthAccessToken).not.toHaveBeenCalled();+ expect(findUser).not.toHaveBeenCalled();+ });++ it('rejects a callback whose state belongs to a different flow', async () => {+ const ownFlow = await request(app).get('/oauth/github').expect(302);+ const otherFlow = await request(app).get('/oauth/github').expect(302);+ const ownCookie = getStateCookie(ownFlow, 'github');+ const otherState = new URL(otherFlow.headers.location).searchParams.get('state');++ const response = await request(app)+ .get('/oauth/github/callback')+ .set('Cookie', asCookie(ownCookie))+ .query({ code: 'unrelated-code', state: otherState })+ .expect(302);++ expect(response.headers.location).toBe(`${APP_URL}/oauth/error`);+ expect(github._oauth2.getOAuthAccessToken).not.toHaveBeenCalled();+ });++ it('rejects a callback that omits the state', async () => {+ const ownFlow = await request(app).get('/oauth/github').expect(302);+ const ownCookie = getStateCookie(ownFlow, 'github');++ const response = await request(app)+ .get('/oauth/github/callback')+ .set('Cookie', asCookie(ownCookie))+ .query({ code: 'unrelated-code' })+ .expect(302);++ expect(response.headers.location).toBe(`${APP_URL}/oauth/error`);+ expect(github._oauth2.getOAuthAccessToken).not.toHaveBeenCalled();+ });++ it('completes the login when the callback returns to the browser that started it', async () => {+ const flow = await request(app).get('/oauth/github').expect(302);+ const cookie = getStateCookie(flow, 'github');+ const state = new URL(flow.headers.location).searchParams.get('state');++ const response = await request(app)+ .get('/oauth/github/callback')+ .set('Cookie', asCookie(cookie))+ .query({ code: 'own-code', state })+ .expect(200);++ expect(response.body).toEqual({ userId: 'user-1' });+ expect(github._oauth2.getOAuthAccessToken).toHaveBeenCalledWith(+ 'own-code',+ expect.objectContaining({ redirect_uri: `${APP_URL}/oauth/github/callback` }),+ expect.any(Function),+ );++ expect(getStateCookie(response, 'github')).toBeUndefined();+ });++ it('still completes the pending login after an unrelated callback reaches the browser', async () => {+ const ownFlow = await request(app).get('/oauth/github').expect(302);+ const otherFlow = await request(app).get('/oauth/github').expect(302);+ const ownCookie = getStateCookie(ownFlow, 'github');++ const unrelated = await request(app)+ .get('/oauth/github/callback')+ .set('Cookie', asCookie(ownCookie))+ .query({ code: 'unrelated-code', state: stateLocation(otherFlow) })+ .expect(302);++ expect(unrelated.headers.location).toBe(`${APP_URL}/oauth/error`);+ expect(getStateCookie(unrelated, 'github')).toBeUndefined();++ await request(app)+ .get('/oauth/github/callback')+ .set('Cookie', asCookie(ownCookie))+ .query({ code: 'own-code', state: stateLocation(ownFlow) })+ .expect(200);++ expect(github._oauth2.getOAuthAccessToken).toHaveBeenCalledTimes(1);+ expect(github._oauth2.getOAuthAccessToken).toHaveBeenCalledWith(+ 'own-code',+ expect.any(Object),+ expect.any(Function),+ );+ });++ it('completes logins started in two tabs, in either order', async () => {+ const firstTab = await request(app).get('/oauth/github').expect(302);+ const secondTab = await request(app)+ .get('/oauth/github')+ .set('Cookie', asCookie(getStateCookie(firstTab, 'github')))+ .expect(302);+ const binding = asCookie(getStateCookie(secondTab, 'github'));++ expect(binding).toBe(asCookie(getStateCookie(firstTab, 'github')));++ await request(app)+ .get('/oauth/github/callback')+ .set('Cookie', binding)+ .query({ code: 'first-code', state: stateLocation(firstTab) })+ .expect(200);++ await request(app)+ .get('/oauth/github/callback')+ .set('Cookie', binding)+ .query({ code: 'second-code', state: stateLocation(secondTab) })+ .expect(200);++ expect(github._oauth2.getOAuthAccessToken).toHaveBeenCalledTimes(2);+ });++ it('completes both logins when two tabs start before either has a binding', async () => {+ const [firstTab, secondTab] = await Promise.all([+ request(app).get('/oauth/github').expect(302),+ request(app).get('/oauth/github').expect(302),+ ]);+ const firstCookie = getStateCookie(firstTab, 'github');+ const secondCookie = getStateCookie(secondTab, 'github');+ const browserCookies = `${asCookie(firstCookie)}; ${asCookie(secondCookie)}`;++ expect(firstCookie.name).not.toBe(secondCookie.name);++ for (const [tab, code] of [+ [secondTab, 'second-code'],+ [firstTab, 'first-code'],+ ]) {+ await request(app)+ .get('/oauth/github/callback')+ .set('Cookie', browserCookies)+ .query({ code, state: stateLocation(tab) })+ .expect(200);+ }++ expect(github._oauth2.getOAuthAccessToken).toHaveBeenCalledTimes(2);+ });+ });++ describe('Apple', () => {+ it('stores a SameSite=None state cookie that survives the cross-site form_post callback', async () => {+ const response = await request(app).get('/oauth/apple').expect(302);++ const location = new URL(response.headers.location);+ const cookie = getStateCookie(response, 'apple');++ expect(location.origin).toBe('https://appleid.apple.com');+ expect(location.searchParams.get('response_mode')).toBe('form_post');+ expect(cookie.value).toMatch(BINDING_PATTERN);+ expect(location.searchParams.get('state')).not.toContain(cookie.value);+ expect(cookie.attributes).toEqual(+ expect.arrayContaining(['httponly', 'secure', 'samesite=none', 'path=/']),+ );+ });++ it('issues a fresh state for every authorization request', async () => {+ const first = await request(app).get('/oauth/apple').expect(302);+ const second = await request(app).get('/oauth/apple').expect(302);++ const firstState = new URL(first.headers.location).searchParams.get('state');+ const secondState = new URL(second.headers.location).searchParams.get('state');++ expect(firstState).not.toBe(secondState);+ expect(getStateCookie(second, 'apple').value).toMatch(BINDING_PATTERN);+ });++ it('rejects a form_post callback from a browser that never started the flow', async () => {+ const otherFlow = await request(app).get('/oauth/apple').expect(302);+ const otherState = new URL(otherFlow.headers.location).searchParams.get('state');++ const response = await request(app)+ .post('/oauth/apple/callback')+ .type('form')+ .send({ code: 'unrelated-code', state: otherState })+ .expect(302);++ expect(response.headers.location).toBe(`${APP_URL}/oauth/error`);+ expect(apple._oauth2.getOAuthAccessToken).not.toHaveBeenCalled();+ });++ it('exchanges the code when the form_post returns to the browser that started the flow', async () => {+ const flow = await request(app).get('/oauth/apple').expect(302);+ const cookie = getStateCookie(flow, 'apple');+ const state = new URL(flow.headers.location).searchParams.get('state');++ await request(app)+ .post('/oauth/apple/callback')+ .set('Cookie', asCookie(cookie))+ .type('form')+ .send({ code: 'own-code', state })+ .expect(500);++ expect(apple._oauth2.getOAuthAccessToken).toHaveBeenCalledWith(+ 'own-code',+ expect.any(Object),+ expect.any(Function),+ );+ });+ });+});diff --git a/api/server/socialLogins.js b/api/server/socialLogins.jsindex f4d088e6d0..8da813f240 100644--- a/api/server/socialLogins.js+++ b/api/server/socialLogins.js@@ -74,28 +74,34 @@ async function configureOpenId(app) {/**** @param {Express.Application} app+ * @param {AppConfig} [appConfig] - Base app config, read for the social login state lifetime.*/-const configureSocialLogins = async (app) => {+const configureSocialLogins = async (app, appConfig) => {logger.info('Configuring social logins...');+ const stateOptions = {+ secret: process.env.JWT_SECRET,+ secureCookie: shouldUseSecureCookie(),+ maxAgeMs: appConfig?.registration?.oauthStateTtlMs,+ };if (process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET) {- passport.use(googleLogin());+ passport.use(googleLogin(stateOptions));passport.use('googleAdmin', googleAdminLogin());}if (process.env.FACEBOOK_CLIENT_ID && process.env.FACEBOOK_CLIENT_SECRET) {- passport.use(facebookLogin());+ passport.use(facebookLogin(stateOptions));passport.use('facebookAdmin', facebookAdminLogin());}if (process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET) {- passport.use(githubLogin());+ passport.use(githubLogin(stateOptions));passport.use('githubAdmin', githubAdminLogin());}if (process.env.DISCORD_CLIENT_ID && process.env.DISCORD_CLIENT_SECRET) {- passport.use(discordLogin());+ passport.use(discordLogin(stateOptions));passport.use('discordAdmin', discordAdminLogin());}if (process.env.APPLE_CLIENT_ID && process.env.APPLE_PRIVATE_KEY_PATH) {- passport.use(appleLogin());+ passport.use(appleLogin(stateOptions));passport.use('appleAdmin', appleAdminLogin());}if (diff --git a/api/server/socialLogins.spec.js b/api/server/socialLogins.spec.jsindex bf016a43eb..c4bd4b8bd4 100644--- a/api/server/socialLogins.spec.js+++ b/api/server/socialLogins.spec.js@@ -141,3 +141,49 @@ describe('configureSocialLogins OpenID session expiry', () => {expect(mockPassportUse).not.toHaveBeenCalled();});});++describe('configureSocialLogins OAuth state options', () => {+ const ORIGINAL_ENV = process.env;++ beforeEach(() => {+ jest.clearAllMocks();+ process.env = {+ JWT_SECRET: 'jwt-secret',+ GITHUB_CLIENT_ID: 'github-client',+ GITHUB_CLIENT_SECRET: 'github-secret',+ APPLE_CLIENT_ID: 'apple-client',+ APPLE_PRIVATE_KEY_PATH: '/keys/apple.p8',+ };+ mockIsEnabled.mockReturnValue(false);+ });++ afterAll(() => {+ process.env = ORIGINAL_ENV;+ });++ it('passes the cookie security setting and configured state lifetime to user strategies', async () => {+ const strategies = require('~/strategies');+ const app = { use: jest.fn() };++ await configureSocialLogins(app, { registration: { oauthStateTtlMs: 120000 } });++ const expected = { secret: 'jwt-secret', secureCookie: true, maxAgeMs: 120000 };+ expect(strategies.githubLogin).toHaveBeenCalledWith(expected);+ expect(strategies.appleLogin).toHaveBeenCalledWith(expected);+ expect(strategies.githubAdminLogin).toHaveBeenCalledWith();+ expect(strategies.appleAdminLogin).toHaveBeenCalledWith();+ });++ it('leaves the state lifetime to the store default when the config omits it', async () => {+ const strategies = require('~/strategies');+ mockShouldUseSecureCookie.mockReturnValueOnce(false);++ await configureSocialLogins({ use: jest.fn() });++ expect(strategies.githubLogin).toHaveBeenCalledWith({+ secret: 'jwt-secret',+ secureCookie: false,+ maxAgeMs: undefined,+ });+ });+});diff --git a/api/strategies/appleStrategy.js b/api/strategies/appleStrategy.jsindex 6eace87bae..398c3fd9ab 100644--- a/api/strategies/appleStrategy.js+++ b/api/strategies/appleStrategy.js@@ -1,6 +1,7 @@const jwt = require('jsonwebtoken');const { logger } = require('@librechat/data-schemas');const { Strategy: AppleStrategy } = require('passport-apple');+const { createOAuthStateStore, deferStateToStore } = require('@librechat/api');const socialLogin = require('./socialLogin');/**@@ -45,11 +46,21 @@ const getAppleConfig = (callbackURL) => ({passReqToCallback: false,});-const appleStrategy = () =>- new AppleStrategy(- getAppleConfig(`${process.env.DOMAIN_SERVER}${process.env.APPLE_CALLBACK_URL}`),+/**+ * Apple returns with a cross-site form POST, so its state cookie must be `SameSite=None`.+ * @param {Omit<import('@librechat/api').OAuthStateStoreOptions, 'provider'>} stateOptions+ */+const appleStrategy = (stateOptions) => {+ const strategy = new AppleStrategy(+ {+ ...getAppleConfig(`${process.env.DOMAIN_SERVER}${process.env.APPLE_CALLBACK_URL}`),+ store: createOAuthStateStore({ ...stateOptions, provider: 'apple', crossSiteCallback: true }),+ },appleLogin,);+ deferStateToStore(strategy);+ return strategy;+};const appleAdminStrategy = () =>new AppleStrategy(diff --git a/api/strategies/discordStrategy.js b/api/strategies/discordStrategy.jsindex 7fb68280d5..2f91996d37 100644--- a/api/strategies/discordStrategy.js+++ b/api/strategies/discordStrategy.js@@ -1,4 +1,5 @@const { Strategy: DiscordStrategy } = require('passport-discord');+const { createOAuthStateStore } = require('@librechat/api');const socialLogin = require('./socialLogin');const getProfileDetails = ({ profile }) => {@@ -32,9 +33,13 @@ const getDiscordConfig = (callbackURL) => ({authorizationURL: 'https://discord.com/api/oauth2/authorize?prompt=none',});-const discordStrategy = () =>+/** @param {Omit<import('@librechat/api').OAuthStateStoreOptions, 'provider'>} stateOptions */+const discordStrategy = (stateOptions) =>new DiscordStrategy(- getDiscordConfig(`${process.env.DOMAIN_SERVER}${process.env.DISCORD_CALLBACK_URL}`),+ {+ ...getDiscordConfig(`${process.env.DOMAIN_SERVER}${process.env.DISCORD_CALLBACK_URL}`),+ store: createOAuthStateStore({ ...stateOptions, provider: 'discord' }),+ },discordLogin,);diff --git a/api/strategies/facebookStrategy.js b/api/strategies/facebookStrategy.jsindex f638c3bfdb..6191b13c6c 100644--- a/api/strategies/facebookStrategy.js+++ b/api/strategies/facebookStrategy.js@@ -1,4 +1,5 @@const FacebookStrategy = require('passport-facebook').Strategy;+const { createOAuthStateStore } = require('@librechat/api');const socialLogin = require('./socialLogin');const getProfileDetails = ({ profile }) => ({@@ -22,9 +23,13 @@ const getFacebookConfig = (callbackURL) => ({profileFields: ['id', 'email', 'name'],});-const facebookStrategy = () =>+/** @param {Omit<import('@librechat/api').OAuthStateStoreOptions, 'provider'>} stateOptions */+const facebookStrategy = (stateOptions) =>new FacebookStrategy(- getFacebookConfig(`${process.env.DOMAIN_SERVER}${process.env.FACEBOOK_CALLBACK_URL}`),+ {+ ...getFacebookConfig(`${process.env.DOMAIN_SERVER}${process.env.FACEBOOK_CALLBACK_URL}`),+ store: createOAuthStateStore({ ...stateOptions, provider: 'facebook' }),+ },facebookLogin,);diff --git a/api/strategies/githubStrategy.js b/api/strategies/githubStrategy.jsindex 363acbfcdb..b0cb9ef679 100644--- a/api/strategies/githubStrategy.js+++ b/api/strategies/githubStrategy.js@@ -1,4 +1,5 @@const { Strategy: GitHubStrategy } = require('passport-github2');+const { createOAuthStateStore } = require('@librechat/api');const socialLogin = require('./socialLogin');const getProfileDetails = ({ profile }) => ({@@ -30,9 +31,13 @@ const getGitHubConfig = (callbackURL) => ({}),});-const githubStrategy = () =>+/** @param {Omit<import('@librechat/api').OAuthStateStoreOptions, 'provider'>} stateOptions */+const githubStrategy = (stateOptions) =>new GitHubStrategy(- getGitHubConfig(`${process.env.DOMAIN_SERVER}${process.env.GITHUB_CALLBACK_URL}`),+ {+ ...getGitHubConfig(`${process.env.DOMAIN_SERVER}${process.env.GITHUB_CALLBACK_URL}`),+ store: createOAuthStateStore({ ...stateOptions, provider: 'github' }),+ },githubLogin,);diff --git a/api/strategies/googleStrategy.js b/api/strategies/googleStrategy.jsindex bee9a061a2..a616ef2502 100644--- a/api/strategies/googleStrategy.js+++ b/api/strategies/googleStrategy.js@@ -1,4 +1,5 @@const { Strategy: GoogleStrategy } = require('passport-google-oauth20');+const { createOAuthStateStore } = require('@librechat/api');const socialLogin = require('./socialLogin');const getProfileDetails = ({ profile }) => ({@@ -20,9 +21,13 @@ const getGoogleConfig = (callbackURL) => ({proxy: true,});-const googleStrategy = () =>+/** @param {Omit<import('@librechat/api').OAuthStateStoreOptions, 'provider'>} stateOptions */+const googleStrategy = (stateOptions) =>new GoogleStrategy(- getGoogleConfig(`${process.env.DOMAIN_SERVER}${process.env.GOOGLE_CALLBACK_URL}`),+ {+ ...getGoogleConfig(`${process.env.DOMAIN_SERVER}${process.env.GOOGLE_CALLBACK_URL}`),+ store: createOAuthStateStore({ ...stateOptions, provider: 'google' }),+ },googleLogin,);diff --git a/client/src/common/types.ts b/client/src/common/types.tsindex d7e2a81a24..ed041c425b 100644--- a/client/src/common/types.ts+++ b/client/src/common/types.ts@@ -491,7 +491,7 @@ export type ToolDialogProps = {};export type TResError = {- response: { data: { message: string } };+ response: { data: { message: string; code?: string } };message: string;};diff --git a/client/src/components/Auth/TwoFactorScreen.tsx b/client/src/components/Auth/TwoFactorScreen.tsxindex 0166f89770..7cd073eca5 100644--- a/client/src/components/Auth/TwoFactorScreen.tsx+++ b/client/src/components/Auth/TwoFactorScreen.tsx@@ -1,6 +1,7 @@import React, { useState, useCallback } from 'react';import { useSearchParams } from 'react-router-dom';import { useToastContext } from '@librechat/client';+import { ErrorTypes } from 'librechat-data-provider';import { useForm, Controller } from 'react-hook-form';import { REGEXP_ONLY_DIGITS, REGEXP_ONLY_DIGITS_AND_CHARS } from 'input-otp';import {@@ -50,11 +51,13 @@ const TwoFactorScreen: React.FC = React.memo(() => {},onError: (error: unknown) => {setIsLoading(false);- const err = error as { response?: { data?: { message?: unknown } } };- const errorMsg =- typeof err.response?.data?.message === 'string'- ? err.response.data.message- : 'Error verifying 2FA';+ const data = (error as { response?: { data?: { message?: unknown; code?: unknown } } })+ .response?.data;+ if (data?.code === ErrorTypes.AUTH_CROSS_ORIGIN) {+ showToast({ message: localize('com_auth_error_login_cross_origin'), status: 'error' });+ return;+ }+ const errorMsg = typeof data?.message === 'string' ? data.message : 'Error verifying 2FA';showToast({ message: errorMsg, status: 'error' });},});diff --git a/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsx b/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsxnew file mode 100644index 0000000000..215df2ced8--- /dev/null+++ b/client/src/components/Auth/__tests__/TwoFactorScreen.spec.tsx@@ -0,0 +1,70 @@+import { MemoryRouter } from 'react-router-dom';+import { act, render } from '@testing-library/react';+import { ErrorTypes } from 'librechat-data-provider';+import TwoFactorScreen from '../TwoFactorScreen';++const mockShowToast = jest.fn();+let mockVerifyOptions: { onError: (error: unknown) => void } | undefined;++jest.mock('@librechat/client', () => ({+ ...jest.requireActual('@librechat/client'),+ useToastContext: () => ({ showToast: mockShowToast }),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++jest.mock('~/data-provider', () => ({+ useVerifyTwoFactorTempMutation: (options: { onError: (error: unknown) => void }) => {+ mockVerifyOptions = options;+ return { mutate: jest.fn() };+ },+}));++function renderScreen() {+ render(+ <MemoryRouter initialEntries={['/login/2fa?tempToken=temp-token']}>+ <TwoFactorScreen />+ </MemoryRouter>,+ );+}++describe('TwoFactorScreen verification errors', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockVerifyOptions = undefined;+ });++ it('shows a localized message when the server rejects a cross-origin submission', () => {+ renderScreen();++ act(() => {+ mockVerifyOptions?.onError({+ response: {+ data: { message: 'Cross-site request rejected', code: ErrorTypes.AUTH_CROSS_ORIGIN },+ },+ });+ });++ expect(mockShowToast).toHaveBeenCalledWith({+ message: 'com_auth_error_login_cross_origin',+ status: 'error',+ });+ });++ it('keeps showing the server message for other verification failures', () => {+ renderScreen();++ act(() => {+ mockVerifyOptions?.onError({+ response: { data: { message: 'Invalid 2FA code or backup code' } },+ });+ });++ expect(mockShowToast).toHaveBeenCalledWith({+ message: 'Invalid 2FA code or backup code',+ status: 'error',+ });+ });+});diff --git a/client/src/hooks/AuthContext.tsx b/client/src/hooks/AuthContext.tsxindex c21eadcd22..5ed99b72f5 100644--- a/client/src/hooks/AuthContext.tsx+++ b/client/src/hooks/AuthContext.tsx@@ -13,6 +13,7 @@ import { useNavigate } from 'react-router-dom';import { useRecoilState, useSetRecoilState } from 'recoil';import {apiBaseUrl,+ ErrorTypes,SystemRoles,setTokenHeader,isSystemRoleName,@@ -146,7 +147,8 @@ const AuthContextProvider = ({},onError: (error: TResError | unknown) => {const resError = error as TResError;- doSetError(resError.message);+ const code = resError.response?.data?.code;+ doSetError(code === ErrorTypes.AUTH_CROSS_ORIGIN ? code : resError.message);// Preserve a valid redirect_to across login failures so the deep link survives retries.// Cannot use buildLoginRedirectUrl() here — it reads the current pathname (already /login)// and would return plain /login, dropping the redirect_to destination.diff --git a/client/src/hooks/__tests__/AuthContext.spec.tsx b/client/src/hooks/__tests__/AuthContext.spec.tsxindex 28ee520c27..85d9fc6b2b 100644--- a/client/src/hooks/__tests__/AuthContext.spec.tsx+++ b/client/src/hooks/__tests__/AuthContext.spec.tsx@@ -81,6 +81,7 @@ function TestConsumer() {data-testid="consumer"data-authenticated={ctx.isAuthenticated}data-auth-ready={ctx.isAuthReady}+ data-error={ctx.error ?? ''}data-roles={JSON.stringify(ctx.roles ?? {})}/>);@@ -212,6 +213,41 @@ describe('AuthContextProvider — login onError redirect handling', () => {expect(mockNavigate).toHaveBeenCalledWith('/login', { replace: true });});+ it('surfaces the cross-origin rejection code instead of the HTTP status message', () => {+ jest.useFakeTimers();+ const { getByTestId } = renderProvider();++ act(() => {+ mockCapturedLoginOptions.onError({+ message: 'Request failed with status code 403',+ response: { data: { message: 'Cross-site request rejected', code: 'auth_cross_origin' } },+ });+ jest.advanceTimersByTime(400);+ });++ expect(getByTestId('consumer')).toHaveAttribute('data-error', 'auth_cross_origin');+ jest.useRealTimers();+ });++ it('keeps the HTTP status message for other rejections that carry a code', () => {+ jest.useFakeTimers();+ const { getByTestId } = renderProvider();++ act(() => {+ mockCapturedLoginOptions.onError({+ message: 'Request failed with status code 429',+ response: { data: { message: 'Too many login attempts', code: 'something_else' } },+ });+ jest.advanceTimersByTime(400);+ });++ expect(getByTestId('consumer')).toHaveAttribute(+ 'data-error',+ 'Request failed with status code 429',+ );+ jest.useRealTimers();+ });+it('preserves redirect_to with query params and hash', () => {const target = '/c/abc123?model=gpt-4#section';window.history.replaceState({}, '', `/login?redirect_to=${encodeURIComponent(target)}`);diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 018d3f4925..75bd3c872f 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -224,6 +224,7 @@"com_auth_error_invalid_reset_token": "This password reset token is no longer valid.","com_auth_error_login": "Unable to login with the information provided. Please check your credentials and try again.","com_auth_error_login_ban": "Your account has been temporarily banned due to violations of our service.",+ "com_auth_error_login_cross_origin": "Sign-in was blocked because the request did not come from this site. Open the login page directly and try again.","com_auth_error_login_rl": "Too many login attempts in a short amount of time. Please try again later.","com_auth_error_login_server": "There was an internal server error. Please wait a few moments and try again.","com_auth_error_login_unverified": "Your account has not been verified. Please check your email for a verification link.",diff --git a/client/src/utils/getLoginError.spec.ts b/client/src/utils/getLoginError.spec.tsnew file mode 100644index 0000000000..0b34fa4901--- /dev/null+++ b/client/src/utils/getLoginError.spec.ts@@ -0,0 +1,16 @@+import { ErrorTypes } from 'librechat-data-provider';+import getLoginError from './getLoginError';++describe('getLoginError', () => {+ it.each([+ [ErrorTypes.AUTH_CROSS_ORIGIN, 'com_auth_error_login_cross_origin'],+ ['Request failed with status code 403', 'com_auth_error_login_ban'],+ ['Request failed with status code 429', 'com_auth_error_login_rl'],+ ['Request failed with status code 422', 'com_auth_error_login_unverified'],+ ['Request failed with status code 500', 'com_auth_error_login_server'],+ ['Request failed with status code 401', 'com_auth_error_login'],+ ['', 'com_auth_error_login'],+ ])('maps %p to %p', (errorText, key) => {+ expect(getLoginError(errorText)).toBe(key);+ });+});diff --git a/client/src/utils/getLoginError.ts b/client/src/utils/getLoginError.tsindex 492948d6e6..602c6dfc85 100644--- a/client/src/utils/getLoginError.ts+++ b/client/src/utils/getLoginError.ts@@ -1,3 +1,4 @@+import { ErrorTypes } from 'librechat-data-provider';import { TranslationKeys } from '~/hooks';const getLoginError = (errorText: string): TranslationKeys => {@@ -8,6 +9,8 @@ const getLoginError = (errorText: string): TranslationKeys => {}switch (true) {+ case errorText === ErrorTypes.AUTH_CROSS_ORIGIN:+ return 'com_auth_error_login_cross_origin';case errorText.includes('429'):return 'com_auth_error_login_rl';case errorText.includes('403'):diff --git a/librechat.example.yaml b/librechat.example.yamlindex dedcf23d31..928588d234 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -344,6 +344,8 @@ registration:socialLogins: ['github', 'google', 'discord', 'openid', 'facebook', 'apple', 'saml']# allowedDomains:# - "gmail.com"+ # How long a started social login may take to return from the provider (ms, default 600000)+ # oauthStateTtlMs: 600000# Example Balance settings# balance:diff --git a/packages/api/src/middleware/index.ts b/packages/api/src/middleware/index.tsindex d91596c25a..7d161ca404 100644--- a/packages/api/src/middleware/index.ts+++ b/packages/api/src/middleware/index.ts@@ -3,6 +3,7 @@ export * from './admin';export * from './error';export * from './email';export * from './notFound';+export * from './origin';export * from './balance';export * from './json';export * from './capabilities';diff --git a/packages/api/src/middleware/origin.spec.ts b/packages/api/src/middleware/origin.spec.tsnew file mode 100644index 0000000000..83b2d9d874--- /dev/null+++ b/packages/api/src/middleware/origin.spec.ts@@ -0,0 +1,182 @@+import express from 'express';+import request from 'supertest';+import { logger } from '@librechat/data-schemas';+import { ErrorTypes } from 'librechat-data-provider';+import { createSameOriginGuard } from './origin';++jest.mock('@librechat/data-schemas', () => ({+ ...jest.requireActual('@librechat/data-schemas'),+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}));++const HOST = 'chat.example.com';++function createApp(trustedOrigins: Array<string | undefined> = []) {+ const handler = jest.fn((_req: express.Request, res: express.Response) => {+ res.status(204).end();+ });+ const app = express();+ app.set('trust proxy', true);+ app.post('/api/auth/login', createSameOriginGuard({ trustedOrigins }), handler);+ return { app, handler };+}++describe('createSameOriginGuard', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it.each(['same-origin', 'none'])('passes a browser request labelled %s', async (fetchSite) => {+ const { app, handler } = createApp();++ await request(app)+ .post('/api/auth/login')+ .set('Host', HOST)+ .set('Sec-Fetch-Site', fetchSite)+ .expect(204);++ expect(handler).toHaveBeenCalledTimes(1);+ });++ it.each(['cross-site', 'same-site'])(+ 'rejects a browser request labelled %s from an untrusted origin',+ async (fetchSite) => {+ const { app, handler } = createApp(['https://chat.example.com']);++ const response = await request(app)+ .post('/api/auth/login')+ .set('Host', HOST)+ .set('Sec-Fetch-Site', fetchSite)+ .set('Origin', 'https://other-site.example.com')+ .type('form')+ .send({ email: '[email protected]', password: 'secret' })+ .expect(403);++ expect(response.body).toEqual({+ message: 'Cross-site request rejected',+ code: ErrorTypes.AUTH_CROSS_ORIGIN,+ });+ expect(response.headers['set-cookie']).toBeUndefined();+ expect(handler).not.toHaveBeenCalled();+ expect(logger.warn).toHaveBeenCalledWith(+ '[requireSameOrigin] Rejected cross-site request',+ expect.objectContaining({+ method: 'POST',+ path: '/api/auth/login',+ fetch_site: fetchSite,+ origin: 'https://other-site.example.com',+ }),+ );+ },+ );++ it('passes a cross-origin request from a trusted origin', async () => {+ const { app, handler } = createApp(['https://client.example.com/app/', undefined]);++ await request(app)+ .post('/api/auth/login')+ .set('Host', HOST)+ .set('Sec-Fetch-Site', 'same-site')+ .set('Origin', 'https://client.example.com')+ .expect(204);++ expect(handler).toHaveBeenCalledTimes(1);+ });++ // Node's HTTP parser strips control characters before they reach Express, so the guard is+ // driven directly here to prove the log-sanitization branch neutralizes them anyway.+ it('strips control characters from request-derived values before logging', () => {+ const guard = createSameOriginGuard({ trustedOrigins: [] });+ const headers: Record<string, string> = {+ origin: 'https://evil.example.com\r\ninjected: 1',+ 'sec-fetch-site': 'cross-site',+ host: HOST,+ };+ const req = {+ method: 'POST',+ baseUrl: '/api/auth',+ path: `/login\r\n${String.fromCharCode(0)}`,+ get: (name: string) => headers[name.toLowerCase()],+ } as unknown as express.Request;+ const res = {+ status: jest.fn().mockReturnThis(),+ json: jest.fn(),+ } as unknown as express.Response;+ const next = jest.fn();++ guard(req, res, next);++ expect(next).not.toHaveBeenCalled();+ const logged = (logger.warn as jest.Mock).mock.calls[0][1];+ for (const field of [logged.origin, logged.path, logged.fetch_site] as string[]) {+ for (const code of [13, 10, 0]) {+ expect(field).not.toContain(String.fromCharCode(code));+ }+ }+ expect(logged.origin).toContain('__injected');+ });++ it('passes a request without browser fetch metadata or an Origin, such as a server-side call', async () => {+ const { app, handler } = createApp();++ await request(app).post('/api/auth/login').set('Host', HOST).expect(204);++ expect(handler).toHaveBeenCalledTimes(1);+ });++ describe('browsers that send Origin without Sec-Fetch-Site', () => {+ it('passes an Origin matching the scheme and Host the request was sent to', async () => {+ const { app, handler } = createApp();++ await request(app)+ .post('/api/auth/login')+ .set('Host', `${HOST}:443`)+ .set('X-Forwarded-Proto', 'https')+ .set('Origin', `https://${HOST}`)+ .expect(204);++ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('rejects an http Origin on the same host as an https request', async () => {+ const { app, handler } = createApp();++ await request(app)+ .post('/api/auth/login')+ .set('Host', HOST)+ .set('X-Forwarded-Proto', 'https')+ .set('Origin', `http://${HOST}`)+ .expect(403);++ expect(handler).not.toHaveBeenCalled();+ });++ it.each(['https://other-site.example.com', 'null', 'not a url'])(+ 'rejects Origin %s',+ async (origin) => {+ const { app, handler } = createApp();++ await request(app)+ .post('/api/auth/login')+ .set('Host', HOST)+ .set('Origin', origin)+ .expect(403);++ expect(handler).not.toHaveBeenCalled();+ },+ );++ it('rejects an Origin on another port of the same host', async () => {+ const { app, handler } = createApp();++ await request(app)+ .post('/api/auth/login')+ .set('Host', HOST)+ .set('X-Forwarded-Proto', 'https')+ .set('Origin', `https://${HOST}:8443`)+ .expect(403);++ expect(handler).not.toHaveBeenCalled();+ });+ });+});diff --git a/packages/api/src/middleware/origin.ts b/packages/api/src/middleware/origin.tsnew file mode 100644index 0000000000..5e648829c9--- /dev/null+++ b/packages/api/src/middleware/origin.ts@@ -0,0 +1,87 @@+import { logger } from '@librechat/data-schemas';+import { ErrorTypes } from 'librechat-data-provider';+import type { Request, RequestHandler } from 'express';++const SAME_ORIGIN_FETCH_SITES: ReadonlySet<string> = new Set(['same-origin', 'none']);+const MAX_LOGGED_HEADER_LENGTH = 200;+/** The `Origin` header is attacker-set on a non-browser request; strip ASCII control+ * characters (CR, LF, NUL and the rest) so a rejected request cannot forge a log line. */+// eslint-disable-next-line no-control-regex+const UNSAFE_LOG_CHARS = new RegExp('[\x00-\x1f\x7f]', 'g');++export interface SameOriginGuardOptions {+ /** Origins allowed to submit from another origin, such as `DOMAIN_CLIENT` and `DOMAIN_SERVER`. */+ trustedOrigins: ReadonlyArray<string | undefined>;+}++function toOrigin(value: string | undefined): string | undefined {+ if (!value) {+ return undefined;+ }+ try {+ const { origin } = new URL(value);+ return origin === 'null' ? undefined : origin;+ } catch {+ return undefined;+ }+}++/** The request's own origin: its scheme (honoring `trust proxy`) and the `Host` it was sent to. */+function matchesRequestOrigin(origin: string, req: Request): boolean {+ const host = req.get('host');+ return host != null && toOrigin(`${req.protocol}://${host}`) === origin;+}++/**+ * A browser labels every request with `Sec-Fetch-Site`, which a page cannot set. Browsers+ * predating it still send `Origin` on a form POST, compared here against the request's own+ * scheme and host. A request carrying neither header did not come from a browser page and passes.+ */+function isCrossSiteRequest(req: Request, trustedOrigins: ReadonlySet<string>): boolean {+ const originHeader = req.get('origin');+ const origin = toOrigin(originHeader);+ if (origin && trustedOrigins.has(origin)) {+ return false;+ }++ const fetchSite = req.get('sec-fetch-site');+ if (fetchSite) {+ return !SAME_ORIGIN_FETCH_SITES.has(fetchSite);+ }+ if (!originHeader) {+ return false;+ }+ return !origin || !matchesRequestOrigin(origin, req);+}++const sanitize = (value: string | undefined): string | undefined =>+ value?.replace(UNSAFE_LOG_CHARS, '_').slice(0, MAX_LOGGED_HEADER_LENGTH);++/**+ * Accepts a request only when the browser sent it from this application's own origin (or a+ * trusted one). Login endpoints set session cookies, so they should only honor submissions made+ * by the application's own pages.+ */+export function createSameOriginGuard({ trustedOrigins }: SameOriginGuardOptions): RequestHandler {+ const trusted: ReadonlySet<string> = new Set(+ trustedOrigins.flatMap((value) => toOrigin(value) ?? []),+ );++ return (req, res, next) => {+ if (!isCrossSiteRequest(req, trusted)) {+ next();+ return;+ }++ logger.warn('[requireSameOrigin] Rejected cross-site request', {+ method: req.method,+ path: sanitize(`${req.baseUrl}${req.path}`),+ fetch_site: sanitize(req.get('sec-fetch-site')),+ origin: sanitize(req.get('origin')),+ });+ res.status(403).json({+ message: 'Cross-site request rejected',+ code: ErrorTypes.AUTH_CROSS_ORIGIN,+ });+ };+}diff --git a/packages/api/src/oauth/index.ts b/packages/api/src/oauth/index.tsindex 40d1a18850..1101b5cde4 100644--- a/packages/api/src/oauth/index.ts+++ b/packages/api/src/oauth/index.ts@@ -1,4 +1,5 @@export * from './csrf';+export * from './state';export * from './expiry';export * from './callback';export * from './failure';diff --git a/packages/api/src/oauth/state.spec.ts b/packages/api/src/oauth/state.spec.tsnew file mode 100644index 0000000000..5b80b8b2cf--- /dev/null+++ b/packages/api/src/oauth/state.spec.ts@@ -0,0 +1,315 @@+import express from 'express';+import request from 'supertest';+import { logger } from '@librechat/data-schemas';+import { DEFAULT_OAUTH_STATE_TTL_MS } from 'librechat-data-provider';+import type { Request } from 'express';+import type { OAuthStateStore, OAuthStateStoreOptions, PresetStateStrategy } from './state';+import { createOAuthStateStore, deferStateToStore } from './state';++jest.mock('@librechat/data-schemas', () => ({+ ...jest.requireActual('@librechat/data-schemas'),+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}));++interface VerifyResult {+ ok: boolean;+ message?: string;+}++/** Mounts the store the way passport-oauth2 drives it: `store` on start, `verify` on callback. */+function createApp(options: OAuthStateStoreOptions) {+ const stateStore: OAuthStateStore = createOAuthStateStore(options);+ const app = express();+ app.use(express.urlencoded({ extended: true }));+ app.use((req, _res, next) => {+ const pairs = (req.get('cookie') ?? '').split(';').map((pair) => pair.trim().split('='));+ req.cookies = Object.fromEntries(pairs.filter(([name]) => name));+ next();+ });+ app.get('/start', (req, res, next) => {+ stateStore.store(req, (err, state) => (err ? next(err) : res.json({ state })));+ });+ const verify = (req: Request, res: express.Response, next: express.NextFunction) => {+ const providedState = req.query.state ?? req.body?.state;+ stateStore.verify(req, providedState, (err, ok, info) =>+ err ? next(err) : res.json({ ok, message: info?.message } satisfies VerifyResult),+ );+ };+ app.get('/oauth/github/callback', verify);+ app.post('/oauth/apple/callback', verify);+ return { app, stateStore };+}++/** The binding cookie a response set under `prefix` (`<prefix>.<id>`). */+function getSetCookie(response: request.Response, prefix: string): string | undefined {+ const headers = ([] as string[]).concat(response.headers['set-cookie'] ?? []);+ return headers.find((header) => header.startsWith(`${prefix}.`));+}++async function start(app: express.Express, prefix: string, cookie?: string) {+ const req = request(app).get('/start');+ const response = await (cookie ? req.set('Cookie', cookie) : req).expect(200);+ const header = getSetCookie(response, prefix);+ const pair = header?.split(';')[0] ?? '';+ const separator = pair.indexOf('=');+ return {+ state: response.body.state as string,+ /** The `name=value` pair a browser sends back. */+ cookie: pair,+ name: pair.slice(0, separator),+ binding: decodeURIComponent(pair.slice(separator + 1)),+ header,+ response,+ };+}++function callback(app: express.Express, cookie: string | undefined, state: string) {+ const req = request(app).get('/oauth/github/callback').query({ state });+ return (cookie ? req.set('Cookie', cookie) : req).expect(200);+}++const SECRET = 'state-signing-secret';+const PLAIN = 'oauth_state_github';+const github: OAuthStateStoreOptions = { provider: 'github', secret: SECRET, secureCookie: false };+const apple: OAuthStateStoreOptions = {+ provider: 'apple',+ secret: SECRET,+ secureCookie: false,+ crossSiteCallback: true,+};++describe('createOAuthStateStore', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it('issues a host-only SameSite=Lax binding cookie on insecure deployments', async () => {+ const { app } = createApp(github);++ const { state, binding, name, header: cookie } = await start(app, PLAIN);++ expect(name).toMatch(/^oauth_state_github\.[A-Za-z0-9_-]{8}$/);+ expect(binding).toMatch(/^[A-Za-z0-9_-]{43}$/);+ expect(state).toMatch(/^[0-9a-z]+\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}$/);+ expect(state).not.toContain(binding);+ expect(cookie).toContain(`Max-Age=${DEFAULT_OAUTH_STATE_TTL_MS / 1000}`);+ expect(cookie).toContain('Path=/;');+ expect(cookie).toContain('HttpOnly');+ expect(cookie).toContain('SameSite=Lax');+ expect(cookie).not.toContain('Secure');+ expect(cookie).not.toContain('Domain=');+ });++ it('uses a __Host- cookie, which a sibling subdomain cannot set, on secure deployments', async () => {+ const { app } = createApp({ ...github, secureCookie: true, maxAgeMs: 120_000 });++ const { response, header: cookie } = await start(app, '__Host-oauth_state_github');++ expect(cookie).toContain('Max-Age=120');+ expect(cookie).toContain('Path=/;');+ expect(cookie).toContain('Secure');+ expect(getSetCookie(response, PLAIN)).toBeUndefined();+ expect(response.headers['set-cookie']).toHaveLength(1);+ });++ it('ignores a plain-named binding on secure deployments', async () => {+ const { app } = createApp({ ...github, secureCookie: true });+ const { state, cookie } = await start(app, '__Host-oauth_state_github');++ const response = await callback(app, cookie.replace('__Host-', ''), state);++ expect(response.body).toEqual({+ ok: false,+ message: 'Unable to verify authorization request state.',+ });+ });++ it('marks a cross-site callback cookie SameSite=None and Secure, even on insecure deployments', async () => {+ const { app } = createApp(apple);++ const { header: cookie } = await start(app, '__Host-oauth_state_apple');++ expect(cookie).toContain('SameSite=None');+ expect(cookie).toContain('Secure');+ });++ it('accepts a state signed for this browser without rewriting the binding', async () => {+ const { app } = createApp(apple);+ const { state, cookie } = await start(app, '__Host-oauth_state_apple');++ const response = await request(app)+ .post('/oauth/apple/callback')+ .set('Cookie', cookie)+ .type('form')+ .send({ state })+ .expect(200);++ expect(response.body).toEqual({ ok: true });+ expect(response.headers['set-cookie']).toBeUndefined();+ });++ it('reuses the binding, so logins started in several tabs all complete', async () => {+ const { app } = createApp(github);+ const first = await start(app, PLAIN);+ const second = await start(app, PLAIN, first.cookie);+ const third = await start(app, PLAIN, second.cookie);++ expect(new Set([first.cookie, second.cookie, third.cookie]).size).toBe(1);+ expect(new Set([first.state, second.state, third.state]).size).toBe(3);++ for (const { state } of [second, first, third]) {+ const response = await callback(app, third.cookie, state);+ expect(response.body).toEqual({ ok: true });+ }+ });++ it('keeps a separate binding for each tab when first starts race', async () => {+ const { app } = createApp(github);+ const [first, second] = await Promise.all([start(app, PLAIN), start(app, PLAIN)]);+ const browserCookies = `${first.cookie}; ${second.cookie}`;++ expect(first.name).not.toBe(second.name);+ for (const { state } of [first, second]) {+ const response = await callback(app, browserCookies, state);+ expect(response.body).toEqual({ ok: true });+ }++ const later = await start(app, PLAIN, browserCookies);+ expect([first.cookie, second.cookie]).toContain(later.cookie);+ });++ it('rejects a state signed for a different browser', async () => {+ const { app } = createApp(github);+ const otherBrowser = await start(app, PLAIN);+ const thisBrowser = await start(app, PLAIN);++ const response = await callback(app, thisBrowser.cookie, otherBrowser.state);++ expect(response.body).toEqual({ ok: false, message: 'Invalid authorization request state.' });+ expect(logger.warn).toHaveBeenCalledWith(+ '[OAuth] Rejected github callback: Invalid authorization request state.',+ { provider: 'github', has_state: true },+ );+ });++ it.each<[string, OAuthStateStoreOptions, string]>([+ ['another provider', { ...github, provider: 'google' }, 'oauth_state_google'],+ ['another secret', { ...github, secret: 'rotated-secret' }, PLAIN],+ ])('rejects a state signed for %s', async (_label, signerOptions, signerCookie) => {+ const { app: signer } = createApp(signerOptions);+ const { app } = createApp(github);+ const { state, binding } = await start(signer, signerCookie);++ const response = await callback(app, `${PLAIN}.tab=${binding}`, state);++ expect(response.body).toEqual({ ok: false, message: 'Invalid authorization request state.' });+ });++ it('expires each state on its own clock while newer flows keep the binding alive', async () => {+ const issuedAt = 1_800_000_000_000;+ const now = jest.spyOn(Date, 'now').mockReturnValue(issuedAt);+ try {+ const { app } = createApp({ ...github, maxAgeMs: 60_000 });+ const older = await start(app, PLAIN);+ now.mockReturnValue(issuedAt + 50_000);+ const newer = await start(app, PLAIN, older.cookie);++ now.mockReturnValue(issuedAt + 59_999);+ const justInTime = await callback(app, newer.cookie, older.state);+ now.mockReturnValue(issuedAt + 60_000);+ const expired = await callback(app, newer.cookie, older.state);+ const current = await callback(app, newer.cookie, newer.state);++ expect(justInTime.body).toEqual({ ok: true });+ expect(expired.body).toEqual({ ok: false, message: 'Authorization request state expired.' });+ expect(current.body).toEqual({ ok: true });+ } finally {+ now.mockRestore();+ }+ });++ it('rejects a state whose issue time was changed', async () => {+ const { app } = createApp(github);+ const { state, cookie } = await start(app, PLAIN);+ const [, nonce, signature] = state.split('.');+ const retimed = `${(Date.now() + 3_600_000).toString(36)}.${nonce}.${signature}`;++ const response = await callback(app, cookie, retimed);++ expect(response.body).toEqual({ ok: false, message: 'Invalid authorization request state.' });+ });++ it.each<[string, (state: string) => string]>([+ ['a truncated signature', (state) => state.slice(0, -1)],+ ['a repeated state parameter', (state) => `${state}&state=${state}`],+ ['an empty state', () => ''],+ ['a bare random value', () => 'b'.repeat(43)],+ ])('rejects %s', async (_label, buildState) => {+ const { app } = createApp(github);+ const { state, cookie } = await start(app, PLAIN);++ const response = await request(app)+ .get(`/oauth/github/callback?state=${buildState(state)}`)+ .set('Cookie', cookie)+ .expect(200);++ expect(response.body).toEqual({ ok: false, message: 'Invalid authorization request state.' });+ });++ it('rejects a callback when this browser holds no binding cookie', async () => {+ const { app } = createApp(github);+ const { state } = await start(app, PLAIN);++ const response = await callback(app, undefined, state);++ expect(response.body).toEqual({+ ok: false,+ message: 'Unable to verify authorization request state.',+ });+ expect(logger.warn).toHaveBeenCalledWith(+ '[OAuth] Rejected github callback: Unable to verify authorization request state.',+ { provider: 'github', has_state: true },+ );+ });++ it('fails the authorization request when no response is attached to the request', () => {+ const { stateStore } = createApp(github);+ const done = jest.fn();++ stateStore.store({} as Request, done);++ expect(done).toHaveBeenCalledWith(expect.any(Error));+ });++ it('refuses to build a store without a signing secret', () => {+ expect(() => createOAuthStateStore({ ...github, secret: '' })).toThrow(+ 'A secret is required to sign github OAuth state',+ );+ });++ it('keeps the arities passport-oauth2 dispatches on', () => {+ const stateStore = createOAuthStateStore(github);++ expect(stateStore.store).toHaveLength(2);+ expect(stateStore.verify).toHaveLength(3);+ });+});++describe('deferStateToStore', () => {+ it('drops a state the strategy fills in without mutating the caller options', () => {+ const strategy: PresetStateStrategy = {+ authorizationParams(options: { state?: string; scope?: string }) {+ options.state = options.state || 'preset-state';+ options.scope = 'name email';+ return options;+ },+ };+ const routeOptions = { session: false };++ deferStateToStore(strategy);+ const params = strategy.authorizationParams(routeOptions);++ expect(params).toEqual({ session: false, scope: 'name email' });+ expect(routeOptions).toEqual({ session: false });+ });+});diff --git a/packages/api/src/oauth/state.ts b/packages/api/src/oauth/state.tsnew file mode 100644index 0000000000..e3aacdb561--- /dev/null+++ b/packages/api/src/oauth/state.ts@@ -0,0 +1,173 @@+import crypto from 'crypto';+import { logger } from '@librechat/data-schemas';+import { DEFAULT_OAUTH_STATE_TTL_MS } from 'librechat-data-provider';+import type { CookieOptions, Request } from 'express';++export const OAUTH_STATE_COOKIE_PREFIX = 'oauth_state_';++/** Browsers refuse a `__Host-` cookie that names a Domain, so a sibling subdomain cannot plant one. */+const HOST_ONLY_COOKIE_PREFIX = '__Host-';+/** Separates this HMAC from other values signed with the same secret. */+const SIGNATURE_CONTEXT = 'librechat:oauth-login-state';+const BINDING_PATTERN = /^[A-Za-z0-9_-]{43}$/;+/** Each binding cookie is `<prefix>.<id>`, so bindings created by concurrent first starts coexist. */+const BINDING_ID_BYTES = 6;+/** `<issued-at, base 36>.<nonce>.<signature>` */+const STATE_PATTERN = /^([0-9a-z]{1,11})\.([A-Za-z0-9_-]{22})\.([A-Za-z0-9_-]{43})$/;+const MISSING_BINDING_MESSAGE = 'Unable to verify authorization request state.';+const INVALID_STATE_MESSAGE = 'Invalid authorization request state.';+const EXPIRED_STATE_MESSAGE = 'Authorization request state expired.';++export interface OAuthStateStoreOptions {+ /** Strategy name; names the cookie, scopes the signature and labels rejections in logs. */+ provider: string;+ /** Signs each state; every replica must share it. */+ secret: string;+ /** Whether the deployment serves `Secure` cookies; secure deployments get a `__Host-` cookie. */+ secureCookie: boolean;+ /** How long a started login may take to reach its callback. */+ maxAgeMs?: number;+ /**+ * The provider returns with a cross-site form POST (Apple's `form_post`), which a+ * `SameSite=Lax` cookie does not accompany.+ */+ crossSiteCallback?: boolean;+}++type StoreCallback = (err: Error | null, state?: string) => void;+type VerifyCallback = (err: Error | null, ok: boolean, info?: { message: string }) => void;++/**+ * State store for `passport-oauth2`, which dispatches on each method's arity:+ * `store(req, callback)` and `verify(req, providedState, callback)`.+ */+export interface OAuthStateStore {+ store(req: Request, callback: StoreCallback): void;+ verify(req: Request, providedState: unknown, callback: VerifyCallback): void;+}++/** A passport strategy whose `authorizationParams` may fill in a `state` of its own. */+export interface PresetStateStrategy {+ authorizationParams(options: object): { state?: string };+}++const randomToken = (bytes: number): string => crypto.randomBytes(bytes).toString('base64url');++function signaturesMatch(expected: string, provided: string): boolean {+ const expectedBuffer = Buffer.from(expected);+ const providedBuffer = Buffer.from(provided);+ if (expectedBuffer.length !== providedBuffer.length) {+ return false;+ }+ return crypto.timingSafeEqual(expectedBuffer, providedBuffer);+}++/**+ * Binds an OAuth login to the browser that started it. The browser holds a random binding in an+ * HttpOnly cookie, reused by every flow it starts, and each `state` is an HMAC over that binding+ * and the time the flow started. The callback proceeds only when the returned `state` was signed+ * for one of this browser's bindings and is younger than `maxAgeMs`, so a callback reaching a+ * browser that did not start the flow ends before its code is exchanged. Nothing is stored per+ * flow, so logins started in separate tabs complete independently. A browser without a binding+ * gets one under a fresh cookie name, so first starts racing in two tabs each keep their own.+ */+export function createOAuthStateStore({+ provider,+ secret,+ secureCookie,+ maxAgeMs = DEFAULT_OAUTH_STATE_TTL_MS,+ crossSiteCallback = false,+}: OAuthStateStoreOptions): OAuthStateStore {+ if (!secret) {+ throw new Error(`A secret is required to sign ${provider} OAuth state`);+ }++ const secure = crossSiteCallback || secureCookie;+ const cookiePrefix = `${secure ? HOST_ONLY_COOKIE_PREFIX : ''}${OAUTH_STATE_COOKIE_PREFIX}${provider}.`;+ const cookieOptions: CookieOptions = {+ httpOnly: true,+ path: '/',+ sameSite: crossSiteCallback ? 'none' : 'lax',+ secure,+ maxAge: maxAgeMs,+ };++ const readBindings = (req: Request): Array<[name: string, binding: string]> =>+ Object.entries((req.cookies as Record<string, string> | undefined) ?? {}).filter(+ ([name, value]) => name.startsWith(cookiePrefix) && BINDING_PATTERN.test(value),+ );++ const sign = (binding: string, issuedAt: string, nonce: string): string =>+ crypto+ .createHmac('sha256', secret)+ .update(`${SIGNATURE_CONTEXT}:${provider}:${binding}:${issuedAt}:${nonce}`)+ .digest('base64url');++ const reject = (callback: VerifyCallback, message: string, hasState: boolean): void => {+ logger.warn(`[OAuth] Rejected ${provider} callback: ${message}`, {+ provider,+ has_state: hasState,+ });+ callback(null, false, { message });+ };++ return {+ store(req, callback) {+ if (!req.res) {+ callback(new Error('OAuth state store requires an Express response'));+ return;+ }+ const [name, binding] = readBindings(req)[0] ?? [+ `${cookiePrefix}${randomToken(BINDING_ID_BYTES)}`,+ randomToken(32),+ ];+ /** Re-issuing the same binding keeps it alive past the newest state it signs. */+ req.res.cookie(name, binding, cookieOptions);+ const issuedAt = Date.now().toString(36);+ const nonce = randomToken(16);+ callback(null, `${issuedAt}.${nonce}.${sign(binding, issuedAt, nonce)}`);+ },++ verify(req, providedState, callback) {+ const hasState = typeof providedState === 'string' && providedState.length > 0;+ const bindings = readBindings(req);+ if (bindings.length === 0) {+ reject(callback, MISSING_BINDING_MESSAGE, hasState);+ return;+ }++ const parsed = hasState ? STATE_PATTERN.exec(providedState) : null;+ if (!parsed) {+ reject(callback, INVALID_STATE_MESSAGE, hasState);+ return;+ }++ const [, issuedAt, nonce, signature] = parsed;+ const signed = bindings.some(([, binding]) =>+ signaturesMatch(sign(binding, issuedAt, nonce), signature),+ );+ if (!signed) {+ reject(callback, INVALID_STATE_MESSAGE, hasState);+ return;+ }+ if (Date.now() - parseInt(issuedAt, 36) >= maxAgeMs) {+ reject(callback, EXPIRED_STATE_MESSAGE, hasState);+ return;+ }+ callback(null, true);+ },+ };+}++/**+ * Leaves `state` to the configured store for strategies that fill in their own. passport-apple+ * assigns one inside `authorizationParams` (on the route's shared options, so it never changes+ * after the first request), and a preset `state` bypasses the store entirely.+ */+export function deferStateToStore(strategy: PresetStateStrategy): void {+ const authorizationParams = strategy.authorizationParams.bind(strategy);+ strategy.authorizationParams = (options) => {+ const { state: _state, ...params } = authorizationParams({ ...options });+ return params;+ };+}diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 39413bf1a8..61ac028835 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -40,6 +40,9 @@ export {export const defaultSocialLogins = ['google', 'facebook', 'openid', 'github', 'discord', 'saml'];+/** How long a started social login may take to return to its callback before its `state` expires. */+export const DEFAULT_OAUTH_STATE_TTL_MS = 10 * 60 * 1000;+export const BASE_ONLY_CONFIG_SECTIONS = ['filters'] as const;/** Sections that may be stored in the tenant's base config document but must* not be overridden or tombstoned by role, group, or user config documents. */@@ -2859,6 +2862,8 @@ export const configSchema = z.object({.object({socialLogins: z.array(z.string()).optional(),allowedDomains: z.array(z.string()).optional(),+ /** Milliseconds a started social login may take to reach its callback; defaults to `DEFAULT_OAUTH_STATE_TTL_MS`. */+ oauthStateTtlMs: z.number().int().min(60_000).max(3_600_000).optional(),}).default({ socialLogins: defaultSocialLogins }),balance: balanceSchema.optional(),@@ -3596,6 +3601,10 @@ export enum ErrorTypes {* Authentication rejected because the account or IP is banned*/AUTH_BANNED = 'auth_banned',+ /**+ * Authentication request was not sent from this application's origin+ */+ AUTH_CROSS_ORIGIN = 'auth_cross_origin',/*** Model refused to respond (content policy violation)*/