feat(settings): add a passkey or connect CoinPay to an existing account (#306)

Assisted recovery (#305) confirms with a passkey or a connected CoinPay
identity, but an account that signed up by email had no way to get either:
the passkey button exists only on the sign-in page, and Sign in with CoinPay
only ever created a new account.

- Settings > Vault email recovery shows what the account has and an "Add a
  passkey" button (the existing register endpoints, which already attach to
  the signed-in user).
- "Connect CoinPay" (shown when CoinPay sign-in is configured) binds the
  CoinPay subject to the signed-in account. An identity that already belongs
  to another account is refused; an account keeps its first identity.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-12-02 22:27:29 -08:00 • committed by GitHub
parent 6ff3089088
commit e04531b73a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 99 additions and 2 deletions

View file

@ -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;
}
});
})();

View file

@ -26,4 +26,7 @@ export async function createUserPasskey(displayName) {
export const userByEmail = (email) => get(`SELECT * FROM users WHERE email = ?`, [String(email).toLowerCase()]); 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]); 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]); export const userById = (uid) => get(`SELECT * FROM users WHERE id = ?`, [uid]);

View file

@ -5,7 +5,7 @@ import { config } from "../config.mjs";
import { COINPAY_UA } from "../lib/coinpay-ua.mjs"; import { COINPAY_UA } from "../lib/coinpay-ua.mjs";
import { token } from "../lib/crypto.mjs"; import { token } from "../lib/crypto.mjs";
import { createSession, setCeremony, getCeremony, clearCeremony, takeNext } from "../lib/session.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 { profiles } from "../lib/profile.mjs";
import { RecoveryError, approveStepup } from "../lib/vault-recovery.mjs"; import { RecoveryError, approveStepup } from "../lib/vault-recovery.mjs";
import { saveOpenProfileContact } from "@profullstack/profile"; 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 // A vault-recovery confirmation rides the same round trip (the redirect URI
// registered with CoinPay is this router's callback); it signs nobody in. // 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; 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); const u = new URL(config.coinpay.oauth.authorizeUrl);
u.searchParams.set("response_type", "code"); 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.")); 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); let user = await userByCoinpay(sub);
if (!user) user = await createUserForCoinpay(sub, info.name || info.username); if (!user) user = await createUserForCoinpay(sub, info.name || info.username);
if (typeof info.openprofile_url === "string") { if (typeof info.openprofile_url === "string") {

View file

@ -291,6 +291,28 @@ export async function vaultRecoveryCard(req) {
: status.enrolled : status.enrolled
? `<form method="post" action="/settings/vault-recovery/disable" style="margin-top:12px">${csrfInput(req)}<button class="btn danger">Turn email recovery off</button></form>` ? `<form method="post" action="/settings/vault-recovery/disable" style="margin-top:12px">${csrfInput(req)}<button class="btn danger">Turn email recovery off</button></form>`
: `<p class="dim" style="font-size:.85rem">Turn it on from the CLI (it needs your unlocked vault): <code>logicsrc vault recovery enable</code></p>`; : `<p class="dim" style="font-size:.85rem">Turn it on from the CLI (it needs your unlocked vault): <code>logicsrc vault recovery enable</code></p>`;
// 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"
? `<div class="notice ok">Passkey added.</div>`
: req.query.coinpay === "linked"
? `<div class="notice ok">CoinPay account connected.</div>`
: typeof req.query.coinpay_err === "string"
? `<div class="notice err">${esc(req.query.coinpay_err)}</div>`
: "";
const secondProof = `
${linked}
<div class="mono" style="font-size:.8rem;display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:10px">
${pill(m.passkey, "passkey on this account", "no passkey")}
${pill(m.coinpay, "CoinPay connected", "CoinPay not connected")}
</div>
<div class="row" style="gap:10px;flex-wrap:wrap;margin-top:10px">
<button class="btn" type="button" id="passkey-add">${m.passkey ? "Add another passkey" : "Add a passkey"}</button>
${!m.coinpay && config.coinpayLoginEnabled ? `<a class="btn" href="/auth/coinpay/start?link=1">Connect CoinPay</a>` : ""}
</div>
<p class="dim" id="passkey-add-msg" style="font-size:.85rem;margin:6px 0 0"></p>
<script src="/vendor/simplewebauthn-browser.umd.js" defer></script><script src="/passkey-add.js" defer></script>`;
return ` return `
<div class="card" id="vault-recovery" style="margin-top:20px"><div class="card-head"><span class="h">Vault email recovery — $${esc(String(status.priceUsd))} lifetime</span></div> <div class="card" id="vault-recovery" style="margin-top:20px"><div class="card-head"><span class="h">Vault email recovery — $${esc(String(status.priceUsd))} lifetime</span></div>
<div class="card-body"> <div class="card-body">
@ -301,6 +323,7 @@ export async function vaultRecoveryCard(req) {
${pill(status.enrolled, `enrolled ${esc(status.enrolledAt ? status.enrolledAt.slice(0, 10) : "")}`, "not enrolled")} ${pill(status.enrolled, `enrolled ${esc(status.enrolledAt ? status.enrolledAt.slice(0, 10) : "")}`, "not enrolled")}
${status.email ? `<span class="faint">codes go to ${esc(status.email)}</span>` : ""} ${status.email ? `<span class="faint">codes go to ${esc(status.email)}</span>` : ""}
</div> </div>
${secondProof}
<p class="dim" style="font-size:.85rem">${status.assisted <p class="dim" style="font-size:.85rem">${status.assisted
? `<b>Assisted recovery is on.</b> 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 <code>logicsrc vault recovery enable</code> (without <code>--assisted</code>).` ? `<b>Assisted recovery is on.</b> 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 <code>logicsrc vault recovery enable</code> (without <code>--assisted</code>).`
: `Delete your email? <code>logicsrc vault recovery enable --assisted</code> 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.`}</p> : `Delete your email? <code>logicsrc vault recovery enable --assisted</code> 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.`}</p>

View file

@ -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"); await vr.approveStepup(stepup.id, user.id, "coinpay");
assert.match(await (await realFetch(`${base}/recover/confirm/${stepup.id}`)).text(), /Go back to your terminal/); 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: "<b>x</b>" }, csrfToken: "t" });
assert.doesNotMatch(bad, /<b>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");
});