passkey-settings.js
| 1 | import { startRegistration } from "/assets/simplewebauthn-browser.js"; |
| 2 | |
| 3 | const section = document.getElementById("passkey-section"); |
| 4 | const btn = document.getElementById("add-passkey-btn"); |
| 5 | const status = document.getElementById("passkey-status"); |
| 6 | |
| 7 | if (section) section.style.display = "block"; |
| 8 | |
| 9 | if (btn) { |
| 10 | const originalText = btn.textContent; |
| 11 | btn.addEventListener("click", async () => { |
| 12 | btn.disabled = true; |
| 13 | btn.textContent = "Waiting for authenticator…"; |
| 14 | if (status) status.textContent = ""; |
| 15 | try { |
| 16 | const optsResp = await fetch("/auth/passkey/register/options", { |
| 17 | method: "POST", |
| 18 | }); |
| 19 | if (!optsResp.ok) { |
| 20 | const err = await optsResp.json().catch(() => ({})); |
| 21 | if (err.reauth) { |
| 22 | window.location.href = err.reauth; |
| 23 | return; |
| 24 | } |
| 25 | throw new Error(err.error ?? "Failed to get options"); |
| 26 | } |
| 27 | const opts = await optsResp.json(); |
| 28 | const result = await startRegistration({ optionsJSON: opts }); |
| 29 | const verResp = await fetch("/auth/passkey/register/verify", { |
| 30 | method: "POST", |
| 31 | headers: { "Content-Type": "application/json" }, |
| 32 | body: JSON.stringify(result), |
| 33 | }); |
| 34 | if (verResp.ok) { |
| 35 | window.location.reload(); |
| 36 | } else { |
| 37 | const err = await verResp.json().catch(() => ({})); |
| 38 | if (status) |
| 39 | status.textContent = |
| 40 | "Error: " + (err.error ?? "Registration failed"); |
| 41 | } |
| 42 | } catch (e) { |
| 43 | if (status) |
| 44 | status.textContent = |
| 45 | "Error: " + |
| 46 | (e instanceof Error ? e.message : String(e)); |
| 47 | } finally { |
| 48 | btn.disabled = false; |
| 49 | btn.textContent = originalText; |
| 50 | } |
| 51 | }); |
| 52 | } |
| 53 |