snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
import type { ReactNode } from 'react';
import GenericGroupPage from './GenericGroupPage';
import TabbedGroupPage from './TabbedGroupPage';
import { useEditableSettingsGroupSections, useEditableSettingsGroupTabs } from '../../EditableSettingsContext';
export type BaseGroupPageProps = {
_id: string;
i18nLabel: string;
headerButtons?: ReactNode;
hasReset?: boolean;
onClickBack?: () => void;
};
const BaseGroupPage = ({ _id, i18nLabel, headerButtons, hasReset, onClickBack, ...props }: BaseGroupPageProps) => {
const tabs = useEditableSettingsGroupTabs(_id);
const sections = useEditableSettingsGroupSections(_id);
if (tabs.length > 1) {
return (
<TabbedGroupPage _id={_id} i18nLabel={i18nLabel} headerButtons={headerButtons} tabs={tabs} onClickBack={onClickBack} {...props} />
);
}
return <GenericGroupPage _id={_id} i18nLabel={i18nLabel} sections={sections} onClickBack={onClickBack} hasReset={hasReset} {...props} />;
};
export default BaseGroupPage;

View File

@@ -0,0 +1,65 @@
import { Accordion, Box } from '@rocket.chat/fuselage';
import { PageScrollableContentWithShadow } from '@rocket.chat/ui-client';
import { useRouter } from '@rocket.chat/ui-contexts';
import { useCallback } from 'react';
import type { MouseEvent } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { useEditableSettingsGroupSections } from '../../EditableSettingsContext';
import SettingsGroupPage from '../SettingsGroupPage';
import Section from '../SettingsSection';
type EnterpriseGroupPageProps = {
_id: string;
i18nLabel: string;
currentTab?: string;
hasReset?: boolean;
onClickBack?: () => void;
};
const useRedirectToRouteLink = (onClick: (event: MouseEvent<HTMLAnchorElement>) => void) => {
const handleClick = useCallback(
(event: MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
onClick(event);
},
[onClick],
);
return { href: '#', onClick: handleClick };
};
const EnterpriseGroupPage = ({ _id, i18nLabel, hasReset, currentTab, onClickBack, ...props }: EnterpriseGroupPageProps) => {
const { t } = useTranslation();
const { navigate } = useRouter();
const redirectProps = useRedirectToRouteLink(() => navigate('/admin/subscription'));
const sections = useEditableSettingsGroupSections(_id);
return (
<SettingsGroupPage isCustom _id={_id} i18nLabel={i18nLabel} onClickBack={onClickBack} {...props}>
<PageScrollableContentWithShadow>
<Box marginBlock='none' marginInline='auto' width='full' maxWidth='x580'>
<Trans
i18nKey='Workspace_license_is_now_managed_from_the_subscription_page'
components={{ a: <Box is='a' fontScale='p2' color='info' {...redirectProps} /> }}
/>
<Accordion>
{sections.map((sectionName) => (
<Section
key={sectionName || ''}
hasReset={hasReset}
groupId={_id}
sectionName={sectionName}
sectionTitle={t('Manual_license_management_deprecated')}
currentTab={currentTab}
solo={false}
/>
))}
</Accordion>
</Box>
</PageScrollableContentWithShadow>
</SettingsGroupPage>
);
};
export default EnterpriseGroupPage;

View File

@@ -0,0 +1,30 @@
import type { ReactNode } from 'react';
import { memo } from 'react';
import SettingsGroupPage from '../SettingsGroupPage';
import Section from '../SettingsSection';
export type GenericGroupPageProps = {
_id: string;
i18nLabel: string;
tabs?: ReactNode;
currentTab?: string;
hasReset?: boolean;
sections: string[];
headerButtons?: ReactNode;
onClickBack?: () => void;
};
function GenericGroupPage({ _id, i18nLabel, sections, tabs, currentTab, hasReset, onClickBack, ...props }: GenericGroupPageProps) {
const solo = sections.length === 1;
return (
<SettingsGroupPage _id={_id} i18nLabel={i18nLabel} onClickBack={onClickBack} tabs={tabs} {...props}>
{sections.map((sectionName) => (
<Section key={sectionName || ''} hasReset={hasReset} groupId={_id} sectionName={sectionName} currentTab={currentTab} solo={solo} />
))}
</SettingsGroupPage>
);
}
export default memo(GenericGroupPage);

