Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165import {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 SignupState} from '#/screens/Signup/state'
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',]
/** 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,}: { url: string /** * Optional URL to load if `url` fails (e.g. the attestation endpoint 404s on * a PDS that hasn't been updated). Lets us try attestation first and fall * back to the standard captcha without ever breaking account creation. */ fallbackUrl?: string stateParam: string state?: SignupState onFallback?: (statusCode?: number) => void onComplete: () => void onSuccess: (code: string) => void onError: (error: unknown) => void}) { // 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 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({error: 'Invalid state or code'}) 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 ALLOWED_HOSTS.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(e.nativeEvent) }} onHttpError={e => { if (tryFallback(e.nativeEvent.url, e.nativeEvent.statusCode)) return onError(e.nativeEvent) }} /> )}