Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532import {AtUri} from '@atproto/api'import {parse} from 'psl'import TLDs from 'tlds'
import {parseSpaceRecordUri, spaceUriOf} from '#/lib/api/space-uri'import {DEFAULT_BRAND_CONFIG} from '#/lib/community/BrandContext'import {BSKY_SERVICE} from '#/lib/constants'import {isInvalidHandle} from '#/lib/strings/handles'import {startUriToStarterPackUri} from '#/lib/strings/starter-pack'import {logger} from '#/logger'
export const BSKY_APP_HOST = DEFAULT_BRAND_CONFIG.web.domains.main
function extractHost(url: string): string { try { return new URL(url).host } catch { return url.replace(/^https?:\/\//, '') }}
const _mainHost = extractHost(DEFAULT_BRAND_CONFIG.web.domains.main).replace( /[.*+?^${}()|[\]\\]/g, '\\$&',)const _shortlinkHost = DEFAULT_BRAND_CONFIG.web.domains.shortlink ? extractHost(DEFAULT_BRAND_CONFIG.web.domains.shortlink).replace( /[.*+?^${}()|[\]\\]/g, '\\$&', ) : null
const BSKY_TRUSTED_HOSTS = [ _mainHost, `staging\\.${_mainHost}`, ...(_shortlinkHost ? [_shortlinkHost] : []), 'rsky\\.dev', 'tektite\\.cc', 'opencollective\\.com', 'github\\.com', 'bsky\\.app', 'bsky\\.social', 'blueskyweb\\.xyz', 'blueskyweb\\.zendesk\\.com', ...(__DEV__ ? ['localhost:19006', 'localhost:8100'] : []),]
/* * This will allow any BSKY_TRUSTED_HOSTS value by itself or with a subdomain. * It will also allow relative paths like /profile as well as #. */const TRUSTED_REGEX = new RegExp( `^(http(s)?://(([\\w-]+\\.)?${BSKY_TRUSTED_HOSTS.join( '|([\\w-]+\\.)?', )})|/|#)`,)
export function isValidDomain(str: string): boolean { return !!TLDs.find(tld => { let i = str.lastIndexOf(tld) if (i === -1) { return false } return str.charAt(i - 1) === '.' && i === str.length - tld.length })}
export function makeRecordUri( didOrName: string, collection: string, rkey: string,) { const urip = new AtUri('at://placeholder.placeholder/') // @ts-expect-error TODO new-sdk-migration urip.host = didOrName urip.collection = collection urip.rkey = rkey return urip.toString()}
export function toNiceDomain(url: string): string { try { const urlp = new URL(url) const normalized = `https://${urlp.host}` if ( normalized === BSKY_SERVICE || normalized === DEFAULT_BRAND_CONFIG.services.pds.url ) { return DEFAULT_BRAND_CONFIG.metadata.displayName } return urlp.host ? urlp.host : url } catch (e) { return url }}
export function toShortUrl(url: string): string { try { const urlp = new URL(url) if (urlp.protocol !== 'http:' && urlp.protocol !== 'https:') { return url } const path = (urlp.pathname === '/' ? '' : urlp.pathname) + urlp.search + urlp.hash if (path.length > 15) { return urlp.host + path.slice(0, 13) + '...' } return urlp.host + path } catch (e) { return url }}
export function toShareUrl(url: string): string { if (!url.startsWith('https')) { // Parse as a relative URL so a query string survives; assigning to // pathname percent-encodes the '?' into the path. url = new URL(url, BSKY_APP_HOST).toString() } return url}
export function toBskyAppUrl(url: string): string { return new URL(url, BSKY_APP_HOST).toString()}
export function isBskyAppUrl(url: string): boolean { const mainDomain = DEFAULT_BRAND_CONFIG.web.domains.main return ( url.startsWith('https://bsky.app/') || url.startsWith(`${mainDomain}/`) || url.startsWith(`${mainDomain.replace('https://', 'https://staging.')}/`) )}
export function isRelativeUrl(url: string): boolean { return /^\/[^/]/.test(url)}
export function isBskyRSSUrl(url: string): boolean { return (isBskyAppUrl(url) || isRelativeUrl(url)) && /\/rss\/?$/.test(url)}
export function isExternalUrl(url: string): boolean { const external = !isBskyAppUrl(url) && url.startsWith('http') const rss = isBskyRSSUrl(url) return external || rss}
export function isTrustedUrl(url: string): boolean { return TRUSTED_REGEX.test(url)}
export function isBskyPostUrl(url: string): boolean { if (isBskyAppUrl(url)) { try { const urlp = new URL(url) return /profile\/(?<name>[^/]+)\/post\/(?<rkey>[^/]+)/i.test( urlp.pathname, ) } catch {} } return false}
export function isBskyCustomFeedUrl(url: string): boolean { if (isBskyAppUrl(url)) { try { const urlp = new URL(url) return /profile\/(?<name>[^/]+)\/feed\/(?<rkey>[^/]+)/i.test( urlp.pathname, ) } catch {} } return false}
export function isBskyListUrl(url: string): boolean { if (isBskyAppUrl(url)) { try { const urlp = new URL(url) return /profile\/(?<name>[^/]+)\/lists\/(?<rkey>[^/]+)/i.test( urlp.pathname, ) } catch { console.error('Unexpected error in isBskyListUrl()', url) } } return false}
export function isBskyStartUrl(url: string): boolean { if (isBskyAppUrl(url)) { try { const urlp = new URL(url) return /start\/(?<name>[^/]+)\/(?<rkey>[^/]+)/i.test(urlp.pathname) } catch { console.error('Unexpected error in isBskyStartUrl()', url) } } return false}
export function isBskyStarterPackUrl(url: string): boolean { if (isBskyAppUrl(url)) { try { const urlp = new URL(url) return /starter-pack\/(?<name>[^/]+)\/(?<rkey>[^/]+)/i.test(urlp.pathname) } catch { console.error('Unexpected error in isBskyStartUrl()', url) } } return false}
// Invite codes are 7 alphanumeric characters long, supporting up to 10 here to future-proof.export const CHAT_INVITE_CODE_REGEX = /^\/chat\/([a-zA-Z0-9]{7,10})$/
export const GROUP_INVITE_CODE_REGEX = /^\/join\/([A-Za-z0-9_-]{43})$/
/** * Linking can emit an already-seen URL again after a warm-app tap. The hook * listener is the authoritative event source for that case; the URL-state * effect must not process the same event a second time. */export function shouldHandleIncomingIntentUrl( url: string, previousUrl: string, fromLinkEvent: boolean,): boolean { if (url !== previousUrl) return true try { const isGroupInvite = GROUP_INVITE_CODE_REGEX.test( new URL(url, BSKY_APP_HOST).pathname, ) return isGroupInvite && fromLinkEvent } catch { return false }}
export function getGroupInviteCodeFromUrl(url: string): string | undefined { let pathname: string if (isBskyAppUrl(url)) { try { pathname = new URL(url).pathname } catch { return undefined } } else if (url.startsWith('/')) { pathname = url.split('?')[0].split('#')[0] } else { return undefined } return pathname.match(GROUP_INVITE_CODE_REGEX)?.[1]}
export function isBskyGroupInviteUrl(url: string): boolean { return getGroupInviteCodeFromUrl(url) !== undefined}
export function getDeepLinkAnalyticsTarget(url: string): string { return isBskyGroupInviteUrl(url) ? 'group-invite' : url}
export function getChatInviteCodeFromUrl(url: string): string | undefined { let pathname: string if (isBskyAppUrl(url)) { try { pathname = new URL(url).pathname } catch { return undefined } } else if (url.startsWith('/')) { pathname = url.split('?')[0].split('#')[0] } else { return undefined } return pathname.match(CHAT_INVITE_CODE_REGEX)?.[1]}
export function isBskyChatInviteUrl(url: string): boolean { return getChatInviteCodeFromUrl(url) !== undefined}
export function isBskyDownloadUrl(url: string): boolean { if (isExternalUrl(url)) { return false } return url === '/download' || url.startsWith('/download?')}
export function convertBskyAppUrlIfNeeded(url: string): string { if (isBskyAppUrl(url)) { try { const urlp = new URL(url)
if (isBskyStartUrl(url)) { return startUriToStarterPackUri(urlp.pathname) }
return urlp.pathname + urlp.search } catch (e) { console.error('Unexpected error in convertBskyAppUrlIfNeeded()', e) } } else if (isShortLink(url)) { // We only want to do this on native, web handles the 301 for us return shortLinkToHref(url) } return url}
export function listUriToHref(url: string): string { try { const {hostname, rkey} = new AtUri(url) return `/profile/${hostname}/lists/${rkey}` } catch { return '' }}
export function feedUriToHref(url: string): string { try { const {hostname, rkey} = new AtUri(url) return `/profile/${hostname}/feed/${rkey}` } catch { return '' }}
export function postUriToRelativePath( uri: string, options?: {handle?: string},): string | undefined { // A space record URI has seven segments and misparses in AtUri. Its author // and rkey come out of the URI itself; the space rides in the query, which // is what rebuilds it on the way back. const spaceRef = parseSpaceRecordUri(uri) if (spaceRef) { return `/profile/${spaceRef.authorDid}/post/${spaceRef.rkey}?space=${encodeURIComponent(spaceUriOf(spaceRef))}` } try { const {hostname, rkey, collection} = new AtUri(uri) const handleOrDid = options?.handle && !isInvalidHandle(options.handle) ? options.handle : hostname const base = `/profile/${handleOrDid}/post/${rkey}` return collection && collection !== 'app.bsky.feed.post' ? `${base}?collection=${collection}` : base } catch { return undefined }}
/** * Checks if the label in the post text matches the host of the link facet. * * Hosts are case-insensitive, so should be lowercase for comparison. * @see https://www.rfc-editor.org/rfc/rfc3986#section-3.2.2 */export function linkRequiresWarning(uri: string, label: string) { const labelDomain = labelToDomain(label)
// We should trust any relative URL or a # since we know it links to internal content if (isRelativeUrl(uri) || uri === '#') { return false }
let urip try { urip = new URL(uri) } catch { return true }
const host = urip.hostname.toLowerCase() if (isTrustedUrl(uri)) { // if this is a link to internal content, warn if it represents itself as a URL to another app return !!labelDomain && labelDomain !== host && isPossiblyAUrl(labelDomain) } else { // if this is a link to external content, warn if the label doesnt match the target if (!labelDomain) { return true } return labelDomain !== host }}
/** * Returns a lowercase domain hostname if the label is a valid URL. * * Hosts are case-insensitive, so should be lowercase for comparison. * @see https://www.rfc-editor.org/rfc/rfc3986#section-3.2.2 */export function labelToDomain(label: string): string | undefined { // any spaces just immediately consider the label a non-url if (/\s/.test(label)) { return undefined } try { return new URL(label).hostname.toLowerCase() } catch {} try { return new URL('https://' + label).hostname.toLowerCase() } catch {} return undefined}
export function isPossiblyAUrl(str: string): boolean { str = str.trim() if (str.startsWith('http://')) { return true } if (str.startsWith('https://')) { return true } const [firstWord] = str.split(/[\s\/]/) return isValidDomain(firstWord)}
export function splitApexDomain(hostname: string): [string, string] { const hostnamep = parse(hostname) as { error?: unknown listed?: boolean domain?: string | null subdomain?: string | null } if (hostnamep.error || !hostnamep.listed || !hostnamep.domain) { return ['', hostname] } return [ hostnamep.subdomain ? `${hostnamep.subdomain}.` : '', hostnamep.domain, ]}
export function createBskyAppAbsoluteUrl(path: string): string { const sanitizedPath = path.replace(BSKY_APP_HOST, '').replace(/^\/+/, '') return `${BSKY_APP_HOST.replace(/\/$/, '')}/${sanitizedPath}`}
export function createProxiedUrl(url: string): string { let u try { u = new URL(url) } catch { return url }
if (u?.protocol !== 'http:' && u?.protocol !== 'https:') { return url }
const shortlinkDomain = DEFAULT_BRAND_CONFIG.web.domains.shortlink || 'https://go.blacksky.community' return `${shortlinkDomain}/redirect?u=${encodeURIComponent(url)}`}
export function isShortLink(url: string): boolean { const shortlinkDomain = DEFAULT_BRAND_CONFIG.web.domains.shortlink || 'https://go.blacksky.community' return url.startsWith(`${shortlinkDomain}/`)}
export function shortLinkToHref(url: string): string { try { const urlp = new URL(url)
// For now we only support starter packs, but in the future we should add additional paths to this check const parts = urlp.pathname.split('/').filter(Boolean) if (parts.length === 1) { return `/starter-pack-short/${parts[0]}` } return url } catch (e) { logger.error('Failed to parse possible short link', {safeMessage: e}) return url }}
export function getHostnameFromUrl(url: string | URL): string | null { let urlp try { urlp = new URL(url) } catch (e) { return null } return urlp.hostname}
export function getServiceAuthAudFromUrl(url: string | URL): string | null { const hostname = getHostnameFromUrl(url) if (!hostname) { return null } return `did:web:${hostname}`}
// passes URL.parse, and has a TLD etcexport 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 }}