View File

@@ -0,0 +1,129 @@
import type { ISetting } from '@rocket.chat/core-typings';
import { Button, Box, TextInput, Field, FieldLabel, FieldRow } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { GenericModal } from '@rocket.chat/ui-client';
import { useSetModal, useToastMessageDispatch, useSetting, useEndpoint } from '@rocket.chat/ui-contexts';
import type { ChangeEvent } from 'react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import BaseGroupPage from './BaseGroupPage';
import { useExternalLink } from '../../../../hooks/useExternalLink';
import { useLdapSync } from '../../../../hooks/useLdapSync';
import { links } from '../../../../lib/links';
import { useEditableSettings } from '../../EditableSettingsContext';
export type LDAPGroupPageProps = ISetting & {
onClickBack?: () => void;
};
function LDAPGroupPage({ _id, i18nLabel, onClickBack, ...group }: LDAPGroupPageProps) {
const { t } = useTranslation();
const dispatchToastMessage = useToastMessageDispatch();
const testConnection = useEndpoint('POST', '/v1/ldap.testConnection');
const testSearch = useEndpoint('POST', '/v1/ldap.testSearch');
const ldapEnabled = useSetting('LDAP_Enable');
const setModal = useSetModal();
const closeModal = useStableCallback(() => setModal());
const handleSyncNow = useLdapSync();
const handleLinkClick = useExternalLink();
const editableSettings = useEditableSettings(
useMemo(
() => ({
group: _id,
}),
[_id],
),
);
const changed = useMemo(() => editableSettings.some(({ changed }) => changed), [editableSettings]);
const handleTestConnectionButtonClick = async (): Promise<void> => {
try {
const { message } = await testConnection();
dispatchToastMessage({ type: 'success', message: t(message as Parameters<typeof t>[0]) });
} catch (error) {
error instanceof Error && dispatchToastMessage({ type: 'error', message: error });
}
};
const handleSearchTestButtonClick = async (): Promise<void> => {
try {
await testConnection();
let username = '';
const handleChangeUsername = (event: ChangeEvent<HTMLInputElement>): void => {
username = event.currentTarget.value;
};
const confirmSearch = async (): Promise<void> => {
try {
const { message } = await testSearch({ username });
dispatchToastMessage({ type: 'success', message: t(message as Parameters<typeof t>[0]) });
} catch (error) {
error instanceof Error && dispatchToastMessage({ type: 'error', message: error });
}
};
setModal(
<GenericModal
wrapperFunction={(props) => (
<Box
is='form'
onSubmit={(e) => {
e.preventDefault();
confirmSearch();
}}
{...props}
/>
)}
variant='info'
confirmText={t('Search')}
cancelText={t('Cancel')}
title={t('Test_LDAP_Search')}
onClose={closeModal}
>
<Field>
<Box display='flex'>
<FieldLabel>{t('LDAP_Username_To_Search')}</FieldLabel>
</Box>
<FieldRow>
<TextInput onChange={handleChangeUsername} />
</FieldRow>
</Field>
</GenericModal>,
);
} catch (error) {
error instanceof Error && dispatchToastMessage({ type: 'error', message: error });
}
};
return (
<BaseGroupPage
_id={_id}
i18nLabel={i18nLabel}
onClickBack={onClickBack}
{...group}
headerButtons={
<>
<Button disabled={!ldapEnabled || changed} onClick={handleTestConnectionButtonClick}>
{t('Test_Connection')}
</Button>
<Button disabled={!ldapEnabled || changed} onClick={handleSearchTestButtonClick}>
{t('Test_LDAP_Search')}
</Button>
<Button disabled={!ldapEnabled || changed} onClick={handleSyncNow}>
{t('LDAP_Sync_Now')}
</Button>
<Button role='link' onClick={() => handleLinkClick(links.go.ldapDocs)}>
{t('LDAP_Documentation')}
</Button>
</>
}
/>
);
}
export default memo(LDAPGroupPage);

