Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/strong-moose-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/localizations': patch
'@clerk/shared': patch
'@clerk/ui': patch
---

Add confirmation dialog for organization domain deletion as part of self-serve SSO
12 changes: 10 additions & 2 deletions packages/localizations/src/en-US.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -213,7 +213,6 @@ export const enUS: LocalizationResource = {
configureSSO: {
confirmation: {
configurationSection: {
certificateLabel: 'Certificate',
configureAgainLink: 'Configure again',
issuerLabel: 'Issuer',
ssoUrlLabel: 'Sign on URL',
Expand DownExpand Up@@ -283,13 +282,23 @@ export const enUS: LocalizationResource = {
badge__verified: 'Verified',
badge__unverified: 'Unverified',
verifiedAtLabel: "Verified on {{ date | shortDate('en-US') }}",
removeButtonTooltip__lastVerifiedDomain: 'At least one verified domain is required to set up SSO.',
removeButtonTooltip__lastVerifiedDomainActive: 'At least one verified domain is required to keep SSO enabled.',
txtRecord: {
instructions: "Add this TXT record to your DNS provider. We'll verify automatically once the record is live.",
typeLabel: 'Type',
hostLabel: 'Host / Name',
valueLabel: 'Value',
},
},
removeDomainDialog: {
title: 'Removing domain',
subtitle__active:
"You're about to remove {{domain}} from this enterprise connection. Users won't be able to sign-in with {{domain}} anymore.",
subtitle__inactive: "You're about to remove {{domain}} from this enterprise connection.",
cancelButton: 'Cancel',
removeButton: 'Remove domain',
},
},
testConfigurationStep: {
title: 'Test your SSO connection',
Expand DownExpand Up@@ -1077,7 +1086,6 @@ export const enUS: LocalizationResource = {
badge__inactive: 'Inactive',
badge__inProgress: 'In Progress',
badge__unconfigured: 'Unconfigured',
certificateLabel: 'Certificate',
descriptionLine1:
'Require members to sign in through your identity provider using their domain email. Members without a matching domain are unaffected.',
descriptionLine2:
Expand Down
20 changes: 18 additions & 2 deletions packages/shared/src/react/hooks/useOrganizationDomains.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';

import { logger } from '../../logger';
import type { GetDomainsParams } from '../../types/organization';
Expand All@@ -24,6 +24,11 @@ export type UseOrganizationDomainsParams = {
* Filter the returned domains by enrollment mode.
*/
enrollmentMode?: OrganizationEnrollmentMode;
/**
* Invoked from the ownership-verification poll whenever an `attempt` resolves
* one or more domains as `verified`.
*/
onOwnershipVerified?: (verifiedDomains: OrganizationDomainResource[]) => void | Promise<void>;
};

export type UseOrganizationDomainsReturn = {
Expand DownExpand Up@@ -59,11 +64,14 @@ export type UseOrganizationDomainsReturn = {
* @internal
*/
function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseOrganizationDomainsReturn {
const { keepPreviousData = true, enabled = true, enrollmentMode } = params;
const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
const clerk = useClerkInstanceContext();
const organization = useOrganizationBase();
const [queryClient] = useClerkQueryClient();

const onOwnershipVerifiedRef = useRef(onOwnershipVerified);
onOwnershipVerifiedRef.current = onOwnershipVerified;

const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
organizationId: organization?.id ?? null,
enrollmentMode,
Expand DownExpand Up@@ -171,6 +179,14 @@ function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseO
return;
}

const verifiedDomains = result?.data.filter(domain => domain.ownershipVerification?.status === 'verified') ?? [];
if (verifiedDomains.length) {
await onOwnershipVerifiedRef.current?.(verifiedDomains);
}
if (cancelled) {
return;
}

// Stop polling once every domain in the attempt response is verified
const allVerified =
!!result?.data.length && result.data.every(domain => domain.ownershipVerification?.status === 'verified');
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/types/enterpriseConnection.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -140,7 +140,7 @@ export type MeEnterpriseConnectionOidcInput = OrganizationEnterpriseConnectionOi

export type CreateOrganizationEnterpriseConnectionParams = {
provider: OrganizationEnterpriseConnectionProvider;
name: string;
name?: string;
/** FQDN strings the connection authenticates. Required by the org-scoped create endpoint. */
domains?: string[];
organizationId?: string | null;
Expand All@@ -153,6 +153,7 @@ export type CreateMeEnterpriseConnectionParams = CreateOrganizationEnterpriseCon

export type UpdateOrganizationEnterpriseConnectionParams = {
name?: string | null;
domains?: string[];
active?: boolean | null;
syncUserAttributes?: boolean | null;
disableAdditionalIdentifications?: boolean | null;
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/types/localization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1153,7 +1153,6 @@ export type __internal_LocalizationResource = {
domainLabel: LocalizationValue;
signOnUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
menuAction__edit: LocalizationValue;
menuAction__activate: LocalizationValue;
menuAction__deactivate: LocalizationValue;
Expand DownExpand Up@@ -1382,13 +1381,22 @@ export type __internal_LocalizationResource = {
badge__verified: LocalizationValue;
badge__unverified: LocalizationValue;
verifiedAtLabel: LocalizationValue<'date'>;
removeButtonTooltip__lastVerifiedDomain: LocalizationValue;
removeButtonTooltip__lastVerifiedDomainActive: LocalizationValue;
txtRecord: {
instructions: LocalizationValue;
typeLabel: LocalizationValue;
hostLabel: LocalizationValue;
valueLabel: LocalizationValue;
};
};
removeDomainDialog: {
title: LocalizationValue;
subtitle__active: LocalizationValue<'domain'>;
subtitle__inactive: LocalizationValue<'domain'>;
cancelButton: LocalizationValue;
removeButton: LocalizationValue;
};
};
testConfigurationStep: {
title: LocalizationValue;
Expand DownExpand Up@@ -1835,7 +1843,6 @@ export type __internal_LocalizationResource = {
title: LocalizationValue;
ssoUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
configureAgainLink: LocalizationValue;
};
resetSection: {
Expand Down
109 changes: 109 additions & 0 deletions packages/ui/src/components/ConfigureSSO/RemoveDomainDialog.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
import { useMemo } from 'react';

import { Col, descriptors, localizationKeys } from '@/customizables';
import { Card } from '@/elements/Card';
import { useCardState, withCardStateProvider } from '@/elements/contexts';
import { Form } from '@/elements/Form';
import { FormButtonContainer } from '@/elements/FormButtons';
import { FormContainer } from '@/elements/FormContainer';
import { Modal } from '@/elements/Modal';
import { handleError } from '@/utils/errorHandler';

type RemoveDomainDialogProps = {
isOpen: boolean;
onClose: () => void;
domain: string;
isConnectionActive: boolean;
onRemove: () => Promise<unknown>;
contentRef: React.RefObject<HTMLDivElement>;
};

export const RemoveDomainDialog = (props: RemoveDomainDialogProps): JSX.Element | null => {
if (!props.isOpen) {
return null;
}

return (
<Modal
handleClose={props.onClose}
canCloseModal={false}
portalRoot={props.contentRef}
containerSx={t => ({
alignItems: 'center',
position: 'absolute',
inset: 0,
width: 'auto',
height: 'auto',
backgroundColor: 'inherit',
backdropFilter: `blur(${t.sizes.$2})`,
})}
>
<RemoveDomainDialogContent {...props} />
</Modal>
);
};

const RemoveDomainDialogContent = withCardStateProvider((props: RemoveDomainDialogProps) => {
const { onClose, onRemove } = props;
const card = useCardState();

const subtitle = useMemo(
() =>
props.isConnectionActive
? localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__active', {
domain: props.domain,
})
: localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__inactive', {
domain: props.domain,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const onSubmit = async () => {
try {
await onRemove();
onClose();
} catch (err) {
handleError(err as Error, [], card.setError);
}
};

return (
<Card.Root
elementDescriptor={descriptors.configureSSORemoveDomainDialog}
sx={t => ({ borderRadius: t.radii.$md })}
>
<Card.Content sx={t => ({ textAlign: 'start', padding: t.sizes.$5 })}>
<FormContainer
headerTitle={localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.title')}
headerSubtitle={subtitle}
sx={t => ({ gap: t.space.$4 })}
>
<Form.Root onSubmit={onSubmit}>
<Col gap={4}>
<FormButtonContainer>
<Form.SubmitButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogSubmitButton}
block={false}
colorScheme='danger'
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.removeButton',
)}
/>
<Form.ResetButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogCancelButton}
block={false}
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.cancelButton',
)}
onClick={onClose}
/>
</FormButtonContainer>
</Col>
</Form.Root>
</FormContainer>
</Card.Content>
</Card.Root>
);
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render, screen, waitFor } from '@/test/utils';
import { CardStateProvider } from '@/ui/elements/contexts';

import { RemoveDomainDialog } from '../RemoveDomainDialog';

const onRemove = vi.fn();

const { createFixtures } = bindCreateFixtures('ConfigureSSO');

const renderDialog = (
wrapper: React.ComponentType<{ children?: React.ReactNode }>,
props: {
isOpen?: boolean;
onClose?: () => void;
domain?: string;
isConnectionActive?: boolean;
} = {},
) => {
const onClose = props.onClose ?? vi.fn();
const utils = render(
<CardStateProvider>
<RemoveDomainDialog
isOpen={props.isOpen ?? true}
onClose={onClose}
domain={props.domain ?? 'acme.com'}
isConnectionActive={props.isConnectionActive ?? false}
onRemove={() => onRemove()}
contentRef={{ current: null }}
/>
</CardStateProvider>,
{ wrapper },
);
return { ...utils, onClose };
};

const resetMocks = () => {
onRemove.mockReset();
onRemove.mockResolvedValue(undefined);
};

describe('RemoveDomainDialog', () => {
it('does not render when `isOpen` is `false`', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { isOpen: false });

expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Removing domain' })).not.toBeInTheDocument();
});

it('renders the dialog chrome and actions when isOpen is true', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com' });

expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Removing domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});

it('warns about sign-in impact when the connection is active', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: true });

expect(screen.getByText(/Users won't be able to sign-in with acme\.com anymore/i)).toBeInTheDocument();
});

it('shows the neutral copy when the connection is inactive', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: false });

expect(screen.getByText("You're about to remove acme.com from this enterprise connection.")).toBeInTheDocument();
expect(screen.queryByText(/Users won't be able to sign-in/i)).not.toBeInTheDocument();
});

it('invokes onClose when Cancel is clicked', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onRemove).not.toHaveBeenCalled();
});

it('awaits the removal and closes on a successful submit', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});

it('keeps the dialog open and surfaces an error when removal fails', async () => {
resetMocks();
onRemove.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'internal_server_error',
long_message: 'Something went wrong while removing the domain.',
message: 'Removal failed.',
},
],
status: 500,
}),
);
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
expect(await screen.findByText('Something went wrong while removing the domain.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});
});
Comment thread
LauraBeatris marked this conversation as resolved.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(ui,shared,localizations): Delete organization domains in self-serve SSO by LauraBeatris · Pull Request #8866 · clerk/javascript · GitHub
Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/strong-moose-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/localizations': patch
'@clerk/shared': patch
'@clerk/ui': patch
---

