Strip top-level domain from generated team subdomain (#13816)

* fix: Strip top-level domain from generated team subdomain

* Move subdomain generation into Team.findAvailableSubdomain and reuse in installation
This commit is contained in:
Tom Moor authored and GitHub committed 2026-09-20 13:31:39 -04:00
1 parent 57cf871c9a
commit a7c1907aa6
5 files changed
+105 -42

No files matched your search

+3 -40
View File
@@ -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);
+29
View File
@@ -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();
+43
View File
@@ -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<Team>
) {
// 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.
*
@@ -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: [],
});
+29
View File
@@ -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();