import Key from '@mui/icons-material/Key' import { Alert, Box, Button, Paper, Stack, TextField, Typography } from '@mui/material' import { useState, type FormEvent } from 'react' import { CODE_PATTERN, PASSKEY_BEGUN_SHAPE, SESSION_SHAPE, request, type PasskeyBegun, type Session } from './api.ts' /** * The sign-in form: the user name, the password and, for a user enrolled for one-time passwords, the code, or a * passkey in a browser with WebAuthn. The server checks them; onSignedIn gets the session, and a failure shows the * server's message. */ export default function SignIn(props: { onSignedIn: (session: Session) => void }) { const [name, setName] = useState('') const [password, setPassword] = useState('') const [code, setCode] = useState('') const [busy, setBusy] = useState(false) const [error, setError] = useState(null) const codeProblem = code !== '' && !CODE_PATTERN.test(code) ? 'Six digits.' : '' const blocked = name === '' || password === '' || codeProblem !== '' async function submit(event: FormEvent) { event.preventDefault() if (blocked) { return } setBusy(true) setError(null) try { props.onSignedIn(await request('POST', '/session', SESSION_SHAPE, code === '' ? { name, password } : { name, password, code })) } catch (caught) { setError((caught as Error).message) setBusy(false) } } /** Signs in with a passkey the browser offers for the server's name. */ async function signInWithPasskey() { setBusy(true) setError(null) try { const begun = await request>('POST', '/session/passkey', PASSKEY_BEGUN_SHAPE, {}) const credential = await navigator.credentials.get({ publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(begun.options.publicKey) }) if (!(credential instanceof PublicKeyCredential)) { throw new Error('The browser gave no passkey.') } props.onSignedIn(await request('POST', '/session/passkey/complete', SESSION_SHAPE, { id: begun.id, credential: credential.toJSON() })) } catch (caught) { setError(caught instanceof DOMException && caught.name === 'NotAllowedError' ? 'No passkey was chosen.' : (caught as Error).message) setBusy(false) } } return ( Sign in {error && {error}} setName(event.target.value.trim())} /> setPassword(event.target.value)} /> setCode(event.target.value.trim())} /> {window.PublicKeyCredential && ( )} ) }