Add confirmation dialog for organization domain deletion as part of self-serve SSO
12 changes: 10 additions & 2 deletions packages/localizations/src/en-US.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -213,7 +213,6 @@ export const enUS: LocalizationResource = {
configureSSO: {
confirmation: {
configurationSection: {
certificateLabel: 'Certificate',
configureAgainLink: 'Configure again',
issuerLabel: 'Issuer',
ssoUrlLabel: 'Sign on URL',
Expand DownExpand Up@@ -283,13 +282,23 @@ export const enUS: LocalizationResource = {
badge__verified: 'Verified',
badge__unverified: 'Unverified',
verifiedAtLabel: "Verified on {{ date | shortDate('en-US') }}",
removeButtonTooltip__lastVerifiedDomain: 'At least one verified domain is required to set up SSO.',
removeButtonTooltip__lastVerifiedDomainActive: 'At least one verified domain is required to keep SSO enabled.',
txtRecord: {
instructions: "Add this TXT record to your DNS provider. We'll verify automatically once the record is live.",
typeLabel: 'Type',
hostLabel: 'Host / Name',
valueLabel: 'Value',
},
},
removeDomainDialog: {
title: 'Removing domain',
subtitle__active:
"You're about to remove {{domain}} from this enterprise connection. Users won't be able to sign-in with {{domain}} anymore.",
subtitle__inactive: "You're about to remove {{domain}} from this enterprise connection.",
cancelButton: 'Cancel',
removeButton: 'Remove domain',
},
},
testConfigurationStep: {
title: 'Test your SSO connection',
Expand DownExpand Up@@ -1077,7 +1086,6 @@ export const enUS: LocalizationResource = {
badge__inactive: 'Inactive',
badge__inProgress: 'In Progress',
badge__unconfigured: 'Unconfigured',
certificateLabel: 'Certificate',
descriptionLine1:
'Require members to sign in through your identity provider using their domain email. Members without a matching domain are unaffected.',
descriptionLine2:
Expand Down
20 changes: 18 additions & 2 deletions packages/shared/src/react/hooks/useOrganizationDomains.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';

import { logger } from '../../logger';
import type { GetDomainsParams } from '../../types/organization';
Expand All@@ -24,6 +24,11 @@ export type UseOrganizationDomainsParams = {
* Filter the returned domains by enrollment mode.
*/
enrollmentMode?: OrganizationEnrollmentMode;
/**
* Invoked from the ownership-verification poll whenever an `attempt` resolves
* one or more domains as `verified`.
*/
onOwnershipVerified?: (verifiedDomains: OrganizationDomainResource[]) => void | Promise<void>;
};

export type UseOrganizationDomainsReturn = {
Expand DownExpand Up@@ -59,11 +64,14 @@ export type UseOrganizationDomainsReturn = {
* @internal
*/
function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseOrganizationDomainsReturn {
const { keepPreviousData = true, enabled = true, enrollmentMode } = params;
const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
const clerk = useClerkInstanceContext();
const organization = useOrganizationBase();
const [queryClient] = useClerkQueryClient();

const onOwnershipVerifiedRef = useRef(onOwnershipVerified);
onOwnershipVerifiedRef.current = onOwnershipVerified;

const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
organizationId: organization?.id ?? null,
enrollmentMode,
Expand DownExpand Up@@ -171,6 +179,14 @@ function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseO
return;
}

const verifiedDomains = result?.data.filter(domain => domain.ownershipVerification?.status === 'verified') ?? [];
if (verifiedDomains.length) {
await onOwnershipVerifiedRef.current?.(verifiedDomains);
}
if (cancelled) {
return;
}

// Stop polling once every domain in the attempt response is verified
const allVerified =
!!result?.data.length && result.data.every(domain => domain.ownershipVerification?.status === 'verified');
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/types/enterpriseConnection.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -140,7 +140,7 @@ export type MeEnterpriseConnectionOidcInput = OrganizationEnterpriseConnectionOi

export type CreateOrganizationEnterpriseConnectionParams = {
provider: OrganizationEnterpriseConnectionProvider;
name: string;
name?: string;
/** FQDN strings the connection authenticates. Required by the org-scoped create endpoint. */
domains?: string[];
organizationId?: string | null;
Expand All@@ -153,6 +153,7 @@ export type CreateMeEnterpriseConnectionParams = CreateOrganizationEnterpriseCon

export type UpdateOrganizationEnterpriseConnectionParams = {
name?: string | null;
domains?: string[];
active?: boolean | null;
syncUserAttributes?: boolean | null;
disableAdditionalIdentifications?: boolean | null;
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/types/localization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1153,7 +1153,6 @@ export type __internal_LocalizationResource = {
domainLabel: LocalizationValue;
signOnUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
menuAction__edit: LocalizationValue;
menuAction__activate: LocalizationValue;
menuAction__deactivate: LocalizationValue;
Expand DownExpand Up@@ -1382,13 +1381,22 @@ export type __internal_LocalizationResource = {
badge__verified: LocalizationValue;
badge__unverified: LocalizationValue;
verifiedAtLabel: LocalizationValue<'date'>;
removeButtonTooltip__lastVerifiedDomain: LocalizationValue;
removeButtonTooltip__lastVerifiedDomainActive: LocalizationValue;
txtRecord: {
instructions: LocalizationValue;
typeLabel: LocalizationValue;
hostLabel: LocalizationValue;
valueLabel: LocalizationValue;
};
};
removeDomainDialog: {
title: LocalizationValue;
subtitle__active: LocalizationValue<'domain'>;
subtitle__inactive: LocalizationValue<'domain'>;
cancelButton: LocalizationValue;
removeButton: LocalizationValue;
};
};
testConfigurationStep: {
title: LocalizationValue;
Expand DownExpand Up@@ -1835,7 +1843,6 @@ export type __internal_LocalizationResource = {
title: LocalizationValue;
ssoUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
configureAgainLink: LocalizationValue;
};
resetSection: {
Expand Down
109 changes: 109 additions & 0 deletions packages/ui/src/components/ConfigureSSO/RemoveDomainDialog.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
import { useMemo } from 'react';

import { Col, descriptors, localizationKeys } from '@/customizables';
import { Card } from '@/elements/Card';
import { useCardState, withCardStateProvider } from '@/elements/contexts';
import { Form } from '@/elements/Form';
import { FormButtonContainer } from '@/elements/FormButtons';
import { FormContainer } from '@/elements/FormContainer';
import { Modal } from '@/elements/Modal';
import { handleError } from '@/utils/errorHandler';

type RemoveDomainDialogProps = {
isOpen: boolean;
onClose: () => void;
domain: string;
isConnectionActive: boolean;
onRemove: () => Promise<unknown>;
contentRef: React.RefObject<HTMLDivElement>;
};

export const RemoveDomainDialog = (props: RemoveDomainDialogProps): JSX.Element | null => {
if (!props.isOpen) {
return null;
}

return (
<Modal
handleClose={props.onClose}
canCloseModal={false}
portalRoot={props.contentRef}
containerSx={t => ({
alignItems: 'center',
position: 'absolute',
inset: 0,
width: 'auto',
height: 'auto',
backgroundColor: 'inherit',
backdropFilter: `blur(${t.sizes.$2})`,
})}
>
<RemoveDomainDialogContent {...props} />
</Modal>
);
};

const RemoveDomainDialogContent = withCardStateProvider((props: RemoveDomainDialogProps) => {
const { onClose, onRemove } = props;
const card = useCardState();

const subtitle = useMemo(
() =>
props.isConnectionActive
? localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__active', {
domain: props.domain,
})
: localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__inactive', {
domain: props.domain,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const onSubmit = async () => {
try {
await onRemove();
onClose();
} catch (err) {
handleError(err as Error, [], card.setError);
}
};

return (
<Card.Root
elementDescriptor={descriptors.configureSSORemoveDomainDialog}
sx={t => ({ borderRadius: t.radii.$md })}
>
<Card.Content sx={t => ({ textAlign: 'start', padding: t.sizes.$5 })}>
<FormContainer
headerTitle={localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.title')}
headerSubtitle={subtitle}
sx={t => ({ gap: t.space.$4 })}
>
<Form.Root onSubmit={onSubmit}>
<Col gap={4}>
<FormButtonContainer>
<Form.SubmitButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogSubmitButton}
block={false}
colorScheme='danger'
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.removeButton',
)}
/>
<Form.ResetButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogCancelButton}
block={false}
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.cancelButton',
)}
onClick={onClose}
/>
</FormButtonContainer>
</Col>
</Form.Root>
</FormContainer>
</Card.Content>
</Card.Root>
);
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render, screen, waitFor } from '@/test/utils';
import { CardStateProvider } from '@/ui/elements/contexts';

import { RemoveDomainDialog } from '../RemoveDomainDialog';

const onRemove = vi.fn();

const { createFixtures } = bindCreateFixtures('ConfigureSSO');

const renderDialog = (
wrapper: React.ComponentType<{ children?: React.ReactNode }>,
props: {
isOpen?: boolean;
onClose?: () => void;
domain?: string;
isConnectionActive?: boolean;
} = {},
) => {
const onClose = props.onClose ?? vi.fn();
const utils = render(
<CardStateProvider>
<RemoveDomainDialog
isOpen={props.isOpen ?? true}
onClose={onClose}
domain={props.domain ?? 'acme.com'}
isConnectionActive={props.isConnectionActive ?? false}
onRemove={() => onRemove()}
contentRef={{ current: null }}
/>
</CardStateProvider>,
{ wrapper },
);
return { ...utils, onClose };
};

const resetMocks = () => {
onRemove.mockReset();
onRemove.mockResolvedValue(undefined);
};

describe('RemoveDomainDialog', () => {
it('does not render when `isOpen` is `false`', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { isOpen: false });

expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Removing domain' })).not.toBeInTheDocument();
});

it('renders the dialog chrome and actions when isOpen is true', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com' });

expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Removing domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});

it('warns about sign-in impact when the connection is active', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: true });

expect(screen.getByText(/Users won't be able to sign-in with acme\.com anymore/i)).toBeInTheDocument();
});

it('shows the neutral copy when the connection is inactive', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: false });

expect(screen.getByText("You're about to remove acme.com from this enterprise connection.")).toBeInTheDocument();
expect(screen.queryByText(/Users won't be able to sign-in/i)).not.toBeInTheDocument();
});

it('invokes onClose when Cancel is clicked', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onRemove).not.toHaveBeenCalled();
});

it('awaits the removal and closes on a successful submit', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});

it('keeps the dialog open and surfaces an error when removal fails', async () => {
resetMocks();
onRemove.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'internal_server_error',
long_message: 'Something went wrong while removing the domain.',
message: 'Removal failed.',
},
],
status: 500,
}),
);
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
expect(await screen.findByText('Something went wrong while removing the domain.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});
});
Comment thread
LauraBeatris marked this conversation as resolved.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(ui,shared,localizations): Delete organization domains in self-serve SSO by LauraBeatris · Pull Request #8866 · clerk/javascript · GitHub
Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/strong-moose-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/localizations': patch
'@clerk/shared': patch
'@clerk/ui': patch
---

