diff --git a/apps/pwa/public/passkey-add.js b/apps/pwa/public/passkey-add.js new file mode 100644 index 00000000..b24d77fc --- /dev/null +++ b/apps/pwa/public/passkey-add.js @@ -0,0 +1,38 @@ +/* Settings: add a passkey to the signed-in account (a second proof for vault recovery). + Uses the @simplewebauthn/browser UMD bundle (/vendor) and the same endpoints as sign-up. */ +(function () { + var btn = document.getElementById("passkey-add"); + var msg = document.getElementById("passkey-add-msg"); + if (!btn) return; + + function csrf() { + var m = document.cookie.match(/(?:^|; )mc_csrf=([^;]+)/); + return m ? decodeURIComponent(m[1]) : ""; + } + function post(url, body) { + return fetch(url, { + method: "POST", + headers: { "content-type": "application/json", "x-csrf-token": csrf() }, + body: JSON.stringify(body || {}), + }); + } + function say(t) { if (msg) msg.textContent = t; } + + btn.addEventListener("click", async function () { + btn.disabled = true; + say("Waiting for your device…"); + try { + var optsRes = await post("/auth/passkey/register/options"); + var opts = await optsRes.json(); + if (!optsRes.ok) throw new Error(opts.error || "Could not start."); + var att = await SimpleWebAuthnBrowser.startRegistration({ optionsJSON: opts }); + var r = await post("/auth/passkey/register/verify", att); + var out = await r.json(); + if (!r.ok || !out.ok) throw new Error(out.error || "Could not add the passkey."); + location.href = "/settings?passkey=added#vault-recovery"; + } catch (e) { + say(e && e.message ? e.message : "Could not add a passkey."); + btn.disabled = false; + } + }); +})(); diff --git a/apps/pwa/src/lib/users.mjs b/apps/pwa/src/lib/users.mjs index 37b23c01..69fcb2c7 100644 --- a/apps/pwa/src/lib/users.mjs +++ b/apps/pwa/src/lib/users.mjs @@ -26,4 +26,7 @@ export async function createUserPasskey(displayName) { export const userByEmail = (email) => get(`SELECT * FROM users WHERE email = ?`, [String(email).toLowerCase()]); export const userByCoinpay = (sub) => get(`SELECT * FROM users WHERE coinpay_sub = ?`, [sub]); +/** Connect a CoinPay identity to an existing account that has none. coinpay_sub is UNIQUE, so one identity is one account. */ +export const linkCoinpay = (userId, sub) => + run(`UPDATE users SET coinpay_sub = ? WHERE id = ? AND coinpay_sub IS NULL`, [sub, userId]); export const userById = (uid) => get(`SELECT * FROM users WHERE id = ?`, [uid]); diff --git a/apps/pwa/src/routes/coinpay.mjs b/apps/pwa/src/routes/coinpay.mjs index 94dc4462..f94f4fef 100644 --- a/apps/pwa/src/routes/coinpay.mjs +++ b/apps/pwa/src/routes/coinpay.mjs @@ -5,7 +5,7 @@ import { config } from "../config.mjs"; import { COINPAY_UA } from "../lib/coinpay-ua.mjs"; import { token } from "../lib/crypto.mjs"; import { createSession, setCeremony, getCeremony, clearCeremony, takeNext } from "../lib/session.mjs"; -import { userByCoinpay, createUserForCoinpay } from "../lib/users.mjs"; +import { userByCoinpay, createUserForCoinpay, linkCoinpay } from "../lib/users.mjs"; import { profiles } from "../lib/profile.mjs"; import { RecoveryError, approveStepup } from "../lib/vault-recovery.mjs"; import { saveOpenProfileContact } from "@profullstack/profile"; @@ -22,7 +22,9 @@ coinpayRouter.get("/auth/coinpay/start", (req, res) => { // A vault-recovery confirmation rides the same round trip (the redirect URI // registered with CoinPay is this router's callback); it signs nobody in. const stepup = typeof req.query.stepup === "string" && /^[A-Za-z0-9_-]{20,64}$/.test(req.query.stepup) ? req.query.stepup : null; - setCeremony(res, "cp", { state, verifier, ...(stepup ? { stepup } : {}) }, 1000 * 60 * 10); + // Settings > "Connect CoinPay": bind this CoinPay identity to the account that is signed in now. + const link = req.query.link === "1" && req.user ? String(req.user.id) : null; + setCeremony(res, "cp", { state, verifier, ...(stepup ? { stepup } : {}), ...(link ? { link } : {}) }, 1000 * 60 * 10); const u = new URL(config.coinpay.oauth.authorizeUrl); u.searchParams.set("response_type", "code"); @@ -77,6 +79,16 @@ coinpayRouter.get("/auth/coinpay/callback", async (req, res) => { return res.redirect(back(e instanceof RecoveryError ? e.message : "Could not confirm with CoinPay.")); } } + if (ceremony.link) { + // Bound by the CoinPay subject, to the account that started this while signed in and is + // still the one signed in. An identity that already belongs to another account is refused. + const settings = (q) => `/settings?${q}#vault-recovery`; + if (!req.user || String(req.user.id) !== ceremony.link) return res.redirect(settings(`coinpay_err=${encodeURIComponent("Sign in again, then connect CoinPay.")}`)); + const owner = await userByCoinpay(sub); + if (owner && String(owner.id) !== ceremony.link) return res.redirect(settings(`coinpay_err=${encodeURIComponent("That CoinPay account is already connected to a different LogicSRC account.")}`)); + if (!owner) await linkCoinpay(ceremony.link, sub); + return res.redirect(settings("coinpay=linked")); + } let user = await userByCoinpay(sub); if (!user) user = await createUserForCoinpay(sub, info.name || info.username); if (typeof info.openprofile_url === "string") { diff --git a/apps/pwa/src/routes/vault-recovery.mjs b/apps/pwa/src/routes/vault-recovery.mjs index 8557c50e..e9c49248 100644 --- a/apps/pwa/src/routes/vault-recovery.mjs +++ b/apps/pwa/src/routes/vault-recovery.mjs @@ -291,6 +291,28 @@ export async function vaultRecoveryCard(req) { : status.enrolled ? `
${csrfInput(req)}
` : `

Turn it on from the CLI (it needs your unlocked vault): logicsrc vault recovery enable

`; + // What the account can confirm an assisted recovery with, and a way to add one. + const m = status.stepupMethods || { passkey: false, coinpay: false }; + const linked = + req.query.passkey === "added" + ? `
Passkey added.
` + : req.query.coinpay === "linked" + ? `
CoinPay account connected.
` + : typeof req.query.coinpay_err === "string" + ? `
${esc(req.query.coinpay_err)}
` + : ""; + const secondProof = ` + ${linked} +
+ ${pill(m.passkey, "passkey on this account", "no passkey")} + ${pill(m.coinpay, "CoinPay connected", "CoinPay not connected")} +
+
+ + ${!m.coinpay && config.coinpayLoginEnabled ? `Connect CoinPay` : ""} +
+

+ `; return `
Vault email recovery — $${esc(String(status.priceUsd))} lifetime
@@ -301,6 +323,7 @@ export async function vaultRecoveryCard(req) { ${pill(status.enrolled, `enrolled ${esc(status.enrolledAt ? status.enrolledAt.slice(0, 10) : "")}`, "not enrolled")} ${status.email ? `codes go to ${esc(status.email)}` : ""}
+ ${secondProof}

${status.assisted ? `Assisted recovery is on. No old email is needed: recovery asks for the emailed one-time code and a passkey or CoinPay sign-in. To make that possible the server keeps both halves of your recovery key, sealed, so it is able to open your vault. Turn it off with logicsrc vault recovery enable (without --assisted).` : `Delete your email? logicsrc vault recovery enable --assisted makes recovery ask for a passkey or CoinPay sign-in instead of the code in the enrollment email. The trade: the server then holds everything needed to open your vault.`}

diff --git a/apps/pwa/test/vault-recovery.test.mjs b/apps/pwa/test/vault-recovery.test.mjs index 5e693619..a6c53874 100644 --- a/apps/pwa/test/vault-recovery.test.mjs +++ b/apps/pwa/test/vault-recovery.test.mjs @@ -488,3 +488,24 @@ test("assisted: the confirmation page shows for a live link, is gone for a dead await vr.approveStepup(stepup.id, user.id, "coinpay"); assert.match(await (await realFetch(`${base}/recover/confirm/${stepup.id}`)).text(), /Go back to your terminal/); }); + +test("the Settings card offers a way to add the second proof, and shows what the account has", async () => { + const { vaultRecoveryCard } = await import("../src/routes/vault-recovery.mjs"); + const card = await vaultRecoveryCard({ user: { id: "u_a", email: "u_a@example.com" }, query: {}, csrfToken: "t" }); + assert.match(card, /id="passkey-add"/); + assert.match(card, /no passkey/); + assert.match(card, /\/passkey-add\.js/); + const added = await vaultRecoveryCard({ user: { id: "u_a", email: "u_a@example.com" }, query: { passkey: "added" }, csrfToken: "t" }); + assert.match(added, /Passkey added\./); + // An error handed back by the CoinPay round trip is shown escaped. + const bad = await vaultRecoveryCard({ user: { id: "u_a", email: "u_a@example.com" }, query: { coinpay_err: "x" }, csrfToken: "t" }); + assert.doesNotMatch(bad, /x<\/b>/); +}); + +test("linkCoinpay connects an identity only to an account that has none", async () => { + const { linkCoinpay, userByCoinpay } = await import("../src/lib/users.mjs"); + await linkCoinpay("u_b", "sub_link_1"); + assert.equal((await userByCoinpay("sub_link_1")).id, "u_b"); + await linkCoinpay("u_b", "sub_link_2"); + assert.ok(!(await userByCoinpay("sub_link_2")), "a second identity does not replace the first"); +});