View File

@@ -0,0 +1,47 @@
import { mockAppRoot } from '@rocket.chat/mock-providers';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CreateOAuthModal from './CreateOAuthModal';
it('should call onClose when Cancel is clicked', async () => {
const onConfirm = jest.fn();
const onClose = jest.fn();
render(<CreateOAuthModal onConfirm={onConfirm} onClose={onClose} />, {
wrapper: mockAppRoot().build(),
});
await userEvent.click(screen.getByText('Cancel'));
expect(onClose).toHaveBeenCalled();
});
it('should call onClose when X is clicked', async () => {
const onConfirm = jest.fn();
const onClose = jest.fn();
render(<CreateOAuthModal onConfirm={onConfirm} onClose={onClose} />, {
wrapper: mockAppRoot().build(),
});
await userEvent.click(screen.getByLabelText('Close'));
expect(onClose).toHaveBeenCalled();
});
it('should call onConfirm when Add button is clicked', async () => {
const onConfirm = jest.fn();
const onClose = jest.fn();
render(<CreateOAuthModal onConfirm={onConfirm} onClose={onClose} />, {
wrapper: mockAppRoot().build(),
});
const custoOAuthNameInput = screen.getByLabelText('Custom_OAuth_name');
await userEvent.type(custoOAuthNameInput, 'Test');
await userEvent.click(screen.getByText('Add'));
await waitFor(() => expect(onConfirm).toHaveBeenCalled());
});

View File

@@ -0,0 +1,61 @@
import { TextInput, Field, FieldLabel, FieldRow, FieldError, Box, FieldHint } from '@rocket.chat/fuselage';
import { GenericModal } from '@rocket.chat/ui-client';
import { useId } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
export type CreateOAuthModalProps = {
onConfirm: (text: string) => Promise<void>;
onClose: () => void;
};
type CreateOAuthModalFields = {
customOAuthName: string;
};
const CreateOAuthModal = ({ onConfirm, onClose }: CreateOAuthModalProps) => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<CreateOAuthModalFields>({
defaultValues: {
customOAuthName: '',
},
});
const { t } = useTranslation();
const customOAuthNameId = useId();
return (
<GenericModal
wrapperFunction={(props) => <Box is='form' onSubmit={handleSubmit(({ customOAuthName }) => onConfirm(customOAuthName))} {...props} />}
title={t('Add_custom_oauth')}
confirmText={t('Add')}
onCancel={onClose}
onClose={onClose}
>
<Field>
<FieldLabel htmlFor={customOAuthNameId}>{t('Custom_OAuth_name')}</FieldLabel>
<FieldRow>
<TextInput
id={customOAuthNameId}
{...register('customOAuthName', { required: t('Required_field', { field: t('Custom_OAuth_name') }) })}
aria-required='true'
aria-describedby={`${customOAuthNameId}-error ${customOAuthNameId}-hint`}
aria-label={t('Custom_OAuth_name')}
/>
</FieldRow>
<FieldHint id={`${customOAuthNameId}-hint`}>{t('Custom_OAuth_name_hint')}</FieldHint>
{errors.customOAuthName && (
<FieldError aria-live='assertive' id={`${customOAuthNameId}-error`}>
{errors.customOAuthName.message}
</FieldError>
)}
</Field>
</GenericModal>
);
};
export default CreateOAuthModal;

View File

