diff options
| author | Christophe Besson <cbesson@gmail.com> | 2026-09-01 01:03:43 +0200 |
|---|---|---|
| committer | Christophe Besson <cbesson@gmail.com> | 2026-09-01 01:03:43 +0200 |
| commit | fe30860c58e0f1b1efd457ff5eb5146d1e592da0 (patch) | |
| tree | 99a3e96994738c4e96f969a365679475dc4cf5cd /packages/meshbay-node | |
| parent | 51d2d734c228f1e46670962480258abfe586d6c4 (diff) | |
| download | meshbay-fe30860c58e0f1b1efd457ff5eb5146d1e592da0.tar.gz | |
feat: passphrase change and account recovery (auth-confirm)
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:<username>).
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GGkxJW9br8Y9bhT8ywJ3oc
Diffstat (limited to 'packages/meshbay-node')
6 files changed, 167 insertions, 19 deletions
diff --git a/packages/meshbay-node/src/meshbay_node/bundle_store.py b/packages/meshbay-node/src/meshbay_node/bundle_store.py index 4cf3236..7f03caa 100644 --- a/packages/meshbay-node/src/meshbay_node/bundle_store.py +++ b/packages/meshbay-node/src/meshbay_node/bundle_store.py @@ -3,7 +3,10 @@ Bundle store — SQLite-backed storage for GEK bundles and keypair bundles. GEK bundles: ECIES-wrapped GEK targeted at a specific user's X25519 key. Keypair bundles: AES-GCM encrypted (Ed25519 + X25519) private keys, encrypted -with the user's password-derived bundle_key. Opaque to the node. +with the user's password-derived bundle_key. Opaque to the node. An optional +second copy (bundle_enc_recovery) is wrapped under the account's recovery key +instead, so a forgotten passphrase does not strand the identity — see +docs/auth-confirm.md §4.3. Both are stored and served over the P2P DataChannel during MNP handshake. """ @@ -29,9 +32,10 @@ CREATE TABLE IF NOT EXISTS gek_bundles ( _SCHEMA_KEYPAIR = """\ CREATE TABLE IF NOT EXISTS keypair_bundles ( - user_id TEXT PRIMARY KEY, - bundle_enc TEXT NOT NULL, - stored_at TEXT NOT NULL DEFAULT (datetime('now')) + user_id TEXT PRIMARY KEY, + bundle_enc TEXT NOT NULL, + bundle_enc_recovery TEXT, + stored_at TEXT NOT NULL DEFAULT (datetime('now')) ); """ @@ -46,8 +50,22 @@ class BundleStore: self._db = await aiosqlite.connect(str(self._db_path)) await self._db.execute(_SCHEMA_GEK) await self._db.execute(_SCHEMA_KEYPAIR) + await self._migrate_keypair_recovery() await self._db.commit() + async def _migrate_keypair_recovery(self) -> None: + """ + Add bundle_enc_recovery to a keypair_bundles table created before it + existed. SQLite has no ADD COLUMN IF NOT EXISTS, so check the columns + first — this table is node-only and has no Alembic history. + """ + assert self._db + async with self._db.execute("PRAGMA table_info(keypair_bundles)") as cur: + cols = {row[1] for row in await cur.fetchall()} + if "bundle_enc_recovery" not in cols: + await self._db.execute( + "ALTER TABLE keypair_bundles ADD COLUMN bundle_enc_recovery TEXT") + async def store( self, group_id: str, @@ -81,23 +99,46 @@ class BundleStore: "wrapped_b64": row[2], } - async def store_keypair(self, user_id: str, bundle_enc: str) -> None: + async def store_keypair( + self, + user_id: str, + bundle_enc: str, + bundle_enc_recovery: str | None = None, + ) -> None: + """ + Store the passphrase-wrapped keypair bundle, and optionally a second + copy wrapped under the account's recovery key. + + A call that omits bundle_enc_recovery — a plain re-backup, or a + passphrase-change re-wrap (docs/auth-confirm.md §3.2) — must not erase a + recovery copy already stored, so the upsert keeps the existing value + when the new one is None. + """ assert self._db await self._db.execute( - "INSERT OR REPLACE INTO keypair_bundles " - "(user_id, bundle_enc, stored_at) VALUES (?, ?, datetime('now'))", - (user_id, bundle_enc), + "INSERT INTO keypair_bundles " + "(user_id, bundle_enc, bundle_enc_recovery, stored_at) " + "VALUES (?, ?, ?, datetime('now')) " + "ON CONFLICT(user_id) DO UPDATE SET " + " bundle_enc = excluded.bundle_enc, " + " bundle_enc_recovery = COALESCE(excluded.bundle_enc_recovery, " + " keypair_bundles.bundle_enc_recovery), " + " stored_at = excluded.stored_at", + (user_id, bundle_enc, bundle_enc_recovery), ) await self._db.commit() - async def fetch_keypair(self, user_id: str) -> str | None: + async def fetch_keypair(self, user_id: str) -> dict | None: assert self._db async with self._db.execute( - "SELECT bundle_enc FROM keypair_bundles WHERE user_id = ?", + "SELECT bundle_enc, bundle_enc_recovery FROM keypair_bundles " + "WHERE user_id = ?", (user_id,), ) as cursor: row = await cursor.fetchone() - return row[0] if row else None + if not row: + return None + return {"bundle_enc": row[0], "bundle_enc_recovery": row[1]} async def delete_keypair(self, user_id: str) -> bool: """ diff --git a/packages/meshbay-node/src/meshbay_node/ops.py b/packages/meshbay-node/src/meshbay_node/ops.py index 07579cd..cd5dc32 100644 --- a/packages/meshbay-node/src/meshbay_node/ops.py +++ b/packages/meshbay-node/src/meshbay_node/ops.py @@ -219,6 +219,16 @@ async def unpin_member(state: dict, user_id: str) -> dict: roster = _roster(state) if not await roster.unpin(user_id): raise OpError("No such pinned identity", status=404) + # Drop the stored keypair bundle too. Left behind, it is served to the next + # connection, which then cannot open it (the passphrase may have changed + # since) and dies in the identity step before it ever reaches the join the + # unpin was meant to enable. + bundle_store = state.get("bundle_store") + if bundle_store: + try: + await bundle_store.delete_keypair(user_id) + except Exception: + log.warning("unpin: could not drop keypair bundle for %s", user_id[:8]) log.info("Identity unpinned: user=%s", user_id[:8]) return {"status": "unpinned", "user_id": user_id} diff --git a/packages/meshbay-node/src/meshbay_node/transport/webrtc_server.py b/packages/meshbay-node/src/meshbay_node/transport/webrtc_server.py index 15309cf..717a27a 100644 --- a/packages/meshbay-node/src/meshbay_node/transport/webrtc_server.py +++ b/packages/meshbay-node/src/meshbay_node/transport/webrtc_server.py @@ -868,14 +868,20 @@ class WebRTCPeerSession: self._send({"type": "error", "detail": "No pending handshake"}) return - bundle_enc = await bundle_store.fetch_keypair(user_id) - if bundle_enc: - self._send({ + kp = await bundle_store.fetch_keypair(user_id) + if kp and kp.get("bundle_enc"): + resp = { "type": MNP.KEYPAIR_BUNDLE_RESP, "v": MNP_VERSION, "found": True, - "bundle_enc": bundle_enc, - }) + "bundle_enc": kp["bundle_enc"], + } + # The recovery-wrapped copy (MNP 0.14) rides along when present, so a + # client holding the recovery key can re-wrap it under a new + # passphrase — docs/auth-confirm.md §4.5. + if kp.get("bundle_enc_recovery"): + resp["bundle_enc_recovery"] = kp["bundle_enc_recovery"] + self._send(resp) else: self._send({"type": MNP.KEYPAIR_BUNDLE_RESP, "v": MNP_VERSION, "found": False}) @@ -891,8 +897,14 @@ class WebRTCPeerSession: self._send({"type": "error", "detail": "Missing bundle_enc"}) return - await bundle_store.store_keypair(self._user_id, bundle_enc) - log.info("Keypair bundle stored for user=%s", self._user_id[:8]) + # Optional second copy wrapped under the recovery key (MNP 0.14). Omitted + # by an older client and by a plain re-backup; the store keeps any + # existing recovery copy when this is absent. + recovery = msg.get("bundle_enc_recovery") or None + + await bundle_store.store_keypair(self._user_id, bundle_enc, recovery) + log.info("Keypair bundle stored for user=%s (recovery=%s)", + self._user_id[:8], bool(recovery)) self._audit("keypair_bundle_store") self._send({ "type": "ack", "v": MNP_VERSION, diff --git a/packages/meshbay-node/tests/test_admin_ops_mnp.py b/packages/meshbay-node/tests/test_admin_ops_mnp.py index 1bf8365..92e50b5 100644 --- a/packages/meshbay-node/tests/test_admin_ops_mnp.py +++ b/packages/meshbay-node/tests/test_admin_ops_mnp.py @@ -100,10 +100,15 @@ async def _session(tmp_path: Path, roster, *, operator: bool) -> WebRTCPeerSessi class _FakeBundleStore: def __init__(self): self.stored = [] + self.deleted_keypairs = [] async def store(self, *args): self.stored.append(args) + async def delete_keypair(self, user_id): + self.deleted_keypairs.append(user_id) + return True + class _FakeHub: class _S: @@ -279,6 +284,9 @@ async def test_the_operator_unpins(tmp_path, roster): assert _last(session)["type"] == MNP.MEMBER_UNPIN_ACK assert await roster.get_identity("bob") is None + # The stored keypair bundle goes too — left behind it blocks the re-join + # the unpin exists to enable. + assert "bob" in session.state["bundle_store"].deleted_keypairs async def test_unpinning_someone_unknown_says_so(tmp_path, roster): diff --git a/packages/meshbay-node/tests/test_bundle_store_recovery.py b/packages/meshbay-node/tests/test_bundle_store_recovery.py new file mode 100644 index 0000000..10a3400 --- /dev/null +++ b/packages/meshbay-node/tests/test_bundle_store_recovery.py @@ -0,0 +1,76 @@ +""" +The recovery-wrapped keypair copy (docs/auth-confirm.md §4.3, MNP 0.14). + +`bundle_enc_recovery` is a second copy of the identity bundle wrapped under the +account's recovery key. The store has to add the column to a database that +predates it, and a plain re-backup that omits the recovery copy must not erase +one already there. +""" + +import aiosqlite +import pytest +from meshbay_node.bundle_store import BundleStore + + +@pytest.mark.asyncio +async def test_round_trip_with_and_without_recovery(tmp_path): + store = BundleStore(db_path=tmp_path / "bundles.db") + await store.open() + + await store.store_keypair("u1", "pass-wrapped-1") + row = await store.fetch_keypair("u1") + assert row == {"bundle_enc": "pass-wrapped-1", "bundle_enc_recovery": None} + + await store.store_keypair("u2", "pass-wrapped-2", "recovery-wrapped-2") + row = await store.fetch_keypair("u2") + assert row["bundle_enc"] == "pass-wrapped-2" + assert row["bundle_enc_recovery"] == "recovery-wrapped-2" + + assert await store.fetch_keypair("nobody") is None + await store.close() + + +@pytest.mark.asyncio +async def test_re_backup_without_recovery_keeps_the_existing_copy(tmp_path): + """A passphrase-change re-wrap sends only bundle_enc; the recovery copy stays.""" + store = BundleStore(db_path=tmp_path / "bundles.db") + await store.open() + + await store.store_keypair("u1", "v1", "recovery-v1") + await store.store_keypair("u1", "v2") # no recovery arg + row = await store.fetch_keypair("u1") + assert row["bundle_enc"] == "v2" + assert row["bundle_enc_recovery"] == "recovery-v1" + + # An explicit new recovery copy does replace it. + await store.store_keypair("u1", "v3", "recovery-v3") + row = await store.fetch_keypair("u1") + assert row == {"bundle_enc": "v3", "bundle_enc_recovery": "recovery-v3"} + await store.close() + + +@pytest.mark.asyncio +async def test_migration_adds_the_column_to_an_old_database(tmp_path): + db_path = tmp_path / "bundles.db" + + # A keypair_bundles table as it looked before MNP 0.14. + async with aiosqlite.connect(str(db_path)) as db: + await db.execute( + "CREATE TABLE keypair_bundles (" + " user_id TEXT PRIMARY KEY," + " bundle_enc TEXT NOT NULL," + " stored_at TEXT NOT NULL DEFAULT (datetime('now')))") + await db.execute( + "INSERT INTO keypair_bundles (user_id, bundle_enc) VALUES ('old', 'legacy')") + await db.commit() + + store = BundleStore(db_path=db_path) + await store.open() # runs the migration + + row = await store.fetch_keypair("old") + assert row == {"bundle_enc": "legacy", "bundle_enc_recovery": None} + + await store.store_keypair("old", "legacy", "recovery-now") + row = await store.fetch_keypair("old") + assert row["bundle_enc_recovery"] == "recovery-now" + await store.close() diff --git a/packages/meshbay-node/tests/test_webrtc_transport.py b/packages/meshbay-node/tests/test_webrtc_transport.py index ec6e987..159ba63 100644 --- a/packages/meshbay-node/tests/test_webrtc_transport.py +++ b/packages/meshbay-node/tests/test_webrtc_transport.py @@ -1359,7 +1359,8 @@ async def test_keypair_bundle_store_and_fetch(sk_node, sk_hub, gek, shared_dir, # Verify in DB stored = await bundle_store.fetch_keypair("user-001") - assert stored == "encrypted-keypair-data-base64" + assert stored["bundle_enc"] == "encrypted-keypair-data-base64" + assert stored["bundle_enc_recovery"] is None await pc1.close() |