Add confirmation dialog for organization domain deletion as part of self-serve SSO
12 changes: 10 additions & 2 deletions packages/localizations/src/en-US.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -213,7 +213,6 @@ export const enUS: LocalizationResource = {
configureSSO: {
confirmation: {
configurationSection: {
certificateLabel: 'Certificate',
configureAgainLink: 'Configure again',
issuerLabel: 'Issuer',
ssoUrlLabel: 'Sign on URL',
Expand DownExpand Up@@ -283,13 +282,23 @@ export const enUS: LocalizationResource = {
badge__verified: 'Verified',
badge__unverified: 'Unverified',
verifiedAtLabel: "Verified on {{ date | shortDate('en-US') }}",
removeButtonTooltip__lastVerifiedDomain: 'At least one verified domain is required to set up SSO.',
removeButtonTooltip__lastVerifiedDomainActive: 'At least one verified domain is required to keep SSO enabled.',
txtRecord: {
instructions: "Add this TXT record to your DNS provider. We'll verify automatically once the record is live.",
typeLabel: 'Type',
hostLabel: 'Host / Name',
valueLabel: 'Value',
},
},
removeDomainDialog: {
title: 'Removing domain',
subtitle__active:
"You're about to remove {{domain}} from this enterprise connection. Users won't be able to sign-in with {{domain}} anymore.",
subtitle__inactive: "You're about to remove {{domain}} from this enterprise connection.",
cancelButton: 'Cancel',
removeButton: 'Remove domain',
},
},
testConfigurationStep: {
title: 'Test your SSO connection',
Expand DownExpand Up@@ -1077,7 +1086,6 @@ export const enUS: LocalizationResource = {
badge__inactive: 'Inactive',
badge__inProgress: 'In Progress',
badge__unconfigured: 'Unconfigured',
certificateLabel: 'Certificate',
descriptionLine1:
'Require members to sign in through your identity provider using their domain email. Members without a matching domain are unaffected.',
descriptionLine2:
Expand Down
20 changes: 18 additions & 2 deletions packages/shared/src/react/hooks/useOrganizationDomains.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';

import { logger } from '../../logger';
import type { GetDomainsParams } from '../../types/organization';
Expand All@@ -24,6 +24,11 @@ export type UseOrganizationDomainsParams = {
* Filter the returned domains by enrollment mode.
*/
enrollmentMode?: OrganizationEnrollmentMode;
/**
* Invoked from the ownership-verification poll whenever an `attempt` resolves
* one or more domains as `verified`.
*/
onOwnershipVerified?: (verifiedDomains: OrganizationDomainResource[]) => void | Promise<void>;
};

export type UseOrganizationDomainsReturn = {
Expand DownExpand Up@@ -59,11 +64,14 @@ export type UseOrganizationDomainsReturn = {
* @internal
*/
function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseOrganizationDomainsReturn {
const { keepPreviousData = true, enabled = true, enrollmentMode } = params;
const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
const clerk = useClerkInstanceContext();
const organization = useOrganizationBase();
const [queryClient] = useClerkQueryClient();

const onOwnershipVerifiedRef = useRef(onOwnershipVerified);
onOwnershipVerifiedRef.current = onOwnershipVerified;

const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
organizationId: organization?.id ?? null,
enrollmentMode,
Expand DownExpand Up@@ -171,6 +179,14 @@ function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseO
return;
}

const verifiedDomains = result?.data.filter(domain => domain.ownershipVerification?.status === 'verified') ?? [];
if (verifiedDomains.length) {
await onOwnershipVerifiedRef.current?.(verifiedDomains);
}
if (cancelled) {
return;
}

// Stop polling once every domain in the attempt response is verified
const allVerified =
!!result?.data.length && result.data.every(domain => domain.ownershipVerification?.status === 'verified');
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/types/enterpriseConnection.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -140,7 +140,7 @@ export type MeEnterpriseConnectionOidcInput = OrganizationEnterpriseConnectionOi

export type CreateOrganizationEnterpriseConnectionParams = {
provider: OrganizationEnterpriseConnectionProvider;
name: string;
name?: string;
/** FQDN strings the connection authenticates. Required by the org-scoped create endpoint. */
domains?: string[];
organizationId?: string | null;
Expand All@@ -153,6 +153,7 @@ export type CreateMeEnterpriseConnectionParams = CreateOrganizationEnterpriseCon

export type UpdateOrganizationEnterpriseConnectionParams = {
name?: string | null;
domains?: string[];
active?: boolean | null;
syncUserAttributes?: boolean | null;
disableAdditionalIdentifications?: boolean | null;
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/types/localization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1153,7 +1153,6 @@ export type __internal_LocalizationResource = {
domainLabel: LocalizationValue;
signOnUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
menuAction__edit: LocalizationValue;
menuAction__activate: LocalizationValue;
menuAction__deactivate: LocalizationValue;
Expand DownExpand Up@@ -1382,13 +1381,22 @@ export type __internal_LocalizationResource = {
badge__verified: LocalizationValue;
badge__unverified: LocalizationValue;
verifiedAtLabel: LocalizationValue<'date'>;
removeButtonTooltip__lastVerifiedDomain: LocalizationValue;
removeButtonTooltip__lastVerifiedDomainActive: LocalizationValue;
txtRecord: {
instructions: LocalizationValue;
typeLabel: LocalizationValue;
hostLabel: LocalizationValue;
valueLabel: LocalizationValue;
};
};
removeDomainDialog: {
title: LocalizationValue;
subtitle__active: LocalizationValue<'domain'>;
subtitle__inactive: LocalizationValue<'domain'>;
cancelButton: LocalizationValue;
removeButton: LocalizationValue;
};
};
testConfigurationStep: {
title: LocalizationValue;
Expand DownExpand Up@@ -1835,7 +1843,6 @@ export type __internal_LocalizationResource = {
title: LocalizationValue;
ssoUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
configureAgainLink: LocalizationValue;
};
resetSection: {
Expand Down
109 changes: 109 additions & 0 deletions packages/ui/src/components/ConfigureSSO/RemoveDomainDialog.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
import { useMemo } from 'react';

import { Col, descriptors, localizationKeys } from '@/customizables';
import { Card } from '@/elements/Card';
import { useCardState, withCardStateProvider } from '@/elements/contexts';
import { Form } from '@/elements/Form';
import { FormButtonContainer } from '@/elements/FormButtons';
import { FormContainer } from '@/elements/FormContainer';
import { Modal } from '@/elements/Modal';
import { handleError } from '@/utils/errorHandler';

type RemoveDomainDialogProps = {
isOpen: boolean;
onClose: () => void;
domain: string;
isConnectionActive: boolean;
onRemove: () => Promise<unknown>;
contentRef: React.RefObject<HTMLDivElement>;
};

export const RemoveDomainDialog = (props: RemoveDomainDialogProps): JSX.Element | null => {
if (!props.isOpen) {
return null;
}

return (
<Modal
handleClose={props.onClose}
canCloseModal={false}
portalRoot={props.contentRef}
containerSx={t => ({
alignItems: 'center',
position: 'absolute',
inset: 0,
width: 'auto',
height: 'auto',
backgroundColor: 'inherit',
backdropFilter: `blur(${t.sizes.$2})`,
})}
>
<RemoveDomainDialogContent {...props} />
</Modal>
);
};

const RemoveDomainDialogContent = withCardStateProvider((props: RemoveDomainDialogProps) => {
const { onClose, onRemove } = props;
const card = useCardState();

const subtitle = useMemo(
() =>
props.isConnectionActive
? localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__active', {
domain: props.domain,
})
: localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__inactive', {
domain: props.domain,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const onSubmit = async () => {
try {
await onRemove();
onClose();
} catch (err) {
handleError(err as Error, [], card.setError);
}
};

return (
<Card.Root
elementDescriptor={descriptors.configureSSORemoveDomainDialog}
sx={t => ({ borderRadius: t.radii.$md })}
>
<Card.Content sx={t => ({ textAlign: 'start', padding: t.sizes.$5 })}>
<FormContainer
headerTitle={localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.title')}
headerSubtitle={subtitle}
sx={t => ({ gap: t.space.$4 })}
>
<Form.Root onSubmit={onSubmit}>
<Col gap={4}>
<FormButtonContainer>
<Form.SubmitButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogSubmitButton}
block={false}
colorScheme='danger'
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.removeButton',
)}
/>
<Form.ResetButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogCancelButton}
block={false}
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.cancelButton',
)}
onClick={onClose}
/>
</FormButtonContainer>
</Col>
</Form.Root>
</FormContainer>
</Card.Content>
</Card.Root>
);
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render, screen, waitFor } from '@/test/utils';
import { CardStateProvider } from '@/ui/elements/contexts';

import { RemoveDomainDialog } from '../RemoveDomainDialog';

const onRemove = vi.fn();

const { createFixtures } = bindCreateFixtures('ConfigureSSO');

const renderDialog = (
wrapper: React.ComponentType<{ children?: React.ReactNode }>,
props: {
isOpen?: boolean;
onClose?: () => void;
domain?: string;
isConnectionActive?: boolean;
} = {},
) => {
const onClose = props.onClose ?? vi.fn();
const utils = render(
<CardStateProvider>
<RemoveDomainDialog
isOpen={props.isOpen ?? true}
onClose={onClose}
domain={props.domain ?? 'acme.com'}
isConnectionActive={props.isConnectionActive ?? false}
onRemove={() => onRemove()}
contentRef={{ current: null }}
/>
</CardStateProvider>,
{ wrapper },
);
return { ...utils, onClose };
};

const resetMocks = () => {
onRemove.mockReset();
onRemove.mockResolvedValue(undefined);
};

describe('RemoveDomainDialog', () => {
it('does not render when `isOpen` is `false`', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { isOpen: false });

expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Removing domain' })).not.toBeInTheDocument();
});

it('renders the dialog chrome and actions when isOpen is true', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com' });

expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Removing domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});

it('warns about sign-in impact when the connection is active', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: true });

expect(screen.getByText(/Users won't be able to sign-in with acme\.com anymore/i)).toBeInTheDocument();
});

it('shows the neutral copy when the connection is inactive', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: false });

expect(screen.getByText("You're about to remove acme.com from this enterprise connection.")).toBeInTheDocument();
expect(screen.queryByText(/Users won't be able to sign-in/i)).not.toBeInTheDocument();
});

it('invokes onClose when Cancel is clicked', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onRemove).not.toHaveBeenCalled();
});

it('awaits the removal and closes on a successful submit', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});

it('keeps the dialog open and surfaces an error when removal fails', async () => {
resetMocks();
onRemove.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'internal_server_error',
long_message: 'Something went wrong while removing the domain.',
message: 'Removal failed.',
},
],
status: 500,
}),
);
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
expect(await screen.findByText('Something went wrong while removing the domain.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});
});
Comment thread
LauraBeatris marked this conversation as resolved.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(ui,shared,localizations): Delete organization domains in self-serve SSO by LauraBeatris · Pull Request #8866 · clerk/javascript · GitHub
Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/strong-moose-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/localizations': patch
'@clerk/shared': patch
'@clerk/ui': patch
---