@@ -0,0 +1,143 @@
import type { ISetting } from '@rocket.chat/core-typings';
import { Button } from '@rocket.chat/fuselage';
import { capitalize } from '@rocket.chat/tools';
import { GenericModal } from '@rocket.chat/ui-client';
import { useToastMessageDispatch, useAbsoluteUrl, useEndpoint, useTranslation, useSetModal } from '@rocket.chat/ui-contexts';
import DOMPurify from 'dompurify';
import { memo, useEffect, useState } from 'react';
import CreateOAuthModal from './CreateOAuthModal';
import { strRight } from '../../../../../../lib/utils/stringUtils';
import { useEditableSettingsGroupSections } from '../../../EditableSettingsContext';
import SettingsGroupPage from '../../SettingsGroupPage';
import SettingsSection from '../../SettingsSection';
export type OAuthGroupPageProps = ISetting & {
onClickBack?: () => void;
};
function OAuthGroupPage({ _id, onClickBack, ...group }: OAuthGroupPageProps) {
const sections = useEditableSettingsGroupSections(_id);
const solo = sections.length === 1;
const t = useTranslation();
const [settingSections, setSettingSections] = useState(sections);
const sectionIsCustomOAuth = (sectionName: string): string | boolean => sectionName && /^Custom OAuth:\s.+/.test(sectionName);
const getAbsoluteUrl = useAbsoluteUrl();
const callbackURL = (sectionName: string): string => {
const id = strRight(sectionName, 'Custom OAuth: ').toLowerCase();
return getAbsoluteUrl(`_oauth/${id}`);
};
const dispatchToastMessage = useToastMessageDispatch();
const refreshOAuthService = useEndpoint('POST', '/v1/settings.refreshOAuthServices');
const addOAuthService = useEndpoint('POST', '/v1/settings.addCustomOAuth');
const removeOAuthService = useEndpoint('POST', '/v1/settings.removeCustomOAuth');
const setModal = useSetModal();
const handleRefreshOAuthServicesButtonClick = async (): Promise<void> => {
dispatchToastMessage({ type: 'info', message: t('Refreshing') });
try {
await refreshOAuthService(undefined);
dispatchToastMessage({ type: 'success', message: t('Done') });
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
};
const handleAddCustomOAuthButtonClick = (): void => {
const onConfirm = async (text: string): Promise<void> => {
try {
await addOAuthService({ name: text });
dispatchToastMessage({ type: 'success', message: t('Custom_OAuth_has_been_added') });
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
} finally {
setModal(null);
}
};
setModal(<CreateOAuthModal onConfirm={onConfirm} onClose={(): void => setModal(null)} />);
};
useEffect(() => {
setSettingSections(sections);
}, [sections]);
const removeCustomOauthFactory =
(id: string): (() => void) =>
(): void => {
const handleConfirm = async (): Promise<void> => {
try {
await removeOAuthService({ name: id });
dispatchToastMessage({ type: 'success', message: t('Custom_OAuth_has_been_removed') });
setSettingSections(settingSections.filter((section) => section !== `Custom OAuth: ${capitalize(id)}`));
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
} finally {
setModal(null);
}
};
setModal(
<GenericModal
onClose={() => setModal(null)}
onCancel={() => setModal(null)}
title={t('Are_you_sure')}
variant='danger'
confirmText={t('Yes_delete_it')}
onConfirm={handleConfirm}
/>,
);
};
return (
<SettingsGroupPage
_id={_id}
{...group}
onClickBack={onClickBack}
headerButtons={
<>
<Button onClick={handleRefreshOAuthServicesButtonClick}>{t('Refresh_oauth_services')}</Button>
<Button onClick={handleAddCustomOAuthButtonClick}>{t('Add_custom_oauth')}</Button>
</>
}
>
{settingSections.map((sectionName) => {
if (sectionIsCustomOAuth(sectionName)) {
const id = strRight(sectionName, 'Custom OAuth: ').toLowerCase();
const handleRemoveCustomOAuthButtonClick = removeCustomOauthFactory(id);
return (
<SettingsSection
key={sectionName}
groupId={_id}
help={
<span
dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(t('Custom_oauth_helper', { url: callbackURL(sectionName) })),
}}
/>
}
sectionName={sectionName}
solo={solo}
>
<div className='submit'>
<Button secondary danger onClick={handleRemoveCustomOAuthButtonClick}>
{t('Remove_custom_oauth')}
</Button>
</div>
</SettingsSection>
);
}
return <SettingsSection key={sectionName} groupId={_id} sectionName={sectionName} solo={solo} />;
})}
</SettingsGroupPage>
);
}
export default memo(OAuthGroupPage);

