aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/api
diff options
context:
space:
mode:
Diffstat (limited to 'packages/meshbay-hub/src/meshbay_hub/api')
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/users.py226
1 files changed, 223 insertions, 3 deletions
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([