Add confirmation dialog for organization domain deletion as part of self-serve SSO
12 changes: 10 additions & 2 deletions packages/localizations/src/en-US.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -213,7 +213,6 @@ export const enUS: LocalizationResource = {
configureSSO: {
confirmation: {
configurationSection: {
certificateLabel: 'Certificate',
configureAgainLink: 'Configure again',
issuerLabel: 'Issuer',
ssoUrlLabel: 'Sign on URL',
Expand DownExpand Up@@ -283,13 +282,23 @@ export const enUS: LocalizationResource = {
badge__verified: 'Verified',
badge__unverified: 'Unverified',
verifiedAtLabel: "Verified on {{ date | shortDate('en-US') }}",
removeButtonTooltip__lastVerifiedDomain: 'At least one verified domain is required to set up SSO.',
removeButtonTooltip__lastVerifiedDomainActive: 'At least one verified domain is required to keep SSO enabled.',
txtRecord: {
instructions: "Add this TXT record to your DNS provider. We'll verify automatically once the record is live.",
typeLabel: 'Type',
hostLabel: 'Host / Name',
valueLabel: 'Value',
},
},
removeDomainDialog: {
title: 'Removing domain',
subtitle__active:
"You're about to remove {{domain}} from this enterprise connection. Users won't be able to sign-in with {{domain}} anymore.",
subtitle__inactive: "You're about to remove {{domain}} from this enterprise connection.",
cancelButton: 'Cancel',
removeButton: 'Remove domain',
},
},
testConfigurationStep: {
title: 'Test your SSO connection',
Expand DownExpand Up@@ -1077,7 +1086,6 @@ export const enUS: LocalizationResource = {
badge__inactive: 'Inactive',
badge__inProgress: 'In Progress',
badge__unconfigured: 'Unconfigured',
certificateLabel: 'Certificate',
descriptionLine1:
'Require members to sign in through your identity provider using their domain email. Members without a matching domain are unaffected.',
descriptionLine2:
Expand Down
20 changes: 18 additions & 2 deletions packages/shared/src/react/hooks/useOrganizationDomains.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';

import { logger } from '../../logger';
import type { GetDomainsParams } from '../../types/organization';
Expand All@@ -24,6 +24,11 @@ export type UseOrganizationDomainsParams = {
* Filter the returned domains by enrollment mode.
*/
enrollmentMode?: OrganizationEnrollmentMode;
/**
* Invoked from the ownership-verification poll whenever an `attempt` resolves
* one or more domains as `verified`.
*/
onOwnershipVerified?: (verifiedDomains: OrganizationDomainResource[]) => void | Promise<void>;
};

export type UseOrganizationDomainsReturn = {
Expand DownExpand Up@@ -59,11 +64,14 @@ export type UseOrganizationDomainsReturn = {
* @internal
*/
function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseOrganizationDomainsReturn {
const { keepPreviousData = true, enabled = true, enrollmentMode } = params;
const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
const clerk = useClerkInstanceContext();
const organization = useOrganizationBase();
const [queryClient] = useClerkQueryClient();

const onOwnershipVerifiedRef = useRef(onOwnershipVerified);
onOwnershipVerifiedRef.current = onOwnershipVerified;

const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
organizationId: organization?.id ?? null,
enrollmentMode,
Expand DownExpand Up@@ -171,6 +179,14 @@ function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseO
return;
}

const verifiedDomains = result?.data.filter(domain => domain.ownershipVerification?.status === 'verified') ?? [];
if (verifiedDomains.length) {
await onOwnershipVerifiedRef.current?.(verifiedDomains);
}
if (cancelled) {
return;
}

// Stop polling once every domain in the attempt response is verified
const allVerified =
!!result?.data.length && result.data.every(domain => domain.ownershipVerification?.status === 'verified');
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/types/enterpriseConnection.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -140,7 +140,7 @@ export type MeEnterpriseConnectionOidcInput = OrganizationEnterpriseConnectionOi

export type CreateOrganizationEnterpriseConnectionParams = {
provider: OrganizationEnterpriseConnectionProvider;
name: string;
name?: string;
/** FQDN strings the connection authenticates. Required by the org-scoped create endpoint. */
domains?: string[];
organizationId?: string | null;
Expand All@@ -153,6 +153,7 @@ export type CreateMeEnterpriseConnectionParams = CreateOrganizationEnterpriseCon

export type UpdateOrganizationEnterpriseConnectionParams = {
name?: string | null;
domains?: string[];
active?: boolean | null;
syncUserAttributes?: boolean | null;
disableAdditionalIdentifications?: boolean | null;
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/types/localization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1153,7 +1153,6 @@ export type __internal_LocalizationResource = {
domainLabel: LocalizationValue;
signOnUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
menuAction__edit: LocalizationValue;
menuAction__activate: LocalizationValue;
menuAction__deactivate: LocalizationValue;
Expand DownExpand Up@@ -1382,13 +1381,22 @@ export type __internal_LocalizationResource = {
badge__verified: LocalizationValue;
badge__unverified: LocalizationValue;
verifiedAtLabel: LocalizationValue<'date'>;
removeButtonTooltip__lastVerifiedDomain: LocalizationValue;
removeButtonTooltip__lastVerifiedDomainActive: LocalizationValue;
txtRecord: {
instructions: LocalizationValue;
typeLabel: LocalizationValue;
hostLabel: LocalizationValue;
valueLabel: LocalizationValue;
};
};
removeDomainDialog: {
title: LocalizationValue;
subtitle__active: LocalizationValue<'domain'>;
subtitle__inactive: LocalizationValue<'domain'>;
cancelButton: LocalizationValue;
removeButton: LocalizationValue;
};
};
testConfigurationStep: {
title: LocalizationValue;
Expand DownExpand Up@@ -1835,7 +1843,6 @@ export type __internal_LocalizationResource = {
title: LocalizationValue;
ssoUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
configureAgainLink: LocalizationValue;
};
resetSection: {
Expand Down
109 changes: 109 additions & 0 deletions packages/ui/src/components/ConfigureSSO/RemoveDomainDialog.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
import { useMemo } from 'react';

import { Col, descriptors, localizationKeys } from '@/customizables';
import { Card } from '@/elements/Card';
import { useCardState, withCardStateProvider } from '@/elements/contexts';
import { Form } from '@/elements/Form';
import { FormButtonContainer } from '@/elements/FormButtons';
import { FormContainer } from '@/elements/FormContainer';
import { Modal } from '@/elements/Modal';
import { handleError } from '@/utils/errorHandler';

type RemoveDomainDialogProps = {
isOpen: boolean;
onClose: () => void;
domain: string;
isConnectionActive: boolean;
onRemove: () => Promise<unknown>;
contentRef: React.RefObject<HTMLDivElement>;
};

export const RemoveDomainDialog = (props: RemoveDomainDialogProps): JSX.Element | null => {
if (!props.isOpen) {
return null;
}

return (
<Modal
handleClose={props.onClose}
canCloseModal={false}
portalRoot={props.contentRef}
containerSx={t => ({
alignItems: 'center',
position: 'absolute',
inset: 0,
width: 'auto',
height: 'auto',
backgroundColor: 'inherit',
backdropFilter: `blur(${t.sizes.$2})`,
})}
>
<RemoveDomainDialogContent {...props} />
</Modal>
);
};

const RemoveDomainDialogContent = withCardStateProvider((props: RemoveDomainDialogProps) => {
const { onClose, onRemove } = props;
const card = useCardState();

const subtitle = useMemo(
() =>
props.isConnectionActive
? localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__active', {
domain: props.domain,
})
: localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__inactive', {
domain: props.domain,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const onSubmit = async () => {
try {
await onRemove();
onClose();
} catch (err) {
handleError(err as Error, [], card.setError);
}
};

return (
<Card.Root
elementDescriptor={descriptors.configureSSORemoveDomainDialog}
sx={t => ({ borderRadius: t.radii.$md })}
>
<Card.Content sx={t => ({ textAlign: 'start', padding: t.sizes.$5 })}>
<FormContainer
headerTitle={localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.title')}
headerSubtitle={subtitle}
sx={t => ({ gap: t.space.$4 })}
>
<Form.Root onSubmit={onSubmit}>
<Col gap={4}>
<FormButtonContainer>
<Form.SubmitButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogSubmitButton}
block={false}
colorScheme='danger'
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.removeButton',
)}
/>
<Form.ResetButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogCancelButton}
block={false}
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.cancelButton',
)}
onClick={onClose}
/>
</FormButtonContainer>
</Col>
</Form.Root>
</FormContainer>
</Card.Content>
</Card.Root>
);
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render, screen, waitFor } from '@/test/utils';
import { CardStateProvider } from '@/ui/elements/contexts';

import { RemoveDomainDialog } from '../RemoveDomainDialog';

const onRemove = vi.fn();

const { createFixtures } = bindCreateFixtures('ConfigureSSO');

const renderDialog = (
wrapper: React.ComponentType<{ children?: React.ReactNode }>,
props: {
isOpen?: boolean;
onClose?: () => void;
domain?: string;
isConnectionActive?: boolean;
} = {},
) => {
const onClose = props.onClose ?? vi.fn();
const utils = render(
<CardStateProvider>
<RemoveDomainDialog
isOpen={props.isOpen ?? true}
onClose={onClose}
domain={props.domain ?? 'acme.com'}
isConnectionActive={props.isConnectionActive ?? false}
onRemove={() => onRemove()}
contentRef={{ current: null }}
/>
</CardStateProvider>,
{ wrapper },
);
return { ...utils, onClose };
};

const resetMocks = () => {
onRemove.mockReset();
onRemove.mockResolvedValue(undefined);
};

describe('RemoveDomainDialog', () => {
it('does not render when `isOpen` is `false`', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { isOpen: false });

expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Removing domain' })).not.toBeInTheDocument();
});

it('renders the dialog chrome and actions when isOpen is true', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com' });

expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Removing domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});

it('warns about sign-in impact when the connection is active', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: true });

expect(screen.getByText(/Users won't be able to sign-in with acme\.com anymore/i)).toBeInTheDocument();
});

it('shows the neutral copy when the connection is inactive', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: false });

expect(screen.getByText("You're about to remove acme.com from this enterprise connection.")).toBeInTheDocument();
expect(screen.queryByText(/Users won't be able to sign-in/i)).not.toBeInTheDocument();
});

it('invokes onClose when Cancel is clicked', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onRemove).not.toHaveBeenCalled();
});

it('awaits the removal and closes on a successful submit', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});

it('keeps the dialog open and surfaces an error when removal fails', async () => {
resetMocks();
onRemove.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'internal_server_error',
long_message: 'Something went wrong while removing the domain.',
message: 'Removal failed.',
},
],
status: 500,
}),
);
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
expect(await screen.findByText('Something went wrong while removing the domain.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});
});
Comment thread
LauraBeatris marked this conversation as resolved.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(ui,shared,localizations): Delete organization domains in self-serve SSO by LauraBeatris · Pull Request #8866 · clerk/javascript · GitHub
Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/strong-moose-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/localizations': patch
'@clerk/shared': patch
'@clerk/ui': patch
---

