Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

improved regex for adding keys

Steven Tey792993ce3dbc
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index 3c48796ca9..db5bb4ebd1 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -324,7 +324,7 @@ function AddEditLinkModal({
.writeText(
linkConstructor({
// remove leading and trailing slashes
- key: data.key.replace(/^\/|\/$/g, ""),
+ key: data.key.replace(/^\/+|\/+$/g, ""),
domain,
}),
)
@@ -460,8 +460,12 @@ function AddEditLinkModal({
name="key"
id={`key-${randomIdx}`}
required
- // Unicode regex to match characters from all languages and numbers (and omit all symbols except for dashes and slashes)
- pattern="[\p{Letter}\p{Mark}\d/-]+"
+ pattern="[\p{L}\p{N}\p{Pd}\/]+"
+ onInvalid={(e) => {
+ e.currentTarget.setCustomValidity(
+ "Only letters, numbers, '-', and '/' are allowed.",
+ );
+ }}
className={`${
keyError
? "border-red-300 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
@@ -471,6 +475,7 @@ function AddEditLinkModal({
value={key}
onChange={(e) => {
setKeyError(null);
+ e.currentTarget.setCustomValidity("");
setData({ ...data, key: e.target.value });
}}
aria-invalid="true"
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 7fb066bad9..e00f0a8298 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -3,7 +3,13 @@ import { DEFAULT_REDIRECTS } from "@/lib/constants";
import prisma from "@/lib/prisma";
import { LinkProps } from "@/lib/types";
import { redis } from "@/lib/upstash";
-import { getParamsFromURL, isReservedKey, nanoid, truncate } from "@/lib/utils";
+import {
+ getParamsFromURL,
+ isReservedKey,
+ nanoid,
+ truncate,
+ validKeyRegex,
+} from "@/lib/utils";
import { NextApiRequest } from "next";
export async function getLinksForProject({
@@ -148,8 +154,20 @@ export async function checkIfKeyExists(domain: string, key: string) {
return !!link;
}
+export function processKey(key: string) {
+ if (!validKeyRegex.test(key)) {
+ return null;
+ }
+ // remove all leading and trailing slashes from key
+ key = key.replace(/^\/+|\/+$/g, "");
+ if (key.length === 0) {
+ return null;
+ }
+ return key;
+}
+
export async function addLink(link: LinkProps) {
- let {
+ const {
domain,
key,
url,
@@ -162,8 +180,6 @@ export async function addLink(link: LinkProps) {
ios,
android,
} = link;
- // remove leading and trailing slashes from key
- key = key.replace(/^\/|\/$/g, "");
const hasPassword = password && password.length > 0 ? true : false;
const exat = expiresAt ? new Date(expiresAt).getTime() / 1000 : null;
const uploadedImage = image && image.startsWith("data:image") ? true : false;
@@ -235,7 +251,7 @@ export async function editLink(
oldKey: string;
},
) {
- let {
+ const {
id,
domain,
key,
@@ -249,8 +265,6 @@ export async function editLink(
ios,
android,
} = link;
- // remove leading and trailing slashes from key
- key = key.replace(/^\/|\/$/g, "");
const hasPassword = password && password.length > 0 ? true : false;
const exat = expiresAt ? new Date(expiresAt).getTime() : null;
const changedKey = key !== oldKey;
diff --git a/lib/utils.ts b/lib/utils.ts
index ee2be49255..23c1779327 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -208,6 +208,8 @@ export const validDomainRegex = new RegExp(
/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,
);
+export const validKeyRegex = new RegExp(/^[0-9A-Za-z\u0080-\uFFFF\/\-]*$/u);
+
export const validSlugRegex = new RegExp(/^[a-zA-Z0-9\-]+$/);
export const getSubdomain = (name: string, apexName: string) => {
diff --git a/pages/api/links/[key]/index.ts b/pages/api/links/[key]/index.ts
index 2e66983ade..1bba13b633 100644
--- a/pages/api/links/[key]/index.ts
+++ b/pages/api/links/[key]/index.ts
@@ -1,5 +1,5 @@
import { withLinksAuth } from "@/lib/auth";
-import { deleteLink, editLink } from "@/lib/api/links";
+import { deleteLink, editLink, processKey } from "@/lib/api/links";
import { isBlacklistedDomain, isBlacklistedKey, log } from "@/lib/utils";
import { GOOGLE_FAVICON_URL } from "@/lib/constants";
@@ -41,14 +41,18 @@ export default withLinksAuth(
if (domainBlacklisted) {
return res.status(422).end("Invalid url.");
}
- } else if (key.split("").every((char) => char === "/")) {
- return res.status(422).end("Key must contain characters other than '/'.");
+ }
+
+ key = processKey(key);
+ if (!key) {
+ return res.status(422).end("Invalid key.");
}
const [response, invalidFavicon] = await Promise.allSettled([
editLink(
{
...req.body,
+ key,
domain: req.body.domain || "dub.sh",
userId: session.user.id,
},
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index f8eb883883..ed4ff699fc 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -1,4 +1,4 @@
-import { addLink, getLinksForProject } from "@/lib/api/links";
+import { addLink, getLinksForProject, processKey } from "@/lib/api/links";
import { withLinksAuth } from "@/lib/auth";
import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/utils";
import { log } from "@/lib/utils";
@@ -57,13 +57,17 @@ export default withLinksAuth(
if (domainBlacklisted) {
return res.status(422).end("Invalid url.");
}
- } else if (key.split("").every((char) => char === "/")) {
- return res.status(422).end("Key must contain characters other than '/'.");
+ }
+
+ key = processKey(key);
+ if (!key) {
+ return res.status(422).end("Invalid key.");
}
const [response, invalidFavicon] = await Promise.allSettled([
addLink({
...req.body,
+ key,
projectId: project?.id || DUB_PROJECT_ID,
userId: session.user.id,
}),