diff --git a/server/models/TeamDomain.test.ts b/server/models/TeamDomain.test.ts index 37da5da9df..1a1d561471 100644 --- a/server/models/TeamDomain.test.ts +++ b/server/models/TeamDomain.test.ts @@ -35,6 +35,34 @@ describe("team domain model", () => { expect(error).toBeDefined(); }); + it("should not allow duplicate domains", async () => { + const team = await buildTeam(); + const user = await buildAdmin({ teamId: team.id }); + + let error; + try { + await TeamDomain.create({ + teamId: team.id, + name: "getoutline.com", + createdById: user.id, + }); + await TeamDomain.create({ + teamId: team.id, + name: "www.getoutline.com", + createdById: user.id, + }); + await TeamDomain.create({ + teamId: team.id, + name: "https://www.getoutline.com", + createdById: user.id, + }); + } catch (err) { + error = err; + } + expect(error.name).toBe("SequelizeUniqueConstraintError"); + expect(error).toBeDefined(); + }); + it("should not allow creation of domains within restricted list", async () => { const team = await buildTeam(); const user = await buildAdmin({ teamId: team.id }); diff --git a/server/models/TeamDomain.ts b/server/models/TeamDomain.ts index 6779f2607f..5faa927b9d 100644 --- a/server/models/TeamDomain.ts +++ b/server/models/TeamDomain.ts @@ -11,6 +11,7 @@ import { } from "sequelize-typescript"; import { MAX_TEAM_DOMAINS } from "@shared/constants"; import { ValidationError } from "@server/errors"; +import { normalizeURL } from "@server/utils/normalizeURL"; import Team from "./Team"; import User from "./User"; import IdModel from "./base/IdModel"; @@ -51,7 +52,7 @@ class TeamDomain extends IdModel { @BeforeValidate static async cleanupDomain(model: TeamDomain) { - model.name = model.name.toLowerCase().trim(); + model.name = normalizeURL(model.name.toLowerCase().trim()); } @BeforeCreate diff --git a/server/utils/normalizeURL.ts b/server/utils/normalizeURL.ts new file mode 100644 index 0000000000..5183ae51b4 --- /dev/null +++ b/server/utils/normalizeURL.ts @@ -0,0 +1,23 @@ +export const normalizeURL = (urlString: string): string => { + urlString = urlString.trim(); + + const hasRelativeProtocol = urlString.startsWith("//"); + const isRelativeURL = !hasRelativeProtocol && /^\.*\//.test(urlString); + + if (!isRelativeURL) { + urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, "https://"); + } + + const urlObject = new URL(urlString); + + // Remove 'www' + urlObject.hostname = urlObject.hostname.replace(/^www\./, ""); + + // Remove trailing `/` + const newURLString = urlObject.toString().replace(/\/$/, ""); + + // Remove protocol + const finalURL = newURLString.replace(/^(?:https?:)?\/\//, ""); + + return finalURL; +};