Add confirmation dialog for organization domain deletion as part of self-serve SSO
12 changes: 10 additions & 2 deletions packages/localizations/src/en-US.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -213,7 +213,6 @@ export const enUS: LocalizationResource = {
configureSSO: {
confirmation: {
configurationSection: {
certificateLabel: 'Certificate',
configureAgainLink: 'Configure again',
issuerLabel: 'Issuer',
ssoUrlLabel: 'Sign on URL',
Expand DownExpand Up@@ -283,13 +282,23 @@ export const enUS: LocalizationResource = {
badge__verified: 'Verified',
badge__unverified: 'Unverified',
verifiedAtLabel: "Verified on {{ date | shortDate('en-US') }}",
removeButtonTooltip__lastVerifiedDomain: 'At least one verified domain is required to set up SSO.',
removeButtonTooltip__lastVerifiedDomainActive: 'At least one verified domain is required to keep SSO enabled.',
txtRecord: {
instructions: "Add this TXT record to your DNS provider. We'll verify automatically once the record is live.",
typeLabel: 'Type',
hostLabel: 'Host / Name',
valueLabel: 'Value',
},
},
removeDomainDialog: {
title: 'Removing domain',
subtitle__active:
"You're about to remove {{domain}} from this enterprise connection. Users won't be able to sign-in with {{domain}} anymore.",
subtitle__inactive: "You're about to remove {{domain}} from this enterprise connection.",
cancelButton: 'Cancel',
removeButton: 'Remove domain',
},
},
testConfigurationStep: {
title: 'Test your SSO connection',
Expand DownExpand Up@@ -1077,7 +1086,6 @@ export const enUS: LocalizationResource = {
badge__inactive: 'Inactive',
badge__inProgress: 'In Progress',
badge__unconfigured: 'Unconfigured',
certificateLabel: 'Certificate',
descriptionLine1:
'Require members to sign in through your identity provider using their domain email. Members without a matching domain are unaffected.',
descriptionLine2:
Expand Down
20 changes: 18 additions & 2 deletions packages/shared/src/react/hooks/useOrganizationDomains.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';

import { logger } from '../../logger';
import type { GetDomainsParams } from '../../types/organization';
Expand All@@ -24,6 +24,11 @@ export type UseOrganizationDomainsParams = {
* Filter the returned domains by enrollment mode.
*/
enrollmentMode?: OrganizationEnrollmentMode;
/**
* Invoked from the ownership-verification poll whenever an `attempt` resolves
* one or more domains as `verified`.
*/
onOwnershipVerified?: (verifiedDomains: OrganizationDomainResource[]) => void | Promise<void>;
};

export type UseOrganizationDomainsReturn = {
Expand DownExpand Up@@ -59,11 +64,14 @@ export type UseOrganizationDomainsReturn = {
* @internal
*/
function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseOrganizationDomainsReturn {
const { keepPreviousData = true, enabled = true, enrollmentMode } = params;
const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
const clerk = useClerkInstanceContext();
const organization = useOrganizationBase();
const [queryClient] = useClerkQueryClient();

const onOwnershipVerifiedRef = useRef(onOwnershipVerified);
onOwnershipVerifiedRef.current = onOwnershipVerified;

const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
organizationId: organization?.id ?? null,
enrollmentMode,
Expand DownExpand Up@@ -171,6 +179,14 @@ function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseO
return;
}

const verifiedDomains = result?.data.filter(domain => domain.ownershipVerification?.status === 'verified') ?? [];
if (verifiedDomains.length) {
await onOwnershipVerifiedRef.current?.(verifiedDomains);
}
if (cancelled) {
return;
}

// Stop polling once every domain in the attempt response is verified
const allVerified =
!!result?.data.length && result.data.every(domain => domain.ownershipVerification?.status === 'verified');
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/types/enterpriseConnection.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -140,7 +140,7 @@ export type MeEnterpriseConnectionOidcInput = OrganizationEnterpriseConnectionOi

export type CreateOrganizationEnterpriseConnectionParams = {
provider: OrganizationEnterpriseConnectionProvider;
name: string;
name?: string;
/** FQDN strings the connection authenticates. Required by the org-scoped create endpoint. */
domains?: string[];
organizationId?: string | null;
Expand All@@ -153,6 +153,7 @@ export type CreateMeEnterpriseConnectionParams = CreateOrganizationEnterpriseCon

export type UpdateOrganizationEnterpriseConnectionParams = {
name?: string | null;
domains?: string[];
active?: boolean | null;
syncUserAttributes?: boolean | null;
disableAdditionalIdentifications?: boolean | null;
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/types/localization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1153,7 +1153,6 @@ export type __internal_LocalizationResource = {
domainLabel: LocalizationValue;
signOnUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
menuAction__edit: LocalizationValue;
menuAction__activate: LocalizationValue;
menuAction__deactivate: LocalizationValue;
Expand DownExpand Up@@ -1382,13 +1381,22 @@ export type __internal_LocalizationResource = {
badge__verified: LocalizationValue;
badge__unverified: LocalizationValue;
verifiedAtLabel: LocalizationValue<'date'>;
removeButtonTooltip__lastVerifiedDomain: LocalizationValue;
removeButtonTooltip__lastVerifiedDomainActive: LocalizationValue;
txtRecord: {
instructions: LocalizationValue;
typeLabel: LocalizationValue;
hostLabel: LocalizationValue;
valueLabel: LocalizationValue;
};
};
removeDomainDialog: {
title: LocalizationValue;
subtitle__active: LocalizationValue<'domain'>;
subtitle__inactive: LocalizationValue<'domain'>;
cancelButton: LocalizationValue;
removeButton: LocalizationValue;
};
};
testConfigurationStep: {
title: LocalizationValue;
Expand DownExpand Up@@ -1835,7 +1843,6 @@ export type __internal_LocalizationResource = {
title: LocalizationValue;
ssoUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
configureAgainLink: LocalizationValue;
};
resetSection: {
Expand Down
109 changes: 109 additions & 0 deletions packages/ui/src/components/ConfigureSSO/RemoveDomainDialog.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
import { useMemo } from 'react';

import { Col, descriptors, localizationKeys } from '@/customizables';
import { Card } from '@/elements/Card';
import { useCardState, withCardStateProvider } from '@/elements/contexts';
import { Form } from '@/elements/Form';
import { FormButtonContainer } from '@/elements/FormButtons';
import { FormContainer } from '@/elements/FormContainer';
import { Modal } from '@/elements/Modal';
import { handleError } from '@/utils/errorHandler';

type RemoveDomainDialogProps = {
isOpen: boolean;
onClose: () => void;
domain: string;
isConnectionActive: boolean;
onRemove: () => Promise<unknown>;
contentRef: React.RefObject<HTMLDivElement>;
};

export const RemoveDomainDialog = (props: RemoveDomainDialogProps): JSX.Element | null => {
if (!props.isOpen) {
return null;
}

return (
<Modal
handleClose={props.onClose}
canCloseModal={false}
portalRoot={props.contentRef}
containerSx={t => ({
alignItems: 'center',
position: 'absolute',
inset: 0,
width: 'auto',
height: 'auto',
backgroundColor: 'inherit',
backdropFilter: `blur(${t.sizes.$2})`,
})}
>
<RemoveDomainDialogContent {...props} />
</Modal>
);
};

const RemoveDomainDialogContent = withCardStateProvider((props: RemoveDomainDialogProps) => {
const { onClose, onRemove } = props;
const card = useCardState();

const subtitle = useMemo(
() =>
props.isConnectionActive
? localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__active', {
domain: props.domain,
})
: localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__inactive', {
domain: props.domain,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const onSubmit = async () => {
try {
await onRemove();
onClose();
} catch (err) {
handleError(err as Error, [], card.setError);
}
};

return (
<Card.Root
elementDescriptor={descriptors.configureSSORemoveDomainDialog}
sx={t => ({ borderRadius: t.radii.$md })}
>
<Card.Content sx={t => ({ textAlign: 'start', padding: t.sizes.$5 })}>
<FormContainer
headerTitle={localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.title')}
headerSubtitle={subtitle}
sx={t => ({ gap: t.space.$4 })}
>
<Form.Root onSubmit={onSubmit}>
<Col gap={4}>
<FormButtonContainer>
<Form.SubmitButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogSubmitButton}
block={false}
colorScheme='danger'
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.removeButton',
)}
/>
<Form.ResetButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogCancelButton}
block={false}
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.cancelButton',
)}
onClick={onClose}
/>
</FormButtonContainer>
</Col>
</Form.Root>
</FormContainer>
</Card.Content>
</Card.Root>
);
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render, screen, waitFor } from '@/test/utils';
import { CardStateProvider } from '@/ui/elements/contexts';

import { RemoveDomainDialog } from '../RemoveDomainDialog';

const onRemove = vi.fn();

const { createFixtures } = bindCreateFixtures('ConfigureSSO');

const renderDialog = (
wrapper: React.ComponentType<{ children?: React.ReactNode }>,
props: {
isOpen?: boolean;
onClose?: () => void;
domain?: string;
isConnectionActive?: boolean;
} = {},
) => {
const onClose = props.onClose ?? vi.fn();
const utils = render(
<CardStateProvider>
<RemoveDomainDialog
isOpen={props.isOpen ?? true}
onClose={onClose}
domain={props.domain ?? 'acme.com'}
isConnectionActive={props.isConnectionActive ?? false}
onRemove={() => onRemove()}
contentRef={{ current: null }}
/>
</CardStateProvider>,
{ wrapper },
);
return { ...utils, onClose };
};

const resetMocks = () => {
onRemove.mockReset();
onRemove.mockResolvedValue(undefined);
};

describe('RemoveDomainDialog', () => {
it('does not render when `isOpen` is `false`', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { isOpen: false });

expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Removing domain' })).not.toBeInTheDocument();
});

it('renders the dialog chrome and actions when isOpen is true', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com' });

expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Removing domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});

it('warns about sign-in impact when the connection is active', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: true });

expect(screen.getByText(/Users won't be able to sign-in with acme\.com anymore/i)).toBeInTheDocument();
});

it('shows the neutral copy when the connection is inactive', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: false });

expect(screen.getByText("You're about to remove acme.com from this enterprise connection.")).toBeInTheDocument();
expect(screen.queryByText(/Users won't be able to sign-in/i)).not.toBeInTheDocument();
});

it('invokes onClose when Cancel is clicked', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onRemove).not.toHaveBeenCalled();
});

it('awaits the removal and closes on a successful submit', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});

it('keeps the dialog open and surfaces an error when removal fails', async () => {
resetMocks();
onRemove.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'internal_server_error',
long_message: 'Something went wrong while removing the domain.',
message: 'Removal failed.',
},
],
status: 500,
}),
);
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
expect(await screen.findByText('Something went wrong while removing the domain.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});
});
Comment thread
LauraBeatris marked this conversation as resolved.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(ui,shared,localizations): Delete organization domains in self-serve SSO by LauraBeatris · Pull Request #8866 · clerk/javascript · GitHub
Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/strong-moose-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/localizations': patch
'@clerk/shared': patch
'@clerk/ui': patch
---

