From 10d5dc3bf4482fcaadf3241572f66d32eb44f8bd Mon Sep 17 00:00:00 2001 From: Angelo Ashmore Date: Mon, 12 Jul 2021 14:59:54 -1000 Subject: [PATCH] fix: better internal url detection --- src/lib/isInternalURL.ts | 7 ++++++- test/lib-isInternalURL.test.ts | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 test/lib-isInternalURL.test.ts diff --git a/src/lib/isInternalURL.ts b/src/lib/isInternalURL.ts index bcb6397..aecf221 100644 --- a/src/lib/isInternalURL.ts +++ b/src/lib/isInternalURL.ts @@ -1 +1,6 @@ -export const isInternalURL = (url: string): boolean => /^\/[^\/]/.test(url); +export const isInternalURL = (url: string): boolean => { + const isInternal = /^(\/(?!\/)|#)/.test(url); + const isSpecialLink = !isInternal && !/^https?:\/\//.test(url); + + return isInternal && !isSpecialLink; +}; diff --git a/test/lib-isInternalURL.test.ts b/test/lib-isInternalURL.test.ts new file mode 100644 index 0000000..94cbdda --- /dev/null +++ b/test/lib-isInternalURL.test.ts @@ -0,0 +1,19 @@ +import test from "ava"; + +import { isInternalURL } from "../src/lib/isInternalURL"; + +test("returns true for internal URLs", (t) => { + t.true(isInternalURL("/")); + t.true(isInternalURL("/internal")); + t.true(isInternalURL("#anchor")); +}); + +test("returns false for external URLs", (t) => { + t.false(isInternalURL("//example.com")); + t.false(isInternalURL("//example.com/image.png")); + t.false(isInternalURL("//example.com#anchor")); + t.false(isInternalURL("https://example.com")); + t.false(isInternalURL("mailto:example.com")); + t.false(isInternalURL("tel:example.com")); + t.false(isInternalURL("ftp:example.com")); +});