From 9df50a167a6c07b40a369a0284a93fcdaa1d7ff7 Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Fri, 24 May 2024 10:42:04 -0300 Subject: [PATCH] refactor: move url check to a separate function --- src/utils/accounts.ts | 28 ++++++++++++++++++++++++++++ src/views/mastodon/accounts.ts | 20 ++------------------ 2 files changed, 30 insertions(+), 18 deletions(-) create mode 100644 src/utils/accounts.ts diff --git a/src/utils/accounts.ts b/src/utils/accounts.ts new file mode 100644 index 00000000..a320c581 --- /dev/null +++ b/src/utils/accounts.ts @@ -0,0 +1,28 @@ +function sanitizeWebsite(website: string | undefined): string | undefined { + if (!website) return undefined; + + if ( + 'https://'.includes(website) || + 'http://'.includes(website) + ) return undefined; + + try { + // See if 'website' is a valid url + new URL(website); + return website; + } catch (_) { + try { + const websiteWithPrefix = 'https://' + website; + // 'website' could still be a valid url + // try adding a 'https' prefix to 'website' + new URL(websiteWithPrefix); + + return websiteWithPrefix; + } catch (_) { + // 'website' is not a valid url even with 'https' prefix + return undefined; + } + } +} + +export { sanitizeWebsite }; diff --git a/src/views/mastodon/accounts.ts b/src/views/mastodon/accounts.ts index a635af38..87c16034 100644 --- a/src/views/mastodon/accounts.ts +++ b/src/views/mastodon/accounts.ts @@ -8,6 +8,7 @@ import { getLnurl } from '@/utils/lnurl.ts'; import { nip05Cache } from '@/utils/nip05.ts'; import { Nip05, nostrDate, nostrNow, parseNip05 } from '@/utils.ts'; import { renderEmojis } from '@/views/mastodon/emojis.ts'; +import { sanitizeWebsite } from '@/utils/accounts.ts'; interface ToAccountOpts { withSource?: boolean; @@ -31,23 +32,6 @@ async function renderAccount( website, } = n.json().pipe(n.metadata()).catch({}).parse(event.content); - let websiteUrl; - try { - // See if 'website' is a valid url - new URL(website as string); - websiteUrl = website; - } catch (_) { - try { - // 'website' could still be a valid url - // try adding a 'https' prefix to 'website' - new URL('https' + website); - websiteUrl = 'https' + website; - } catch (_) { - // 'website' is not a valid url even with 'https' prefix - websiteUrl = ''; - } - } - const npub = nip19.npubEncode(pubkey); const parsed05 = await parseAndVerifyNip05(nip05, pubkey); const role = event.user?.tags.find(([name]) => name === 'role')?.[1] ?? 'user'; @@ -103,7 +87,7 @@ async function renderAccount( pubkey, lud16, }, - website: websiteUrl, + website: sanitizeWebsite(website) ?? '', }; }