From fe30860c58e0f1b1efd457ff5eb5146d1e592da0 Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Tue, 1 Sep 2026 01:03:43 +0200 Subject: feat: passphrase change and account recovery (auth-confirm) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The passphrase derives two independent client-side values: auth_key (the hub verifier) and bundle_key (AES-GCM key for the per-node identity bundles, which live on nodes and never on the hub). Changing or recovering a passphrase is therefore two operations — swap the hub verifier, and re-wrap every reachable node's identity bundle. Flow A — change a known passphrase (Profile page) - POST /v1/users/password re-proves the current passphrase, swaps pw_hash/salt/version, revokes every refresh token and returns a fresh pair so the tab that made the change stays signed in. - MeshBayTransport.rewrapAllNodes: for every group's online node, connect with the old key, read the identity off the handshake, store it back under the new key. Returns updated / unreachable / failed so the UI can point at the operator-unpin fallback for the gaps. Always-shown confirmation dialog listing reachable and unreachable groups. Recovery key - keyderive.js generateRecoveryKey (32 random bytes, grouped Base32) and deriveRecoveryKey (HKDF-SHA256, domain meshbay:recovery:v1:). - Every per-node identity gets a second copy wrapped under the recovery key: keypair_bundles.bundle_enc_recovery (node-only column, added in _SCHEMA_KEYPAIR and via a PRAGMA-guarded ALTER for existing DBs), carried on keypair_bundle_store / _resp. MNP 0.13 -> 0.14, additive. - session.recoveryKey is persisted in IndexedDB (slot rk) and lazy-loaded on connect, so a group joined in any later session still leaves a recovery copy. - Shown once at registration; optionally folded into the verification e-mail as a pass-through the hub never stores or logs, with an opt-out. - Profile -> Recovery key re-loads R and backfills every reachable node via rewrapAllNodes in bundleKey mode (no passphrase re-entry). Flow B — recover a lost passphrase (#/reset, linked from sign-in) - POST /v1/users/password/reset-request {username, email}: both must be the pair on file, checked against the blind email_hash (never decrypted). A mismatch — wrong e-mail, unknown username, non-active account — takes the identical no-op path (no code, no mail, same 200), so it reveals nothing and cannot be used to spray reset mail from a username alone. 5/min, 1-hour single-use code. - POST /v1/users/password/reset {username, code, new_auth_key}: same expiry / attempts / single-use checks as e-mail verification; revokes every session and deletes every registered device key so a stored one cannot sign back in past the reset. - ResetPasswordPage: request code -> code + optional recovery key + new passphrase -> reset + sign-in -> fan-out. connect() falls back to the recovery-wrapped copy when the passphrase key cannot open bundle_enc. Without a recovery key: sign-in is restored and each group needs the operator-unpin fallback. Supporting fixes (found in live testing) - member unpin now also deletes the keypair bundle; connect() mints a fresh identity when handed a bundle it cannot open (unless _rewrapOnly, set by rewrapAllNodes), so a rejoin completes instead of dead-ending before the invite-code prompt. - A browser with no bundle key gets a passphrase prompt on the group page instead of a "go back to the browser you registered on" message. - RegisterPage / LoginPage / ResetPasswordPage trim the username so every key derivation matches the hub's stored form. Docs: docs/auth-confirm.md. Locale keys across all ten catalogues. Tests: test_password_change, test_password_reset, test_recovery_email, test_recovery_key, test_rewrap_fanout, test_bundle_store_recovery, plus additions to test_admin_ops_mnp and test_webrtc_transport. Hub suite 492 passed; node suite 741 passed (the lone test_packaging_units failure is a pre-existing RPM-spec flake, reproducible on main). Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01GGkxJW9br8Y9bhT8ywJ3oc --- packages/meshbay-hub/src/meshbay_hub/api/users.py | 226 +++++++++++++++++++++- 1 file changed, 223 insertions(+), 3 deletions(-) (limited to 'packages/meshbay-hub/src/meshbay_hub/api') diff --git a/packages/meshbay-hub/src/meshbay_hub/api/users.py b/packages/meshbay-hub/src/meshbay_hub/api/users.py index 953ad1b..fa74368 100644 --- a/packages/meshbay-hub/src/meshbay_hub/api/users.py +++ b/packages/meshbay-hub/src/meshbay_hub/api/users.py @@ -67,6 +67,10 @@ class RegisterRequest(BaseModel): email: str password: str | None = None # deprecated — legacy native clients auth_key: str | None = None # PBKDF2-derived, new clients + # Client-generated account recovery key (docs/auth-confirm.md §4.4). Pure + # pass-through: appended to the verification e-mail so the user's mailbox + # backs it up, then dropped. Never written to any table, never logged. + recovery_key: str | None = None @field_validator("username") @classmethod @@ -125,7 +129,8 @@ async def register( if found: if found.status == "pending" and found.email_hash == eh: # Same person retrying before validation — resend a code - await _create_and_send_verification(db, found, body.email, eh) + await _create_and_send_verification( + db, found, body.email, eh, body.recovery_key) await db.commit() return {"user_id": found.id, "email_verification_required": True} raise HTTPException(status_code=409, detail="Username already taken") @@ -161,7 +166,7 @@ async def register( detail=body.username, )) - await _create_and_send_verification(db, user, body.email, eh) + await _create_and_send_verification(db, user, body.email, eh, body.recovery_key) await db.commit() return {"user_id": user.id, "email_verification_required": True} @@ -169,6 +174,7 @@ async def register( async def _create_and_send_verification( db: AsyncSession, user: User, email: str, eh: str, + recovery_key: str | None = None, ) -> None: user.status = "pending" # Invalidate any previous pending verification for this user @@ -190,7 +196,7 @@ async def _create_and_send_verification( expires_at=datetime.now(timezone.utc) + timedelta(seconds=VERIFICATION_TTL), )) await db.flush() - mail.send_verification_code(email, code) + mail.send_verification_code(email, code, recovery_key=recovery_key) class VerifyEmailRequest(BaseModel): @@ -716,6 +722,220 @@ async def verify_email_change( return {"status": "verified", "email": email} +# ── Passphrase change (Flow A) ────────────────────────────────────────────── +# +# docs/auth-confirm.md §3. The passphrase derives two independent values on the +# client: auth_key (verified here) and bundle_key (AES-GCM key for the per-node +# identity bundles, which live on nodes and never on the hub). The client +# re-wraps those bundles from the old bundle_key to the new one on every +# reachable node *before* calling this; the hub only swaps its auth_key +# verifier. There is no email round-trip — the current passphrase is the second +# factor, exactly as for account deletion. + + +class ChangePasswordRequest(BaseModel): + old_auth_key: str + new_auth_key: str + + +@router.post("/password") +@limiter.limit("5/minute") +async def change_password( + body: ChangePasswordRequest, + request: Request, + current_user: User = Depends(require_user_scope), + db: AsyncSession = Depends(get_db), +): + if not verify_password(body.old_auth_key, current_user.pw_hash, + current_user.pw_salt, current_user.pw_version): + raise HTTPException(status_code=403, + detail="Current passphrase does not match") + if body.new_auth_key == body.old_auth_key: + raise HTTPException(status_code=400, + detail="New passphrase must differ from the current one") + + new_hash, new_salt = hash_password(body.new_auth_key) + current_user.pw_hash = new_hash + current_user.pw_salt = new_salt + current_user.pw_version = current_pw_version() + + # Every existing session goes stale. Revoke all refresh tokens, then hand + # this caller a fresh pair so the tab that made the change stays signed in; + # other browsers fail their next renewal and drop to the sign-in form. + await db.execute( + update(RefreshToken) + .where(RefreshToken.user_id == current_user.id) + .values(revoked=True)) + + memberships = await db.execute( + select(GroupMember.group_id).where(GroupMember.user_id == current_user.id)) + group_ids = [gid for (gid,) in memberships.all()] + access_token = issue_access_token(current_user.id, ttl=_ttl(), groups=group_ids) + raw_rt, rt_hash = generate_refresh_token() + expires_at = datetime.now(timezone.utc) + timedelta(seconds=_refresh_ttl()) + db.add(RefreshToken( + user_id=current_user.id, token_hash=rt_hash, + family_id=str(uuid.uuid4()), expires_at=expires_at, + )) + db.add(IPLog(user_id=current_user.id, event="password_change", + ip_address=client_ip(request))) + await db.commit() + + return { + "status": "changed", + "access_token": access_token, + "refresh_token": raw_rt, + "token_type": "bearer", + "expires_in": _ttl(), + } + + +# ── Passphrase reset (Flow B) ────────────────────────────────────────────── +# +# docs/auth-confirm.md §4.2. An e-mail code re-opens hub login for someone who +# has lost their passphrase. It recovers no group content — that needs the +# recovery key, which the client applies on its own after the reset. +# reset-request never reveals whether an account exists. + +PASSWORD_RESET_TTL = 3600 # 1 hour — shorter than sign-up verification + + +class ResetRequestRequest(BaseModel): + username: str + email: str # must match the address on file for `username` + + @field_validator("email") + @classmethod + def email_shape(cls, v: str) -> str: + v = v.strip() + local, sep, domain = v.partition("@") + if (not sep or not local or not domain + or "." not in domain + or len(v) > 254 + or any(c.isspace() or ord(c) < 32 for c in v)): + raise ValueError("invalid email address") + return v + + +class ResetPasswordRequest(BaseModel): + username: str + code: str + new_auth_key: str + + +@router.post("/password/reset-request") +@limiter.limit("5/minute") +async def password_reset_request( + body: ResetRequestRequest, + request: Request, + db: AsyncSession = Depends(get_db), +): + result = await db.execute(select(User).where(User.username == body.username)) + user = result.scalar_one_or_none() + + # The username and the e-mail must be the pair on file. A mismatch is + # answered exactly like an unknown account — no reset code is created, no + # mail is sent — so this reveals nothing and cannot be used to spray reset + # mail at someone by knowing only their username. + matched = ( + user is not None + and user.status == "active" + and user.email_hash == hash_email_blind(body.email) + ) + + if matched: + prev = await db.execute( + select(EmailVerification).where( + EmailVerification.user_id == user.id, + EmailVerification.purpose == "password_reset", + EmailVerification.verified_at.is_(None), + )) + for old in prev.scalars().all(): + await db.delete(old) + + code = _generate_code() + db.add(EmailVerification( + email_hash=user.email_hash or "", + code=code, + purpose="password_reset", + user_id=user.id, + expires_at=datetime.now(timezone.utc) + + timedelta(seconds=PASSWORD_RESET_TTL), + )) + db.add(IPLog(user_id=user.id, event="password_reset_request", + ip_address=client_ip(request))) + await db.flush() + try: + mail.send_password_reset_code(decrypt_email(user.email), code) + except Exception: + log.exception("Failed to send passphrase reset code") + await db.commit() + else: + db.add(IPLog( + user_id=user.id if user else None, + event="password_reset_request", + ip_address=client_ip(request), detail=body.username)) + await db.commit() + + # Same answer whether or not the username/e-mail pair matched an account. + return {"status": "sent_if_exists"} + + +@router.post("/password/reset") +@limiter.limit("10/minute") +async def password_reset( + body: ResetPasswordRequest, + request: Request, + db: AsyncSession = Depends(get_db), +): + now = datetime.now(timezone.utc) + result = await db.execute(select(User).where(User.username == body.username)) + user = result.scalar_one_or_none() + if not user: + raise HTTPException(status_code=400, detail="Invalid code") + + vres = await db.execute( + select(EmailVerification).where( + EmailVerification.user_id == user.id, + EmailVerification.purpose == "password_reset", + EmailVerification.verified_at.is_(None), + ).order_by(EmailVerification.created_at.desc())) + verif = vres.scalar_one_or_none() + if not verif: + raise HTTPException(status_code=404, + detail="No pending reset for this account") + if verif.expires_at.replace(tzinfo=timezone.utc) < now: + raise HTTPException(status_code=410, detail="Reset code expired") + if verif.attempts >= VERIFICATION_MAX_ATTEMPTS: + raise HTTPException(status_code=429, detail="Too many attempts") + + verif.attempts += 1 + if verif.code != body.code.strip(): + await db.commit() + raise HTTPException(status_code=400, detail="Invalid code") + + verif.verified_at = now + new_hash, new_salt = hash_password(body.new_auth_key) + user.pw_hash = new_hash + user.pw_salt = new_salt + user.pw_version = current_pw_version() + + # A lost passphrase is a "control may be lost" event: every session dies and + # every registered device key is dropped, so a stored one cannot sign back + # in past the reset. Each device re-enrols with the new passphrase. + await db.execute( + update(RefreshToken).where(RefreshToken.user_id == user.id) + .values(revoked=True)) + await db.execute(delete(UserDevice).where(UserDevice.user_id == user.id)) + db.add(IPLog(user_id=user.id, event="password_reset", + ip_address=client_ip(request))) + await db.commit() + + # The client already holds new_auth_key; it signs in through the normal + # path next, which issues tokens and the membership claim. + return {"status": "reset"} + + # ── User preferences ──────────────────────────────────────────────────────── ALLOWED_PREF_KEYS = frozenset([ -- cgit v1.2.3