Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(teams): domain auto join (#4860)

Will Hutchinsonc6cd9a5d5cd2
diff --git a/.sqlx/query-3572db68ccc07d9903b46d266c48b04139488fd312055ab7c22b2f7bf75f9c4c.json b/.sqlx/query-3572db68ccc07d9903b46d266c48b04139488fd312055ab7c22b2f7bf75f9c4c.json
new file mode 100644
index 0000000000..50699df976
--- /dev/null
+++ b/.sqlx/query-3572db68ccc07d9903b46d266c48b04139488fd312055ab7c22b2f7bf75f9c4c.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE team\n SET auto_join_domain = $2\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3572db68ccc07d9903b46d266c48b04139488fd312055ab7c22b2f7bf75f9c4c"
+}
diff --git a/.sqlx/query-852f9fa0ab92523b6300999164f2b720b7ece28d838cf6ed1a5551c4a3adbad5.json b/.sqlx/query-852f9fa0ab92523b6300999164f2b720b7ece28d838cf6ed1a5551c4a3adbad5.json
new file mode 100644
index 0000000000..e9c40f2ed1
--- /dev/null
+++ b/.sqlx/query-852f9fa0ab92523b6300999164f2b720b7ece28d838cf6ed1a5551c4a3adbad5.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id\n FROM team\n WHERE auto_join_domain = $1\n ORDER BY id\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "852f9fa0ab92523b6300999164f2b720b7ece28d838cf6ed1a5551c4a3adbad5"
+}
diff --git a/.sqlx/query-4c49a19453f820f3daa2f654a67db0bc895b15a7cd5f282133e292f97e42ec19.json b/.sqlx/query-bbf73370ac43c4f2378584e005b10a8d854b7c0203978dfb28c2fa7a70996bdd.json
similarity index 61%
rename from .sqlx/query-4c49a19453f820f3daa2f654a67db0bc895b15a7cd5f282133e292f97e42ec19.json
rename to .sqlx/query-bbf73370ac43c4f2378584e005b10a8d854b7c0203978dfb28c2fa7a70996bdd.json
index 7133edad58..224d49cbd0 100644
--- a/.sqlx/query-4c49a19453f820f3daa2f654a67db0bc895b15a7cd5f282133e292f97e42ec19.json
+++ b/.sqlx/query-bbf73370ac43c4f2378584e005b10a8d854b7c0203978dfb28c2fa7a70996bdd.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT t.id, t.name, t.slug, t.owner_id,\n COALESCE(tcs.crm_enabled, FALSE) AS \"crm_enabled!\"\n FROM team t\n JOIN team_user tu ON t.id = tu.team_id\n LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id\n WHERE tu.user_id = $1\n ",
+ "query": "\n SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain,\n COALESCE(tcs.crm_enabled, FALSE) AS \"crm_enabled!\"\n FROM team t\n JOIN team_user tu ON t.id = tu.team_id\n LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id\n WHERE tu.user_id = $1\n ",
"describe": {
"columns": [
{
@@ -25,6 +25,11 @@
},
{
"ordinal": 4,
+ "name": "auto_join_domain",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
"name": "crm_enabled!",
"type_info": "Bool"
}
@@ -39,8 +44,9 @@
false,
false,
false,
+ true,
null
]
},
- "hash": "4c49a19453f820f3daa2f654a67db0bc895b15a7cd5f282133e292f97e42ec19"
+ "hash": "bbf73370ac43c4f2378584e005b10a8d854b7c0203978dfb28c2fa7a70996bdd"
}
diff --git a/.sqlx/query-e4282f7baf0bdb2d19f4ee146f80cf2985c8c916faa8e5c81dd20b9402d3f2bd.json b/.sqlx/query-e4282f7baf0bdb2d19f4ee146f80cf2985c8c916faa8e5c81dd20b9402d3f2bd.json
new file mode 100644
index 0000000000..4e6a33dde1
--- /dev/null
+++ b/.sqlx/query-e4282f7baf0bdb2d19f4ee146f80cf2985c8c916faa8e5c81dd20b9402d3f2bd.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT auto_join_domain, owner_id\n FROM team\n WHERE id = $1\n FOR UPDATE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "auto_join_domain",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ false
+ ]
+ },
+ "hash": "e4282f7baf0bdb2d19f4ee146f80cf2985c8c916faa8e5c81dd20b9402d3f2bd"
+}
diff --git a/.sqlx/query-e4ee183ffef06ea668eaa3573a115aefd2944414d8ff507a5abf590b0cd8c0c3.json b/.sqlx/query-e4ee183ffef06ea668eaa3573a115aefd2944414d8ff507a5abf590b0cd8c0c3.json
new file mode 100644
index 0000000000..436bf003a3
--- /dev/null
+++ b/.sqlx/query-e4ee183ffef06ea668eaa3573a115aefd2944414d8ff507a5abf590b0cd8c0c3.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_user (team_id, user_id, team_role)\n VALUES ($1, $2, 'member')\n ON CONFLICT DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e4ee183ffef06ea668eaa3573a115aefd2944414d8ff507a5abf590b0cd8c0c3"
+}
diff --git a/.sqlx/query-c2628632426ab991146cd647e78158438a5126b027a0c12b834b8874a166c9c5.json b/.sqlx/query-f9a6fffccca132ccefa2654e7e08d87320c51e5103e589615b475f18c3f07f68.json
similarity index 64%
rename from .sqlx/query-c2628632426ab991146cd647e78158438a5126b027a0c12b834b8874a166c9c5.json
rename to .sqlx/query-f9a6fffccca132ccefa2654e7e08d87320c51e5103e589615b475f18c3f07f68.json
index 8aa827f2d3..cee1ed3162 100644
--- a/.sqlx/query-c2628632426ab991146cd647e78158438a5126b027a0c12b834b8874a166c9c5.json
+++ b/.sqlx/query-f9a6fffccca132ccefa2654e7e08d87320c51e5103e589615b475f18c3f07f68.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT t.id, t.name, t.slug, t.owner_id,\n COALESCE(tcs.crm_enabled, FALSE) AS \"crm_enabled!\"\n FROM team t\n LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id\n WHERE t.id = $1\n ",
+ "query": "\n SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain,\n COALESCE(tcs.crm_enabled, FALSE) AS \"crm_enabled!\"\n FROM team t\n LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id\n WHERE t.id = $1\n ",
"describe": {
"columns": [
{
@@ -25,6 +25,11 @@
},
{
"ordinal": 4,
+ "name": "auto_join_domain",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
"name": "crm_enabled!",
"type_info": "Bool"
}
@@ -39,8 +44,9 @@
false,
false,
false,
+ true,
null
]
},
- "hash": "c2628632426ab991146cd647e78158438a5126b027a0c12b834b8874a166c9c5"
+ "hash": "f9a6fffccca132ccefa2654e7e08d87320c51e5103e589615b475f18c3f07f68"
}
diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsx
index 56f38fd16e..27807535fc 100644
--- a/apps/web/src/features/settings/Team.tsx
+++ b/apps/web/src/features/settings/Team.tsx
@@ -39,12 +39,13 @@ import {
useDeleteTeamMutation,
usePatchTeamMutation,
useTeamQuery,
+ useToggleAutoJoinDomainMutation,
useUserTeamsQuery,
} from '@queries/team/teams';
import type { TeamInviteDetails } from '@service-auth/generated/schemas/teamInviteDetails';
import type { TeamMember } from '@service-auth/generated/schemas/teamMember';
import { TeamRole } from '@service-auth/generated/schemas/teamRole';
-import { Button, cn, Dialog, Panel, Tooltip } from '@ui';
+import { Button, cn, Dialog, Panel, ToggleSwitch, Tooltip } from '@ui';
import {
createMemo,
createSignal,
@@ -856,6 +857,7 @@ function TeamManagement(props: {
const patchTeamMutation = usePatchTeamMutation();
const inviteToTeamMutation = useInviteToTeamMutation();
const deleteTeamMutation = useDeleteTeamMutation();
+ const toggleAutoJoinMutation = useToggleAutoJoinDomainMutation();
const requiresUpgrade = useRequiresPaidUpgrade();
const { showPaywall } = usePaywallState();
@@ -983,13 +985,29 @@ function TeamManagement(props: {
(member) => member.user_id === currentUserId
)?.role;
});
- const canManageMemberRemovals = () => isTeamAdminOrOwner(currentUserRole());
+ const isAdminOrOwner = () => isTeamAdminOrOwner(currentUserRole());
+ const canManageMemberRemovals = () => isAdminOrOwner();
const isOwner = createMemo(() => {
const currentUserId = userId();
if (!currentUserId) return false;
return props.ownerId === currentUserId;
});
+ // The team's auto-join domain doubles as the toggle state: a string means
+ // auto-join is on for that domain, null/undefined means it's off.
+ const autoJoinDomain = () => teamQuery.data?.team.auto_join_domain ?? null;
+ const autoJoinDescription = () => {
+ const domain = autoJoinDomain();
+ return domain
+ ? `New sign-ups with an @${domain} email automatically join this team.`
+ : "Automatically add new sign-ups whose email matches the team owner's domain.";
+ };
+
+ const handleToggleAutoJoin = () => {
+ if (!props.teamId || toggleAutoJoinMutation.isPending) return;
+ toggleAutoJoinMutation.mutate({ teamId: props.teamId });
+ };
+
const handleSaveTeamName = () => {
const newName = editingTeamName()?.trim();
if (!props.teamId || !newName) return;
@@ -1242,6 +1260,23 @@ function TeamManagement(props: {
</div>
</Show>
</SettingsRow>
+
+ <Show when={isAdminOrOwner()}>
+ <SettingsRow
+ label="Auto-join on domain"
+ description={autoJoinDescription()}
+ hideDescriptionOnMobile
+ >
+ <ToggleSwitch
+ size="md"
+ checked={!!autoJoinDomain()}
+ disabled={
+ toggleAutoJoinMutation.isPending || teamQuery.isLoading
+ }
+ onChange={handleToggleAutoJoin}
+ />
+ </SettingsRow>
+ </Show>
</SettingsCard>
</SettingsSection>
diff --git a/apps/web/src/lib/queries/team/teams.ts b/apps/web/src/lib/queries/team/teams.ts
index 5f533d4920..663199bece 100644
--- a/apps/web/src/lib/queries/team/teams.ts
+++ b/apps/web/src/lib/queries/team/teams.ts
@@ -1,11 +1,16 @@
import { toast } from '@core/component/Toast/Toast';
import { useUserId } from '@core/context/user';
-import { throwOnErr } from '@core/util/result';
-import { authServiceClient } from '@service-auth/client';
+import { ThrownResultError, throwOnErr } from '@core/util/result';
+import {
+ authServiceClient,
+ type ToggleAutoJoinDomainErrorCode,
+} from '@service-auth/client';
import type { CreateTeamRequest } from '@service-auth/generated/schemas/createTeamRequest';
import type { PatchTeamRequest } from '@service-auth/generated/schemas/patchTeamRequest';
import type { Team } from '@service-auth/generated/schemas/team';
import { TeamRole } from '@service-auth/generated/schemas/teamRole';
+import type { TeamWithMembers } from '@service-auth/generated/schemas/teamWithMembers';
+import type { ToggleAutoJoinDomainResponse } from '@service-auth/generated/schemas/toggleAutoJoinDomainResponse';
import { useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
@@ -126,6 +131,84 @@ export function usePatchTeamMutation(callbacks?: PatchTeamCallbacks) {
}));
}
+type ToggleAutoJoinDomainArgs = { teamId: string };
+type ToggleAutoJoinDomainCallbacks = MutationCallbacks<
+ ToggleAutoJoinDomainResponse,
+ Error,
+ ToggleAutoJoinDomainArgs
+>;
+
+/** True when the failure is the backend rejecting a generic email provider
+ * domain (e.g. gmail.com) — the one case whose message we show verbatim. */
+function isGenericDomainError(error: Error): boolean {
+ return (
+ error instanceof ThrownResultError &&
+ error.errors.some(
+ (e) =>
+ e.code ===
+ ('GENERIC_DOMAIN_NOT_ALLOWED' satisfies ToggleAutoJoinDomainErrorCode)
+ )
+ );
+}
+
+export function useToggleAutoJoinDomainMutation(
+ callbacks?: ToggleAutoJoinDomainCallbacks
+) {
+ return useMutation(() => ({
+ mutationFn: async (_args: ToggleAutoJoinDomainArgs) =>
+ await throwOnErr(() => authServiceClient.toggleTeamAutoJoinDomain()),
+
+ ...withCallbacks<
+ ToggleAutoJoinDomainResponse,
+ Error,
+ ToggleAutoJoinDomainArgs
+ >(
+ {
+ onSuccess: (data, { teamId }) => {
+ // The response carries the authoritative new value — reflect it
+ // in the cached team right away so the switch doesn't lag behind
+ // the refetch, then invalidate as usual.
+ const applyDomain = (old: TeamWithMembers | null | undefined) =>
+ old
+ ? {
+ ...old,
+ team: {
+ ...old.team,
+ auto_join_domain: data.auto_join_domain ?? null,
+ },
+ }
+ : old;
+ queryClient.setQueryData<TeamWithMembers | null>(
+ teamKeys.detail(teamId).queryKey,
+ applyDomain
+ );
+ queryClient.setQueryData<TeamWithMembers | null>(
+ teamKeys.currentTeam.queryKey,
+ applyDomain
+ );
+ invalidateTeam(teamId);
+ invalidateUserTeams();
+ toast.success(
+ data.auto_join_domain
+ ? `Auto-join enabled for @${data.auto_join_domain}`
+ : 'Auto-join disabled'
+ );
+ },
+
+ onError: (error) => {
+ console.error('Failed to toggle team auto-join', error);
+ toast.failure(
+ isGenericDomainError(error)
+ ? error.message
+ : 'Failed to update auto-join'
+ );
+ },
+ },
+ callbacks
+ ),
+ }));
+}
+
type DeleteTeamArgs = { teamId: string };
type DeleteTeamContext = { previousTeams: Team[] | undefined };
type DeleteTeamCallbacks = MutationCallbacks<
@@ -236,6 +319,7 @@ export function useCreateTeamWithInvitesMutation(
slug: 'MACRO', // optimisitc slug
owner_id: userInfo.userId,
crm_enabled: false,
+ auto_join_domain: null,
};
queryClient.setQueryData<Team[]>(
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index 5fcc3b7418..3e2d3bc218 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -44,6 +44,7 @@ import type { PutUserNameQueryParams } from './generated/schemas/putUserNameQuer
import type { Team } from './generated/schemas/team';
import type { TeamInvitesResponse } from './generated/schemas/teamInvitesResponse';
import type { TeamWithMembers } from './generated/schemas/teamWithMembers';
+import type { ToggleAutoJoinDomainResponse } from './generated/schemas/toggleAutoJoinDomainResponse';
import type { UserLinkResponse } from './generated/schemas/userLinkResponse';
import type { UserName } from './generated/schemas/userName';
import type { UserNames } from './generated/schemas/userNames';
@@ -138,6 +139,10 @@ async function getAccessToken(): Promise<string | null> {
export type GithubReauthenticationErrorCode = 'REAUTHENTICATION_REQUIRED';
+/** The team owner's email domain is a generic provider (e.g. gmail.com),
+ * so auto-join cannot be enabled for it. */
+export type ToggleAutoJoinDomainErrorCode = 'GENERIC_DOMAIN_NOT_ALLOWED';
+
const githubErrorResponseHandler: ErrorResponseHandler<GithubReauthenticationErrorCode> =
async function handleGithubErrorResponse(response) {
switch (response.status) {
@@ -713,6 +718,46 @@ export const authServiceClient = {
).map(() => undefined);
},
+ /**
+ * Toggles automatic domain joining for the caller's team: sets the
+ * auto-join domain from the team owner's email domain when unset,
+ * removes it when set. Returns the domain after the toggle (null when
+ * it was just disabled). Admin/Owner only.
+ */
+ async toggleTeamAutoJoinDomain() {
+ return (
+ await fetchWithAuth<
+ ToggleAutoJoinDomainResponse,
+ ToggleAutoJoinDomainErrorCode
+ >(`${authHost}/team/auto-join-domain/toggle`, {
+ method: 'POST',
+ // The backend rejects enabling auto-join for generic email
+ // provider domains (e.g. gmail.com) with a 400 whose message
+ // names the domain — keep that message so the UI can toast it
+ // verbatim.
+ errorResponseHandler: async (response) => {
+ if (response.status === 400) {
+ const message = await response
+ .json()
+ .then((body) => body?.message)
+ .catch(() => undefined);
+ return {
+ code: 'GENERIC_DOMAIN_NOT_ALLOWED',
+ message:
+ typeof message === 'string'
+ ? message
+ : 'This domain cannot be used for auto-join',
+ };
+ }
+ return {
+ code: 'HTTP_ERROR',
+ message: `HTTP error! status: ${response.status}`,
+ };
+ },
+ })
+ ).map((result) => result);
+ },
+
async deleteTeamInvite(teamInviteId: string) {
return (
await fetchWithAuth<{}>(`${authHost}/team/invite/${teamInviteId}`, {
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index 0125899900..ae333faee2 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -56,6 +56,7 @@ import type {
Team,
TeamInvitesResponse,
TeamWithMembers,
+ ToggleAutoJoinDomainResponse,
UserLinkResponse,
UserName,
UserNames,
@@ -2245,6 +2246,86 @@ export const patchTeam = async (
} as patchTeamResponse;
};
+/**
+ * @summary Toggles automatic domain joining for the team. When the team has no
+auto-join domain, sets it to the team owner's email domain — rejected
+with a 400 when that domain is a generic email provider domain (e.g.
+gmail.com). When one is already set, removes it. New users whose email
+domain matches a team's auto-join domain are added to that team on
+signup. Requires the caller to be an Admin or Owner of the team.
+ */
+export type toggleTeamAutoJoinDomainResponse200 = {
+ data: ToggleAutoJoinDomainResponse;
+ status: 200;
+};
+
+export type toggleTeamAutoJoinDomainResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type toggleTeamAutoJoinDomainResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type toggleTeamAutoJoinDomainResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type toggleTeamAutoJoinDomainResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type toggleTeamAutoJoinDomainResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type toggleTeamAutoJoinDomainResponseSuccess =
+ toggleTeamAutoJoinDomainResponse200 & {
+ headers: Headers;
+ };
+export type toggleTeamAutoJoinDomainResponseError = (
+ | toggleTeamAutoJoinDomainResponse400
+ | toggleTeamAutoJoinDomainResponse401
+ | toggleTeamAutoJoinDomainResponse403
+ | toggleTeamAutoJoinDomainResponse404
+ | toggleTeamAutoJoinDomainResponse500
+) & {
+ headers: Headers;
+};
+
+export type toggleTeamAutoJoinDomainResponse =
+ | toggleTeamAutoJoinDomainResponseSuccess
+ | toggleTeamAutoJoinDomainResponseError;
+
+export const getToggleTeamAutoJoinDomainUrl = () => {
+ return `/team/auto-join-domain/toggle`;
+};
+
+export const toggleTeamAutoJoinDomain = async (
+ options?: RequestInit
+): Promise<toggleTeamAutoJoinDomainResponse> => {
+ const res = await fetch(getToggleTeamAutoJoinDomainUrl(), {
+ ...options,
+ method: 'POST',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: toggleTeamAutoJoinDomainResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as toggleTeamAutoJoinDomainResponse;
+};
+
/**
* @summary Enables or disables CRM for the team. On enable with `backfill`
(the default), kicks off a best-effort backfill that enqueues a
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
index 58d5a01607..decb544443 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
@@ -98,12 +98,15 @@ export * from './ssoLoginParams';
export * from './ssoRequiredResponse';
export * from './stripeSessionResponse';
export * from './team';
+export * from './teamAutoJoinDomain';
export * from './teamInviteDetails';
export * from './teamInvitesResponse';
export * from './teamMember';
export * from './teamPlan';
export * from './teamRole';
export * from './teamWithMembers';
+export * from './toggleAutoJoinDomainResponse';
+export * from './toggleAutoJoinDomainResponseAutoJoinDomain';
export * from './userLinkResponse';
export * from './userName';
export * from './userNameFirstName';
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/team.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/team.ts
index d160c92d48..3d4d1899b0 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/team.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/team.ts
@@ -4,11 +4,15 @@
* authentication_service
* OpenAPI spec version: 0.1.0
*/
+import type { TeamAutoJoinDomain } from './teamAutoJoinDomain';
/**
* The Team struct
*/
export interface Team {
+ /** The email domain new users are automatically joined to this team
+with, when automatic domain joining is enabled (None otherwise). */
+ auto_join_domain?: TeamAutoJoinDomain;
/** Whether the CRM is enabled for this team (from `team_crm_settings`;
`false` when no row exists). */
crm_enabled: boolean;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamAutoJoinDomain.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamAutoJoinDomain.ts
new file mode 100644
index 0000000000..f606337aa5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/teamAutoJoinDomain.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The email domain new users are automatically joined to this team
+with, when automatic domain joining is enabled (None otherwise).
+ */
+export type TeamAutoJoinDomain = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/toggleAutoJoinDomainResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/toggleAutoJoinDomainResponse.ts
new file mode 100644
index 0000000000..b16a27be0c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/toggleAutoJoinDomainResponse.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ToggleAutoJoinDomainResponseAutoJoinDomain } from './toggleAutoJoinDomainResponseAutoJoinDomain';
+
+/**
+ * Response for the toggle auto-join domain endpoint.
+ */
+export interface ToggleAutoJoinDomainResponse {
+ /** The team's auto-join domain after the toggle (null when it was
+unset by this call). */
+ auto_join_domain?: ToggleAutoJoinDomainResponseAutoJoinDomain;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/toggleAutoJoinDomainResponseAutoJoinDomain.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/toggleAutoJoinDomainResponseAutoJoinDomain.ts
new file mode 100644
index 0000000000..e43c2f6236
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/toggleAutoJoinDomainResponseAutoJoinDomain.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The team's auto-join domain after the toggle (null when it was
+unset by this call).
+ */
+export type ToggleAutoJoinDomainResponseAutoJoinDomain = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index a90dbc023d..b6891816a2 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -1883,6 +1883,75 @@
}
}
},
+ "/team/auto-join-domain/toggle": {
+ "post": {
+ "tags": ["teams::inbound::axum_router::toggle_auto_join_domain"],
+ "summary": "Toggles automatic domain joining for the team. When the team has no\nauto-join domain, sets it to the team owner's email domain — rejected\nwith a 400 when that domain is a generic email provider domain (e.g.\ngmail.com). When one is already set, removes it. New users whose email\ndomain matches a team's auto-join domain are added to that team on\nsignup. Requires the caller to be an Admin or Owner of the team.",
+ "operationId": "toggle_team_auto_join_domain",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ToggleAutoJoinDomainResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/team/crm": {
"patch": {
"tags": ["teams::inbound::axum_router::patch_team_crm_settings"],
@@ -4214,6 +4283,10 @@
"description": "The Team struct",
"required": ["id", "name", "slug", "owner_id", "crm_enabled"],
"properties": {
+ "auto_join_domain": {
+ "type": ["string", "null"],
+ "description": "The email domain new users are automatically joined to this team\nwith, when automatic domain joining is enabled (None otherwise)."
+ },
"crm_enabled": {
"type": "boolean",
"description": "Whether the CRM is enabled for this team (from `team_crm_settings`;\n`false` when no row exists)."
@@ -4342,6 +4415,16 @@
}
}
},
+ "ToggleAutoJoinDomainResponse": {
+ "type": "object",
+ "description": "Response for the toggle auto-join domain endpoint.",
+ "properties": {
+ "auto_join_domain": {
+ "type": ["string", "null"],
+ "description": "The team's auto-join domain after the toggle (null when it was\nunset by this call)."
+ }
+ }
+ },
"UserLinkResponse": {
"type": "object",
"required": ["link_exists"],
diff --git a/crates/macro_db_client/migrations/20260715123810_add_team_auto_join_domain.sql b/crates/macro_db_client/migrations/20260715123810_add_team_auto_join_domain.sql
new file mode 100644
index 0000000000..e04ea93652
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260715123810_add_team_auto_join_domain.sql
@@ -0,0 +1,10 @@
+-- Teams can opt in to automatic joining: any new user whose email domain
+-- matches a team's auto_join_domain is added to that team on signup.
+ALTER TABLE team
+ ADD COLUMN auto_join_domain TEXT;
+
+-- Partial index: auto_join_domain is looked up alone (by new-user signup
+-- auto-join) and is NULL for the vast majority of teams.
+CREATE INDEX team_auto_join_domain_idx
+ ON team (auto_join_domain)
+ WHERE auto_join_domain IS NOT NULL;
diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rs
index 864dcf2212..7e22aeca56 100644
--- a/crates/teams/src/domain/model.rs
+++ b/crates/teams/src/domain/model.rs
@@ -238,6 +238,83 @@ pub struct TeamCheckoutSessionRequest {
pub team_plan: TeamPlan,
}
+/// Email domains of generic (free / consumer) email providers.
+///
+/// Teams may not enable automatic domain joining for these domains — a
+/// match on e.g. `gmail.com` would auto-join complete strangers to the
+/// team. Entries must be lowercase and sorted (verified by test) so
+/// [`is_generic_email_domain`] can binary search.
+pub const GENERIC_EMAIL_DOMAINS: &[&str] = &[
+ "126.com",
+ "163.com",
+ "aol.com",
+ "att.net",
+ "bellsouth.net",
+ "btinternet.com",
+ "charter.net",
+ "comcast.net",
+ "cox.net",
+ "daum.net",
+ "duck.com",
+ "earthlink.net",
+ "fastmail.com",
+ "free.fr",
+ "gmail.com",
+ "gmx.com",
+ "gmx.de",
+ "gmx.net",
+ "googlemail.com",
+ "hey.com",
+ "hotmail.co.uk",
+ "hotmail.com",
+ "hotmail.fr",
+ "icloud.com",
+ "laposte.net",
+ "live.com",
+ "mac.com",
+ "mail.com",
+ "mail.ru",
+ "me.com",
+ "msn.com",
+ "naver.com",
+ "orange.fr",
+ "outlook.com",
+ "pm.me",
+ "proton.me",
+ "protonmail.com",
+ "qq.com",
+ "rediffmail.com",
+ "rocketmail.com",
+ "sbcglobal.net",
+ "seznam.cz",
+ "sina.com",
+ "sky.com",
+ "t-online.de",
+ "tuta.com",
+ "tutanota.com",
+ "verizon.net",
+ "wanadoo.fr",
+ "web.de",
+ "yahoo.co.in",
+ "yahoo.co.uk",
+ "yahoo.com",
+ "yahoo.fr",
+ "yandex.com",
+ "yandex.ru",
+ "ymail.com",
+ "zoho.com",
+];
+
+/// Returns true when the email domain belongs to a generic (free /
+/// consumer) email provider that may not be used for automatic team
+/// joining. Matching is case-insensitive.
+pub fn is_generic_email_domain(domain: &str) -> bool {
+ let domain = domain.to_ascii_lowercase();
+ GENERIC_EMAIL_DOMAINS
+ .binary_search(&domain.as_str())
+ .is_ok()
+}
+
/// The Team struct
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
@@ -250,10 +327,14 @@ pub struct Team {
/// Whether the CRM is enabled for this team (from `team_crm_settings`;
/// `false` when no row exists).
pub(crate) crm_enabled: bool,
+ /// The email domain new users are automatically joined to this team
+ /// with, when automatic domain joining is enabled (None otherwise).
+ pub(crate) auto_join_domain: Option<String>,
}
impl Team {
- /// Creates a new Team
+ /// Creates a new Team. New teams start without an auto-join domain;
+ /// it is toggled on later via the auto-join domain endpoint.
pub fn new(
id: uuid::Uuid,
name: String,
@@ -267,6 +348,7 @@ impl Team {
slug,
owner_id,
crm_enabled,
+ auto_join_domain: None,
}
}
}
@@ -296,6 +378,11 @@ impl Team {
pub fn crm_enabled(&self) -> bool {
self.crm_enabled
}
+
+ /// The team's auto-join domain, when automatic domain joining is enabled
+ pub fn auto_join_domain(&self) -> Option<&str> {
+ self.auto_join_domain.as_deref()
+ }
}
/// Request to create a new team
@@ -545,6 +632,28 @@ pub enum JoinTeamError {
AddRolesToUserError(#[from] UserRolesAndPermissionsError),
}
+/// Errors for toggling a team's auto-join domain
+#[derive(Debug, thiserror::Error)]
+pub enum ToggleAutoJoinDomainError {
+ /// The team owner's email domain is a generic email provider domain
+ #[error("The domain {0} is a generic email domain and cannot be used for auto-join")]
+ GenericDomainNotAllowed(String),
+ /// Underlying team error
+ #[error("Underlying team error {0}")]
+ TeamError(#[from] TeamError),
+}
+
+/// Errors for automatically joining a team by email domain
+#[derive(Debug, thiserror::Error)]
+pub enum TryJoinTeamByDomainError {
+ /// Underlying team error
+ #[error("Underlying team error {0}")]
+ TeamError(#[from] TeamError),
+ /// Underlying join team error
+ #[error("Underlying join team error {0}")]
+ JoinTeamError(#[from] JoinTeamError),
+}
+
/// Errors for revoking permissions for team members
#[derive(Debug, thiserror::Error)]
pub enum RevokePermissionsForTeamMembersError {
diff --git a/crates/teams/src/domain/model/test.rs b/crates/teams/src/domain/model/test.rs
index dcd0560071..abf3440ba2 100644
--- a/crates/teams/src/domain/model/test.rs
+++ b/crates/teams/src/domain/model/test.rs
@@ -49,3 +49,37 @@ fn team_checkout_error_preserves_customer_storage_error() {
let error = TeamCheckoutError::from(customer_storage_error());
assert_preserves_customer_storage_error(error);
}
+
+#[test]
+fn generic_email_domains_are_lowercase_and_sorted() {
+ // is_generic_email_domain binary searches the list, which is only
+ // correct when the entries are sorted (and lowercase, since lookups
+ // are lowercased).
+ assert!(GENERIC_EMAIL_DOMAINS.is_sorted());
+ assert!(
+ GENERIC_EMAIL_DOMAINS
+ .iter()
+ .all(|domain| *domain == domain.to_ascii_lowercase())
+ );
+}
+
+#[test]
+fn is_generic_email_domain_matches_generic_providers() {
+ assert!(is_generic_email_domain("gmail.com"));
+ assert!(is_generic_email_domain("hotmail.co.uk"));
+ assert!(is_generic_email_domain("zoho.com"));
+ assert!(is_generic_email_domain("126.com"));
+}
+
+#[test]
+fn is_generic_email_domain_is_case_insensitive() {
+ assert!(is_generic_email_domain("GMAIL.COM"));
+ assert!(is_generic_email_domain("Outlook.Com"));
+}
+
+#[test]
+fn is_generic_email_domain_allows_company_domains() {
+ assert!(!is_generic_email_domain("macro.com"));
+ assert!(!is_generic_email_domain("example.org"));
+ assert!(!is_generic_email_domain("gmail.com.evil.com"));
+}
diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rs
index 09c03a4760..37cd29c1ff 100644
--- a/crates/teams/src/domain/team_repo.rs
+++ b/crates/teams/src/domain/team_repo.rs
@@ -12,6 +12,7 @@ use crate::domain::model::{
PatchTeamCrmSettingsResponse, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,
TeamInvite, TeamInviteDetails, TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,
+ ToggleAutoJoinDomainError, TryJoinTeamByDomainError,
};
/// The TeamChannelsRepository defines a set of actions related to team channels
@@ -263,6 +264,41 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
team_id: &uuid::Uuid,
team_plan: TeamPlan,
) -> impl Future<Output = Result<(), TeamError>> + Send;
+
+ /// Toggles the team's automatic domain joining.
+ ///
+ /// When the team currently has no auto-join domain, sets it to the
+ /// domain of the team owner's email — unless that domain is a generic
+ /// email provider domain (see
+ /// [`crate::domain::model::GENERIC_EMAIL_DOMAINS`]), which is rejected.
+ /// When a domain is already set, unsets it.
+ ///
+ /// Returns the team's auto-join domain after the toggle (None when it
+ /// was unset).
+ fn toggle_auto_join_domain(
+ &self,
+ team_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Option<String>, ToggleAutoJoinDomainError>> + Send;
+
+ /// Gets the id of the team whose auto-join domain matches the email
+ /// domain of the provided user id, if any.
+ fn get_team_id_by_domain(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<uuid::Uuid>, TeamError>> + Send;
+
+ /// Adds the user directly to the team as a member (no invite involved),
+ /// bumping the team's seat count. Returns None when the user is already
+ /// on the team.
+ ///
+ /// NOTE: this only touches team membership — billing, roles, and
+ /// channel membership are handled by the service (see
+ /// `TeamService::try_join_team_by_domain`).
+ fn add_user_to_team(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<TeamMember<'static>>, TeamError>> + Send;
}
/// The TeamMembersService defines read-only team membership queries.
@@ -418,4 +454,28 @@ pub trait TeamService: Clone + Send + Sync + 'static {
enabled: bool,
backfill: bool,
) -> impl Future<Output = Result<PatchTeamCrmSettingsResponse, TeamError>> + Send;
+
+ /// Toggles the team's automatic domain joining: sets the auto-join
+ /// domain from the team owner's email domain when unset, removes it
+ /// when set. Only team admins and above may do this.
+ ///
+ /// Returns the team's auto-join domain after the toggle (None when it
+ /// was unset).
+ fn toggle_auto_join_domain(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
+ ) -> impl Future<Output = Result<Option<String>, ToggleAutoJoinDomainError>> + Send;
+
+ /// Automatically joins the user to the team whose auto-join domain
+ /// matches the user's email domain, if such a team exists. The user is
+ /// added to the team directly (no invite), with the same billing /
+ /// roles / channel side effects as `join_team`.
+ ///
+ /// Returns the new team member, or None when no team matched or the
+ /// user could not be joined (already a member, team at its seat cap,
+ /// ...).
+ fn try_join_team_by_domain(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<TeamMember<'static>>, TryJoinTeamByDomainError>> + Send;
}
diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rs
index dde7741b0c..e649e926cd 100644
--- a/crates/teams/src/domain/team_service.rs
+++ b/crates/teams/src/domain/team_service.rs
@@ -29,7 +29,8 @@ use crate::domain::{
PatchTeamCrmSettingsResponse, PatchTeamRequest, RemoveTeamInviteError,
RemoveUserFromTeamError, RestorePermissionsForTeamMembersError,
RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,
- TeamMember, TeamMembers, TeamRole, TeamWithMembers,
+ TeamMember, TeamMembers, TeamRole, TeamWithMembers, ToggleAutoJoinDomainError,
+ TryJoinTeamByDomainError,
},
team_analytics::{NoOpTeamAnalytics, TeamAnalytics, TeamAnalyticsEvent},
team_crm_settings_repo::TeamCrmSettingsRepository,
@@ -283,6 +284,30 @@ where
Ok(())
}
+ /// Best-effort rollback of a direct team add (from
+ /// `try_join_team_by_domain`): removes the membership again and undoes
+ /// the team seat count bump. Failures are logged and swallowed, like
+ /// the other join rollbacks.
+ async fn rollback_add_user_to_team(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ failed_step: &str,
+ ) {
+ self.team_repository
+ .remove_user_from_team(team_id, user_id)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error = ?rollback_err,
+ %team_id,
+ %user_id,
+ "unable to rollback auto-joined team member after {failed_step} failed"
+ );
+ })
+ .ok();
+ }
+
/// Sends an invite notification for a team invite
#[tracing::instrument(skip(self), err)]
async fn send_invite_notification(
@@ -1236,4 +1261,165 @@ where
})
}
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn toggle_auto_join_domain(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
+ ) -> Result<Option<String>, ToggleAutoJoinDomainError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+
+ self.team_repository.toggle_auto_join_domain(&team_id).await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn try_join_team_by_domain(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Option<TeamMember<'static>>, TryJoinTeamByDomainError> {
+ let Some(team_id) = self.team_repository.get_team_id_by_domain(user_id).await? else {
+ return Ok(None);
+ };
+
+ // Mirror the seat-cap check from invite_users_to_team — an
+ // auto-join must not push the team past its plan's seat cap.
+ if let Some(team_plan) = self.team_repository.get_team_plan(&team_id).await? {
+ let seat_count = self.team_repository.get_team_seat_count(&team_id).await?;
+ if seat_count + 1 > team_plan.seat_cap() {
+ tracing::info!(%team_id, %user_id, "skipping team auto-join: team is at its seat cap");
+ return Ok(None);
+ }
+ }
+
+ // Add the user to the team directly (no invite), then run the same
+ // billing / roles / channels side effects as join_team, rolling
+ // the membership back if any of them fail.
+ let Some(team_member) = self
+ .team_repository
+ .add_user_to_team(&team_id, user_id)
+ .await?
+ else {
+ tracing::info!(%team_id, %user_id, "skipping team auto-join: user is already a member");
+ return Ok(None);
+ };
+
+ if !self
+ .team_repository
+ .get_team_payment_status(&team_id)
+ .await?
+ {
+ // If the team has a subscription id and they are set to not paying continue to error
+ if self
+ .team_repository
+ .get_team_subscription_id(&team_id)
+ .await?
+ .is_some()
+ {
+ self.rollback_add_user_to_team(&team_id, user_id, "the payment status check")
+ .await;
+ return Err(JoinTeamError::TeamError(TeamError::TeamNotPaying).into());
+ }
+
+ if let Err(e) = self.backfill_legacy_team_subscription(&team_id).await {
+ self.rollback_add_user_to_team(&team_id, user_id, "backfilling team subscription")
+ .await;
+ return Err(e.into_join_team_error().into());
+ }
+ }
+
+ let subscription_id = match self.get_team_subscription(&team_id).await {
+ Ok(subscription_id) => subscription_id,
+ Err(e) => {
+ self.rollback_add_user_to_team(&team_id, user_id, "getting team subscription")
+ .await;
+ return Err(e.into_join_team_error().into());
+ }
+ };
+
+ if let Err(e) = self
+ .customer_repository
+ .increment_seat_count(&subscription_id, 1)
+ .await
+ {
+ self.rollback_add_user_to_team(&team_id, user_id, "incrementing seat count")
+ .await;
+ return Err(JoinTeamError::CustomerError(e).into());
+ }
+
+ // subscribe the user to professional features from the TeamSubscriber role and the role associated with their tier
+ let roles_to_add = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
+ let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();
+
+ if let Err(e) = self
+ .user_roles_and_permissions_service
+ .dangerous_upsert_roles_for_user(user_id, roles)
+ .await
+ {
+ self.customer_repository
+ .decrement_seat_count(&subscription_id, 1)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback customer seat count after adding team member roles failed"
+ );
+ })
+ .ok();
+ self.rollback_add_user_to_team(&team_id, user_id, "adding team member roles")
+ .await;
+ return Err(JoinTeamError::AddRolesToUserError(e).into());
+ }
+
+ if let Err(e) = self
+ .team_channels_repository
+ .add_team_member_to_channels(&team_id, user_id)
+ .await
+ {
+ let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();
+ self.user_roles_and_permissions_service
+ .dangerous_remove_roles_from_user(user_id, &roles)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback team member roles after adding team member to channels failed"
+ );
+ })
+ .ok();
+ self.customer_repository
+ .decrement_seat_count(&subscription_id, 1)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback customer seat count after adding team member to channels failed"
+ );
+ })
+ .ok();
+ self.rollback_add_user_to_team(&team_id, user_id, "adding team member to channels")
+ .await;
+ return Err(JoinTeamError::TeamError(e).into());
+ }
+
+ // Best-effort: ask the email service to seed CRM tables from this
+ // user's historical sent mail, same as join_team.
+ if let Err(e) = self
+ .crm_enqueuer
+ .enqueue_populate_crm_for_user(user_id)
+ .await
+ {
+ tracing::error!(
+ error = ?e,
+ team_id = %team_id,
+ macro_id = %user_id,
+ "Failed to enqueue PopulateCrmForUser after team auto-join; CRM tables will not be seeded from sent-mail history (per-message fan-out will still cover future sends)"
+ );
+ }
+
+ // NOTE: no TeamJoined analytics event here — that event is tied to
+ // the team invite that was accepted, and a domain auto-join has none.
+
+ Ok(Some(team_member))
+ }
}
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index 5ac3e3a94a..bcf8780c78 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -44,6 +44,7 @@ use crate::domain::{
AcceptedTeamInvite, CustomerError, PatchTeamRequest, PatchTeamUserRole,
RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,
TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
+ ToggleAutoJoinDomainError, TryJoinTeamByDomainError,
},
team_repo::{TeamChannelsRepository, TeamRepository},
};
@@ -75,6 +76,11 @@ struct MockTeamRepository {
payment_update_calls: Arc<Mutex<Vec<(uuid::Uuid, bool)>>>,
fail_github_installation_move: bool,
fail_invite_users_to_team: bool,
+ team_id_for_domain: Option<uuid::Uuid>,
+ team_plan: Option<TeamPlan>,
+ seat_count: i32,
+ add_user_to_team_result: Option<TeamMember<'static>>,
+ remove_user_calls: Arc<Mutex<usize>>,
}
impl MockTeamRepository {
@@ -115,6 +121,11 @@ impl MockTeamRepository {
payment_update_calls: Arc::new(Mutex::new(Vec::new())),
fail_github_installation_move: false,
fail_invite_users_to_team: false,
+ team_id_for_domain: None,
+ team_plan: None,
+ seat_count: 0,
+ add_user_to_team_result: None,
+ remove_user_calls: Arc::new(Mutex::new(0)),
}
}
@@ -250,6 +261,7 @@ impl TeamRepository for MockTeamRepository {
_: &uuid::Uuid,
_: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<TeamMember<'static>, RemoveUserFromTeamError>> + Send {
+ *self.remove_user_calls.lock().unwrap() += 1;
let removed_member = self.removed_member.clone();
async move { removed_member.ok_or(RemoveUserFromTeamError::UserNotInTeam) }
}
@@ -461,14 +473,16 @@ impl TeamRepository for MockTeamRepository {
&self,
_: &uuid::Uuid,
) -> impl Future<Output = Result<i32, TeamError>> + Send {
- async { Ok(0) }
+ let seat_count = self.seat_count;
+ async move { Ok(seat_count) }
}
fn get_team_plan(
&self,
_: &uuid::Uuid,
) -> impl Future<Output = Result<Option<TeamPlan>, TeamError>> + Send {
- async { Ok(None) }
+ let team_plan = self.team_plan;
+ async move { Ok(team_plan) }
}
fn patch_team_plan(
@@ -478,6 +492,30 @@ impl TeamRepository for MockTeamRepository {
) -> impl Future<Output = Result<(), TeamError>> + Send {
async { unimplemented!() }
}
+
+ fn toggle_auto_join_domain(
+ &self,
+ _: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Option<String>, ToggleAutoJoinDomainError>> + Send {
+ async { unimplemented!() }
+ }
+
+ fn get_team_id_by_domain(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<uuid::Uuid>, TeamError>> + Send {
+ let team_id = self.team_id_for_domain;
+ async move { Ok(team_id) }
+ }
+
+ fn add_user_to_team(
+ &self,
+ _: &uuid::Uuid,
+ _: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<TeamMember<'static>>, TeamError>> + Send {
+ let member = self.add_user_to_team_result.clone();
+ async move { Ok(member) }
+ }
}
// -- Mock CustomerRepository --
@@ -2485,3 +2523,218 @@ async fn team_analytics_remove_user_from_team_does_not_emit_when_remove_is_rolle
assert!(matches!(err, RemoveUserFromTeamError::TeamError(_)));
assert!(events.lock().unwrap().is_empty());
}
+
+#[tokio::test]
+async fn test_try_join_team_by_domain_no_matching_team_returns_none() {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ let team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+
+ let customer_repo = MockCustomerRepository::default();
+ let increment_calls = customer_repo.increment_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ );
+
+ let member = service.try_join_team_by_domain(&user_id).await.unwrap();
+
+ assert!(member.is_none());
+ assert!(increment_calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn test_try_join_team_by_domain_adds_member_directly() {
+ let team_id = uuid::Uuid::from_u128(77);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.team_id_for_domain = Some(team_id);
+ team_repo.add_user_to_team_result = Some(make_team_member(
+ team_id,
+ TeamRole::Member,
+ ));
+ team_repo.team_subscription_id = Some(subscription_id.clone());
+ let remove_user_calls = team_repo.remove_user_calls.clone();
+
+ let customer_repo = MockCustomerRepository {
+ subscription_id: subscription_id.clone(),
+ ..Default::default()
+ };
+ let increment_calls = customer_repo.increment_calls.clone();
+ let decrement_calls = customer_repo.decrement_calls.clone();
+
+ let channels_repo = MockTeamChannelsRepository::default();
+ let add_channel_calls = channels_repo.add_calls.clone();
+ let roles_service = MockUserRolesAndPermissionsService::default();
+ let upsert_role_calls = roles_service.upsert_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ channels_repo,
+ roles_service,
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ );
+
+ let member = service
+ .try_join_team_by_domain(&user_id)
+ .await
+ .unwrap()
+ .expect("user should have been auto-joined");
+
+ assert_eq!(member.team_id, team_id);
+ assert_eq!(member.user_id.as_ref(), user_id.as_ref());
+ assert_eq!(member.role, TeamRole::Member);
+ assert_eq!(
+ *increment_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert!(decrement_calls.lock().unwrap().is_empty());
+ assert_eq!(
+ *add_channel_calls.lock().unwrap(),
+ vec![(team_id, user_id.as_ref().to_string())]
+ );
+ assert_eq!(upsert_role_calls.lock().unwrap().len(), 1);
+ assert_eq!(*remove_user_calls.lock().unwrap(), 0);
+}
+
+#[tokio::test]
+async fn test_try_join_team_by_domain_returns_none_when_already_member() {
+ let team_id = uuid::Uuid::from_u128(78);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ // add_user_to_team returns None: the user is already on the team.
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.team_id_for_domain = Some(team_id);
+ team_repo.add_user_to_team_result = None;
+
+ let customer_repo = MockCustomerRepository::default();
+ let increment_calls = customer_repo.increment_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ );
+
+ let member = service.try_join_team_by_domain(&user_id).await.unwrap();
+
+ assert!(member.is_none());
+ assert!(increment_calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn test_try_join_team_by_domain_skips_team_at_seat_cap() {
+ let team_id = uuid::Uuid::from_u128(79);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ // The mock would add the member, so a None result proves the seat-cap
+ // check short-circuited before the membership insert.
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.team_id_for_domain = Some(team_id);
+ team_repo.add_user_to_team_result = Some(make_team_member(
+ team_id,
+ TeamRole::Member,
+ ));
+ team_repo.team_plan = Some(TeamPlan::Idea);
+ team_repo.seat_count = TeamPlan::Idea.seat_cap();
+
+ let customer_repo = MockCustomerRepository::default();
+ let increment_calls = customer_repo.increment_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ );
+
+ let member = service.try_join_team_by_domain(&user_id).await.unwrap();
+
+ assert!(member.is_none());
+ assert!(increment_calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn test_try_join_team_by_domain_rolls_back_membership_when_roles_fail() {
+ let team_id = uuid::Uuid::from_u128(80);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ let member = make_team_member(team_id, "macro|[email protected]", TeamRole::Member);
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.team_id_for_domain = Some(team_id);
+ team_repo.add_user_to_team_result = Some(member.clone());
+ // The rollback removes the freshly added member again.
+ team_repo.removed_member = Some(member);
+ team_repo.team_subscription_id = Some(subscription_id.clone());
+ let remove_user_calls = team_repo.remove_user_calls.clone();
+
+ let customer_repo = MockCustomerRepository {
+ subscription_id: subscription_id.clone(),
+ ..Default::default()
+ };
+ let increment_calls = customer_repo.increment_calls.clone();
+ let decrement_calls = customer_repo.decrement_calls.clone();
+
+ let roles_service = MockUserRolesAndPermissionsService {
+ fail_upsert: true,
+ ..Default::default()
+ };
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ MockTeamChannelsRepository::default(),
+ roles_service,
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ );
+
+ let err = service
+ .try_join_team_by_domain(&user_id)
+ .await
+ .err()
+ .unwrap();
+
+ assert!(matches!(
+ err,
+ TryJoinTeamByDomainError::JoinTeamError(JoinTeamError::AddRolesToUserError(_))
+ ));
+ // The seat increment happened, was rolled back, and the membership
+ // itself was removed again.
+ assert_eq!(
+ *increment_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert_eq!(
+ *decrement_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert_eq!(*remove_user_calls.lock().unwrap(), 1);
+}
diff --git a/crates/teams/src/inbound/axum_router/mod.rs b/crates/teams/src/inbound/axum_router/mod.rs
index 9b7626c4a5..68f373cc03 100644
--- a/crates/teams/src/inbound/axum_router/mod.rs
+++ b/crates/teams/src/inbound/axum_router/mod.rs
@@ -28,6 +28,8 @@ pub mod premium_user;
pub mod reject_invitation;
/// Remove a user from a team.
pub mod remove_user_from_team;
+/// Toggle automatic domain joining for a team.
+pub mod toggle_auto_join_domain;
#[cfg(test)]
mod test;
@@ -47,7 +49,7 @@ use model_error_response::ErrorResponse;
use crate::domain::{
model::{
CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
- RemoveTeamInviteError, RemoveUserFromTeamError, TeamError,
+ RemoveTeamInviteError, RemoveUserFromTeamError, TeamError, ToggleAutoJoinDomainError,
},
team_repo::TeamService,
};
@@ -92,6 +94,10 @@ where
.route("/", patch(patch_team::handler::<T, Eas>))
.route("/", delete(delete_team::handler::<T, Eas>))
.route("/crm", patch(patch_team_crm_settings::handler::<T, Eas>))
+ .route(
+ "/auto-join-domain/toggle",
+ post(toggle_auto_join_domain::handler::<T, Eas>),
+ )
.route("/invites", get(get_team_invites::handler::<T, Eas>))
.route("/invite", post(invite_to_team::handler::<T, Eas>))
.route(
@@ -150,6 +156,21 @@ impl IntoResponse for TeamError {
}
}
+impl IntoResponse for ToggleAutoJoinDomainError {
+ fn into_response(self) -> Response {
+ match self {
+ ToggleAutoJoinDomainError::GenericDomainNotAllowed(_) => (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ )
+ .into_response(),
+ ToggleAutoJoinDomainError::TeamError(e) => e.into_response(),
+ }
+ }
+}
+
impl IntoResponse for CreateTeamError {
fn into_response(self) -> Response {
match self {
diff --git a/crates/teams/src/inbound/axum_router/test.rs b/crates/teams/src/inbound/axum_router/test.rs
index 79775517d0..7f1094aef3 100644
--- a/crates/teams/src/inbound/axum_router/test.rs
+++ b/crates/teams/src/inbound/axum_router/test.rs
@@ -3,7 +3,7 @@ use serde_json::{Value, json};
use crate::domain::model::{
CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, RemoveTeamInviteError,
- RemoveUserFromTeamError,
+ RemoveUserFromTeamError, TeamError, ToggleAutoJoinDomainError,
};
use super::invite_to_team::InviteToTeamError;
@@ -98,3 +98,37 @@ async fn remove_team_owner_validation_response_is_preserved() {
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body_text, r#"{"message":"cannot remove owner"}"#);
}
+
+#[tokio::test]
+async fn toggle_auto_join_domain_generic_domain_response_is_bad_request() {
+ let (status, body_text, _) = response_parts(
+ ToggleAutoJoinDomainError::GenericDomainNotAllowed("gmail.com".to_string()),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(body_text.contains("gmail.com"));
+}
+
+#[tokio::test]
+async fn toggle_auto_join_domain_storage_error_response_is_obfuscated() {
+ let (status, body_text, body_json) = response_parts(ToggleAutoJoinDomainError::TeamError(
+ TeamError::StorageLayerError(anyhow::anyhow!(CUSTOMER_ERROR_SENTINEL)),
+ ))
+ .await;
+
+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(body_text, r#"{"message":"internal server error"}"#);
+ assert_eq!(body_json, json!({ "message": "internal server error" }));
+}
+
+#[tokio::test]
+async fn toggle_auto_join_domain_missing_team_response_is_not_found() {
+ let (status, body_text, _) = response_parts(ToggleAutoJoinDomainError::TeamError(
+ TeamError::TeamDoesNotExist,
+ ))
+ .await;
+
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ assert_eq!(body_text, r#"{"message":"team does not exist"}"#);
+}
diff --git a/crates/teams/src/inbound/axum_router/toggle_auto_join_domain.rs b/crates/teams/src/inbound/axum_router/toggle_auto_join_domain.rs
new file mode 100644
index 0000000000..7c97f1c1fb
--- /dev/null
+++ b/crates/teams/src/inbound/axum_router/toggle_auto_join_domain.rs
@@ -0,0 +1,49 @@
+use axum::{Json, extract::State};
+use entity_access::{
+ domain::{models::AdminTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
+};
+use model_error_response::ErrorResponse;
+
+use crate::domain::{model::ToggleAutoJoinDomainError, team_repo::TeamService};
+
+use super::TeamRouterState;
+
+/// Response for the toggle auto-join domain endpoint.
+#[derive(serde::Serialize, utoipa::ToSchema)]
+pub struct ToggleAutoJoinDomainResponse {
+ /// The team's auto-join domain after the toggle (null when it was
+ /// unset by this call).
+ pub auto_join_domain: Option<String>,
+}
+
+/// Toggles automatic domain joining for the team. When the team has no
+/// auto-join domain, sets it to the team owner's email domain — rejected
+/// with a 400 when that domain is a generic email provider domain (e.g.
+/// gmail.com). When one is already set, removes it. New users whose email
+/// domain matches a team's auto-join domain are added to that team on
+/// signup. Requires the caller to be an Admin or Owner of the team.
+#[utoipa::path(
+ post,
+ path = "/team/auto-join-domain/toggle",
+ operation_id = "toggle_team_auto_join_domain",
+ responses(
+ (status = 200, body = ToggleAutoJoinDomainResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<AdminTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
+) -> Result<Json<ToggleAutoJoinDomainResponse>, ToggleAutoJoinDomainError> {
+ let auto_join_domain = state
+ .service
+ .toggle_auto_join_domain(access.entity_access_receipt)
+ .await?;
+ Ok(Json(ToggleAutoJoinDomainResponse { auto_join_domain }))
+}
diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rs
index d0a314da72..5adb9b1132 100644
--- a/crates/teams/src/outbound/team_repo.rs
+++ b/crates/teams/src/outbound/team_repo.rs
@@ -4,12 +4,15 @@ use crate::domain::{
AcceptedTeamInvite, CreateTeamError, InviteUsersToTeamError, PatchTeamRequest,
RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,
TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamMembers, TeamPlan, TeamRole,
- TeamWithMembers,
+ TeamWithMembers, ToggleAutoJoinDomainError, is_generic_email_domain,
},
team_repo::{TeamMembersService, TeamRepository},
};
use macro_user_id::{
- cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,
+ cowlike::CowLike,
+ email::{Email, ReadEmailParts},
+ lowercased::Lowercase,
+ user_id::MacroUserIdStr,
};
use sqlx::{PgPool, Row};
use std::str::FromStr;
@@ -162,6 +165,8 @@ impl TeamRepositoryImpl {
.into_owned(),
// New teams have no team_crm_settings row yet.
crm_enabled: false,
+ // New teams start without an auto-join domain.
+ auto_join_domain: None,
})
})
.fetch_one(&mut *transaction)
@@ -231,6 +236,12 @@ impl From<sqlx::Error> for RemoveTeamInviteError {
}
}
+impl From<sqlx::Error> for ToggleAutoJoinDomainError {
+ fn from(e: sqlx::Error) -> Self {
+ Self::TeamError(e.into())
+ }
+}
+
impl TeamMembersService for TeamRepositoryImpl {
#[tracing::instrument(skip(self), err)]
async fn list_team_members(
@@ -1051,7 +1062,7 @@ impl TeamRepository for TeamRepositoryImpl {
async fn get_team_by_id(&self, team_id: &uuid::Uuid) -> Result<TeamWithMembers, TeamError> {
let team = sqlx::query!(
r#"
- SELECT t.id, t.name, t.slug, t.owner_id,
+ SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain,
COALESCE(tcs.crm_enabled, FALSE) AS "crm_enabled!"
FROM team t
LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id
@@ -1068,6 +1079,7 @@ impl TeamRepository for TeamRepositoryImpl {
.map_err(type_err)?
.into_owned(),
crm_enabled: row.crm_enabled,
+ auto_join_domain: row.auto_join_domain,
})
})
.fetch_one(&self.pool)
@@ -1105,7 +1117,7 @@ impl TeamRepository for TeamRepositoryImpl {
async fn get_user_teams(&self, user_id: &MacroUserIdStr<'_>) -> Result<Vec<Team>, TeamError> {
let teams = sqlx::query!(
r#"
- SELECT t.id, t.name, t.slug, t.owner_id,
+ SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain,
COALESCE(tcs.crm_enabled, FALSE) AS "crm_enabled!"
FROM team t
JOIN team_user tu ON t.id = tu.team_id
@@ -1123,6 +1135,7 @@ impl TeamRepository for TeamRepositoryImpl {
.map_err(type_err)?
.into_owned(),
crm_enabled: row.crm_enabled,
+ auto_join_domain: row.auto_join_domain,
})
})
.fetch_all(&self.pool)
@@ -1393,4 +1406,121 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(())
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn toggle_auto_join_domain(
+ &self,
+ team_id: &uuid::Uuid,
+ ) -> Result<Option<String>, ToggleAutoJoinDomainError> {
+ let mut transaction = self.pool.begin().await.map_err(TeamError::from)?;
+
+ // Lock the row so concurrent toggles serialize instead of both
+ // reading the same current value.
+ let team = sqlx::query!(
+ r#"
+ SELECT auto_join_domain, owner_id
+ FROM team
+ WHERE id = $1
+ FOR UPDATE
+ "#,
+ team_id,
+ )
+ .fetch_one(&mut *transaction)
+ .await?;
+
+ let new_domain = if team.auto_join_domain.is_some() {
+ None
+ } else {
+ let owner_id = MacroUserIdStr::parse_from_str(&team.owner_id)
+ .map_err(|e| TeamError::StorageLayerError(e.into()))?;
+ let owner_email = owner_id.email_part().lowercase();
+ let domain = owner_email.domain_part();
+
+ if is_generic_email_domain(domain) {
+ return Err(ToggleAutoJoinDomainError::GenericDomainNotAllowed(
+ domain.to_owned(),
+ ));
+ }
+
+ Some(domain.to_owned())
+ };
+
+ sqlx::query!(
+ r#"
+ UPDATE team
+ SET auto_join_domain = $2
+ WHERE id = $1
+ "#,
+ team_id,
+ new_domain.as_deref(),
+ )
+ .execute(&mut *transaction)
+ .await?;
+
+ transaction.commit().await.map_err(TeamError::from)?;
+
+ Ok(new_domain)
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn add_user_to_team(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Option<TeamMember<'static>>, TeamError> {
+ let mut transaction = self.pool.begin().await?;
+
+ let inserted = sqlx::query!(
+ r#"
+ INSERT INTO team_user (team_id, user_id, team_role)
+ VALUES ($1, $2, 'member')
+ ON CONFLICT DO NOTHING
+ "#,
+ team_id,
+ user_id.as_ref(),
+ )
+ .execute(&mut *transaction)
+ .await?;
+
+ // Already a member — nothing was added, so don't touch the seat count.
+ if inserted.rows_affected() == 0 {
+ return Ok(None);
+ }
+
+ TeamRepositoryImpl::bump_seat_count(&mut transaction, team_id, 1).await?;
+
+ transaction.commit().await?;
+
+ Ok(Some(TeamMember {
+ team_id: *team_id,
+ user_id: user_id.clone().into_owned(),
+ role: TeamRole::Member,
+ }))
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_team_id_by_domain(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Option<uuid::Uuid>, TeamError> {
+ let user_email = user_id.email_part().lowercase();
+ let domain = user_email.domain_part();
+
+ // Uses the partial index on auto_join_domain; when several teams
+ // claim the same domain, pick the oldest (ids are UUIDv7).
+ let team_id = sqlx::query_scalar!(
+ r#"
+ SELECT id
+ FROM team
+ WHERE auto_join_domain = $1
+ ORDER BY id
+ LIMIT 1
+ "#,
+ domain,
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ Ok(team_id)
+ }
}
diff --git a/crates/teams/src/outbound/team_repo/test.rs b/crates/teams/src/outbound/team_repo/test.rs
index 29c39fba15..573c884d29 100644
--- a/crates/teams/src/outbound/team_repo/test.rs
+++ b/crates/teams/src/outbound/team_repo/test.rs
@@ -1455,3 +1455,210 @@ async fn test_patch_team_user_role(pool: Pool<Postgres>) -> anyhow::Result<()> {
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_toggle_auto_join_domain(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let team_repo = TeamRepositoryImpl::new(pool.clone());
+
+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
+
+ // First toggle sets the domain of the team owner (macro|[email protected]).
+ let domain = team_repo.toggle_auto_join_domain(&team_id).await?;
+ assert_eq!(domain.as_deref(), Some("user.com"));
+
+ let stored: Option<String> =
+ sqlx::query_scalar("SELECT auto_join_domain FROM team WHERE id = $1")
+ .bind(team_id)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(stored.as_deref(), Some("user.com"));
+
+ // The domain is surfaced on the Team model (read by GET /team).
+ let team = team_repo.get_team_by_id(&team_id).await?.team;
+ assert_eq!(team.auto_join_domain(), Some("user.com"));
+
+ // Second toggle unsets it.
+ let domain = team_repo.toggle_auto_join_domain(&team_id).await?;
+ assert_eq!(domain, None);
+
+ let stored: Option<String> =
+ sqlx::query_scalar("SELECT auto_join_domain FROM team WHERE id = $1")
+ .bind(team_id)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(stored, None);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_toggle_auto_join_domain_rejects_generic_domain(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let team_id = macro_uuid::string_to_uuid("33333333-3333-3333-3333-333333333333")?;
+ sqlx::query(
+ "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ('a5555555-5555-5555-5555-555555555555', '[email protected]', '[email protected]', 'cus_gmail_owner')",
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query(
+ r#"INSERT INTO "User" (id, email, name, macro_user_id) VALUES ('macro|[email protected]', '[email protected]', 'Gmail Owner', 'a5555555-5555-5555-5555-555555555555')"#,
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO team (id, name, owner_id) VALUES ($1, 'gmail team', 'macro|[email protected]')",
+ )
+ .bind(team_id)
+ .execute(&pool)
+ .await?;
+
+ let team_repo = TeamRepositoryImpl::new(pool.clone());
+
+ let err = team_repo
+ .toggle_auto_join_domain(&team_id)
+ .await
+ .err()
+ .unwrap();
+
+ assert!(matches!(
+ &err,
+ ToggleAutoJoinDomainError::GenericDomainNotAllowed(domain) if domain.as_str() == "gmail.com"
+ ));
+
+ // The rejected toggle must not have set anything.
+ let stored: Option<String> =
+ sqlx::query_scalar("SELECT auto_join_domain FROM team WHERE id = $1")
+ .bind(team_id)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(stored, None);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_toggle_auto_join_domain_missing_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let team_repo = TeamRepositoryImpl::new(pool);
+
+ let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;
+ let err = team_repo
+ .toggle_auto_join_domain(&missing_team_id)
+ .await
+ .err()
+ .unwrap();
+
+ assert!(err.to_string().contains("does not exist"));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_get_team_id_by_domain(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let team_repo = TeamRepositoryImpl::new(pool.clone());
+
+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
+
+ // No team has an auto-join domain yet.
+ let found = team_repo
+ .get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
+ .await?;
+ assert_eq!(found, None);
+
+ team_repo.toggle_auto_join_domain(&team_id).await?;
+
+ let found = team_repo
+ .get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
+ .await?;
+ assert_eq!(found, Some(team_id));
+
+ // Domain matching is case-insensitive on the user's email domain.
+ let found = team_repo
+ .get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
+ .await?;
+ assert_eq!(found, Some(team_id));
+
+ // Unrelated domains do not match.
+ let found = team_repo
+ .get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
+ .await?;
+ assert_eq!(found, None);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_get_team_id_by_domain_prefers_oldest_team(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ sqlx::query("UPDATE team SET auto_join_domain = 'user.com'")
+ .execute(&pool)
+ .await?;
+
+ let team_repo = TeamRepositoryImpl::new(pool);
+
+ // Both fixture teams claim user.com; the one with the lowest id wins.
+ let found = team_repo
+ .get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
+ .await?;
+ assert_eq!(
+ found,
+ Some(macro_uuid::string_to_uuid(
+ "11111111-1111-1111-1111-111111111111"
+ )?)
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_add_user_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let team_repo = TeamRepositoryImpl::new(pool.clone());
+
+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+
+ let seat_count_before = team_repo.get_team_seat_count(&team_id).await?;
+
+ let member = team_repo
+ .add_user_to_team(&team_id, &user_id)
+ .await?
+ .expect("user should have been added");
+
+ assert_eq!(member.team_id, team_id);
+ assert_eq!(member.user_id.as_ref(), user_id.as_ref());
+ assert_eq!(member.role, TeamRole::Member);
+
+ let role = team_repo.get_team_role(&team_id, &user_id).await?;
+ assert_eq!(role, Some(TeamRole::Member));
+
+ let seat_count = team_repo.get_team_seat_count(&team_id).await?;
+ assert_eq!(seat_count, seat_count_before + 1);
+
+ // Adding again is a no-op: no member returned, no extra seat counted.
+ let member = team_repo.add_user_to_team(&team_id, &user_id).await?;
+ assert!(member.is_none());
+
+ let seat_count = team_repo.get_team_seat_count(&team_id).await?;
+ assert_eq!(seat_count, seat_count_before + 1);
+
+ Ok(())
+}
diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rs
index 150a447fc5..81871adad3 100644
--- a/services/authentication_service/src/api/swagger.rs
+++ b/services/authentication_service/src/api/swagger.rs
@@ -10,6 +10,7 @@ use teams::domain::model::{
};
use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;
use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;
+use teams::inbound::axum_router::toggle_auto_join_domain::ToggleAutoJoinDomainResponse;
use teams::inbound::axum_router::{
create_team::CreateTeamRequest, invite_to_team::InviteToTeamRequest,
};
@@ -131,6 +132,7 @@ use model::user::{
teams::inbound::axum_router::get_team_invites::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::patch_team::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::patch_team_crm_settings::handler::<crate::api::context::TeamsServiceType>,
+ teams::inbound::axum_router::toggle_auto_join_domain::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::reject_invitation::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::get_user_teams::handler::<crate::api::context::TeamsServiceType>,
@@ -214,6 +216,7 @@ use model::user::{
PatchTeamUserRole,
PatchTeamCrmSettingsRequest,
PatchTeamCrmSettingsResponse,
+ ToggleAutoJoinDomainResponse,
TeamTeamInvitesResponse,
UserTeamInvitesResponse,
diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
index 0f790b4a4d..d3db690b12 100644
--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
@@ -10,8 +10,9 @@ use rand::Rng;
use crate::{api::context::ApiContext, rate_limit_config::RATE_LIMIT_CONFIG};
use authentication_service::service::user::create_user::create_user;
use fusionauth::error::FusionAuthClientError;
-use macro_user_id::email::Email;
+use macro_user_id::{email::Email, user_id::MacroUserIdStr};
use model::authentication::webhooks::FusionAuthUserWebhook;
+use teams::domain::team_repo::TeamService;
/// FusionAuth create user webhook
#[tracing::instrument(skip(ctx, req, _internal_access), fields(email=%req.event.user.email, fusionauth_user_id=%req.event.user.id, username=?req.event.user.username, event_type=%req.event.event_type, ip_address=%req.event.info.ip_address))]
@@ -222,6 +223,32 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an
}
});
+ // Automatically add the new user to a team whose auto-join domain
+ // matches their email domain. Fire-and-forget: a failed auto-join must
+ // never block user creation.
+ tokio::spawn({
+ let teams_service = ctx.teams_service.clone();
+ let user_id = user_id.clone();
+ async move {
+ let user_id = match MacroUserIdStr::parse_from_str(&user_id) {
+ Ok(user_id) => user_id,
+ Err(e) => {
+ tracing::error!(error=?e, "unable to parse user id for team auto-join");
+ return;
+ }
+ };
+ match teams_service.try_join_team_by_domain(&user_id).await {
+ Ok(Some(member)) => {
+ tracing::info!(team_id=%member.team_id, %user_id, "auto-joined user to team by email domain");
+ }
+ Ok(None) => {}
+ Err(e) => {
+ tracing::error!(error=?e, %user_id, "failed to auto-join user to team by email domain");
+ }
+ }
+ }
+ });
+
tracing::trace!(email, fusionauth_user_id, elapsed=?start_time.elapsed(), "created user");
// Allow to fail silently