Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: warn admins before restricting members to verified domains (#76895)

Alex Lider60e6327e0d60
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 790eb6b81f87..5d1962e2c177 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -3605,7 +3605,9 @@ const api = {
},
organizationMembers: {
- async list(params: ListOrganizationMembersParams = {}): Promise<PaginatedResponse<OrganizationMemberType>> {
+ async list(
+ params: ListOrganizationMembersParams = {}
+ ): Promise<CountedPaginatedResponse<OrganizationMemberType>> {
return await new ApiRequest().organizationMembers().withQueryString(params).get()
},
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/EnforceVerifiedDomains.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/EnforceVerifiedDomains.tsx
index b140f3c1bb48..c6c11fc6c525 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/EnforceVerifiedDomains.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/EnforceVerifiedDomains.tsx
@@ -5,17 +5,19 @@ import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedAr
import { OrganizationMembershipLevel } from 'lib/constants'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch/LemonSwitch'
import { organizationLogic } from 'scenes/organizationLogic'
-import { userLogic } from 'scenes/userLogic'
import { AvailableFeature } from '~/types'
+import { verifiedDomainImpactLogic } from './verifiedDomainImpactLogic'
+import { EnforceVerifiedDomainsModal } from './VerifiedDomainImpactModals'
import { verifiedDomainsLogic } from './verifiedDomainsLogic'
export function EnforceVerifiedDomains(): JSX.Element {
const { currentOrganization, currentOrganizationLoading } = useValues(organizationLogic)
const { updateOrganization } = useActions(organizationLogic)
- const { verifiedDomains, verifiedDomainsLoading } = useValues(verifiedDomainsLogic)
- const { user } = useValues(userLogic)
+ const { verifiedDomains, verifiedDomainsLoading, ownVerifiedDomain } = useValues(verifiedDomainsLogic)
+ const { enforcementImpactLoading } = useValues(verifiedDomainImpactLogic)
+ const { promptEnforceVerifiedDomains } = useActions(verifiedDomainImpactLogic)
const restrictionReason = useRestrictedArea({
minimumAccessLevel: OrganizationMembershipLevel.Admin,
@@ -23,17 +25,13 @@ export function EnforceVerifiedDomains(): JSX.Element {
})
const hasVerifiedDomains = verifiedDomains.some((domain) => domain.is_verified)
- const ownEmailDomain = user?.email.split('@')[1]?.toLowerCase()
- const ownEmailDomainVerified = verifiedDomains.some(
- (domain) => domain.is_verified && domain.domain.toLowerCase() === ownEmailDomain
- )
// Only gates turning it on — an organization that ends up misconfigured must still be able to turn it off.
let enableBlockedReason: string | undefined
if (!verifiedDomainsLoading && !currentOrganization?.enforce_verified_domains) {
if (!hasVerifiedDomains) {
enableBlockedReason = 'Verify at least one domain to enable this setting'
- } else if (!ownEmailDomainVerified) {
+ } else if (!ownVerifiedDomain) {
enableBlockedReason = 'Verify the domain of your own email address first, otherwise this would lock you out'
}
}
@@ -48,10 +46,16 @@ export function EnforceVerifiedDomains(): JSX.Element {
label="Restrict membership to verified email domains"
bordered
checked={!!currentOrganization?.enforce_verified_domains}
- onChange={(enforce_verified_domains) => updateOrganization({ enforce_verified_domains })}
- loading={currentOrganizationLoading}
+ onChange={(enforce_verified_domains) =>
+ // Turning it on can remove members, so it goes through an impact check and confirmation first.
+ enforce_verified_domains
+ ? promptEnforceVerifiedDomains()
+ : updateOrganization({ enforce_verified_domains })
+ }
+ loading={currentOrganizationLoading || enforcementImpactLoading}
disabledReason={restrictionReason ?? enableBlockedReason}
/>
+ <EnforceVerifiedDomainsModal />
</PayGateMini>
)
}
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomainImpactModals.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomainImpactModals.tsx
new file mode 100644
index 000000000000..602a0bb06ae6
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomainImpactModals.tsx
@@ -0,0 +1,180 @@
+import { useActions, useValues } from 'kea'
+
+import { CountedPaginatedResponse } from 'lib/api'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+import { membershipLevelToName } from 'lib/utils/permissioning'
+import { fullName } from 'lib/utils/strings'
+import { userLogic } from 'scenes/userLogic'
+
+import { OrganizationMemberType } from '~/types'
+
+import { verifiedDomainImpactLogic } from './verifiedDomainImpactLogic'
+
+function impactedMemberColumns(currentUserUuid?: string): LemonTableColumns<OrganizationMemberType> {
+ return [
+ {
+ key: 'user_profile_picture',
+ width: 32,
+ render: function ProfilePictureRender(_, member) {
+ return <ProfilePicture user={member.user} />
+ },
+ },
+ {
+ key: 'user',
+ title: 'Name',
+ render: function NameRender(_, member) {
+ return (
+ <div className="ph-no-capture">
+ <div>
+ {member.user.uuid === currentUserUuid
+ ? `${fullName(member.user)} (you)`
+ : fullName(member.user)}
+ </div>
+ <div className="text-secondary">{member.user.email}</div>
+ </div>
+ )
+ },
+ },
+ {
+ key: 'level',
+ title: 'Level',
+ render: function LevelRender(_, member) {
+ return membershipLevelToName.get(member.level) ?? `unknown (${member.level})`
+ },
+ },
+ ]
+}
+
+function ImpactedMembersTable({
+ impact,
+ loading,
+}: {
+ impact: CountedPaginatedResponse<OrganizationMemberType> | null
+ loading: boolean
+}): JSX.Element {
+ const { user } = useValues(userLogic)
+ const members = impact?.results ?? []
+ const count = impact?.count ?? members.length
+ return (
+ <>
+ <LemonTable
+ dataSource={members}
+ columns={impactedMemberColumns(user?.uuid)}
+ loading={loading}
+ rowKey="id"
+ size="small"
+ pagination={{ pageSize: 8, hideOnSinglePage: true }}
+ embedded
+ />
+ {count > members.length && (
+ <div className="text-secondary text-xs mt-1">
+ Showing {members.length} of {count} members.
+ </div>
+ )}
+ </>
+ )
+}
+
+export function RemoveDomainModal(): JSX.Element {
+ const { removeDomainPrompt, domainImpact, domainImpactLoading, currentOrganization } =
+ useValues(verifiedDomainImpactLogic)
+ const { closeRemoveDomainPrompt, confirmRemoveDomain } = useActions(verifiedDomainImpactLogic)
+
+ const impactedCount = domainImpact?.count ?? 0
+ const showImpact =
+ !!currentOrganization?.enforce_verified_domains &&
+ !!removeDomainPrompt?.is_verified &&
+ (domainImpactLoading || impactedCount > 0)
+
+ return (
+ <LemonModal
+ title={`Remove ${removeDomainPrompt?.domain ?? 'domain'}?`}
+ isOpen={!!removeDomainPrompt}
+ onClose={closeRemoveDomainPrompt}
+ width={showImpact ? 600 : undefined}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closeRemoveDomainPrompt}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ status="danger"
+ type="primary"
+ onClick={confirmRemoveDomain}
+ loading={domainImpactLoading}
+ >
+ Remove domain
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="space-y-2">
+ <p>
+ {removeDomainPrompt?.is_verified
+ ? 'This cannot be undone. If you have SAML configured or SSO enforced, it will be immediately disabled.'
+ : 'This cannot be undone.'}
+ </p>
+ {showImpact && (
+ <>
+ <p>
+ Logins are restricted to verified email domains. Removing this domain means{' '}
+ {impactedCount === 1 ? 'this member' : `these ${impactedCount} members`} can no longer log
+ in:
+ </p>
+ <ImpactedMembersTable impact={domainImpact} loading={domainImpactLoading} />
+ </>
+ )}
+ </div>
+ </LemonModal>
+ )
+}
+
+export function EnforceVerifiedDomainsModal(): JSX.Element {
+ const { enforcementPromptOpen, enforcementImpact, enforcementImpactLoading, enforcementRemovalLoading } =
+ useValues(verifiedDomainImpactLogic)
+ const { closeEnforcementPrompt, confirmEnforceVerifiedDomains } = useActions(verifiedDomainImpactLogic)
+
+ const impactedCount = enforcementImpact?.count ?? 0
+
+ return (
+ <LemonModal
+ title="Restrict logins to verified email domains?"
+ isOpen={enforcementPromptOpen}
+ onClose={closeEnforcementPrompt}
+ width={600}
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={closeEnforcementPrompt}
+ disabledReason={enforcementRemovalLoading ? 'Removing members...' : undefined}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ status="danger"
+ type="primary"
+ onClick={confirmEnforceVerifiedDomains}
+ loading={enforcementRemovalLoading}
+ >
+ {impactedCount === 1
+ ? 'Remove 1 member and restrict'
+ : `Remove ${impactedCount} members and restrict`}
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="space-y-2">
+ <p>
+ {impactedCount === 1 ? '1 member has' : `${impactedCount} members have`} an email address outside
+ your verified domains and will no longer be able to log in. Confirming also removes them from this
+ organization.
+ </p>
+ <ImpactedMembersTable impact={enforcementImpact} loading={enforcementImpactLoading} />
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
index 9619779a3f3f..577adf664eab 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
@@ -9,7 +9,6 @@ import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { IconExclamation } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { More } from 'lib/lemon-ui/LemonButton/More'
-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch/LemonSwitch'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag/LemonTag'
@@ -29,6 +28,8 @@ import { ConfigureSAMLModal } from './ConfigureSAMLModal'
import { ConfigureSCIMModal } from './ConfigureSCIMModal'
import { ScimLogsModal } from './ScimLogsModal'
import { SSOSelect } from './SSOSelect'
+import { verifiedDomainImpactLogic } from './verifiedDomainImpactLogic'
+import { RemoveDomainModal } from './VerifiedDomainImpactModals'
import { verifiedDomainsLogic } from './verifiedDomainsLogic'
import { VerifyDomainModal } from './VerifyDomainModal'
@@ -108,17 +109,18 @@ function VerifiedDomainsTable(): JSX.Element {
isSAMLAvailable,
isSCIMAvailable,
isXAAAuthenticationAvailable,
+ ownVerifiedDomain,
} = useValues(verifiedDomainsLogic)
const { currentOrganization } = useValues(organizationLogic)
const {
updateDomain,
- deleteVerifiedDomain,
setVerifyModal,
setConfigureSAMLModalId,
setConfigureSCIMModalId,
setConfigureIdJagModalId,
setScimLogsModalId,
} = useActions(verifiedDomainsLogic)
+ const { promptRemoveDomain } = useActions(verifiedDomainImpactLogic)
const { preflight } = useValues(preflightLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -132,6 +134,17 @@ function VerifiedDomainsTable(): JSX.Element {
const verifiedDomainsList = verifiedDomains.filter((d) => d.is_verified)
const unverifiedDomainsList = verifiedDomains.filter((d) => !d.is_verified)
+ // Mirrors the guard on `OrganizationDomainViewSet.destroy`: with the restriction on, an admin
+ // can't remove a domain if their own email would be left outside the verified ones.
+ const removeBlockedReason = (domain: OrganizationDomainType): string | undefined => {
+ if (!currentOrganization?.enforce_verified_domains || !domain.is_verified) {
+ return undefined
+ }
+ return ownVerifiedDomain && ownVerifiedDomain.id !== domain.id
+ ? undefined
+ : 'Your own email address would no longer be allowed. Turn off the domain restriction first'
+ }
+
const verifiedColumns: LemonTableColumns<OrganizationDomainType> = [
{
key: 'domain',
@@ -298,7 +311,8 @@ function VerifiedDomainsTable(): JSX.Element {
key: 'actions',
width: 32,
align: 'center',
- render: function RenderActions(_, { id, domain }) {
+ render: function RenderActions(_, domainRecord) {
+ const { id } = domainRecord
return (
<More
overlay={
@@ -341,24 +355,10 @@ function VerifiedDomainsTable(): JSX.Element {
)}
<LemonButton
status="danger"
- onClick={() =>
- LemonDialog.open({
- title: `Remove ${domain}?`,
- description:
- 'This cannot be undone. If you have SAML configured or SSO enforced, it will be immediately disabled.',
- primaryButton: {
- status: 'danger',
- children: 'Remove domain',
- onClick: () => deleteVerifiedDomain(id),
- },
- secondaryButton: {
- children: 'Cancel',
- },
- })
- }
+ onClick={() => promptRemoveDomain(domainRecord)}
fullWidth
icon={<IconTrash />}
- disabledReason={restrictionReason}
+ disabledReason={restrictionReason ?? removeBlockedReason(domainRecord)}
>
Remove domain
</LemonButton>
@@ -415,26 +415,13 @@ function VerifiedDomainsTable(): JSX.Element {
key: 'actions',
width: 32,
align: 'center',
- render: function RenderActions(_, { id, domain }) {
+ render: function RenderActions(_, domainRecord) {
return (
<More
overlay={
<LemonButton
status="danger"
- onClick={() =>
- LemonDialog.open({
- title: `Remove ${domain}?`,
- description: 'This cannot be undone.',
- primaryButton: {
- status: 'danger',
- children: 'Remove domain',
- onClick: () => deleteVerifiedDomain(id),
- },
- secondaryButton: {
- children: 'Cancel',
- },
- })
- }
+ onClick={() => promptRemoveDomain(domainRecord)}
fullWidth
icon={<IconTrash />}
disabledReason={restrictionReason}
@@ -474,6 +461,7 @@ function VerifiedDomainsTable(): JSX.Element {
{showXAAControls && <ConfigureIdJagModal />}
<ScimLogsModal />
<VerifyDomainModal />
+ <RemoveDomainModal />
</div>
)
}
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap b/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
index 7b66b7c3f330..ec38e9632ded 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
@@ -31,6 +31,7 @@ exports[`verifiedDomainsLogic values has proper defaults 1`] = `
"isSamlConfigSubmitting": false,
"isSamlConfigValid": true,
"isXAAAuthenticationAvailable": false,
+ "ownVerifiedDomain": null,
"samlConfig": {},
"samlConfigAllErrors": {
"saml_acs_url": undefined,
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainImpactLogic.ts b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainImpactLogic.ts
new file mode 100644
index 000000000000..ef7bd958f493
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainImpactLogic.ts
@@ -0,0 +1,273 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api, { CountedPaginatedResponse } from 'lib/api'
+import { OrganizationMembershipLevel } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { membersLogic } from 'scenes/organization/membersLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import { OrganizationDomainType, OrganizationMemberType, OrganizationType } from '~/types'
+
+import { verifiedDomainsLogic } from './verifiedDomainsLogic'
+
+/** How many impacted members to fetch for the modal; the total count still comes from the response. */
+const IMPACTED_MEMBERS_FETCH_LIMIT = 100
+
+interface EnforcementRemovalResult {
+ success: boolean
+ removed_members: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface verifiedDomainImpactLogicValues {
+ currentOrganization: OrganizationType | null // organizationLogic
+ domainImpact: CountedPaginatedResponse<OrganizationMemberType> | null
+ domainImpactLoading: boolean
+ enforcementImpact: CountedPaginatedResponse<OrganizationMemberType> | null
+ enforcementImpactLoading: boolean
+ enforcementPromptOpen: boolean
+ enforcementRemoval: EnforcementRemovalResult | null
+ enforcementRemovalLoading: boolean
+ removeDomainPrompt: OrganizationDomainType | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface verifiedDomainImpactLogicActions {
+ loadCurrentOrganization: () => any // organizationLogic
+ updateOrganization: (
+ payload: Partial<
+ Pick<
+ OrganizationType,
+ | 'allow_publicly_shared_resources'
+ | 'default_anonymize_ips'
+ | 'default_experiment_stats_method'
+ | 'default_role_id'
+ | 'enforce_2fa'
+ | 'enforce_verified_domains'
+ | 'is_ai_data_processing_approved'
+ | 'is_ai_training_opted_in'
+ | 'logo_media_id'
+ | 'members_can_create_projects'
+ | 'members_can_invite'
+ | 'members_can_see_org_members'
+ | 'members_can_use_personal_api_keys'
+ | 'name'
+ >
+ >
+ ) => Partial<
+ Pick<
+ OrganizationType,
+ | 'allow_publicly_shared_resources'
+ | 'default_anonymize_ips'
+ | 'default_experiment_stats_method'
+ | 'default_role_id'
+ | 'enforce_2fa'
+ | 'enforce_verified_domains'
+ | 'is_ai_data_processing_approved'
+ | 'is_ai_training_opted_in'
+ | 'logo_media_id'
+ | 'members_can_create_projects'
+ | 'members_can_invite'
+ | 'members_can_see_org_members'
+ | 'members_can_use_personal_api_keys'
+ | 'name'
+ >
+ > // organizationLogic
+ closeEnforcementPrompt: () => {
+ value: true
+ }
+ closeRemoveDomainPrompt: () => {
+ value: true
+ }
+ confirmEnforceVerifiedDomains: () => {
+ value: true
+ }
+ confirmEnforceVerifiedDomainsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ confirmEnforceVerifiedDomainsSuccess: (
+ enforcementRemoval: EnforcementRemovalResult,
+ payload?: {
+ value: true
+ }
+ ) => {
+ enforcementRemoval: EnforcementRemovalResult
+ payload?: {
+ value: true
+ }
+ }
+ confirmRemoveDomain: () => {
+ value: true
+ }
+ loadDomainImpact: (domain: OrganizationDomainType) => {
+ domain: OrganizationDomainType
+ }
+ loadDomainImpactFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDomainImpactSuccess: (
+ domainImpact: CountedPaginatedResponse<OrganizationMemberType>,
+ payload?: {
+ domain: OrganizationDomainType
+ }
+ ) => {
+ domainImpact: CountedPaginatedResponse<OrganizationMemberType>
+ payload?: {
+ domain: OrganizationDomainType
+ }
+ }
+ loadEnforcementImpact: () => {
+ value: true
+ }
+ loadEnforcementImpactFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadEnforcementImpactSuccess: (
+ enforcementImpact: CountedPaginatedResponse<OrganizationMemberType>,
+ payload?: {
+ value: true
+ }
+ ) => {
+ enforcementImpact: CountedPaginatedResponse<OrganizationMemberType>
+ payload?: {
+ value: true
+ }
+ }
+ promptEnforceVerifiedDomains: () => {
+ value: true
+ }
+ promptRemoveDomain: (domain: OrganizationDomainType) => {
+ domain: OrganizationDomainType
+ }
+}
+
+export type verifiedDomainImpactLogicType = MakeLogicType<
+ verifiedDomainImpactLogicValues,
+ verifiedDomainImpactLogicActions
+>
+
+/**
+ * Impact previews for the two destructive verified-domain actions: removing a verified domain while
+ * membership is restricted to verified email domains, and turning that restriction on. Both fetch
+ * the members who would lose access so the confirmation modal can list them.
+ */
+export const verifiedDomainImpactLogic = kea<verifiedDomainImpactLogicType>([
+ path(['scenes', 'organization', 'verifiedDomainImpactLogic']),
+ connect(() => ({
+ values: [organizationLogic, ['currentOrganization']],
+ actions: [organizationLogic, ['updateOrganization', 'loadCurrentOrganization']],
+ })),
+ actions({
+ promptRemoveDomain: (domain: OrganizationDomainType) => ({ domain }),
+ closeRemoveDomainPrompt: true,
+ confirmRemoveDomain: true,
+ promptEnforceVerifiedDomains: true,
+ closeEnforcementPrompt: true,
+ loadDomainImpact: (domain: OrganizationDomainType) => ({ domain }),
+ loadEnforcementImpact: true,
+ confirmEnforceVerifiedDomains: true,
+ }),
+ loaders(({ values }) => ({
+ domainImpact: [
+ null as CountedPaginatedResponse<OrganizationMemberType> | null,
+ {
+ loadDomainImpact: async ({ domain }: { domain: OrganizationDomainType }) => {
+ return await api.organizationMembers.list({
+ email_domain: domain.domain,
+ limit: IMPACTED_MEMBERS_FETCH_LIMIT,
+ })
+ },
+ },
+ ],
+ enforcementImpact: [
+ null as CountedPaginatedResponse<OrganizationMemberType> | null,
+ {
+ loadEnforcementImpact: async () => {
+ return await api.organizationMembers.list({
+ outside_verified_domains: true,
+ // Owners are never removed, so listing them would overstate the count.
+ levels: [OrganizationMembershipLevel.Member, OrganizationMembershipLevel.Admin].join(','),
+ limit: IMPACTED_MEMBERS_FETCH_LIMIT,
+ })
+ },
+ },
+ ],
+ enforcementRemoval: [
+ null as EnforcementRemovalResult | null,
+ {
+ confirmEnforceVerifiedDomains: async () => {
+ return await api.create<EnforcementRemovalResult>(
+ `api/organizations/${values.currentOrganization?.id}/remove_blocked_members_and_enforce_verified_domains`
+ )
+ },
+ },
+ ],
+ })),
+ reducers({
+ removeDomainPrompt: [
+ null as OrganizationDomainType | null,
+ {
+ promptRemoveDomain: (_, { domain }) => domain,
+ closeRemoveDomainPrompt: () => null,
+ },
+ ],
+ domainImpact: {
+ promptRemoveDomain: () => null,
+ },
+ enforcementPromptOpen: [
+ false,
+ {
+ loadEnforcementImpactSuccess: (_, { enforcementImpact }) => (enforcementImpact?.count ?? 0) > 0,
+ closeEnforcementPrompt: () => false,
+ confirmEnforceVerifiedDomainsSuccess: () => false,
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ promptRemoveDomain: ({ domain }) => {
+ // The list is only meaningful when the restriction is on and the domain counts as verified.
+ if (values.currentOrganization?.enforce_verified_domains && domain.is_verified) {
+ actions.loadDomainImpact(domain)
+ }
+ },
+ confirmRemoveDomain: () => {
+ const domain = values.removeDomainPrompt
+ if (domain) {
+ verifiedDomainsLogic.actions.deleteVerifiedDomain(domain.id)
+ }
+ actions.closeRemoveDomainPrompt()
+ },
+ promptEnforceVerifiedDomains: () => {
+ actions.loadEnforcementImpact()
+ },
+ loadEnforcementImpactSuccess: () => {
+ if ((values.enforcementImpact?.count ?? 0) === 0) {
+ // Nobody is impacted, no confirmation needed.
+ actions.updateOrganization({ enforce_verified_domains: true })
+ }
+ },
+ confirmEnforceVerifiedDomainsSuccess: ({ enforcementRemoval }) => {
+ const removed = enforcementRemoval?.removed_members ?? 0
+ lemonToast.success(
+ removed === 1
+ ? 'Logins restricted to verified email domains. 1 member was removed.'
+ : `Logins restricted to verified email domains. ${removed} members were removed.`
+ )
+ actions.loadCurrentOrganization()
+ membersLogic.findMounted()?.actions.loadAllMembers()
+ },
+ })),
+])
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
index 61f40aaffd7f..42ab9de88f69 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
@@ -18,7 +18,7 @@ import {
identityProviderConfigsScimTokenCreate,
} from '~/generated/core/api'
import { IdentityProviderConfigApi } from '~/generated/core/api.schemas'
-import { AvailableFeature, OrganizationDomainType, PaginatedSCIMRequestLogs } from '~/types'
+import { AvailableFeature, OrganizationDomainType, PaginatedSCIMRequestLogs, UserType } from '~/types'
/**
* Resolve the `IdentityProviderConfig` id that backs a domain, creating and linking an empty
@@ -138,6 +138,7 @@ export interface verifiedDomainsLogicValues {
isSamlConfigSubmitting: boolean
isSamlConfigValid: boolean
isXAAAuthenticationAvailable: boolean
+ ownVerifiedDomain: OrganizationDomainType | null
samlConfig: Partial<
Pick<IdentityProviderConfigApi, 'saml_acs_url' | 'saml_entity_id' | 'saml_x509_cert'> & {
id: string
@@ -602,6 +603,10 @@ export interface verifiedDomainsLogicMeta {
verifiedDomains: OrganizationDomainType[],
verifyModal: string | null
) => OrganizationDomainType | null
+ ownVerifiedDomain: (
+ verifiedDomains: OrganizationDomainType[],
+ user: UserType | null
+ ) => OrganizationDomainType | null
isSSOEnforcementAvailable: (
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
) => boolean
@@ -938,6 +943,18 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
(verifiedDomains: OrganizationDomainType[], verifyingId: string | null): OrganizationDomainType | null =>
(verifyingId && verifiedDomains.find(({ id }) => id === verifyingId)) || null,
],
+ ownVerifiedDomain: [
+ (s) => [s.verifiedDomains, userLogic.selectors.user],
+ (verifiedDomains: OrganizationDomainType[], user: UserType | null): OrganizationDomainType | null => {
+ // Domains are unique across organizations, so at most one can admit the user's email.
+ const emailDomain = user?.email.split('@')[1]?.toLowerCase()
+ return (
+ verifiedDomains.find(
+ (domain) => domain.is_verified && domain.domain.toLowerCase() === emailDomain
+ ) ?? null
+ )
+ },
+ ],
isSSOEnforcementAvailable: [
() => [userLogic.selectors.hasAvailableFeature],
(hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean): boolean =>
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index bffb17c16a73..3479d5395c2e 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -682,6 +682,12 @@ export interface ListOrganizationMembersParams {
limit?: number
updated_after?: string
search?: string
+ /** Only members whose email is on this domain. */
+ email_domain?: string
+ /** Only members whose email is outside the organization's verified domains. */
+ outside_verified_domains?: boolean
+ /** Comma-separated membership levels to return, e.g. `1,8`. */
+ levels?: string
}
export interface APIErrorType {
diff --git a/posthog/api/organization.py b/posthog/api/organization.py
index 108a231187d0..7113bd699ebf 100644
--- a/posthog/api/organization.py
+++ b/posthog/api/organization.py
@@ -2,6 +2,7 @@ from collections.abc import Callable
from functools import cached_property
from typing import Any, Literal, Union, cast
+from django.db import transaction
from django.db.models import Model, QuerySet
from django.shortcuts import get_object_or_404
@@ -34,7 +35,7 @@ from posthog.event_usage import (
)
from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import validate_display_name
-from posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR
+from posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR, verified_domain_email_q
from posthog.models import Organization, User
from posthog.models.activity_logging.model_activity import ImpersonatedContext
from posthog.models.organization import OrganizationMembership
@@ -405,6 +406,13 @@ class OrganizationAIAccessRequestResponseSerializer(serializers.Serializer):
)
+class OrganizationRemoveBlockedMembersResponseSerializer(serializers.Serializer):
+ success = serializers.BooleanField(help_text="Whether verified-domain enforcement was turned on.")
+ removed_members = serializers.IntegerField(
+ help_text="How many members with an email outside the verified domains were removed from the organization. Owners are never removed."
+ )
+
+
class DataFreshnessSourceSerializer(serializers.Serializer):
data_source = serializers.CharField(
help_text=(
@@ -680,6 +688,40 @@ class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
return Response({"success": True})
+ @extend_schema(
+ request=None,
+ responses={200: OrganizationRemoveBlockedMembersResponseSerializer},
+ )
+ @action(detail=True, methods=["post"], url_path="remove_blocked_members_and_enforce_verified_domains")
+ def remove_blocked_members_and_enforce_verified_domains(self, request: Request, **kwargs) -> Response:
+ """
+ Remove the members whose email domain is outside the organization's verified domains and turn
+ `enforce_verified_domains` on, in one transaction. Owners are never removed; they keep gated
+ access and can disable the setting themselves. Admin only.
+
+ Use this only when the caller has confirmed the removals. To turn the setting on without
+ touching memberships, PATCH `enforce_verified_domains` on the organization instead.
+ """
+ organization = self.organization
+ self.check_object_permissions(request, organization)
+
+ # Reuses the paygate and the would-block-self guard on the field's validator.
+ serializer = self.get_serializer(organization, data={"enforce_verified_domains": True}, partial=True)
+ serializer.is_valid(raise_exception=True)
+
+ blocked = organization.memberships.exclude(level=OrganizationMembership.Level.OWNER).select_related("user")
+ admitted = verified_domain_email_q(organization)
+ if admitted is not None:
+ blocked = blocked.exclude(admitted)
+
+ removed = 0
+ with transaction.atomic():
+ for membership in blocked:
+ membership.user.leave(organization=organization)
+ removed += 1
+ serializer.save()
+ return Response({"success": True, "removed_members": removed})
+
@extend_schema(request=None, responses={200: OrganizationDataFreshnessSerializer})
@action(detail=True, methods=["GET"], url_path="teams/data_freshness", pagination_class=None)
def data_freshness(self, request: Request, **kwargs) -> Response:
diff --git a/posthog/api/organization_member.py b/posthog/api/organization_member.py
index 07dbc5e22ac7..e4ecd6eb9bfe 100644
--- a/posthog/api/organization_member.py
+++ b/posthog/api/organization_member.py
@@ -34,6 +34,7 @@ from posthog.helpers.trigram_search import (
drop_similar_when_exact_exists,
normalize_search_term,
)
+from posthog.helpers.verified_domain_enforcement import verified_domain_email_q
from posthog.models import OrganizationMembership
from posthog.models.user import User
from posthog.models.webauthn_credential import WebauthnCredential
@@ -159,6 +160,21 @@ class OrganizationMemberGithubLoginSerializer(serializers.Serializer):
type=OpenApiTypes.STR,
description="Match against member `first_name`, `last_name`, and `email`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`. Capped at 200 characters.",
),
+ OpenApiParameter(
+ name="email_domain",
+ type=OpenApiTypes.STR,
+ description="Only return members whose email address is on this domain (case-insensitive).",
+ ),
+ OpenApiParameter(
+ name="outside_verified_domains",
+ type=OpenApiTypes.BOOL,
+ description="When `true`, only return members whose email domain is not one of the organization's verified domains — the members who would lose access under verified-domain enforcement.",
+ ),
+ OpenApiParameter(
+ name="levels",
+ type=OpenApiTypes.STR,
+ description="Comma-separated membership levels to return, e.g. `1,8`. Levels are 1 member, 8 admin, 15 owner.",
+ ),
],
),
)
@@ -242,6 +258,21 @@ class OrganizationMemberViewSet(
if "email" in params:
queryset = queryset.filter(user__email=params["email"])
+ if "email_domain" in params:
+ queryset = queryset.filter(user__email__iendswith=f"@{params['email_domain']}")
+
+ if params.get("outside_verified_domains") == "true":
+ admitted = verified_domain_email_q(organization)
+ if admitted is not None:
+ queryset = queryset.exclude(admitted)
+
+ if "levels" in params:
+ try:
+ levels = [int(level) for level in params["levels"].split(",") if level]
+ except ValueError:
+ raise serializers.ValidationError({"levels": "Must be a comma-separated list of integers."})
+ queryset = queryset.filter(level__in=levels)
+
if "updated_after" in params:
queryset = queryset.filter(updated_at__gt=params["updated_after"])
diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.py
index 96a55e1e0ac4..918152a28c8a 100644
--- a/posthog/api/test/test_organization.py
+++ b/posthog/api/test/test_organization.py
@@ -14,7 +14,7 @@ from rest_framework.test import APIRequestFactory
from posthog.api.organization import OrganizationSerializer, _fetch_member_count, _org_serializer_cache_version
from posthog.constants import AvailableFeature
-from posthog.models import Organization, OrganizationMembership, Team
+from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.personal_api_key import PersonalAPIKey
@@ -383,6 +383,65 @@ class TestOrganizationAPI(APIBaseTest):
self.organization.refresh_from_db()
self.assertTrue(self.organization.enforce_verified_domains)
+ def test_enabling_enforcement_removes_blocked_members_but_never_the_owner(self):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.organization.available_product_features = [{"key": AvailableFeature.AUTOMATIC_PROVISIONING}]
+ self.organization.save()
+ OrganizationDomain.objects.create(
+ domain="posthog.com", organization=self.organization, verified_at=timezone.now()
+ )
+ admitted = User.objects.create_and_join(self.organization, "[email protected]", None)
+ blocked = User.objects.create_and_join(self.organization, "[email protected]", None)
+ owner = User.objects.create_and_join(
+ self.organization, "[email protected]", None, level=OrganizationMembership.Level.OWNER
+ )
+
+ # The modal previews the removals with these filters, so the two must agree — an owner shown
+ # there would promise a removal that never happens.
+ preview = self.client.get(
+ "/api/organizations/@current/members/",
+ {
+ "outside_verified_domains": "true",
+ "levels": f"{OrganizationMembership.Level.MEMBER},{OrganizationMembership.Level.ADMIN}",
+ },
+ )
+ self.assertEqual(
+ {member["user"]["email"] for member in preview.json()["results"]},
+ {blocked.email},
+ )
+
+ response = self.client.post(
+ f"/api/organizations/{self.organization.id}/remove_blocked_members_and_enforce_verified_domains/"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True, "removed_members": 1})
+ self.organization.refresh_from_db()
+ self.assertTrue(self.organization.enforce_verified_domains)
+ self.assertCountEqual(
+ self.organization.memberships.values_list("user__email", flat=True),
+ [self.user.email, admitted.email, owner.email],
+ )
+ self.assertFalse(blocked.organization_memberships.exists())
+
+ def test_members_cannot_enable_enforcement_through_the_removal_action(self):
+ self.organization.available_product_features = [{"key": AvailableFeature.AUTOMATIC_PROVISIONING}]
+ self.organization.save()
+ OrganizationDomain.objects.create(
+ domain="posthog.com", organization=self.organization, verified_at=timezone.now()
+ )
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+
+ response = self.client.post(
+ f"/api/organizations/{self.organization.id}/remove_blocked_members_and_enforce_verified_domains/"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.organization.refresh_from_db()
+ self.assertNotEqual(self.organization.enforce_verified_domains, True)
+ self.assertEqual(self.organization.memberships.count(), 2)
+
def test_cannot_update_allow_publicly_shared_resources_without_feature(self):
"""Test that allow_publicly_shared_resources cannot be updated without ORGANIZATION_SECURITY_SETTINGS feature."""
self.organization_membership.level = OrganizationMembership.Level.ADMIN
diff --git a/posthog/api/test/test_organization_members.py b/posthog/api/test/test_organization_members.py
index 6e55fb57c877..0b0f1d01bb17 100644
--- a/posthog/api/test/test_organization_members.py
+++ b/posthog/api/test/test_organization_members.py
@@ -4,6 +4,7 @@ from posthog.test.base import APIBaseTest, QueryMatchingTest
from unittest.mock import ANY, patch
from django.test import override_settings
+from django.utils import timezone
from django_otp.plugins.otp_totp.models import TOTPDevice
from parameterized import parameterized
@@ -11,6 +12,7 @@ from rest_framework import status
from social_django.models import UserSocialAuth
from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.organization_domain import OrganizationDomain
from posthog.models.user import User
from posthog.models.webauthn_credential import WebauthnCredential
@@ -725,3 +727,43 @@ class TestOrganizationMembersAPI(APIBaseTest, QueryMatchingTest):
member = next(m for m in results if m["user"]["email"] == f"{_name}@posthog.com")
self.assertEqual(member["is_2fa_enabled"], expected)
+
+ @parameterized.expand(
+ [
+ # `@`-anchored, so a domain that merely ends with the filter value must not match.
+ (
+ "email_domain",
+ True,
+ {"email_domain": "posthog.com"},
+ ),
+ (
+ "outside_verified_domains",
+ True,
+ {"outside_verified_domains": "true"},
+ ),
+ # Pins which way the empty case reads: no verified domain admits nobody, so everyone is
+ # outside. The opposite reading (nobody is outside) is the one that silently blocks an org.
+ (
+ "outside_verified_domains_with_nothing_verified",
+ False,
+ {"outside_verified_domains": "true"},
+ ),
+ ]
+ )
+ def test_list_organization_members_filter_by_domain(self, _name, verify_domain, params, expected_emails):
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+ OrganizationDomain.objects.create(
+ domain="posthog.com",
+ organization=self.organization,
+ verified_at=timezone.now() if verify_domain else None,
+ )
+
+ response = self.client.get("/api/organizations/@current/members/", params)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertSetEqual({member["user"]["email"] for member in response.json()["results"]}, expected_emails)
diff --git a/posthog/helpers/verified_domain_enforcement.py b/posthog/helpers/verified_domain_enforcement.py
index 5fded91c115e..d7f9b2a0b24a 100644
--- a/posthog/helpers/verified_domain_enforcement.py
+++ b/posthog/helpers/verified_domain_enforcement.py
@@ -1,4 +1,7 @@
import re
+from typing import Optional
+
+from django.db.models import Q
import structlog
from loginas.utils import is_impersonated_session
@@ -6,7 +9,7 @@ from rest_framework.exceptions import PermissionDenied
from rest_framework.request import Request
from posthog.helpers.two_factor_session import is_path_whitelisted
-from posthog.models.organization import OrganizationMembership
+from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.user import User
@@ -29,6 +32,24 @@ def is_enforcement_disable_request(request: Request) -> bool:
return request.method == "PATCH" and bool(_ORGANIZATION_DETAIL_PATH.match(request.path))
+def verified_domain_email_q(organization: Organization) -> Optional[Q]:
+ """
+ Q matching `OrganizationMembership` rows whose user's email is on one of the organization's
+ verified domains, or None when the organization has no verified domains (every membership is
+ then outside them). Independent of `enforce_verified_domains`, so callers can preview the
+ impact of enabling it.
+ """
+ domains = list(
+ OrganizationDomain.objects.verified_domains().filter(organization=organization).values_list("domain", flat=True)
+ )
+ if not domains:
+ return None
+ admitted = Q()
+ for domain in domains:
+ admitted |= Q(user__email__iendswith=f"@{domain}")
+ return admitted
+
+
def enforce_verified_domain(request: Request, user: User) -> None:
"""
Deny requests from members whose email is outside their current organization's verified domains,
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 5cf055dba4de..a7689f7fc71c 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -246,6 +246,13 @@ export interface PatchedOrganizationApi {
readonly is_pending_deletion?: boolean | null
}
+export interface OrganizationRemoveBlockedMembersResponseApi {
+ /** Whether verified-domain enforcement was turned on. */
+ success: boolean
+ /** How many members with an email outside the verified domains were removed from the organization. Owners are never removed. */
+ removed_members: number
+}
+
export interface OrganizationAIAccessRequestResponseApi {
/** Whether the access request was accepted and the organization admins were notified. */
success: boolean
@@ -1002,6 +1009,14 @@ export type ListParams = {
}
export type MembersListParams = {
+ /**
+ * Only return members whose email address is on this domain (case-insensitive).
+ */
+ email_domain?: string
+ /**
+ * Comma-separated membership levels to return, e.g. `1,8`. Levels are 1 member, 8 admin, 15 owner.
+ */
+ levels?: string
/**
* Number of results to return per page.
*/
@@ -1014,6 +1029,10 @@ export type MembersListParams = {
* Sort order. Defaults to `-joined_at`.
*/
order?: string
+ /**
+ * When `true`, only return members whose email domain is not one of the organization's verified domains — the members who would lose access under verified-domain enforcement.
+ */
+ outside_verified_domains?: boolean
/**
* Match against member `first_name`, `last_name`, and `email`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`. Capped at 200 characters.
*/
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index 722129dda740..df291492a227 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -30,6 +30,7 @@ import type {
OrganizationDataFreshnessApi,
OrganizationMemberApi,
OrganizationMemberGithubLoginApi,
+ OrganizationRemoveBlockedMembersResponseApi,
PaginatedActivityLogListApi,
PaginatedApprovalPolicyListApi,
PaginatedChangeRequestListApi,
@@ -165,6 +166,31 @@ export const destroy = async (id: string, options?: RequestInit): Promise<void>
})
}
+export const getRemoveBlockedMembersAndEnforceVerifiedDomainsCreateUrl = (id: string) => {
+ return `/api/organizations/${id}/remove_blocked_members_and_enforce_verified_domains/`
+}
+
+/**
+ * Remove the members whose email domain is outside the organization's verified domains and turn
+ * `enforce_verified_domains` on, in one transaction. Owners are never removed; they keep gated
+ * access and can disable the setting themselves. Admin only.
+ *
+ * Use this only when the caller has confirmed the removals. To turn the setting on without
+ * touching memberships, PATCH `enforce_verified_domains` on the organization instead.
+ */
+export const removeBlockedMembersAndEnforceVerifiedDomainsCreate = async (
+ id: string,
+ options?: RequestInit
+): Promise<OrganizationRemoveBlockedMembersResponseApi> => {
+ return apiMutator<OrganizationRemoveBlockedMembersResponseApi>(
+ getRemoveBlockedMembersAndEnforceVerifiedDomainsCreateUrl(id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
export const getRequestAiAccessCreateUrl = (id: string) => {
return `/api/organizations/${id}/request_ai_access/`
}
diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yaml
index 1b1cc4481166..470d94d5ace7 100644
--- a/products/platform_features/mcp/tools.yaml
+++ b/products/platform_features/mcp/tools.yaml
@@ -485,6 +485,9 @@ tools:
personal-api-keys-list:
operation: personal_api_keys_list
enabled: false
+ remove-blocked-members-and-enforce-verified-domains-create:
+ operation: remove_blocked_members_and_enforce_verified_domains_create
+ enabled: false
request-ai-access-create:
operation: request_ai_access_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9ba4eeb68708..291c88c65242 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -47369,6 +47369,13 @@ export namespace Schemas {
readonly created_at: string;
}
+ export interface OrganizationRemoveBlockedMembersResponse {
+ /** Whether verified-domain enforcement was turned on. */
+ success: boolean;
+ /** How many members with an email outside the verified domains were removed from the organization. Owners are never removed. */
+ removed_members: number;
+ }
+
/**
* * `onboarding` - Onboarding
* * `error_tracking` - Error Tracking
@@ -81241,6 +81248,14 @@ export namespace Schemas {
};
export type MembersListParams = {
+ /**
+ * Only return members whose email address is on this domain (case-insensitive).
+ */
+ email_domain?: string;
+ /**
+ * Comma-separated membership levels to return, e.g. `1,8`. Levels are 1 member, 8 admin, 15 owner.
+ */
+ levels?: string;
/**
* Number of results to return per page.
*/
@@ -81253,6 +81268,10 @@ export namespace Schemas {
* Sort order. Defaults to `-joined_at`.
*/
order?: string;
+ /**
+ * When `true`, only return members whose email domain is not one of the organization's verified domains — the members who would lose access under verified-domain enforcement.
+ */
+ outside_verified_domains?: boolean;
/**
* Match against member `first_name`, `last_name`, and `email`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`. Capped at 200 characters.
*/
diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.ts
index c230bb4898b0..8676017fa669 100644
--- a/services/mcp/src/generated/platform_features/api.ts
+++ b/services/mcp/src/generated/platform_features/api.ts
@@ -82,9 +82,23 @@ export const MembersListParams = /* @__PURE__ */ zod.object({
})
export const MembersListQueryParams = /* @__PURE__ */ zod.object({
+ email_domain: zod
+ .string()
+ .optional()
+ .describe('Only return members whose email address is on this domain (case-insensitive).'),
+ levels: zod
+ .string()
+ .optional()
+ .describe('Comma-separated membership levels to return, e.g. `1,8`. Levels are 1 member, 8 admin, 15 owner.'),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
order: zod.string().optional().describe('Sort order. Defaults to `-joined_at`.'),
+ outside_verified_domains: zod
+ .boolean()
+ .optional()
+ .describe(
+ "When `true`, only return members whose email domain is not one of the organization's verified domains — the members who would lose access under verified-domain enforcement."
+ ),
search: zod
.string()
.optional()
diff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.ts
index a8e9c0381be5..37508ee4ce76 100644
--- a/services/mcp/src/tools/generated/platform_features.ts
+++ b/services/mcp/src/tools/generated/platform_features.ts
@@ -530,9 +530,12 @@ const orgMembersList = (): ToolBase<typeof OrgMembersListSchema, Schemas.Paginat
method: 'GET',
path: `/api/organizations/${encodeURIComponent(String(orgId))}/members/`,
query: {
+ email_domain: params.email_domain,
+ levels: params.levels,
limit: params.limit,
offset: params.offset,
order: params.order,
+ outside_verified_domains: params.outside_verified_domains,
search: params.search,
},
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/org-members-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/org-members-list.json
index 5f9cade10e12..ab8ab375cf5e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/org-members-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/org-members-list.json
@@ -1,6 +1,14 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "email_domain": {
+ "description": "Only return members whose email address is on this domain (case-insensitive).",
+ "type": "string"
+ },
+ "levels": {
+ "description": "Comma-separated membership levels to return, e.g. `1,8`. Levels are 1 member, 8 admin, 15 owner.",
+ "type": "string"
+ },
"limit": {
"description": "Number of results to return per page.",
"type": "number"
@@ -13,6 +21,10 @@
"description": "Sort order. Defaults to `-joined_at`.",
"type": "string"
},
+ "outside_verified_domains": {
+ "description": "When `true`, only return members whose email domain is not one of the organization's verified domains — the members who would lose access under verified-domain enforcement.",
+ "type": "boolean"
+ },
"search": {
"description": "Match against member `first_name`, `last_name`, and `email`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`. Capped at 200 characters.",
"type": "string"