import { useState , useEffect } from 'react' ; import Tty from 'teleport/lib/term/tty' ; import { TermEventEnum } from 'teleport/lib/term/enums' ; import { makeMfaAuthenticateChallenge , makeWebauthnAssertionResponse , } from 'teleport/services/auth' ; export default function useWebauthn ( tty ) { const [ state , setState ] = useState ( { requested : false , errorText : '' , publicKey : null as PublicKeyCredentialRequestOptions , } ) ; function authenticate ( ) { if ( ! window . PublicKeyCredential ) { const errorText = 'This browser does not support WebAuthn required for hardware tokens, \
      please try the latest version of Chrome, Firefox or Safari.' ; setState ( { ... state , errorText , } ) ; return ; } navigator . credentials . get ( { publicKey : state . publicKey } ) . then ( res => { const credential = makeWebauthnAssertionResponse ( res ) ; tty . send ( JSON . stringify ( credential ) ) ; setState ( { ... state , requested : false , errorText : '' , } ) ; } ) . catch ( ( err ) => { setState ( { ... state , errorText : err . message , } ) ; } ) ; } useEffect ( ( ) => { if ( tty ) { tty . on ( TermEventEnum . WEBAUTHN_CHALLENGE , challenge => { const json = JSON . parse ( challenge ) ; const publicKey = makeMfaAuthenticateChallenge ( json ) . webauthnPublicKey ; setState ( { ... state , requested : true , publicKey , } ) ; } ) ; } } , [ tty ] ) ; return { errorText : state . errorText , requested : state . requested , authenticate , } ; }