const $ = s => document.querySelector(s); const fail = e => { $('#err').textContent = e && e.name === 'NotAllowedError' ? 'Cancelled. Try again.' : (e.message || String(e)); }; async function signIn() { $('#err').textContent = ''; try { await passkeyLogin(); location.replace('/'); } catch (e) { fail(e); } } async function init() { if (!window.PublicKeyCredential) { $('#sub').textContent = ''; return fail(new Error('This browser does not support passkeys.')); } const st = await (await fetch('/api/auth/state')).json(); if (st.authed) return location.replace('/'); if (st.registered) { $('#sub').textContent = 'Sign in with your passkey'; $('#ui').innerHTML = ''; $('#go').onclick = signIn; signIn(); // prompt straight away; the button is there if it's dismissed } else { $('#sub').textContent = 'First-time setup: create a passkey for this device'; $('#ui').innerHTML = `
`; $('#f').onsubmit = async e => { e.preventDefault(); $('#err').textContent = ''; try { await passkeyRegister($('#sc').value.trim(), $('#nm').value.trim() || 'Passkey'); location.replace('/'); } catch (err) { fail(err); } }; } } init().catch(fail);