Add confirmation dialog for organization domain deletion as part of self-serve SSO
12 changes: 10 additions & 2 deletions packages/localizations/src/en-US.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -213,7 +213,6 @@ export const enUS: LocalizationResource = {
configureSSO: {
confirmation: {
configurationSection: {
certificateLabel: 'Certificate',
configureAgainLink: 'Configure again',
issuerLabel: 'Issuer',
ssoUrlLabel: 'Sign on URL',
Expand DownExpand Up@@ -283,13 +282,23 @@ export const enUS: LocalizationResource = {
badge__verified: 'Verified',
badge__unverified: 'Unverified',
verifiedAtLabel: "Verified on {{ date | shortDate('en-US') }}",
removeButtonTooltip__lastVerifiedDomain: 'At least one verified domain is required to set up SSO.',
removeButtonTooltip__lastVerifiedDomainActive: 'At least one verified domain is required to keep SSO enabled.',
txtRecord: {
instructions: "Add this TXT record to your DNS provider. We'll verify automatically once the record is live.",
typeLabel: 'Type',
hostLabel: 'Host / Name',
valueLabel: 'Value',
},
},
removeDomainDialog: {
title: 'Removing domain',
subtitle__active:
"You're about to remove {{domain}} from this enterprise connection. Users won't be able to sign-in with {{domain}} anymore.",
subtitle__inactive: "You're about to remove {{domain}} from this enterprise connection.",
cancelButton: 'Cancel',
removeButton: 'Remove domain',
},
},
testConfigurationStep: {
title: 'Test your SSO connection',
Expand DownExpand Up@@ -1077,7 +1086,6 @@ export const enUS: LocalizationResource = {
badge__inactive: 'Inactive',
badge__inProgress: 'In Progress',
badge__unconfigured: 'Unconfigured',
certificateLabel: 'Certificate',
descriptionLine1:
'Require members to sign in through your identity provider using their domain email. Members without a matching domain are unaffected.',
descriptionLine2:
Expand Down
20 changes: 18 additions & 2 deletions packages/shared/src/react/hooks/useOrganizationDomains.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';

import { logger } from '../../logger';
import type { GetDomainsParams } from '../../types/organization';
Expand All@@ -24,6 +24,11 @@ export type UseOrganizationDomainsParams = {
* Filter the returned domains by enrollment mode.
*/
enrollmentMode?: OrganizationEnrollmentMode;
/**
* Invoked from the ownership-verification poll whenever an `attempt` resolves
* one or more domains as `verified`.
*/
onOwnershipVerified?: (verifiedDomains: OrganizationDomainResource[]) => void | Promise<void>;
};

export type UseOrganizationDomainsReturn = {
Expand DownExpand Up@@ -59,11 +64,14 @@ export type UseOrganizationDomainsReturn = {
* @internal
*/
function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseOrganizationDomainsReturn {
const { keepPreviousData = true, enabled = true, enrollmentMode } = params;
const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
const clerk = useClerkInstanceContext();
const organization = useOrganizationBase();
const [queryClient] = useClerkQueryClient();

const onOwnershipVerifiedRef = useRef(onOwnershipVerified);
onOwnershipVerifiedRef.current = onOwnershipVerified;

const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
organizationId: organization?.id ?? null,
enrollmentMode,
Expand DownExpand Up@@ -171,6 +179,14 @@ function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseO
return;
}

const verifiedDomains = result?.data.filter(domain => domain.ownershipVerification?.status === 'verified') ?? [];
if (verifiedDomains.length) {
await onOwnershipVerifiedRef.current?.(verifiedDomains);
}
if (cancelled) {
return;
}

// Stop polling once every domain in the attempt response is verified
const allVerified =
!!result?.data.length && result.data.every(domain => domain.ownershipVerification?.status === 'verified');
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/types/enterpriseConnection.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -140,7 +140,7 @@ export type MeEnterpriseConnectionOidcInput = OrganizationEnterpriseConnectionOi

export type CreateOrganizationEnterpriseConnectionParams = {
provider: OrganizationEnterpriseConnectionProvider;
name: string;
name?: string;
/** FQDN strings the connection authenticates. Required by the org-scoped create endpoint. */
domains?: string[];
organizationId?: string | null;
Expand All@@ -153,6 +153,7 @@ export type CreateMeEnterpriseConnectionParams = CreateOrganizationEnterpriseCon

export type UpdateOrganizationEnterpriseConnectionParams = {
name?: string | null;
domains?: string[];
active?: boolean | null;
syncUserAttributes?: boolean | null;
disableAdditionalIdentifications?: boolean | null;
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/types/localization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1153,7 +1153,6 @@ export type __internal_LocalizationResource = {
domainLabel: LocalizationValue;
signOnUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
menuAction__edit: LocalizationValue;
menuAction__activate: LocalizationValue;
menuAction__deactivate: LocalizationValue;
Expand DownExpand Up@@ -1382,13 +1381,22 @@ export type __internal_LocalizationResource = {
badge__verified: LocalizationValue;
badge__unverified: LocalizationValue;
verifiedAtLabel: LocalizationValue<'date'>;
removeButtonTooltip__lastVerifiedDomain: LocalizationValue;
removeButtonTooltip__lastVerifiedDomainActive: LocalizationValue;
txtRecord: {
instructions: LocalizationValue;
typeLabel: LocalizationValue;
hostLabel: LocalizationValue;
valueLabel: LocalizationValue;
};
};
removeDomainDialog: {
title: LocalizationValue;
subtitle__active: LocalizationValue<'domain'>;
subtitle__inactive: LocalizationValue<'domain'>;
cancelButton: LocalizationValue;
removeButton: LocalizationValue;
};
};
testConfigurationStep: {
title: LocalizationValue;
Expand DownExpand Up@@ -1835,7 +1843,6 @@ export type __internal_LocalizationResource = {
title: LocalizationValue;
ssoUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
configureAgainLink: LocalizationValue;
};
resetSection: {
Expand Down
109 changes: 109 additions & 0 deletions packages/ui/src/components/ConfigureSSO/RemoveDomainDialog.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
import { useMemo } from 'react';

import { Col, descriptors, localizationKeys } from '@/customizables';
import { Card } from '@/elements/Card';
import { useCardState, withCardStateProvider } from '@/elements/contexts';
import { Form } from '@/elements/Form';
import { FormButtonContainer } from '@/elements/FormButtons';
import { FormContainer } from '@/elements/FormContainer';
import { Modal } from '@/elements/Modal';
import { handleError } from '@/utils/errorHandler';

type RemoveDomainDialogProps = {
isOpen: boolean;
onClose: () => void;
domain: string;
isConnectionActive: boolean;
onRemove: () => Promise<unknown>;
contentRef: React.RefObject<HTMLDivElement>;
};

export const RemoveDomainDialog = (props: RemoveDomainDialogProps): JSX.Element | null => {
if (!props.isOpen) {
return null;
}

return (
<Modal
handleClose={props.onClose}
canCloseModal={false}
portalRoot={props.contentRef}
containerSx={t => ({
alignItems: 'center',
position: 'absolute',
inset: 0,
width: 'auto',
height: 'auto',
backgroundColor: 'inherit',
backdropFilter: `blur(${t.sizes.$2})`,
})}
>
<RemoveDomainDialogContent {...props} />
</Modal>
);
};

const RemoveDomainDialogContent = withCardStateProvider((props: RemoveDomainDialogProps) => {
const { onClose, onRemove } = props;
const card = useCardState();

const subtitle = useMemo(
() =>
props.isConnectionActive
? localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__active', {
domain: props.domain,
})
: localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__inactive', {
domain: props.domain,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const onSubmit = async () => {
try {
await onRemove();
onClose();
} catch (err) {
handleError(err as Error, [], card.setError);
}
};

return (
<Card.Root
elementDescriptor={descriptors.configureSSORemoveDomainDialog}
sx={t => ({ borderRadius: t.radii.$md })}
>
<Card.Content sx={t => ({ textAlign: 'start', padding: t.sizes.$5 })}>
<FormContainer
headerTitle={localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.title')}
headerSubtitle={subtitle}
sx={t => ({ gap: t.space.$4 })}
>
<Form.Root onSubmit={onSubmit}>
<Col gap={4}>
<FormButtonContainer>
<Form.SubmitButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogSubmitButton}
block={false}
colorScheme='danger'
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.removeButton',
)}
/>
<Form.ResetButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogCancelButton}
block={false}
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.cancelButton',
)}
onClick={onClose}
/>
</FormButtonContainer>
</Col>
</Form.Root>
</FormContainer>
</Card.Content>
</Card.Root>
);
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render, screen, waitFor } from '@/test/utils';
import { CardStateProvider } from '@/ui/elements/contexts';

import { RemoveDomainDialog } from '../RemoveDomainDialog';

const onRemove = vi.fn();

const { createFixtures } = bindCreateFixtures('ConfigureSSO');

const renderDialog = (
wrapper: React.ComponentType<{ children?: React.ReactNode }>,
props: {
isOpen?: boolean;
onClose?: () => void;
domain?: string;
isConnectionActive?: boolean;
} = {},
) => {
const onClose = props.onClose ?? vi.fn();
const utils = render(
<CardStateProvider>
<RemoveDomainDialog
isOpen={props.isOpen ?? true}
onClose={onClose}
domain={props.domain ?? 'acme.com'}
isConnectionActive={props.isConnectionActive ?? false}
onRemove={() => onRemove()}
contentRef={{ current: null }}
/>
</CardStateProvider>,
{ wrapper },
);
return { ...utils, onClose };
};

const resetMocks = () => {
onRemove.mockReset();
onRemove.mockResolvedValue(undefined);
};

describe('RemoveDomainDialog', () => {
it('does not render when `isOpen` is `false`', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { isOpen: false });

expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Removing domain' })).not.toBeInTheDocument();
});

it('renders the dialog chrome and actions when isOpen is true', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com' });

expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Removing domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});

it('warns about sign-in impact when the connection is active', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: true });

expect(screen.getByText(/Users won't be able to sign-in with acme\.com anymore/i)).toBeInTheDocument();
});

it('shows the neutral copy when the connection is inactive', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: false });

expect(screen.getByText("You're about to remove acme.com from this enterprise connection.")).toBeInTheDocument();
expect(screen.queryByText(/Users won't be able to sign-in/i)).not.toBeInTheDocument();
});

it('invokes onClose when Cancel is clicked', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onRemove).not.toHaveBeenCalled();
});

it('awaits the removal and closes on a successful submit', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});

it('keeps the dialog open and surfaces an error when removal fails', async () => {
resetMocks();
onRemove.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'internal_server_error',
long_message: 'Something went wrong while removing the domain.',
message: 'Removal failed.',
},
],
status: 500,
}),
);
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
expect(await screen.findByText('Something went wrong while removing the domain.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});
});
Comment thread
LauraBeatris marked this conversation as resolved.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(ui,shared,localizations): Delete organization domains in self-serve SSO by LauraBeatris · Pull Request #8866 · clerk/javascript · GitHub
Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/strong-moose-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/localizations': patch
'@clerk/shared': patch
'@clerk/ui': patch
---

