diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 8b0fb9df9..09de57aee 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -1464,11 +1464,6 @@ "count": 1 } }, - "src/screens/Signup/StepCaptcha/CaptchaWebView.tsx": { - "react-hooks/purity": { - "count": 1 - } - }, "src/screens/Signup/StepHandle/index.tsx": { "@typescript-eslint/no-misused-promises": { "count": 1 @@ -2460,4 +2455,4 @@ "count": 1 } } -} \ No newline at end of file +} diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index 3390d314b..041ca6d5a 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -174,6 +174,18 @@ export type Events = { } 'signup:captchaSuccess': {} 'signup:captchaFailure': {} + 'signup:attestationToken': { + platform: 'ios' | 'android' + succeeded: boolean + } + 'signup:attestationGate': { + platform: 'ios' | 'android' + selected: 'attestation' | 'captcha' + } + 'signup:attestationFallback': { + platform: 'ios' | 'android' + statusCode?: number + } 'signup:fieldError': { field: string errorCount: number diff --git a/src/screens/Signup/StepCaptcha/CaptchaWebView.tsx b/src/screens/Signup/StepCaptcha/CaptchaWebView.tsx index 58cc745d6..816c22fc1 100644 --- a/src/screens/Signup/StepCaptcha/CaptchaWebView.tsx +++ b/src/screens/Signup/StepCaptcha/CaptchaWebView.tsx @@ -1,7 +1,8 @@ -import {useEffect, useMemo, useRef} from 'react' +import {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 = [ @@ -16,33 +17,71 @@ const ALLOWED_HOSTS = [ 'api2.hcaptcha.com', ] -const MIN_DELAY = 3_500 +/** 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 }) { - const startedAt = useRef(Date.now()) - const successTo = useRef(undefined) - - useEffect(() => { - return () => { - if (successTo.current) { - clearTimeout(successTo.current) - } + // 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' @@ -55,40 +94,54 @@ export function CaptchaWebView({ const wasSuccessful = useRef(false) - const onShouldStartLoadWithRequest = (event: ShouldStartLoadRequest) => { - const urlp = new URL(event.url) - return ALLOWED_HOSTS.includes(urlp.host) - } + const handleCallbackUrl = (candidateUrl: string): boolean => { + if (wasSuccessful.current) return false - const onNavigationStateChange = (e: WebViewNavigation) => { - if (wasSuccessful.current) return + let urlp: URL + try { + urlp = new URL(candidateUrl) + } catch { + return false + } - const urlp = new URL(e.url) - if (urlp.host !== redirectHost || urlp.pathname === '/gate/signup') return + // 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 + return true } - // We want to delay the completion of this screen ever so slightly so that it doesn't appear to be a glitch if it completes too fast wasSuccessful.current = true onComplete() - const now = Date.now() - const timeTaken = now - startedAt.current - if (timeTaken < MIN_DELAY) { - successTo.current = setTimeout(() => { - onSuccess(code) - }, MIN_DELAY - timeTaken) - } else { - onSuccess(code) + 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 ( { + if (tryFallback(e.nativeEvent.url)) return onError(e.nativeEvent) }} onHttpError={e => { + if (tryFallback(e.nativeEvent.url, e.nativeEvent.statusCode)) return onError(e.nativeEvent) }} /> diff --git a/src/screens/Signup/StepCaptcha/index.tsx b/src/screens/Signup/StepCaptcha/index.tsx index f80335d91..91898fb8d 100644 --- a/src/screens/Signup/StepCaptcha/index.tsx +++ b/src/screens/Signup/StepCaptcha/index.tsx @@ -15,10 +15,8 @@ import {useAnalytics} from '#/analytics' import {GCP_PROJECT_ID, IS_ANDROID, IS_IOS, IS_NATIVE, IS_WEB} from '#/env' import {BackNextButtons} from '../BackNextButtons' -const CAPTCHA_PATH = - IS_WEB || GCP_PROJECT_ID === 0 - ? '/gate/signup' - : '/gate/signup/attempt-attest' +const CAPTCHA_PATH = '/gate/signup' +const ATTEST_PATH = '/gate/signup/attempt-attest' export function StepCaptcha() { if (IS_WEB) { @@ -29,6 +27,7 @@ export function StepCaptcha() { } export function StepCaptchaNative() { + const ax = useAnalytics() const [token, setToken] = useState() const [payload, setPayload] = useState() const [ready, setReady] = useState(false) @@ -36,26 +35,32 @@ export function StepCaptchaNative() { useEffect(() => { void (async () => { logger.debug('trying to generate attestation token...') + let succeeded = false try { if (IS_IOS) { logger.debug('starting to generate devicecheck token...') const token = await ReactNativeDeviceAttest.getDeviceCheckToken() setToken(token) - logger.debug(`generated devicecheck token: ${token}`) + succeeded = Boolean(token) } else { const {token, payload} = await ReactNativeDeviceAttest.getIntegrityToken('signup') setToken(token) setPayload(base64UrlEncode(payload)) + succeeded = Boolean(token) } } catch (err) { const e = err as Error logger.error(e) } finally { + ax.metric('signup:attestationToken', { + platform: IS_IOS ? 'ios' : 'android', + succeeded, + }) setReady(true) } })() - }, []) + }, [ax]) if (!ready) { return @@ -79,30 +84,47 @@ function StepCaptchaInner({ const [completed, setCompleted] = useState(false) const stateParam = useMemo(() => nanoid(15), []) - const url = useMemo(() => { - const newUrl = new URL(state.serviceUrl) - newUrl.pathname = CAPTCHA_PATH - newUrl.searchParams.set( - 'handle', - createFullHandle(state.handle, state.userDomain), - ) - newUrl.searchParams.set('state', stateParam) - newUrl.searchParams.set('colorScheme', theme.name) - - if (IS_WEB) { - // @ts-ignore web only - newUrl.searchParams.set('redirect_url', window.location.origin) - } - if (IS_NATIVE && token) { - newUrl.searchParams.set('platform', Platform.OS) - newUrl.searchParams.set('token', token) - if (IS_ANDROID && payload) { - newUrl.searchParams.set('payload', payload) + // Build both the standard captcha URL and (when applicable) the + // attestation-first URL. We optimistically try attestation and fall back to + // the captcha URL if the attestation endpoint is unavailable on this PDS - so + // account creation never breaks on a PDS that lacks the attestation route or + // credentials. See CaptchaWebView's fallback handling. + const {captchaUrl, attestUrl} = useMemo(() => { + const build = (path: string, withAttestation: boolean) => { + const newUrl = new URL(state.serviceUrl) + newUrl.pathname = path + newUrl.searchParams.set( + 'handle', + createFullHandle(state.handle, state.userDomain), + ) + newUrl.searchParams.set('state', stateParam) + newUrl.searchParams.set('colorScheme', theme.name) + + if (IS_WEB) { + // @ts-ignore web only + newUrl.searchParams.set('redirect_url', window.location.origin) + } + + if (withAttestation && IS_NATIVE && token) { + newUrl.searchParams.set('platform', Platform.OS) + newUrl.searchParams.set('token', token) + if (IS_ANDROID && payload) { + newUrl.searchParams.set('payload', payload) + } } + + return newUrl.href } - return newUrl.href + // Only attempt attestation on native, when a project is configured, and we + // actually managed to generate a token. Otherwise go straight to captcha. + const attestUrl = + IS_NATIVE && GCP_PROJECT_ID !== 0 && token + ? build(ATTEST_PATH, true) + : undefined + + return {captchaUrl: build(CAPTCHA_PATH, false), attestUrl} }, [ state.serviceUrl, state.handle, @@ -113,6 +135,27 @@ function StepCaptchaInner({ payload, ]) + const url = attestUrl ?? captchaUrl + const fallbackUrl = attestUrl ? captchaUrl : undefined + + useEffect(() => { + if (!IS_NATIVE) return + ax.metric('signup:attestationGate', { + platform: IS_IOS ? 'ios' : 'android', + selected: attestUrl ? 'attestation' : 'captcha', + }) + }, [ax, attestUrl]) + + const onFallback = useCallback( + (statusCode?: number) => { + ax.metric('signup:attestationFallback', { + platform: IS_IOS ? 'ios' : 'android', + statusCode, + }) + }, + [ax], + ) + const onSuccess = useCallback( (code: string) => { setCompleted(true) @@ -162,9 +205,12 @@ function StepCaptchaInner({ ]}> {!completed ? ( setCompleted(true)} onSuccess={onSuccess} onError={onError}