From a0bd8042621e108f47e09dd096cf0d73fe1cee53 Mon Sep 17 00:00:00 2001 From: Samuel Newman Date: Sat, 10 May 2025 00:06:06 +0300 Subject: Live (#8354) --- src/lib/strings/url-helpers.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'src/lib/strings') diff --git a/src/lib/strings/url-helpers.ts b/src/lib/strings/url-helpers.ts index 20c3fabbc..ad194714a 100644 --- a/src/lib/strings/url-helpers.ts +++ b/src/lib/strings/url-helpers.ts @@ -372,3 +372,33 @@ export function getServiceAuthAudFromUrl(url: string | URL): string | null { } return `did:web:${hostname}` } + +// passes URL.parse, and has a TLD etc +export function definitelyUrl(maybeUrl: string) { + try { + if (maybeUrl.endsWith('.')) return null + + // Prepend 'https://' if the input doesn't start with a protocol + if (!maybeUrl.startsWith('https://') && !maybeUrl.startsWith('http://')) { + maybeUrl = 'https://' + maybeUrl + } + + const url = new URL(maybeUrl) + + // Extract the hostname and split it into labels + const hostname = url.hostname + const labels = hostname.split('.') + + // Ensure there are at least two labels (e.g., 'example' and 'com') + if (labels.length < 2) return null + + const tld = labels[labels.length - 1] + + // Check that the TLD is at least two characters long and contains only letters + if (!/^[a-z]{2,}$/i.test(tld)) return null + + return url.toString() + } catch { + return null + } +} -- cgit 1.4.1