Add confirmation dialog for organization domain deletion as part of self-serve SSO
12 changes: 10 additions & 2 deletions packages/localizations/src/en-US.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -213,7 +213,6 @@ export const enUS: LocalizationResource = {
configureSSO: {
confirmation: {
configurationSection: {
certificateLabel: 'Certificate',
configureAgainLink: 'Configure again',
issuerLabel: 'Issuer',
ssoUrlLabel: 'Sign on URL',
Expand DownExpand Up@@ -283,13 +282,23 @@ export const enUS: LocalizationResource = {
badge__verified: 'Verified',
badge__unverified: 'Unverified',
verifiedAtLabel: "Verified on {{ date | shortDate('en-US') }}",
removeButtonTooltip__lastVerifiedDomain: 'At least one verified domain is required to set up SSO.',
removeButtonTooltip__lastVerifiedDomainActive: 'At least one verified domain is required to keep SSO enabled.',
txtRecord: {
instructions: "Add this TXT record to your DNS provider. We'll verify automatically once the record is live.",
typeLabel: 'Type',
hostLabel: 'Host / Name',
valueLabel: 'Value',
},
},
removeDomainDialog: {
title: 'Removing domain',
subtitle__active:
"You're about to remove {{domain}} from this enterprise connection. Users won't be able to sign-in with {{domain}} anymore.",
subtitle__inactive: "You're about to remove {{domain}} from this enterprise connection.",
cancelButton: 'Cancel',
removeButton: 'Remove domain',
},
},
testConfigurationStep: {
title: 'Test your SSO connection',
Expand DownExpand Up@@ -1077,7 +1086,6 @@ export const enUS: LocalizationResource = {
badge__inactive: 'Inactive',
badge__inProgress: 'In Progress',
badge__unconfigured: 'Unconfigured',
certificateLabel: 'Certificate',
descriptionLine1:
'Require members to sign in through your identity provider using their domain email. Members without a matching domain are unaffected.',
descriptionLine2:
Expand Down
20 changes: 18 additions & 2 deletions packages/shared/src/react/hooks/useOrganizationDomains.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';

import { logger } from '../../logger';
import type { GetDomainsParams } from '../../types/organization';
Expand All@@ -24,6 +24,11 @@ export type UseOrganizationDomainsParams = {
* Filter the returned domains by enrollment mode.
*/
enrollmentMode?: OrganizationEnrollmentMode;
/**
* Invoked from the ownership-verification poll whenever an `attempt` resolves
* one or more domains as `verified`.
*/
onOwnershipVerified?: (verifiedDomains: OrganizationDomainResource[]) => void | Promise<void>;
};

export type UseOrganizationDomainsReturn = {
Expand DownExpand Up@@ -59,11 +64,14 @@ export type UseOrganizationDomainsReturn = {
* @internal
*/
function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseOrganizationDomainsReturn {
const { keepPreviousData = true, enabled = true, enrollmentMode } = params;
const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
const clerk = useClerkInstanceContext();
const organization = useOrganizationBase();
const [queryClient] = useClerkQueryClient();

const onOwnershipVerifiedRef = useRef(onOwnershipVerified);
onOwnershipVerifiedRef.current = onOwnershipVerified;

const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
organizationId: organization?.id ?? null,
enrollmentMode,
Expand DownExpand Up@@ -171,6 +179,14 @@ function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseO
return;
}

const verifiedDomains = result?.data.filter(domain => domain.ownershipVerification?.status === 'verified') ?? [];
if (verifiedDomains.length) {
await onOwnershipVerifiedRef.current?.(verifiedDomains);
}
if (cancelled) {
return;
}

// Stop polling once every domain in the attempt response is verified
const allVerified =
!!result?.data.length && result.data.every(domain => domain.ownershipVerification?.status === 'verified');
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/types/enterpriseConnection.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -140,7 +140,7 @@ export type MeEnterpriseConnectionOidcInput = OrganizationEnterpriseConnectionOi

export type CreateOrganizationEnterpriseConnectionParams = {
provider: OrganizationEnterpriseConnectionProvider;
name: string;
name?: string;
/** FQDN strings the connection authenticates. Required by the org-scoped create endpoint. */
domains?: string[];
organizationId?: string | null;
Expand All@@ -153,6 +153,7 @@ export type CreateMeEnterpriseConnectionParams = CreateOrganizationEnterpriseCon

export type UpdateOrganizationEnterpriseConnectionParams = {
name?: string | null;
domains?: string[];
active?: boolean | null;
syncUserAttributes?: boolean | null;
disableAdditionalIdentifications?: boolean | null;
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/types/localization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1153,7 +1153,6 @@ export type __internal_LocalizationResource = {
domainLabel: LocalizationValue;
signOnUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
menuAction__edit: LocalizationValue;
menuAction__activate: LocalizationValue;
menuAction__deactivate: LocalizationValue;
Expand DownExpand Up@@ -1382,13 +1381,22 @@ export type __internal_LocalizationResource = {
badge__verified: LocalizationValue;
badge__unverified: LocalizationValue;
verifiedAtLabel: LocalizationValue<'date'>;
removeButtonTooltip__lastVerifiedDomain: LocalizationValue;
removeButtonTooltip__lastVerifiedDomainActive: LocalizationValue;
txtRecord: {
instructions: LocalizationValue;
typeLabel: LocalizationValue;
hostLabel: LocalizationValue;
valueLabel: LocalizationValue;
};
};
removeDomainDialog: {
title: LocalizationValue;
subtitle__active: LocalizationValue<'domain'>;
subtitle__inactive: LocalizationValue<'domain'>;
cancelButton: LocalizationValue;
removeButton: LocalizationValue;
};
};
testConfigurationStep: {
title: LocalizationValue;
Expand DownExpand Up@@ -1835,7 +1843,6 @@ export type __internal_LocalizationResource = {
title: LocalizationValue;
ssoUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
configureAgainLink: LocalizationValue;
};
resetSection: {
Expand Down
109 changes: 109 additions & 0 deletions packages/ui/src/components/ConfigureSSO/RemoveDomainDialog.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
import { useMemo } from 'react';

import { Col, descriptors, localizationKeys } from '@/customizables';
import { Card } from '@/elements/Card';
import { useCardState, withCardStateProvider } from '@/elements/contexts';
import { Form } from '@/elements/Form';
import { FormButtonContainer } from '@/elements/FormButtons';
import { FormContainer } from '@/elements/FormContainer';
import { Modal } from '@/elements/Modal';
import { handleError } from '@/utils/errorHandler';

type RemoveDomainDialogProps = {
isOpen: boolean;
onClose: () => void;
domain: string;
isConnectionActive: boolean;
onRemove: () => Promise<unknown>;
contentRef: React.RefObject<HTMLDivElement>;
};

export const RemoveDomainDialog = (props: RemoveDomainDialogProps): JSX.Element | null => {
if (!props.isOpen) {
return null;
}

return (
<Modal
handleClose={props.onClose}
canCloseModal={false}
portalRoot={props.contentRef}
containerSx={t => ({
alignItems: 'center',
position: 'absolute',
inset: 0,
width: 'auto',
height: 'auto',
backgroundColor: 'inherit',
backdropFilter: `blur(${t.sizes.$2})`,
})}
>
<RemoveDomainDialogContent {...props} />
</Modal>
);
};

const RemoveDomainDialogContent = withCardStateProvider((props: RemoveDomainDialogProps) => {
const { onClose, onRemove } = props;
const card = useCardState();

const subtitle = useMemo(
() =>
props.isConnectionActive
? localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__active', {
domain: props.domain,
})
: localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__inactive', {
domain: props.domain,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const onSubmit = async () => {
try {
await onRemove();
onClose();
} catch (err) {
handleError(err as Error, [], card.setError);
}
};

return (
<Card.Root
elementDescriptor={descriptors.configureSSORemoveDomainDialog}
sx={t => ({ borderRadius: t.radii.$md })}
>
<Card.Content sx={t => ({ textAlign: 'start', padding: t.sizes.$5 })}>
<FormContainer
headerTitle={localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.title')}
headerSubtitle={subtitle}
sx={t => ({ gap: t.space.$4 })}
>
<Form.Root onSubmit={onSubmit}>
<Col gap={4}>
<FormButtonContainer>
<Form.SubmitButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogSubmitButton}
block={false}
colorScheme='danger'
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.removeButton',
)}
/>
<Form.ResetButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogCancelButton}
block={false}
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.cancelButton',
)}
onClick={onClose}
/>
</FormButtonContainer>
</Col>
</Form.Root>
</FormContainer>
</Card.Content>
</Card.Root>
);
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render, screen, waitFor } from '@/test/utils';
import { CardStateProvider } from '@/ui/elements/contexts';

import { RemoveDomainDialog } from '../RemoveDomainDialog';

const onRemove = vi.fn();

const { createFixtures } = bindCreateFixtures('ConfigureSSO');

const renderDialog = (
wrapper: React.ComponentType<{ children?: React.ReactNode }>,
props: {
isOpen?: boolean;
onClose?: () => void;
domain?: string;
isConnectionActive?: boolean;
} = {},
) => {
const onClose = props.onClose ?? vi.fn();
const utils = render(
<CardStateProvider>
<RemoveDomainDialog
isOpen={props.isOpen ?? true}
onClose={onClose}
domain={props.domain ?? 'acme.com'}
isConnectionActive={props.isConnectionActive ?? false}
onRemove={() => onRemove()}
contentRef={{ current: null }}
/>
</CardStateProvider>,
{ wrapper },
);
return { ...utils, onClose };
};

const resetMocks = () => {
onRemove.mockReset();
onRemove.mockResolvedValue(undefined);
};

describe('RemoveDomainDialog', () => {
it('does not render when `isOpen` is `false`', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { isOpen: false });

expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Removing domain' })).not.toBeInTheDocument();
});

it('renders the dialog chrome and actions when isOpen is true', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com' });

expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Removing domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});

it('warns about sign-in impact when the connection is active', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: true });

expect(screen.getByText(/Users won't be able to sign-in with acme\.com anymore/i)).toBeInTheDocument();
});

it('shows the neutral copy when the connection is inactive', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: false });

expect(screen.getByText("You're about to remove acme.com from this enterprise connection.")).toBeInTheDocument();
expect(screen.queryByText(/Users won't be able to sign-in/i)).not.toBeInTheDocument();
});

it('invokes onClose when Cancel is clicked', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onRemove).not.toHaveBeenCalled();
});

it('awaits the removal and closes on a successful submit', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});

it('keeps the dialog open and surfaces an error when removal fails', async () => {
resetMocks();
onRemove.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'internal_server_error',
long_message: 'Something went wrong while removing the domain.',
message: 'Removal failed.',
},
],
status: 500,
}),
);
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
expect(await screen.findByText('Something went wrong while removing the domain.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});
});
Comment thread
LauraBeatris marked this conversation as resolved.
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat(ui,shared,localizations): Delete organization domains in self-serve SSO by LauraBeatris · Pull Request #8866 · clerk/javascript · GitHub
Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/strong-moose-retire.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
---
'@clerk/localizations': patch
'@clerk/shared': patch
'@clerk/ui': patch
---

