// Adds a passkey from Settings. The button ships hidden and is shown only // where the browser can make a passkey, so with scripts off, or in a browser // without passkeys, Settings has no button that cannot work. // // The ceremony is rastrillo's webauthn.mjs; Base's /passkey/register pair // mints the challenge and stores the credential for the signed-in member. const btn = document.querySelector("[data-passkey-add]"); async function post(url, body) { const res = await fetch(url, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!res.ok) throw new Error("status " + res.status); return res.json(); } if (btn && window.PublicKeyCredential) { const msg = document.getElementById(btn.getAttribute("aria-describedby") || ""); import(btn.dataset.module).then((m) => { if (!m.available || !m.available()) return; btn.hidden = false; btn.addEventListener("click", async () => { // A second click while one ceremony runs would start another. if (btn.getAttribute("aria-busy") === "true") return; btn.setAttribute("aria-busy", "true"); if (msg) msg.textContent = ""; try { const begin = await post(btn.dataset.begin, {}); const made = await m.register({ challenge: begin.challenge, rpId: location.hostname, rpName: btn.dataset.rpName, userId: btn.dataset.userId, userName: btn.dataset.userName, }); const done = await post(btn.dataset.finish, { clientDataJSON: made.clientDataJSON, attestationObject: made.attestationObject, }); if (!done || done.ok !== true) throw new Error("not stored"); location.assign(btn.dataset.done); return; } catch (err) { // NotAllowedError is the browser's answer when the person closes the // prompt (or it times out): gentler words than a failure. const cancelled = err && err.name === "NotAllowedError"; if (msg) msg.textContent = cancelled ? btn.dataset.cancelled : btn.dataset.failed; } btn.removeAttribute("aria-busy"); }); }, () => {}); }