logicsrc/apps/pwa/src/lib/users.mjs
Anthony Ettinger e04531b73a
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>
2026-12-02 22:27:29 -08:00

32 lines
1.6 KiB
JavaScript

// User creation + lookups.
import { get, run } from "../db.mjs";
import { id } from "./crypto.mjs";
export async function createUserWithPassword(email, passwordHash, displayName) {
const uid = id();
await run(`INSERT INTO users (id, email, password_hash, display_name, created_at) VALUES (?,?,?,?,?)`,
[uid, email, passwordHash, displayName || email.split("@")[0], Date.now()]);
return get(`SELECT * FROM users WHERE id = ?`, [uid]);
}
export async function createUserForCoinpay(sub, displayName) {
const uid = id();
await run(`INSERT INTO users (id, coinpay_sub, display_name, created_at) VALUES (?,?,?,?)`,
[uid, sub, displayName || "logicsrc user", Date.now()]);
return get(`SELECT * FROM users WHERE id = ?`, [uid]);
}
// Passkey-first signup (no email/password yet).
export async function createUserPasskey(displayName) {
const uid = id();
await run(`INSERT INTO users (id, display_name, created_at) VALUES (?,?,?)`,
[uid, displayName || "logicsrc user", Date.now()]);
return get(`SELECT * FROM users WHERE id = ?`, [uid]);
}
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]);