View File

@@ -0,0 +1 @@
export { default } from './OAuthGroupPage';

View File

@@ -0,0 +1,81 @@
import type { ISetting } from '@rocket.chat/core-typings';
import { Button } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { useEndpoint, useSetModal, useToastMessageDispatch, useSettingStructure } from '@rocket.chat/ui-contexts';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import SamlMetadataModal from './SamlMetadataModal';
import type { SamlMetadataValues } from './SamlMetadataModal';
import { useEditableSettings, useEditableSettingsDispatch } from '../../../EditableSettingsContext';
import BaseGroupPage from '../BaseGroupPage';
type SAMLGroupPageProps = ISetting & {
onClickBack?: () => void;
};
function SAMLGroupPage({ _id, i18nLabel, onClickBack, ...group }: SAMLGroupPageProps) {
const { t } = useTranslation();
const dispatchToastMessage = useToastMessageDispatch();
const parseMetadata = useEndpoint('POST', '/v1/saml.parseMetadata');
const setModal = useSetModal();
const closeModal = useStableCallback(() => setModal());
const dispatch = useEditableSettingsDispatch();
const certSetting = useSettingStructure('SAML_Custom_Default_cert');
const entryPointSetting = useSettingStructure('SAML_Custom_Default_entry_point');
const sloSetting = useSettingStructure('SAML_Custom_Default_idp_slo_redirect_url');
const identifierFormatSetting = useSettingStructure('SAML_Custom_Default_identifier_format');
const editableSettings = useEditableSettings(useMemo(() => ({ group: _id }), [_id]));
const changed = useMemo(() => editableSettings.some(({ changed }) => changed), [editableSettings]);
const handleApply = useStableCallback((values: SamlMetadataValues) => {
// identifier_format is only registered on Enterprise installs; skip any setting that isn't present.
const add = (setting: ISetting | undefined, value?: string) =>
setting && value !== undefined ? [{ _id: setting._id, value, changed: JSON.stringify(setting.value) !== JSON.stringify(value) }] : [];
const changes = [
...add(certSetting, values.cert),
...add(entryPointSetting, values.entryPoint),
...add(sloSetting, values.idpSLORedirectURL),
...add(identifierFormatSetting, values.identifierFormat),
];
dispatch(changes);
closeModal();
if (changes.length === 0) {
dispatchToastMessage({ type: 'warning', message: t('SAML_Metadata_no_values') });
return;
}
dispatchToastMessage({ type: 'success', message: t('SAML_Metadata_applied') });
});
const handleImportClick = () =>
setModal(
<SamlMetadataModal
onClose={closeModal}
onFetch={(url) => parseMetadata({ url })}
onApply={handleApply}
showIdentifierFormat={identifierFormatSetting !== undefined}
/>,
);
return (
<BaseGroupPage
_id={_id}
i18nLabel={i18nLabel}
onClickBack={onClickBack}
{...group}
headerButtons={
<Button disabled={changed} onClick={handleImportClick}>
{t('SAML_Import_metadata')}
</Button>
}
/>
);
}
export default memo(SAMLGroupPage);

View File

