diff --git a/app/components/Sharing/Collection/SharePopover.tsx b/app/components/Sharing/Collection/SharePopover.tsx index 3efdd6a909..588d78dc81 100644 --- a/app/components/Sharing/Collection/SharePopover.tsx +++ b/app/components/Sharing/Collection/SharePopover.tsx @@ -231,7 +231,9 @@ function SharePopover({ { email: idOrEmail, name: idOrEmail, - role: inviteRole, + role: team.isTeamDomain(idOrEmail) + ? team.defaultUserRole + : inviteRole, }, ]); user = response[0]; @@ -328,6 +330,7 @@ function SharePopover({ isOwnerInvite, t, inviteRole, + team, users, ] ); diff --git a/app/components/Sharing/Document/SharePopover.tsx b/app/components/Sharing/Document/SharePopover.tsx index d47d32eb55..8b6b607490 100644 --- a/app/components/Sharing/Document/SharePopover.tsx +++ b/app/components/Sharing/Document/SharePopover.tsx @@ -191,7 +191,9 @@ function SharePopover({ { email: idOrEmail, name: idOrEmail, - role: inviteRole, + role: team.isTeamDomain(idOrEmail) + ? team.defaultUserRole + : inviteRole, }, ]); user = response[0]; @@ -287,6 +289,7 @@ function SharePopover({ isOwnerInvite, t, inviteRole, + team, users, ] ); diff --git a/app/models/Team.ts b/app/models/Team.ts index fe3571923e..8325e94f55 100644 --- a/app/models/Team.ts +++ b/app/models/Team.ts @@ -127,6 +127,17 @@ class Team extends Model { return access !== CommentingAccess.None && access !== false; } + /** + * Whether the email address is on one of the team's domains. + * + * @param email The email address to check. + * @returns true if the email domain matches a team domain. + */ + isTeamDomain(email: string): boolean { + const domain = email.split("@").pop()?.toLowerCase(); + return !!domain && !!this.allowedDomains?.includes(domain); + } + /** * Whether the team is entitled to use the given feature. * diff --git a/server/commands/userInviter.test.ts b/server/commands/userInviter.test.ts index a00ce409a2..bf43e049fe 100644 --- a/server/commands/userInviter.test.ts +++ b/server/commands/userInviter.test.ts @@ -1,9 +1,9 @@ import { faker } from "@faker-js/faker"; -import { UserRole } from "@shared/types"; -import { buildTeam, buildUser } from "@server/test/factories"; +import { Plan, UserRole } from "@shared/types"; +import { buildAdmin, buildTeam, buildUser } from "@server/test/factories"; import userInviter from "./userInviter"; import { withContext } from "@server/test/support"; -import { TeamDomain } from "@server/models"; +import { Team, TeamDomain } from "@server/models"; describe("userInviter", () => { it("should return sent invites", async () => { @@ -90,6 +90,94 @@ describe("userInviter", () => { expect(response.sent[0].email).toEqual(`test@${allowedDomain}`); }); + it("should error on guest invites for workspace domains", async () => { + const planSpy = vi + .spyOn(Team.prototype, "plan", "get") + .mockReturnValue(Plan.Business); + onTestFinished(() => planSpy.mockRestore()); + const team = await buildTeam(); + const user = await buildAdmin({ teamId: team.id }); + + await TeamDomain.create({ + teamId: team.id, + name: "acme.org", + createdById: user.id, + }); + + await withContext(user, (ctx) => + expect( + userInviter(ctx, { + invites: [ + { + role: UserRole.Guest, + email: "Test@Acme.org", + name: "Test", + }, + ], + }) + ).rejects.toThrow( + "Users with an email on a workspace domain cannot be added as guests" + ) + ); + }); + + it("should skip guest invites for existing members on workspace domains", async () => { + const planSpy = vi + .spyOn(Team.prototype, "plan", "get") + .mockReturnValue(Plan.Business); + onTestFinished(() => planSpy.mockRestore()); + const team = await buildTeam(); + const user = await buildAdmin({ teamId: team.id }); + await buildUser({ teamId: team.id, email: "member@acme.org" }); + + await TeamDomain.create({ + teamId: team.id, + name: "acme.org", + createdById: user.id, + }); + + const response = await withContext(user, (ctx) => + userInviter(ctx, { + invites: [ + { + role: UserRole.Guest, + email: "member@acme.org", + name: "Test", + }, + ], + }) + ); + expect(response.unsent.length).toEqual(1); + }); + + it("should allow guest invites for other domains", async () => { + const planSpy = vi + .spyOn(Team.prototype, "plan", "get") + .mockReturnValue(Plan.Business); + onTestFinished(() => planSpy.mockRestore()); + const team = await buildTeam(); + const user = await buildAdmin({ teamId: team.id }); + + await TeamDomain.create({ + teamId: team.id, + name: "acme.org", + createdById: user.id, + }); + + const response = await withContext(user, (ctx) => + userInviter(ctx, { + invites: [ + { + role: UserRole.Guest, + email: "test@other.com", + name: "Test", + }, + ], + }) + ); + expect(response.sent.length).toEqual(1); + }); + it("should filter obviously bunk emails", async () => { const user = await buildUser(); const response = await withContext(user, (ctx) => diff --git a/server/commands/userInviter.ts b/server/commands/userInviter.ts index 908c25dee6..702fbc97a7 100644 --- a/server/commands/userInviter.ts +++ b/server/commands/userInviter.ts @@ -6,7 +6,7 @@ import Logger from "@server/logging/Logger"; import { User, Team } from "@server/models"; import { UserFlag } from "@server/models/User"; import type { Context } from "@server/types"; -import { DomainNotAllowedError } from "@server/errors"; +import { DomainNotAllowedError, ValidationError } from "@server/errors"; import { authorize, can } from "@server/policies"; export type Invite = { @@ -71,6 +71,18 @@ export default async function userInviter( normalizedInvites, (invite) => existingEmails.includes(invite.email) ); + + for (const invite of filteredInvites) { + if ( + invite.role === UserRole.Guest && + (await team.isTeamDomain(invite.email)) + ) { + throw ValidationError( + "Users with an email on a workspace domain cannot be added as guests" + ); + } + } + const users = []; // send and record remaining invites diff --git a/server/models/Team.test.ts b/server/models/Team.test.ts index 8a2a8af3eb..c698d5901f 100644 --- a/server/models/Team.test.ts +++ b/server/models/Team.test.ts @@ -1,11 +1,12 @@ import { randomUUID } from "node:crypto"; import { TeamValidation } from "@shared/validations"; -import { Team } from "@server/models"; +import { Team, TeamDomain } from "@server/models"; import { buildTeam, buildCollection, buildAttachment, buildSubdomain, + buildUser, } from "@server/test/factories"; describe("Team", () => { @@ -103,6 +104,28 @@ describe("Team", () => { }); }); + describe("isTeamDomain", () => { + it("should return false when the team has no domains", async () => { + const team = await buildTeam(); + expect(await team.isTeamDomain("test@acme.org")).toEqual(false); + }); + + it("should match emails and domains regardless of case", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + await TeamDomain.create({ + teamId: team.id, + name: "Acme.org", + createdById: user.id, + }); + + expect(await team.isTeamDomain("test@acme.org")).toEqual(true); + expect(await team.isTeamDomain("Test@ACME.org")).toEqual(true); + expect(await team.isTeamDomain("ACME.ORG")).toEqual(true); + expect(await team.isTeamDomain("test@other.org")).toEqual(false); + }); + }); + describe("collectionIds", () => { it("should return non-private collection ids", async () => { const team = await buildTeam(); diff --git a/server/models/Team.ts b/server/models/Team.ts index fb2aaa7041..5ca251b762 100644 --- a/server/models/Team.ts +++ b/server/models/Team.ts @@ -2,7 +2,11 @@ import crypto from "node:crypto"; import { URL } from "node:url"; import { addDays, subMinutes } from "date-fns"; import type { InferAttributes, InferCreationAttributes } from "sequelize"; -import { type FindOptions, type SaveOptions } from "sequelize"; +import { + type FindOptions, + type SaveOptions, + type Transaction, +} from "sequelize"; import { Op } from "sequelize"; import { Column, @@ -494,6 +498,29 @@ class Team extends ParanoidModel< ); }; + /** + * Find whether the passed domain or email matches one of the team's domains. + * Unlike isDomainAllowed, this returns false if no domains are set. + * + * @param domainOrEmail The domain or email to check. + * @param options Options such as the transaction to query with. + * @returns True if the domain matches a team domain. + */ + public isTeamDomain = async function ( + this: Team, + domainOrEmail: string, + options?: { transaction?: Transaction | null } + ): Promise { + const allowedDomains = (await this.$get("allowedDomains", options)) || []; + const domain = isEmail(domainOrEmail) + ? parseEmail(domainOrEmail).domain + : domainOrEmail.toLowerCase(); + + return allowedDomains.some( + (d: TeamDomain) => d.name.toLowerCase() === domain + ); + }; + // associations @HasMany(() => Collection) diff --git a/server/routes/api/users/users.ts b/server/routes/api/users/users.ts index 68a6a56702..249151921b 100644 --- a/server/routes/api/users/users.ts +++ b/server/routes/api/users/users.ts @@ -386,9 +386,10 @@ async function updateRole(ctx: Context) { }); authorize(actor, "update", user); - await Team.findByPk(user.teamId, { + const team = await Team.findByPk(user.teamId, { transaction, lock: transaction.LOCK.NO_KEY_UPDATE, + rejectOnEmpty: true, }); let name; @@ -410,6 +411,12 @@ async function updateRole(ctx: Context) { } if (role === UserRole.Guest) { authorize(actor, "addGuest", actor.team); + + if (user.email && (await team.isTeamDomain(user.email, { transaction }))) { + throw ValidationError( + "Users with an email on a workspace domain cannot be added as guests" + ); + } } await user.updateWithCtx(ctx, { role }, { name });