Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Refactor domain validation in addSite function and update regex for improved accuracy

Bill Yangeefacc9f5a25
diff --git a/client/src/lib/utils.ts b/client/src/lib/utils.ts
index 4771f91f7..5131e4407 100644
--- a/client/src/lib/utils.ts
+++ b/client/src/lib/utils.ts
@@ -116,7 +116,7 @@ export function normalizeDomain(domain: string): string {
* - Requires the TLD to be alphabetical (e.g. .com)
*/
export function isValidDomain(domain: string): boolean {
- const domainRegex = /^(?:https?:\/\/)?(?:[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?\.)+\p{L}{2,}$/u;
+ const domainRegex = /^(?:https?:\/\/)?(?:[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?\.)+\p{L}{2,}\/?$/u;
return domainRegex.test(domain);
}
diff --git a/server/src/api/sites/addSite.ts b/server/src/api/sites/addSite.ts
index 0e1b49d1c..296e71d2a 100644
--- a/server/src/api/sites/addSite.ts
+++ b/server/src/api/sites/addSite.ts
@@ -21,19 +21,20 @@ export async function addSite(
const { organizationId } = request.params;
const { domain, name, public: isPublic, saltUserIds, blockBots } = request.body;
+ // Strip protocol and trailing slash before validation
+ const cleanedDomain = domain.replace(/^https?:\/\//, "").replace(/\/+$/, "");
+
// Validate domain format using regex
const domainRegex = /^(?:[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?\.)+\p{L}{2,}$/u;
- if (!domainRegex.test(domain)) {
+ if (!domainRegex.test(cleanedDomain)) {
return reply.status(400).send({
error: "Invalid domain format. Must be a valid domain like example.com or sub.example.com",
});
}
try {
- // Auth and org admin check handled by requireOrgAdminFromBody middleware
const userId = request.user?.id;
- // Generate a random 12-character hex ID
const id = randomBytes(6).toString("hex");
// Create the new site
@@ -41,7 +42,7 @@ export async function addSite(
.insert(sites)
.values({
id,
- domain,
+ domain: cleanedDomain,
name,
createdBy: userId,
organizationId,