diff --git a/server/commands/teamCreator.ts b/server/commands/teamCreator.ts index 96957cc3a5..0b16cd201a 100644 --- a/server/commands/teamCreator.ts +++ b/server/commands/teamCreator.ts @@ -1,6 +1,4 @@ import type { InferCreationAttributes } from "sequelize"; -import slugify from "slugify"; -import { RESERVED_SUBDOMAINS } from "@shared/utils/domains"; import { traceFunction } from "@server/logging/tracing"; import { Team } from "@server/models"; import type { APIContext } from "@server/types"; @@ -31,7 +29,9 @@ async function teamCreator( avatarUrl = null; } - const availableSubdomain = await findAvailableSubdomain(ctx, subdomain); + const availableSubdomain = await Team.findAvailableSubdomain(subdomain, { + transaction: ctx.state.transaction, + }); return await Team.createWithCtx( ctx, { @@ -47,43 +47,6 @@ async function teamCreator( ); } -async function findAvailableSubdomain( - ctx: APIContext, - requestedSubdomain: string -) { - // filter subdomain to only valid characters - // if there are less than the minimum length, use a default subdomain - const normalizedSubdomain = slugify(requestedSubdomain, { - lower: true, - strict: true, - }); - const baseSubdomain = - normalizedSubdomain.length < 3 || - RESERVED_SUBDOMAINS.includes(normalizedSubdomain) - ? "team" - : normalizedSubdomain; - - let subdomain = baseSubdomain; - let append = 0; - - for (;;) { - const existing = await Team.findOne({ - where: { subdomain }, - paranoid: false, - transaction: ctx.state.transaction, - }); - - if (existing) { - // subdomain was invalid or already used, try another - subdomain = `${baseSubdomain}${++append}`; - } else { - break; - } - } - - return subdomain; -} - export default traceFunction({ spanName: "teamCreator", })(teamCreator); diff --git a/server/models/Team.test.ts b/server/models/Team.test.ts index d78108df38..10e55b25bc 100644 --- a/server/models/Team.test.ts +++ b/server/models/Team.test.ts @@ -4,6 +4,7 @@ import { buildTeam, buildCollection, buildAttachment, + buildSubdomain, } from "@server/test/factories"; describe("Team", () => { @@ -49,6 +50,34 @@ describe("Team", () => { }); }); + describe("findAvailableSubdomain", () => { + it("should slugify the requested value", async () => { + const slug = buildSubdomain(); + const subdomain = await Team.findAvailableSubdomain( + `${slug.toUpperCase()} Inc` + ); + expect(subdomain).toEqual(`${slug}-inc`); + }); + + it("should strip a trailing top-level domain", async () => { + const slug = buildSubdomain(); + expect(await Team.findAvailableSubdomain(`${slug}.com`)).toEqual(slug); + expect(await Team.findAvailableSubdomain(`${slug} .com`)).toEqual(slug); + expect(await Team.findAvailableSubdomain(`${slug}.io`)).toEqual(slug); + }); + + it("should fall back to a default when too short or reserved", async () => { + expect(await Team.findAvailableSubdomain("ab")).toMatch(/^team\d*$/); + expect(await Team.findAvailableSubdomain("www")).toMatch(/^team\d*$/); + }); + + it("should append a number when the subdomain is taken", async () => { + const slug = buildSubdomain(); + await buildTeam({ subdomain: slug }); + expect(await Team.findAvailableSubdomain(slug)).toEqual(`${slug}1`); + }); + }); + 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 5eef983318..233a1a1dad 100644 --- a/server/models/Team.ts +++ b/server/models/Team.ts @@ -24,6 +24,7 @@ import { BeforeCreate, IsNumeric, } from "sequelize-typescript"; +import slugify from "slugify"; import { isEmail } from "validator"; import { TeamPreferenceDefaults } from "@shared/constants"; import type { TeamPreferences } from "@shared/types"; @@ -598,6 +599,48 @@ class Team extends ParanoidModel< ); } + /** + * Find a subdomain that is not yet in use, derived from the requested value. + * A trailing top-level domain is removed and the remainder is slugified, + * a numeric suffix is appended until a free subdomain is found. + * + * @param requested - The preferred subdomain or team name. + * @param options - Additional find options to pass to the query. + * @returns An available subdomain. + */ + static async findAvailableSubdomain( + requested: string, + options?: FindOptions + ) { + // strip a trailing top-level domain so "acme.com" becomes "acme" + const withoutTld = requested.replace(/\s*\.[a-z]{2,}\s*$/i, ""); + + // filter subdomain to only valid characters + // if there are less than the minimum length, use a default subdomain + const normalized = slugify(withoutTld, { lower: true, strict: true }); + const base = + normalized.length < 3 || RESERVED_SUBDOMAINS.includes(normalized) + ? "team" + : normalized; + + let subdomain = base; + let append = 0; + + for (;;) { + const existing = await this.findOne({ + ...options, + where: { subdomain }, + paranoid: false, + }); + + if (!existing) { + return subdomain; + } + + subdomain = `${base}${++append}`; + } + } + /** * Find a team by its previous subdomain. * diff --git a/server/routes/api/installation/installation.ts b/server/routes/api/installation/installation.ts index 2c84417f5c..b99b510ccc 100644 --- a/server/routes/api/installation/installation.ts +++ b/server/routes/api/installation/installation.ts @@ -1,6 +1,5 @@ import Router from "koa-router"; import { Client, UserRole } from "@shared/types"; -import slugify from "@shared/utils/slugify"; import teamCreator from "@server/commands/teamCreator"; import { ValidationError } from "@server/errors"; import auth from "@server/middlewares/authentication"; @@ -31,7 +30,7 @@ router.post( const team = await teamCreator(ctx, { name: teamName, - subdomain: slugify(teamName), + subdomain: teamName, authenticationProviders: [], }); diff --git a/server/routes/api/teams/teams.test.ts b/server/routes/api/teams/teams.test.ts index 1bd39d535d..769a49158a 100644 --- a/server/routes/api/teams/teams.test.ts +++ b/server/routes/api/teams/teams.test.ts @@ -3,6 +3,7 @@ import { TeamDomain } from "@server/models"; import { buildAdmin, buildCollection, + buildSubdomain, buildTeam, buildUser, } from "@server/test/factories"; @@ -25,6 +26,34 @@ describe("teams.create", () => { expect(body.data.team.name).toEqual(name); }); + it("strips a top-level domain from the generated subdomain", async () => { + const team = await buildTeam(); + const user = await buildAdmin({ teamId: team.id }); + const slug = buildSubdomain(); + const res = await server.post("/api/teams.create", user, { + body: { + name: `${slug}.com`, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.team.subdomain).toEqual(slug); + }); + + it("strips a top-level domain preceded by whitespace", async () => { + const team = await buildTeam(); + const user = await buildAdmin({ teamId: team.id }); + const slug = buildSubdomain(); + const res = await server.post("/api/teams.create", user, { + body: { + name: `${slug} .com`, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.team.subdomain).toEqual(slug); + }); + it.skip("requires a cloud hosted deployment", async () => { setSelfHosted();