summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/tests/test_recovery_key.py
diff options
context:
space:
mode:
authorChristophe Besson <cbesson@gmail.com>2026-09-01 01:03:43 +0200
committerChristophe Besson <cbesson@gmail.com>2026-09-01 01:03:43 +0200
commitfe30860c58e0f1b1efd457ff5eb5146d1e592da0 (patch)
tree99a3e96994738c4e96f969a365679475dc4cf5cd /packages/meshbay-hub/tests/test_recovery_key.py
parent51d2d734c228f1e46670962480258abfe586d6c4 (diff)
downloadmeshbay-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-hub/tests/test_recovery_key.py')
-rw-r--r--packages/meshbay-hub/tests/test_recovery_key.py136
1 files changed, 136 insertions, 0 deletions
diff --git a/packages/meshbay-hub/tests/test_recovery_key.py b/packages/meshbay-hub/tests/test_recovery_key.py
new file mode 100644
index 0000000..378758a
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_recovery_key.py
@@ -0,0 +1,136 @@
+"""
+The account recovery key (docs/auth-confirm.md §4.3).
+
+`generateRecoveryKey` / `deriveRecoveryKey` in keyderive.js are run here under
+node against the real WebCrypto, rather than reimplemented: the mnemonic has to
+round-trip its bytes exactly, and the derived key has to be deterministic per
+account and domain-separated between accounts, or a recovery would hand back a
+key that opens nothing.
+"""
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static"
+KEYDERIVE = STATIC / "keyderive.js"
+
+pytestmark = pytest.mark.skipif(
+ shutil.which("node") is None or not KEYDERIVE.exists(),
+ reason="node or keyderive.js is unavailable",
+)
+
+_HARNESS = r"""
+const fs = require('fs');
+const webcrypto = require('crypto').webcrypto;
+global.self = global;
+global.window = global;
+global.crypto = webcrypto;
+
+// keyderive.js is a classic script ending in `window.MeshBayKeys = {...}`.
+eval(fs.readFileSync(process.argv[2], 'utf8'));
+const K = window.MeshBayKeys;
+
+const hex = (buf) => Buffer.from(buf).toString('hex');
+
+// deriveRecoveryKey yields a non-extractable AES-GCM key, so two keys are
+// compared by encrypting a fixed block with a fixed IV: same key => same bytes.
+const fp = async (key) => hex(await webcrypto.subtle.encrypt(
+ { name: 'AES-GCM', iv: new Uint8Array(12) }, key, new Uint8Array(16)));
+
+(async () => {
+ const out = {};
+
+ // 1. mnemonic round-trips the exact 32 bytes, 200 random draws: the key
+ // derived from the mnemonic string must match the key from the raw bytes.
+ let roundTripOk = true;
+ for (let i = 0; i < 200; i++) {
+ const rk = K.generateRecoveryKey(); // { rawB64, mnemonic }
+ const raw = Uint8Array.from(atob(rk.rawB64), c => c.charCodeAt(0));
+ const a = await fp(await K.deriveRecoveryKey(rk.mnemonic, 'u'));
+ const b = await fp(await K.deriveRecoveryKey(raw, 'u'));
+ if (a !== b) { roundTripOk = false; break; }
+ }
+ out.round_trip_ok = roundTripOk;
+
+ // 2. deterministic per account, different per account.
+ const rk = K.generateRecoveryKey();
+ const raw = Uint8Array.from(atob(rk.rawB64), c => c.charCodeAt(0));
+ const k1 = await fp(await K.deriveRecoveryKey(raw, 'alice'));
+ const k1again = await fp(await K.deriveRecoveryKey(raw, 'alice'));
+ const k2 = await fp(await K.deriveRecoveryKey(raw, 'bob'));
+ out.deterministic = (k1 === k1again);
+ out.domain_separated = (k1 !== k2);
+
+ // 3. mnemonic is grouped Base32, 52 significant chars for 32 bytes.
+ out.mnemonic_shape_ok =
+ /^[A-Z2-7]{4}( [A-Z2-7]{1,4})+$/.test(rk.mnemonic) &&
+ rk.mnemonic.replace(/ /g, '').length === 52;
+
+ // 4. a garbled key is rejected, not silently truncated.
+ let rejected = false;
+ try { await K.deriveRecoveryKey('too short', 'u'); }
+ catch { rejected = true; }
+ out.rejects_short = rejected;
+
+ // 5. the building block connect()'s Flow B fallback relies on: a bundle
+ // wrapped under one recovery key does not open under a wrong one, and does
+ // open under the right one.
+ {
+ const kA = await K.deriveRecoveryKey(raw, 'acc-A');
+ const kB = await K.deriveRecoveryKey(raw, 'acc-B');
+ const skEd = new Uint8Array([1, 2, 3]);
+ const skX = new Uint8Array([4, 5, 6]);
+ const blob = await K.encryptBundleWithKey(skEd, skX, kA);
+ let wrongRejected = false;
+ try { await K.decryptBundleWithKey(blob, kB); } catch { wrongRejected = true; }
+ const opened = await K.decryptBundleWithKey(blob, kA);
+ out.recovery_wrap_isolates = wrongRejected
+ && opened.skEd === btoa(String.fromCharCode(1, 2, 3))
+ && opened.skX === btoa(String.fromCharCode(4, 5, 6));
+ }
+
+ process.stdout.write(JSON.stringify(out));
+})().catch(e => { console.error(e); process.exit(1); });
+"""
+
+
+@pytest.fixture(scope="module")
+def result(tmp_path_factory):
+ d = tmp_path_factory.mktemp("recovery")
+ harness = d / "harness.cjs"
+ harness.write_text(_HARNESS)
+ proc = subprocess.run(
+ ["node", str(harness), str(KEYDERIVE)],
+ capture_output=True, text=True, timeout=120,
+ )
+ if proc.returncode != 0:
+ pytest.fail(f"node harness failed:\n{proc.stderr[-2000:]}")
+ return json.loads(proc.stdout)
+
+
+def test_mnemonic_round_trips_the_exact_bytes(result):
+ assert result["round_trip_ok"]
+
+
+def test_derived_key_is_deterministic_per_account(result):
+ assert result["deterministic"]
+
+
+def test_derived_key_is_domain_separated_between_accounts(result):
+ assert result["domain_separated"]
+
+
+def test_mnemonic_is_grouped_base32(result):
+ assert result["mnemonic_shape_ok"]
+
+
+def test_a_malformed_recovery_key_is_rejected(result):
+ assert result["rejects_short"]
+
+
+def test_a_recovery_wrapped_bundle_only_opens_under_the_matching_key(result):
+ assert result["recovery_wrap_isolates"]