@@ -0,0 +1,122 @@
import { mockAppRoot } from '@rocket.chat/mock-providers';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import SamlMetadataModal from './SamlMetadataModal';
const setup = (overrides: Partial<Parameters<typeof SamlMetadataModal>[0]> = {}) => {
const props = {
onClose: jest.fn(),
onFetch: jest.fn().mockResolvedValue({
cert: 'CERTDATA',
entryPoint: 'https://idp.test/sso',
idpSLORedirectURL: 'https://idp.test/slo',
warnings: [],
}),
onApply: jest.fn(),
...overrides,
};
render(<SamlMetadataModal {...props} />, { wrapper: mockAppRoot().build() });
return props;
};
it('fetches metadata and shows the preview, then applies edited values', async () => {
const props = setup();
await userEvent.type(screen.getByLabelText('SAML_Metadata_url'), 'https://idp.test/metadata.xml');
await userEvent.click(screen.getByText('SAML_Metadata_fetch'));
await waitFor(() => expect(props.onFetch).toHaveBeenCalledWith('https://idp.test/metadata.xml'));
const entryPointInput = await screen.findByLabelText('SAML_Custom_Entry_point');
expect(entryPointInput).toHaveValue('https://idp.test/sso');
expect(screen.getByLabelText('SAML_Custom_Cert')).toHaveValue('CERTDATA');
expect(screen.getByLabelText('SAML_Custom_IDP_SLO_Redirect_URL')).toHaveValue('https://idp.test/slo');
await userEvent.clear(entryPointInput);
await userEvent.type(entryPointInput, 'https://idp.test/sso-edited');
await userEvent.click(screen.getByText('Apply'));
expect(props.onApply).toHaveBeenCalledWith({
cert: 'CERTDATA',
entryPoint: 'https://idp.test/sso-edited',
idpSLORedirectURL: 'https://idp.test/slo',
});
});
it('shows a warning callout when the fetch result carries warnings', async () => {
setup({
onFetch: jest.fn().mockResolvedValue({ cert: 'CERTDATA', warnings: ['SAML_Metadata_warning_multiple_certs'] }),
});
await userEvent.type(screen.getByLabelText('SAML_Metadata_url'), 'https://idp.test/metadata.xml');
await userEvent.click(screen.getByText('SAML_Metadata_fetch'));
expect(await screen.findByText('SAML_Metadata_warning_multiple_certs')).toBeInTheDocument();
});
it('returns to Fetch mode when the URL is edited after a successful fetch', async () => {
setup();
await userEvent.type(screen.getByLabelText('SAML_Metadata_url'), 'https://idp.test/metadata.xml');
await userEvent.click(screen.getByText('SAML_Metadata_fetch'));
expect(await screen.findByText('Apply')).toBeInTheDocument();
await userEvent.type(screen.getByLabelText('SAML_Metadata_url'), '2');
expect(await screen.findByText('SAML_Metadata_fetch')).toBeInTheDocument();
expect(screen.queryByText('Apply')).not.toBeInTheDocument();
});
it('shows the Identifier Format row only when showIdentifierFormat is true', async () => {
setup({
showIdentifierFormat: true,
onFetch: jest.fn().mockResolvedValue({
cert: 'CERTDATA',
entryPoint: 'https://idp.test/sso',
idpSLORedirectURL: 'https://idp.test/slo',
identifierFormat: 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient',
warnings: [],
}),
});
await userEvent.type(screen.getByLabelText('SAML_Metadata_url'), 'https://idp.test/metadata.xml');
await userEvent.click(screen.getByText('SAML_Metadata_fetch'));
expect(await screen.findByLabelText('SAML_Identifier_Format')).toHaveValue('urn:oasis:names:tc:SAML:2.0:nameid-format:transient');
});
it('does not show the Identifier Format row when showIdentifierFormat is false', async () => {
setup();
await userEvent.type(screen.getByLabelText('SAML_Metadata_url'), 'https://idp.test/metadata.xml');
await userEvent.click(screen.getByText('SAML_Metadata_fetch'));
expect(await screen.findByLabelText('SAML_Custom_Cert')).toBeInTheDocument();
expect(screen.queryByLabelText('SAML_Identifier_Format')).not.toBeInTheDocument();
});
it('calls onClose when Cancel is clicked', async () => {
const props = setup();
await userEvent.click(screen.getByText('Cancel'));
expect(props.onClose).toHaveBeenCalled();
});
it('shows a danger callout and allows retry when fetch fails', async () => {
setup({
onFetch: jest.fn().mockRejectedValueOnce({ success: false, error: 'SAML_Metadata_fetch_failed' }),
});
await userEvent.type(screen.getByLabelText('SAML_Metadata_url'), 'https://idp.test/metadata.xml');
await userEvent.click(screen.getByText('SAML_Metadata_fetch'));
expect(await screen.findByText('SAML_Metadata_fetch_failed')).toBeInTheDocument();
const confirmButton = screen.getByText('SAML_Metadata_fetch');
expect(confirmButton).toBeInTheDocument();
expect(confirmButton).not.toBeDisabled();
const urlInput = screen.getByLabelText('SAML_Metadata_url') as HTMLInputElement;
expect(urlInput.value).toBe('https://idp.test/metadata.xml');
});

