Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import {useMemo, useRef, useState} from 'react'import {WebView, type WebViewNavigation} from 'react-native-webview'import {type ShouldStartLoadRequest} from 'react-native-webview/lib/WebViewTypes'
import {logger} from '#/logger'import {type CaptchaWebViewProps} from './CaptchaWebView.shared'
const ALLOWED_HOSTS = [ 'bsky.social', 'bsky.app', 'blacksky.app', 'blacksky.community', 'staging.bsky.app', 'staging.bsky.dev', 'js.hcaptcha.com', 'newassets.hcaptcha.com', 'api2.hcaptcha.com',]
export function buildAllowedHosts(serviceUrl?: string): string[] { if (!serviceUrl) return ALLOWED_HOSTS
try { const {host} = new URL(serviceUrl) return ALLOWED_HOSTS.includes(host) ? ALLOWED_HOSTS : [...ALLOWED_HOSTS, host] } catch { return ALLOWED_HOSTS }}
function safeHost(url: string): string { try { return new URL(url).host } catch { return 'unparseable' }}
/** True if the two URLs point at the same host + path (query ignored). */function isSameEndpoint(a: string, b: string): boolean { try { const ua = new URL(a) const ub = new URL(b) return ua.host === ub.host && ua.pathname === ub.pathname } catch { return false }}
export function CaptchaWebView({ url, fallbackUrl, stateParam, state, onFallback, onComplete, onSuccess, onError,}: CaptchaWebViewProps) { // The URL currently loaded in the WebView. Starts at `url` and switches to // `fallbackUrl` once if the primary endpoint fails to load. Callers should // key this component on `url` so a changed primary URL remounts and resets // both this state and `usedFallback`. const [uri, setUri] = useState(url) const usedFallback = useRef(false)
// Attempt to recover from a failed load of the primary (attestation) URL by // silently reloading the fallback (captcha) URL. Returns true if it handled // the error, false if the caller should surface it. const tryFallback = ( failedUrl: string | undefined, statusCode?: number, ): boolean => { if ( fallbackUrl && !usedFallback.current && // Only react to the main gate document failing, not subresources. (!failedUrl || isSameEndpoint(failedUrl, uri)) ) { logger.warn( 'Signup captcha: primary gate endpoint failed, falling back to captcha', ) usedFallback.current = true onFallback?.(statusCode) setUri(fallbackUrl) return true } return false }
const redirectHost = useMemo(() => { if (!state?.serviceUrl) return 'blacksky.community'
return state?.serviceUrl && new URL(state?.serviceUrl).host === 'staging.bsky.dev' ? 'app.staging.bsky.dev' : 'blacksky.community' }, [state?.serviceUrl])
const allowedHosts = useMemo( () => buildAllowedHosts(state?.serviceUrl), [state?.serviceUrl], )
const wasSuccessful = useRef(false)
const handleCallbackUrl = (candidateUrl: string): boolean => { if (wasSuccessful.current) return false
let urlp: URL try { urlp = new URL(candidateUrl) } catch { return false }
// Ignore navigations that are still on a gate page (the captcha or the // attestation page). We only act on the final redirect back to the app, // which carries the verification code. if (urlp.host !== redirectHost || urlp.pathname.startsWith('/gate/signup')) return false
const code = urlp.searchParams.get('code') if (urlp.searchParams.get('state') !== stateParam || !code) { onError({reason: 'state-mismatch', host: urlp.host}) return true }
wasSuccessful.current = true onComplete() onSuccess(code)
return true }
const onShouldStartLoadWithRequest = (event: ShouldStartLoadRequest) => { // Consume the callback before loading it. An immediate server redirect may // not publish a navigation-state change before the WebView settles. if (handleCallbackUrl(event.url)) return false
try { return allowedHosts.includes(new URL(event.url).host) } catch { return false } }
const onNavigationStateChange = (e: WebViewNavigation) => { handleCallbackUrl(e.url) }
return ( <WebView source={{uri}} javaScriptEnabled style={{ flex: 1, backgroundColor: 'transparent', borderRadius: 10, }} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} onNavigationStateChange={onNavigationStateChange} scrollEnabled={false} onError={e => { if (tryFallback(e.nativeEvent.url)) return onError({ reason: 'webview-error', host: safeHost(e.nativeEvent.url), cause: e.nativeEvent, }) }} onHttpError={e => { if (tryFallback(e.nativeEvent.url, e.nativeEvent.statusCode)) return onError({ reason: 'http-error', host: safeHost(e.nativeEvent.url), statusCode: e.nativeEvent.statusCode, cause: e.nativeEvent, }) }} /> )}