') + ')', '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('^' + ".*" + ', '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" + ', '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('^' + ".*" + ', '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); } })(); })(); feat(ui): Self-serve SSO within `OrganizationProfile` by LauraBeatris · Pull Request #8600 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/dull-plums-sleep.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
---
'@clerk/localizations': minor
'@clerk/clerk-js': minor
'@clerk/shared': minor
'@clerk/ui': minor
---

Display "Single Sign-on (SSO)" section in `OrganizationProfile` if self-serve SSO is enabled on the current active organization
3 changes: 3 additions & 0 deletions packages/clerk-js/src/core/resources/Organization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,6 +49,7 @@ export class Organization extends BaseResource implements OrganizationResource {
membersCount = 0;
pendingInvitationsCount = 0;
maxAllowedMemberships!: number;
selfServeSSOEnabled = false;

constructor(data: OrganizationJSON | OrganizationJSONSnapshot) {
super();
Expand DownExpand Up@@ -303,6 +304,7 @@ export class Organization extends BaseResource implements OrganizationResource {
this.pendingInvitationsCount = data.pending_invitations_count || 0;
this.maxAllowedMemberships = data.max_allowed_memberships || 0;
this.adminDeleteEnabled = data.admin_delete_enabled || false;
this.selfServeSSOEnabled = data.self_serve_sso_enabled || false;
this.createdAt = unixEpochToDate(data.created_at);
this.updatedAt = unixEpochToDate(data.updated_at);
return this;
Expand All@@ -321,6 +323,7 @@ export class Organization extends BaseResource implements OrganizationResource {
pending_invitations_count: this.pendingInvitationsCount,
max_allowed_memberships: this.maxAllowedMemberships,
admin_delete_enabled: this.adminDeleteEnabled,
self_serve_sso_enabled: this.selfServeSSOEnabled,
created_at: this.createdAt.getTime(),
updated_at: this.updatedAt.getTime(),
};
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ describe('Organization', () => {
admin_delete_enabled: true,
max_allowed_memberships: 3,
has_image: true,
self_serve_sso_enabled: true,
});

expect(organization).toMatchObject({
Expand All@@ -32,6 +33,7 @@ describe('Organization', () => {
pendingInvitationsCount: 10,
maxAllowedMemberships: 3,
adminDeleteEnabled: true,
selfServeSSOEnabled: true,
createdAt: expect.any(Date),
updatedAt: expect.any(Date),
publicMetadata: {
Expand Down
1 change: 1 addition & 0 deletions packages/localizations/src/en-US.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -794,6 +794,7 @@ export const enUS: LocalizationResource = {
navbar: {
apiKeys: 'API keys',
billing: 'Billing',
selfServeSSO: 'Single Sign-On (SSO)',
description: 'Manage your organization.',
general: 'General',
members: 'Members',
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/json.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -393,6 +393,7 @@ export interface OrganizationJSON extends ClerkResourceJSON {
pending_invitations_count: number;
admin_delete_enabled: boolean;
max_allowed_memberships: number;
self_serve_sso_enabled?: boolean;
}

export interface OrganizationMembershipJSON extends ClerkResourceJSON {
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/localization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1021,6 +1021,7 @@ export type __internal_LocalizationResource = {
members: LocalizationValue;
billing: LocalizationValue;
apiKeys: LocalizationValue;
selfServeSSO: LocalizationValue;
};
badge__unverified: LocalizationValue;
badge__automaticInvitation: LocalizationValue;
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/organization.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,6 +46,7 @@ export interface OrganizationResource extends ClerkResource, BillingPayerMethods
publicMetadata: OrganizationPublicMetadata;
adminDeleteEnabled: boolean;
maxAllowedMemberships: number;
selfServeSSOEnabled: boolean;
createdAt: Date;
updatedAt: Date;
update: (params: UpdateOrganizationParams) => Promise<OrganizationResource>;
Expand Down
30 changes: 15 additions & 15 deletions packages/ui/src/components/ConfigureSSO/ConfigureSSO.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,16 +58,14 @@ const AuthenticatedContent = withCoreUserGuard(() => {
flex: 1,
})}
>
<ConfigureSSOCardProtect>
<ConfigureSSOCardContent contentRef={contentRef} />
</ConfigureSSOCardProtect>
<ConfigureSSOContent contentRef={contentRef} />
</Col>
</ConfigureSSONavbar>
</ProfileCard.Root>
);
});

const ConfigureSSOCardContent = ({ contentRef }: { contentRef: React.RefObject<HTMLDivElement> }) => {
export const ConfigureSSOContent = ({ contentRef }: { contentRef: React.RefObject<HTMLDivElement> }) => {
const {
data: enterpriseConnections,
isLoading: isLoadingEnterpriseConnections,
Expand All@@ -86,16 +84,18 @@ const ConfigureSSOCardContent = ({ contentRef }: { contentRef: React.RefObject<H
}

return (
<ConfigureSSOProvider
hasSuccessfulTestRun={hasSuccessfulTestRun}
enterpriseConnection={enterpriseConnection}
contentRef={contentRef}
createEnterpriseConnection={createEnterpriseConnection}
updateEnterpriseConnection={updateEnterpriseConnection}
deleteEnterpriseConnection={deleteEnterpriseConnection}
>
<ConfigureSSOSteps />
</ConfigureSSOProvider>
<ConfigureSSOProtect>
<ConfigureSSOProvider
hasSuccessfulTestRun={hasSuccessfulTestRun}
enterpriseConnection={enterpriseConnection}
contentRef={contentRef}
createEnterpriseConnection={createEnterpriseConnection}
updateEnterpriseConnection={updateEnterpriseConnection}
deleteEnterpriseConnection={deleteEnterpriseConnection}
>
<ConfigureSSOSteps />
</ConfigureSSOProvider>
</ConfigureSSOProtect>
);
};

Expand DownExpand Up@@ -151,7 +151,7 @@ const ConfigureSSOSteps = () => {
);
};

const ConfigureSSOCardProtect = ({ children }: { children: React.ReactNode }) => {
const ConfigureSSOProtect = ({ children }: { children: React.ReactNode }) => {
const { session } = useSession();
const isPersonalWorkspace = !session?.lastActiveOrganizationId;
const canManageEnterpriseConnections = useProtect(
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@ describe('ConfigureSSO', () => {
describe('within an organization', () => {
it('shows a warning if the active organization membership lacks the manage enterprise connections permission', async () => {
const { wrapper, fixtures } = await createFixtures(f => {
f.withEnterpriseSso({ selfServeSso: true });
f.withEnterpriseSso({ selfServeSSO: true });
f.withEmailAddress();
f.withOrganizations();
f.withUser({
Expand All@@ -31,7 +31,7 @@ describe('ConfigureSSO', () => {

it('renders the wizard when the active organization membership has the manage enterprise connections permission', async () => {
const { wrapper, fixtures } = await createFixtures(f => {
f.withEnterpriseSso({ selfServeSso: true });
f.withEnterpriseSso({ selfServeSSO: true });
f.withEmailAddress();
f.withOrganizations();
f.withUser({
Expand All@@ -54,7 +54,7 @@ describe('ConfigureSSO', () => {
describe('in a personal workspace', () => {
it('renders the wizard without checking the manage enterprise connections permission', async () => {
const { wrapper, fixtures } = await createFixtures(f => {
f.withEnterpriseSso({ selfServeSso: true });
f.withEnterpriseSso({ selfServeSSO: true });
f.withEmailAddress();
f.withUser({ email_addresses: ['test@clerk.com'] });
});
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,14 +37,22 @@ const OrganizationPaymentAttemptPage = lazy(() =>
})),
);

const OrganizationSelfServeSSOPage = lazy(() =>
import(/* webpackChunkName: "op-self-serve-sso-page"*/ './OrganizationSelfServeSSOPage').then(module => ({
default: module.OrganizationSelfServeSSOPage,
})),
);

export const OrganizationProfileRoutes = () => {
const {
pages,
isMembersPageRoot,
isGeneralPageRoot,
isBillingPageRoot,
isAPIKeysPageRoot,
isSelfServeSsoPageRoot,
shouldShowBilling,
shouldShowSelfServeSSO,
apiKeysProps,
} = useOrganizationProfileContext();

Expand DownExpand Up@@ -142,6 +150,17 @@ export const OrganizationProfileRoutes = () => {
</Route>
</Protect>
)}
{shouldShowSelfServeSSO ? (
<Route path={isSelfServeSsoPageRoot ? undefined : 'organization-self-serve-sso'}>
<Switch>
<Route index>
<Suspense fallback={''}>
<OrganizationSelfServeSSOPage />
</Suspense>
</Route>
</Switch>
</Route>
) : null}
Comment thread
LauraBeatris marked this conversation as resolved.
</Route>
</Switch>
);
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
import { useOrganization } from '@clerk/shared/react';
import { useRef } from 'react';

import { ConfigureSSOContent } from '../ConfigureSSO/ConfigureSSO';

export const OrganizationSelfServeSSOPage = () => {
const { organization } = useOrganization();
const contentRef = useRef<HTMLDivElement>(null);

if (!organization) {
// We should never reach this point, but we'll return null to make TS happy
return null;
}

return <ConfigureSSOContent contentRef={contentRef} />;
};
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,10 @@ import type { CustomPage } from '@clerk/shared/types';
import { describe, expect, it } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render, screen, waitFor } from '@/test/utils';
import { cleanup, render, screen, waitFor } from '@/test/utils';

import { OrganizationProfile } from '../';
import { OrganizationSelfServeSSOPage } from '../OrganizationSelfServeSSOPage';

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

Expand DownExpand Up@@ -476,6 +477,97 @@ describe('OrganizationProfile', () => {
});
});

describe('SSO visibility', () => {
it('includes SSO when enabled at the instance and the org has opted in', async () => {
const { wrapper } = await createFixtures(f => {
f.withEnterpriseSso({ selfServeSSO: true });
f.withOrganizations();
f.withUser({
email_addresses: ['test@clerk.com'],
organization_memberships: [
{
name: 'Org1',
self_serve_sso_enabled: true,
permissions: ['org:sys_entconns:manage'],
},
],
});
});

render(<OrganizationProfile />, { wrapper });
expect(await screen.findByText('Single Sign-On (SSO)')).toBeDefined();
});

it('does not include SSO when disabled at the instance level', async () => {
const { wrapper } = await createFixtures(f => {
f.withEnterpriseSso({ selfServeSSO: false });
f.withOrganizations();
f.withUser({
email_addresses: ['test@clerk.com'],
organization_memberships: [
{
name: 'Org1',
self_serve_sso_enabled: true,
permissions: ['org:sys_entconns:manage'],
},
],
});
});

const { queryByText } = render(<OrganizationProfile />, { wrapper });
await waitFor(() => expect(queryByText('Single Sign-On (SSO)')).toBeNull());
});

it('does not include SSO when the org has not opted in, even if the instance has it enabled', async () => {
const { wrapper } = await createFixtures(f => {
f.withEnterpriseSso({ selfServeSSO: true });
f.withOrganizations();
f.withUser({
email_addresses: ['test@clerk.com'],
organization_memberships: [
{
name: 'Org1',
self_serve_sso_enabled: false,
permissions: ['org:sys_entconns:manage'],
},
],
});
});

const { queryByText } = render(<OrganizationProfile />, { wrapper });
await waitFor(() => expect(queryByText('Single Sign-On (SSO)')).toBeNull());
});

it('includes SSO even when the user does not have the manage enterprise connections permission, but the page surfaces a warning', async () => {
const { wrapper, fixtures } = await createFixtures(f => {
f.withEnterpriseSso({ selfServeSSO: true });
f.withOrganizations();
f.withUser({
email_addresses: ['test@clerk.com'],
organization_memberships: [
{
name: 'Org1',
self_serve_sso_enabled: true,
permissions: [],
},
],
});
});

fixtures.clerk.user?.getEnterpriseConnections.mockResolvedValue([]);

render(<OrganizationProfile />, { wrapper });
expect(await screen.findByText('Single Sign-On (SSO)')).toBeDefined();

cleanup();
render(<OrganizationSelfServeSSOPage />, { wrapper });
expect(await screen.findByText(/you do not have permission to manage single sign-on/i)).toBeDefined();
expect(
screen.queryByText(/contact your organization.*administrator to upgrade your permissions/i),
).toBeInTheDocument();
});
});

it('removes member nav item if user is lacking permissions', async () => {
const { wrapper } = await createFixtures(f => {
f.withOrganizations();
Expand Down
1 change: 1 addition & 0 deletions packages/ui/src/constants.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ export const ORGANIZATION_PROFILE_NAVBAR_ROUTE_ID = {
MEMBERS: 'members',
BILLING: 'billing',
API_KEYS: 'apiKeys',
SELF_SERVE_SSO: 'selfServeSSO',
};

export const USER_BUTTON_ITEM_ID = {
Expand Down
Loading
Loading