View File

@@ -0,0 +1,184 @@
import { Box, Callout, Field, FieldLabel, FieldRow, TextAreaInput, TextInput } from '@rocket.chat/fuselage';
import { GenericModal } from '@rocket.chat/ui-client';
import type { ChangeEvent } from 'react';
import { useId, useState } from 'react';
import { useTranslation } from 'react-i18next';
export type SamlMetadataValues = {
cert?: string;
entryPoint?: string;
idpSLORedirectURL?: string;
identifierFormat?: string;
};
type SamlMetadataFetchResult = SamlMetadataValues & { warnings: string[] };
type SamlMetadataModalProps = {
onClose: () => void;
onFetch: (url: string) => Promise<SamlMetadataFetchResult>;
onApply: (values: SamlMetadataValues) => void;
showIdentifierFormat?: boolean;
};
const KNOWN_SAML_METADATA_ERROR_KEYS = [
'SAML_Metadata_url_blocked',
'SAML_Metadata_fetch_failed',
'SAML_Metadata_too_large',
'SAML_Metadata_invalid',
];
const getSamlMetadataErrorKey = (error: unknown): string => {
const key = (error as { error?: unknown } | undefined)?.error;
return typeof key === 'string' && KNOWN_SAML_METADATA_ERROR_KEYS.includes(key) ? key : 'SAML_Metadata_fetch_failed';
};
const SamlMetadataModal = ({ onClose, onFetch, onApply, showIdentifierFormat = false }: SamlMetadataModalProps) => {
const { t } = useTranslation();
const [url, setUrl] = useState('');
const [fetching, setFetching] = useState(false);
const [error, setError] = useState<string | null>(null);
const [warnings, setWarnings] = useState<string[]>([]);
const [values, setValues] = useState<SamlMetadataValues | null>(null);
const urlFieldId = useId();
const certFieldId = useId();
const entryPointFieldId = useId();
const sloFieldId = useId();
const identifierFormatFieldId = useId();
const handleFetch = async () => {
if (!url.trim()) {
return;
}
setFetching(true);
setError(null);
try {
const { cert, entryPoint, idpSLORedirectURL, identifierFormat, warnings: fetchWarnings } = await onFetch(url.trim());
setValues({ cert, entryPoint, idpSLORedirectURL, identifierFormat });
setWarnings(fetchWarnings);
} catch (e) {
setError(getSamlMetadataErrorKey(e));
} finally {
setFetching(false);
}
};
const handleApply = () => {
if (values) {
onApply(values);
}
};
const setValue = (key: keyof SamlMetadataValues) => (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { value } = event.currentTarget;
setValues((current) => ({ ...current, [key]: value }));
};
return (
<GenericModal
variant='info'
title={t('SAML_Import_metadata')}
confirmText={values ? t('Apply') : t('SAML_Metadata_fetch')}
cancelText={t('Cancel')}
wrapperFunction={(props) => (
<Box
is='form'
onSubmit={(e) => {
e.preventDefault();
if (values) {
handleApply();
} else {
void handleFetch();
}
}}
{...props}
/>
)}
onCancel={onClose}
onClose={onClose}
confirmDisabled={fetching || (!values && url.trim() === '')}
confirmLoading={fetching}
>
<Box display='flex' flexDirection='column'>
<Box marginBlockEnd={16}>{t('SAML_Metadata_modal_description')}</Box>
<Field>
<FieldLabel htmlFor={urlFieldId}>{t('SAML_Metadata_url')}</FieldLabel>
<FieldRow>
<TextInput
id={urlFieldId}
value={url}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
setUrl(e.currentTarget.value);
setValues(null);
setError(null);
setWarnings([]);
}}
/>
</FieldRow>
</Field>
{error && (
<Callout type='danger' marginBlockStart={16}>
{t(error as Parameters<typeof t>[0])}
</Callout>
)}
{warnings.map((warning) => (
<Callout key={warning} type='warning' marginBlockStart={16}>
{t(warning as Parameters<typeof t>[0])}
</Callout>
))}
{values && (
<>
<Field marginBlockStart={16}>
<FieldLabel htmlFor={entryPointFieldId}>{t('SAML_Custom_Entry_point')}</FieldLabel>
<FieldRow>
<TextInput
id={entryPointFieldId}
value={values.entryPoint ?? ''}
placeholder={t('SAML_Metadata_not_found')}
onChange={setValue('entryPoint')}
/>
</FieldRow>
</Field>
<Field marginBlockStart={16}>
<FieldLabel htmlFor={sloFieldId}>{t('SAML_Custom_IDP_SLO_Redirect_URL')}</FieldLabel>
<FieldRow>
<TextInput
id={sloFieldId}
value={values.idpSLORedirectURL ?? ''}
placeholder={t('SAML_Metadata_not_found')}
onChange={setValue('idpSLORedirectURL')}
/>
</FieldRow>
</Field>
<Field marginBlockStart={16}>
<FieldLabel htmlFor={certFieldId}>{t('SAML_Custom_Cert')}</FieldLabel>
<FieldRow>
<TextAreaInput
id={certFieldId}
rows={5}
value={values.cert ?? ''}
placeholder={t('SAML_Metadata_not_found')}
onChange={setValue('cert')}
/>
</FieldRow>
</Field>
{showIdentifierFormat && (
<Field marginBlockStart={16}>
<FieldLabel htmlFor={identifierFormatFieldId}>{t('SAML_Identifier_Format')}</FieldLabel>
<FieldRow>
<TextInput
id={identifierFormatFieldId}
value={values.identifierFormat ?? ''}
placeholder={t('SAML_Metadata_not_found')}
onChange={setValue('identifierFormat')}
/>
</FieldRow>
</Field>
)}
</>
)}
</Box>
</GenericModal>
);
};
export default SamlMetadataModal;