Add confirmation dialog for organization domain deletion as part of self-serve SSO
12 changes: 10 additions & 2 deletions packages/localizations/src/en-US.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -213,7 +213,6 @@ export const enUS: LocalizationResource = {
configureSSO: {
confirmation: {
configurationSection: {
certificateLabel: 'Certificate',
configureAgainLink: 'Configure again',
issuerLabel: 'Issuer',
ssoUrlLabel: 'Sign on URL',
Expand DownExpand Up@@ -283,13 +282,23 @@ export const enUS: LocalizationResource = {
badge__verified: 'Verified',
badge__unverified: 'Unverified',
verifiedAtLabel: "Verified on {{ date | shortDate('en-US') }}",
removeButtonTooltip__lastVerifiedDomain: 'At least one verified domain is required to set up SSO.',
removeButtonTooltip__lastVerifiedDomainActive: 'At least one verified domain is required to keep SSO enabled.',
txtRecord: {
instructions: "Add this TXT record to your DNS provider. We'll verify automatically once the record is live.",
typeLabel: 'Type',
hostLabel: 'Host / Name',
valueLabel: 'Value',
},
},
removeDomainDialog: {
title: 'Removing domain',
subtitle__active:
"You're about to remove {{domain}} from this enterprise connection. Users won't be able to sign-in with {{domain}} anymore.",
subtitle__inactive: "You're about to remove {{domain}} from this enterprise connection.",
cancelButton: 'Cancel',
removeButton: 'Remove domain',
},
},
testConfigurationStep: {
title: 'Test your SSO connection',
Expand DownExpand Up@@ -1077,7 +1086,6 @@ export const enUS: LocalizationResource = {
badge__inactive: 'Inactive',
badge__inProgress: 'In Progress',
badge__unconfigured: 'Unconfigured',
certificateLabel: 'Certificate',
descriptionLine1:
'Require members to sign in through your identity provider using their domain email. Members without a matching domain are unaffected.',
descriptionLine2:
Expand Down
20 changes: 18 additions & 2 deletions packages/shared/src/react/hooks/useOrganizationDomains.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';

import { logger } from '../../logger';
import type { GetDomainsParams } from '../../types/organization';
Expand All@@ -24,6 +24,11 @@ export type UseOrganizationDomainsParams = {
* Filter the returned domains by enrollment mode.
*/
enrollmentMode?: OrganizationEnrollmentMode;
/**
* Invoked from the ownership-verification poll whenever an `attempt` resolves
* one or more domains as `verified`.
*/
onOwnershipVerified?: (verifiedDomains: OrganizationDomainResource[]) => void | Promise<void>;
};

export type UseOrganizationDomainsReturn = {
Expand DownExpand Up@@ -59,11 +64,14 @@ export type UseOrganizationDomainsReturn = {
* @internal
*/
function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseOrganizationDomainsReturn {
const { keepPreviousData = true, enabled = true, enrollmentMode } = params;
const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
const clerk = useClerkInstanceContext();
const organization = useOrganizationBase();
const [queryClient] = useClerkQueryClient();

const onOwnershipVerifiedRef = useRef(onOwnershipVerified);
onOwnershipVerifiedRef.current = onOwnershipVerified;

const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
organizationId: organization?.id ?? null,
enrollmentMode,
Expand DownExpand Up@@ -171,6 +179,14 @@ function useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseO
return;
}

const verifiedDomains = result?.data.filter(domain => domain.ownershipVerification?.status === 'verified') ?? [];
if (verifiedDomains.length) {
await onOwnershipVerifiedRef.current?.(verifiedDomains);
}
if (cancelled) {
return;
}

// Stop polling once every domain in the attempt response is verified
const allVerified =
!!result?.data.length && result.data.every(domain => domain.ownershipVerification?.status === 'verified');
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/src/types/enterpriseConnection.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -140,7 +140,7 @@ export type MeEnterpriseConnectionOidcInput = OrganizationEnterpriseConnectionOi

export type CreateOrganizationEnterpriseConnectionParams = {
provider: OrganizationEnterpriseConnectionProvider;
name: string;
name?: string;
/** FQDN strings the connection authenticates. Required by the org-scoped create endpoint. */
domains?: string[];
organizationId?: string | null;
Expand All@@ -153,6 +153,7 @@ export type CreateMeEnterpriseConnectionParams = CreateOrganizationEnterpriseCon

export type UpdateOrganizationEnterpriseConnectionParams = {
name?: string | null;
domains?: string[];
active?: boolean | null;
syncUserAttributes?: boolean | null;
disableAdditionalIdentifications?: boolean | null;
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/types/localization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1153,7 +1153,6 @@ export type __internal_LocalizationResource = {
domainLabel: LocalizationValue;
signOnUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
menuAction__edit: LocalizationValue;
menuAction__activate: LocalizationValue;
menuAction__deactivate: LocalizationValue;
Expand DownExpand Up@@ -1382,13 +1381,22 @@ export type __internal_LocalizationResource = {
badge__verified: LocalizationValue;
badge__unverified: LocalizationValue;
verifiedAtLabel: LocalizationValue<'date'>;
removeButtonTooltip__lastVerifiedDomain: LocalizationValue;
removeButtonTooltip__lastVerifiedDomainActive: LocalizationValue;
txtRecord: {
instructions: LocalizationValue;
typeLabel: LocalizationValue;
hostLabel: LocalizationValue;
valueLabel: LocalizationValue;
};
};
removeDomainDialog: {
title: LocalizationValue;
subtitle__active: LocalizationValue<'domain'>;
subtitle__inactive: LocalizationValue<'domain'>;
cancelButton: LocalizationValue;
removeButton: LocalizationValue;
};
};
testConfigurationStep: {
title: LocalizationValue;
Expand DownExpand Up@@ -1835,7 +1843,6 @@ export type __internal_LocalizationResource = {
title: LocalizationValue;
ssoUrlLabel: LocalizationValue;
issuerLabel: LocalizationValue;
certificateLabel: LocalizationValue;
configureAgainLink: LocalizationValue;
};
resetSection: {
Expand Down
109 changes: 109 additions & 0 deletions packages/ui/src/components/ConfigureSSO/RemoveDomainDialog.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
import { useMemo } from 'react';

import { Col, descriptors, localizationKeys } from '@/customizables';
import { Card } from '@/elements/Card';
import { useCardState, withCardStateProvider } from '@/elements/contexts';
import { Form } from '@/elements/Form';
import { FormButtonContainer } from '@/elements/FormButtons';
import { FormContainer } from '@/elements/FormContainer';
import { Modal } from '@/elements/Modal';
import { handleError } from '@/utils/errorHandler';

type RemoveDomainDialogProps = {
isOpen: boolean;
onClose: () => void;
domain: string;
isConnectionActive: boolean;
onRemove: () => Promise<unknown>;
contentRef: React.RefObject<HTMLDivElement>;
};

export const RemoveDomainDialog = (props: RemoveDomainDialogProps): JSX.Element | null => {
if (!props.isOpen) {
return null;
}

return (
<Modal
handleClose={props.onClose}
canCloseModal={false}
portalRoot={props.contentRef}
containerSx={t => ({
alignItems: 'center',
position: 'absolute',
inset: 0,
width: 'auto',
height: 'auto',
backgroundColor: 'inherit',
backdropFilter: `blur(${t.sizes.$2})`,
})}
>
<RemoveDomainDialogContent {...props} />
</Modal>
);
};

const RemoveDomainDialogContent = withCardStateProvider((props: RemoveDomainDialogProps) => {
const { onClose, onRemove } = props;
const card = useCardState();

const subtitle = useMemo(
() =>
props.isConnectionActive
? localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__active', {
domain: props.domain,
})
: localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.subtitle__inactive', {
domain: props.domain,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const onSubmit = async () => {
try {
await onRemove();
onClose();
} catch (err) {
handleError(err as Error, [], card.setError);
}
};

return (
<Card.Root
elementDescriptor={descriptors.configureSSORemoveDomainDialog}
sx={t => ({ borderRadius: t.radii.$md })}
>
<Card.Content sx={t => ({ textAlign: 'start', padding: t.sizes.$5 })}>
<FormContainer
headerTitle={localizationKeys('configureSSO.organizationDomainsStep.removeDomainDialog.title')}
headerSubtitle={subtitle}
sx={t => ({ gap: t.space.$4 })}
>
<Form.Root onSubmit={onSubmit}>
<Col gap={4}>
<FormButtonContainer>
<Form.SubmitButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogSubmitButton}
block={false}
colorScheme='danger'
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.removeButton',
)}
/>
<Form.ResetButton
elementDescriptor={descriptors.configureSSORemoveDomainDialogCancelButton}
block={false}
localizationKey={localizationKeys(
'configureSSO.organizationDomainsStep.removeDomainDialog.cancelButton',
)}
onClick={onClose}
/>
</FormButtonContainer>
</Col>
</Form.Root>
</FormContainer>
</Card.Content>
</Card.Root>
);
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
import { ClerkAPIResponseError } from '@clerk/shared/error';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render, screen, waitFor } from '@/test/utils';
import { CardStateProvider } from '@/ui/elements/contexts';

import { RemoveDomainDialog } from '../RemoveDomainDialog';

const onRemove = vi.fn();

const { createFixtures } = bindCreateFixtures('ConfigureSSO');

const renderDialog = (
wrapper: React.ComponentType<{ children?: React.ReactNode }>,
props: {
isOpen?: boolean;
onClose?: () => void;
domain?: string;
isConnectionActive?: boolean;
} = {},
) => {
const onClose = props.onClose ?? vi.fn();
const utils = render(
<CardStateProvider>
<RemoveDomainDialog
isOpen={props.isOpen ?? true}
onClose={onClose}
domain={props.domain ?? 'acme.com'}
isConnectionActive={props.isConnectionActive ?? false}
onRemove={() => onRemove()}
contentRef={{ current: null }}
/>
</CardStateProvider>,
{ wrapper },
);
return { ...utils, onClose };
};

const resetMocks = () => {
onRemove.mockReset();
onRemove.mockResolvedValue(undefined);
};

describe('RemoveDomainDialog', () => {
it('does not render when `isOpen` is `false`', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { isOpen: false });

expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Removing domain' })).not.toBeInTheDocument();
});

it('renders the dialog chrome and actions when isOpen is true', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com' });

expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Removing domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove domain' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});

it('warns about sign-in impact when the connection is active', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: true });

expect(screen.getByText(/Users won't be able to sign-in with acme\.com anymore/i)).toBeInTheDocument();
});

it('shows the neutral copy when the connection is inactive', async () => {
resetMocks();
const { wrapper } = await createFixtures();
renderDialog(wrapper, { domain: 'acme.com', isConnectionActive: false });

expect(screen.getByText("You're about to remove acme.com from this enterprise connection.")).toBeInTheDocument();
expect(screen.queryByText(/Users won't be able to sign-in/i)).not.toBeInTheDocument();
});

it('invokes onClose when Cancel is clicked', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onRemove).not.toHaveBeenCalled();
});

it('awaits the removal and closes on a successful submit', async () => {
resetMocks();
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
await waitFor(() => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});

it('keeps the dialog open and surfaces an error when removal fails', async () => {
resetMocks();
onRemove.mockRejectedValueOnce(
new ClerkAPIResponseError('Error', {
data: [
{
code: 'internal_server_error',
long_message: 'Something went wrong while removing the domain.',
message: 'Removal failed.',
},
],
status: 500,
}),
);
const onClose = vi.fn();
const { wrapper } = await createFixtures();
const { userEvent } = renderDialog(wrapper, { onClose });

await userEvent.click(screen.getByRole('button', { name: 'Remove domain' }));

await waitFor(() => {
expect(onRemove).toHaveBeenCalledTimes(1);
});
expect(await screen.findByText('Something went wrong while removing the domain.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});
});
Comment thread
LauraBeatris marked this conversation as resolved.
Loading
Loading