Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 5 additions & 17 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"format:check": "prettier --check 'src/**/*.{ts,tsx,css,json}'"
},
"dependencies": {
"@clickhouse/click-ui": "0.2.0-rc.4",
"@clickhouse/click-ui": "0.9.1",
"@librechat/data-schemas": "^0.0.56",
"@radix-ui/react-dialog": "1.1.15",
"@tailwindcss/vite": "^4.3.1",
Expand Down
31 changes: 21 additions & 10 deletions src/components/AuthCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export function AuthCard({
if (result.error || !result.authUrl) {
setAutoRedirectFailed(true);
setGeneralError(result.message || localize('com_auth_sso_redirect_failed'));
setSsoLoading(false);
return;
}
const authUrl = new URL(result.authUrl);
Expand All @@ -71,10 +72,20 @@ export function AuthCard({
.catch(() => {
setAutoRedirectFailed(true);
setGeneralError(localize('com_auth_sso_redirect_failed'));
})
.finally(() => setSsoLoading(false));
setSsoLoading(false);
});
}, [autoRedirectSso, localize, redirectTo]);

useEffect(() => {
// A bfcache restore (browser Back from the IdP) revives the pre-navigation
// React state, so reset the loading flag left true by the outbound redirect.
const handlePageShow = (event: PageTransitionEvent) => {
if (event.persisted) setSsoLoading(false);
};
window.addEventListener('pageshow', handlePageShow);
return () => window.removeEventListener('pageshow', handlePageShow);
}, []);

const emailSchema = useMemo(
() => z.string().email(localize('com_auth_email_invalid')),
[localize],
Expand Down Expand Up @@ -196,24 +207,23 @@ export function AuthCard({
setSsoLoading(true);
try {
const result = await openidLoginFn();
if (result.error) {
if (result.error || !result.authUrl) {
setGeneralError(result.message || localize('com_auth_login_failed'));
setSsoLoading(false);
return;
}
if (result.authUrl) {
window.location.href = result.authUrl;
}
window.location.href = result.authUrl;
Comment thread
dustinhealy marked this conversation as resolved.
} catch {
setGeneralError(localize('com_auth_unable_connect'));
} finally {
setSsoLoading(false);
}
};

if (showAutoRedirect) {
return (
<Panel
className="auth-card w-full max-w-md"
className="auth-card max-w-md min-w-70"
fillWidth
padding="xl"
radii="lg"
hasBorder
Expand All @@ -233,7 +243,8 @@ export function AuthCard({

return (
<Panel
className="auth-card w-full max-w-md"
className="auth-card max-w-md min-w-70"
fillWidth
padding="xl"
radii="lg"
hasBorder
Expand Down Expand Up @@ -334,7 +345,7 @@ export function AuthCard({
}
type="secondary"
onClick={handleSsoLogin}
disabled={ssoLoading}
loading={ssoLoading}
/>
</>
)}
Expand Down
153 changes: 153 additions & 0 deletions src/components/__tests__/AuthCard.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type * as t from '@/types';
import { openidLoginFn } from '@/server';
import { AuthCard } from '../AuthCard';

vi.mock('@/server', () => ({
adminLoginFn: vi.fn(),
adminVerify2FAFn: vi.fn(),
openidLoginFn: vi.fn(),
openIdCheckOptions: { queryKey: ['openIdCheck'], queryFn: vi.fn() },
}));

vi.mock('@tanstack/react-router', () => ({
useRouter: () => ({ invalidate: vi.fn(), navigate: vi.fn() }),
}));

vi.mock('@/hooks', () => ({
useLocalize: () => (key: string) => key,
}));

type SsoLoginResult = Awaited<ReturnType<typeof openidLoginFn>>;

const openidLoginFnMock = vi.mocked(openidLoginFn);

function renderAuthCard(props: Partial<t.AuthCardProps> = {}) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={queryClient}>
<AuthCard ssoAvailable {...props} />
</QueryClientProvider>,
);
}

function getSsoButton() {
return screen.getByRole('button', { name: 'com_auth_sso_sign_in' });
}

function getSsoRedirectingButton() {
return screen.getByRole('button', { name: 'com_auth_sso_redirecting' });
}

describe('AuthCard SSO login', () => {
const locationStub = { href: 'http://localhost:3000/' };

beforeEach(() => {
locationStub.href = 'http://localhost:3000/';
vi.stubGlobal('location', locationStub);
});

afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});

it('shows the loading state while the SSO login request is pending', async () => {
openidLoginFnMock.mockImplementation(() => new Promise<SsoLoginResult>(() => {}));
renderAuthCard();

fireEvent.click(getSsoButton());

await waitFor(() => {
const button = getSsoRedirectingButton();
expect(button).toHaveAttribute('aria-busy', 'true');
expect(button).toBeDisabled();
});
});

it('keeps the button loading after resolving and navigates to the auth URL', async () => {
const authUrl = 'https://idp.example.com/authorize';
openidLoginFnMock.mockResolvedValue({ error: false, authUrl });
renderAuthCard();

fireEvent.click(getSsoButton());

await waitFor(() => expect(locationStub.href).toBe(authUrl));
const button = getSsoRedirectingButton();
expect(button).toHaveAttribute('aria-busy', 'true');
expect(button).toBeDisabled();
});

it('resets the loading state when the page is restored from the back-forward cache', async () => {
const authUrl = 'https://idp.example.com/authorize';
openidLoginFnMock.mockResolvedValue({ error: false, authUrl });
renderAuthCard();

fireEvent.click(getSsoButton());
await waitFor(() => expect(locationStub.href).toBe(authUrl));

fireEvent(window, Object.assign(new Event('pageshow'), { persisted: false }));
expect(getSsoRedirectingButton()).toBeDisabled();

fireEvent(window, Object.assign(new Event('pageshow'), { persisted: true }));
const button = getSsoButton();
expect(button).not.toHaveAttribute('aria-busy');
expect(button).toBeEnabled();
});

it('returns the button to non-loading when the request resolves with an error', async () => {
openidLoginFnMock.mockResolvedValue({ error: true, message: 'Failed to initiate SSO login' });
renderAuthCard();

fireEvent.click(getSsoButton());

await waitFor(() =>
expect(screen.getByText('Failed to initiate SSO login')).toBeInTheDocument(),
);
const button = getSsoButton();
expect(button).not.toHaveAttribute('aria-busy');
expect(button).toBeEnabled();
expect(locationStub.href).toBe('http://localhost:3000/');
});

it('returns the button to non-loading when the request rejects', async () => {
openidLoginFnMock.mockRejectedValue(new Error('network down'));
renderAuthCard();

fireEvent.click(getSsoButton());

await waitFor(() => expect(screen.getByText('com_auth_unable_connect')).toBeInTheDocument());
const button = getSsoButton();
expect(button).not.toHaveAttribute('aria-busy');
expect(button).toBeEnabled();
});
});

describe('AuthCard panel width', () => {
afterEach(() => {
vi.clearAllMocks();
});

it('renders the login panel with fillWidth and a min width', () => {
const { container } = renderAuthCard();

const panel = container.querySelector<HTMLElement>('.auth-card');
expect(panel).not.toBeNull();
expect(panel?.style.getPropertyValue('--panel-width')).toBe('100%');
expect(panel?.classList.contains('min-w-70')).toBe(true);
expect(panel?.classList.contains('max-w-md')).toBe(true);
});

it('renders the auto-redirect panel with fillWidth and a min width', () => {
openidLoginFnMock.mockImplementation(() => new Promise<SsoLoginResult>(() => {}));
const { container } = renderAuthCard({ autoRedirectSso: true });

const panel = container.querySelector<HTMLElement>('.auth-card');
expect(panel).not.toBeNull();
expect(panel?.style.getPropertyValue('--panel-width')).toBe('100%');
expect(panel?.classList.contains('min-w-70')).toBe(true);
expect(panel?.classList.contains('max-w-md')).toBe(true);
});
});
7 changes: 6 additions & 1 deletion vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ export default defineConfig({
environment: 'jsdom',
globals: true,
setupFiles: ['./src/test/setup.ts'],
exclude: ['e2e/**', 'node_modules/**', 'tools/**'],
exclude: ['e2e/**', 'node_modules/**', 'tools/**', '.claude/**'],
server: {
deps: {
inline: ['@clickhouse/click-ui'],
},
},
},
})