View File

@@ -0,0 +1 @@
export { default } from './SAMLGroupPage';

View File

@@ -0,0 +1,48 @@
import { Tabs, TabsItem } from '@rocket.chat/fuselage';
import type { TranslationKey } from '@rocket.chat/ui-contexts';
import type { ReactNode } from 'react';
import { memo, useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import GenericGroupPage from './GenericGroupPage';
import { useEditableSettingsGroupSections } from '../../EditableSettingsContext';
export type TabbedGroupPageProps = {
headerButtons?: ReactNode;
_id: string;
i18nLabel: string;
tabs: string[];
onClickBack?: () => void;
};
function TabbedGroupPage({ _id, tabs, i18nLabel, onClickBack, ...props }: TabbedGroupPageProps) {
const { t } = useTranslation();
const [currentTab, setCurrentTab] = useState(tabs[0]);
const handleTabClick = useMemo(() => (tab: string) => (): void => setCurrentTab(tab), [setCurrentTab]);
const sections = useEditableSettingsGroupSections(_id, currentTab);
const tabsComponent = (
<Tabs>
{tabs.map((tabName) => (
<TabsItem key={tabName || ''} selected={currentTab === tabName} onClick={handleTabClick(tabName)}>
{tabName ? t(tabName as TranslationKey) : t(_id as TranslationKey)}
</TabsItem>
))}
</Tabs>
);
return (
<GenericGroupPage
_id={_id}
i18nLabel={i18nLabel}
onClickBack={onClickBack}
sections={sections}
currentTab={currentTab}
tabs={tabsComponent}
{...props}
/>
);
}
export default memo(TabbedGroupPage);