| 1 | // Adds a passkey from Settings. The button ships hidden and is shown only |
| 2 | // where the browser can make a passkey, so with scripts off, or in a browser |
| 3 | // without passkeys, Settings has no button that cannot work. |
| 4 | // |
| 5 | // The ceremony is rastrillo's webauthn.mjs; Base's /passkey/register pair |
| 6 | // mints the challenge and stores the credential for the signed-in member. |
| 7 | |
| 8 | const btn = document.querySelector("[data-passkey-add]"); |
| 9 | |
| 10 | async function post(url, body) { |
| 11 | const res = await fetch(url, { |
| 12 | method: "POST", |
| 13 | credentials: "same-origin", |
| 14 | headers: { "Content-Type": "application/json" }, |
| 15 | body: JSON.stringify(body), |
| 16 | }); |
| 17 | if (!res.ok) throw new Error("status " + res.status); |
| 18 | return res.json(); |
| 19 | } |
| 20 | |
| 21 | if (btn && window.PublicKeyCredential) { |
| 22 | const msg = document.getElementById(btn.getAttribute("aria-describedby") || ""); |
| 23 | import(btn.dataset.module).then((m) => { |
| 24 | if (!m.available || !m.available()) return; |
| 25 | btn.hidden = false; |
| 26 | btn.addEventListener("click", async () => { |
| 27 | // A second click while one ceremony runs would start another. |
| 28 | if (btn.getAttribute("aria-busy") === "true") return; |
| 29 | btn.setAttribute("aria-busy", "true"); |
| 30 | if (msg) msg.textContent = ""; |
| 31 | try { |
| 32 | const begin = await post(btn.dataset.begin, {}); |
| 33 | const made = await m.register({ |
| 34 | challenge: begin.challenge, |
| 35 | rpId: location.hostname, |
| 36 | rpName: btn.dataset.rpName, |
| 37 | userId: btn.dataset.userId, |
| 38 | userName: btn.dataset.userName, |
| 39 | }); |
| 40 | const done = await post(btn.dataset.finish, { |
| 41 | clientDataJSON: made.clientDataJSON, |
| 42 | attestationObject: made.attestationObject, |
| 43 | }); |
| 44 | if (!done || done.ok !== true) throw new Error("not stored"); |
| 45 | location.assign(btn.dataset.done); |
| 46 | return; |
| 47 | } catch (err) { |
| 48 | // NotAllowedError is the browser's answer when the person closes the |
| 49 | // prompt (or it times out): gentler words than a failure. |
| 50 | const cancelled = err && err.name === "NotAllowedError"; |
| 51 | if (msg) msg.textContent = cancelled ? btn.dataset.cancelled : btn.dataset.failed; |
| 52 | } |
| 53 | btn.removeAttribute("aria-busy"); |
| 54 | }); |
| 55 | }, () => {}); |
| 56 | } |
| 57 | |