about summary refs log tree commit diff
path: root/src/screens/Signup/StepCaptcha/CaptchaWebView.web.tsx
blob: 8faaf90a030843ad1da9041c23bac88a7234cbd7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import React from 'react'
import {StyleSheet} from 'react-native'

// @ts-ignore web only, we will always redirect to the app on web (CORS)
const REDIRECT_HOST = new URL(window.location.href).host

export function CaptchaWebView({
  url,
  stateParam,
  onSuccess,
  onError,
}: {
  url: string
  stateParam: string
  onSuccess: (code: string) => void
  onError: (error: unknown) => void
}) {
  React.useEffect(() => {
    const timeout = setTimeout(() => {
      onError({
        errorMessage: 'User did not complete the captcha within 30 seconds',
      })
    }, 30e3)

    return () => {
      clearTimeout(timeout)
    }
  }, [onError])

  const onLoad = React.useCallback(() => {
    // @ts-ignore web
    const frame: HTMLIFrameElement = document.getElementById(
      'captcha-iframe',
    ) as HTMLIFrameElement

    try {
      // @ts-ignore web
      const href = frame?.contentWindow?.location.href
      if (!href) return
      const urlp = new URL(href)

      // This shouldn't happen with CORS protections, but for good measure
      if (urlp.host !== REDIRECT_HOST) return

      const code = urlp.searchParams.get('code')
      if (urlp.searchParams.get('state') !== stateParam || !code) {
        onError({error: 'Invalid state or code'})
        return
      }
      onSuccess(code)
    } catch (e: unknown) {
      // We don't actually want to record an error here, because this will happen quite a bit. We will only be able to
      // get hte href of the iframe if it's on our domain, so all the hcaptcha requests will throw here, although it's
      // harmless. Our other indicators of time-to-complete and back press should be more reliable in catching issues.
    }
  }, [stateParam, onSuccess, onError])

  return (
    <iframe
      src={url}
      style={styles.iframe}
      id="captcha-iframe"
      onLoad={onLoad}
    />
  )
}

const styles = StyleSheet.create({
  iframe: {
    flex: 1,
    borderWidth: 0,
    borderRadius: 10,
    backgroundColor: 'transparent',
  },
})