aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/tests
diff options
context:
space:
mode:
authorChristophe Besson <cbesson@gmail.com>2026-10-15 14:25:00 +0200
committerChristophe Besson <cbesson@gmail.com>2026-10-15 14:25:00 +0200
commit28c77b7648b2a44a18be64ec44344d91cccfd742 (patch)
tree72e0398306639817922cf292e4da6725182c23dd /packages/meshbay-hub/tests
parentac4c3302783a3137e55dcede54c466bdf8aa55b7 (diff)
downloadmeshbay-28c77b7648b2a44a18be64ec44344d91cccfd742.tar.gz
feat(auth): the recovery key never reaches the hub
Ticking "also e-mail it to me" at registration sent the recovery key R in the register body, and the hub appended it to the verification e-mail: the hub saw R in clear on its way out, and the resend door — no captcha — let anyone who knew a pending username and address have the hub mail a "recovery key" of their choosing. The box is gone. The recovery screen offers "E-mail it to myself", a mailto: link that opens the person's own mail application with the key filled in; the desktop shell hands mailto: to the system (http, https and mailto only) and the Android shell to a mail application (ACTION_SENDTO). The CLI drops --email-recovery-key and prints the key, as before. The hub mails the code alone, and refuses a register that still carries a recovery_key rather than dropping it, so an older client offering the option cannot tell someone their key was sent when it was not. A mailbox holding R remains, with the reset code that reaches the same mailbox, enough to recover the account's identities; the link says so, and it is the person's choice. Checked in Chrome and Firefox (headless, the real page against a stubbed hub) and by the CLI's end-to-end registration against a local hub. The Android change was not built here, and the desktop link was not clicked in the application. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'packages/meshbay-hub/tests')
-rw-r--r--packages/meshbay-hub/tests/conftest.py2
-rw-r--r--packages/meshbay-hub/tests/test_android_shell.py4
-rw-r--r--packages/meshbay-hub/tests/test_desktop_shell.py18
-rw-r--r--packages/meshbay-hub/tests/test_recovery_email.py93
-rw-r--r--packages/meshbay-hub/tests/test_recovery_mailto.py70
5 files changed, 132 insertions, 55 deletions
diff --git a/packages/meshbay-hub/tests/conftest.py b/packages/meshbay-hub/tests/conftest.py
index 5104ae2..79a9e9a 100644
--- a/packages/meshbay-hub/tests/conftest.py
+++ b/packages/meshbay-hub/tests/conftest.py
@@ -100,7 +100,7 @@ async def db_session(app):
@pytest.fixture(autouse=True)
def _skip_email_verification(monkeypatch):
"""Skip email verification in tests — users are active immediately."""
- async def _noop(db, user, email, eh, recovery_key=None):
+ async def _noop(db, user, email, eh):
pass
monkeypatch.setattr(
diff --git a/packages/meshbay-hub/tests/test_android_shell.py b/packages/meshbay-hub/tests/test_android_shell.py
index 1049a5f..c68234d 100644
--- a/packages/meshbay-hub/tests/test_android_shell.py
+++ b/packages/meshbay-hub/tests/test_android_shell.py
@@ -62,6 +62,10 @@ def test_the_webview_loads_the_package_and_nothing_else():
assert "loadDataWithBaseURL" not in activity and "loadData(" not in activity
# The hub never becomes the document origin; a link out leaves the app.
assert "shouldOverrideUrlLoading" in activity and "openExternally" in activity
+ # The recovery screen's "e-mail it to myself" (§3.6) goes to a mail
+ # application, and only as a mail address: SENDTO, not a VIEW of anything.
+ assert 'url.scheme == "mailto") openMail(url)' in activity
+ assert "Intent(Intent.ACTION_SENDTO, url)" in activity
def test_the_policy_is_the_desktop_policy_sent_as_a_header():
diff --git a/packages/meshbay-hub/tests/test_desktop_shell.py b/packages/meshbay-hub/tests/test_desktop_shell.py
index 7a26dfb..587103f 100644
--- a/packages/meshbay-hub/tests/test_desktop_shell.py
+++ b/packages/meshbay-hub/tests/test_desktop_shell.py
@@ -72,6 +72,24 @@ def test_navigation_away_from_the_package_is_refused():
assert "event.preventDefault()" in source
+def test_only_web_and_mail_links_reach_the_system():
+ """`shell.openExternal` hands a URL to whatever the system registered for
+ its scheme, so the handler names the schemes it passes: the web, and
+ `mailto:` for the recovery screen's "e-mail it to myself" (§3.6). A
+ `file:` or a custom scheme from the page would run a local program."""
+ import subprocess
+ source = _main()
+ block = source[source.index("setWindowOpenHandler"):]
+ block = block[:block.index("});")]
+ match = re.search(r"if \((/[^/]+/)\.test\(new URL\(url\)\.protocol\)\) shell\.openExternal\(url\)", block)
+ assert match, block
+ probe = ("const re = " + match.group(1) + ";"
+ "process.stdout.write(JSON.stringify(['https:','http:','mailto:','file:',"
+ "'javascript:','smb:','ms-settings:','vbscript:'].filter(p => re.test(p))))")
+ out = subprocess.run(["node", "-e", probe], capture_output=True, text=True, check=True)
+ assert json.loads(out.stdout) == ["https:", "http:", "mailto:"]
+
+
def _granted_permissions() -> set[str]:
"""The allowlist, read out of the source rather than described here."""
match = re.search(r"GRANTED_PERMISSIONS = new Set\(\[([^\]]*)\]\)", _main())
diff --git a/packages/meshbay-hub/tests/test_recovery_email.py b/packages/meshbay-hub/tests/test_recovery_email.py
index 96dde5d..0e19be9 100644
--- a/packages/meshbay-hub/tests/test_recovery_email.py
+++ b/packages/meshbay-hub/tests/test_recovery_email.py
@@ -1,10 +1,12 @@
"""
-The recovery key in the registration e-mail (docs/MESHBAY_DESIGN.md §3.6).
+The recovery key never reaches the hub (docs/MESHBAY_DESIGN.md §3.6).
-When the client sends `recovery_key`, the hub appends it to the verification
-e-mail and stores it nowhere. When it does not, the e-mail carries only the
-code. `recovery_key` is a pass-through — no column, no log line beyond a
-boolean.
+It used to: a client that ticked "e-mail it to me" sent it in the register body
+and the hub appended it to the verification e-mail, so the hub saw it in clear
+and so did anyone who could make the hub mail one (the resend door). The person
+now mails it to themselves from their own application. The hub refuses the
+field rather than dropping it, so an older client that still offers the option
+cannot tell somebody their key was sent when it was not.
"""
import base64
@@ -12,7 +14,7 @@ import hashlib
import pytest
from meshbay_hub import mail
-from meshbay_hub.db.models import EmailVerification, User
+from meshbay_hub.db.models import User
from sqlalchemy import select
RECOVERY = "ABCD EFGH JKLM NPQR STUV WXYZ 2345 6789 ABCD EFGH JKLM NPQR STUV"
@@ -31,74 +33,57 @@ def _skip_email_verification(monkeypatch):
run so the e-mail is actually built. Capture it instead of sending.
"""
sent = []
- # `**_` swallows the `purpose` keyword `_send` now requires — the gate
- # that keeps this hub off the open-relay list. What this module is
- # about is the body of the message, so the gate is stubbed away with
- # the socket; `test_mail_is_not_a_relay.py` is where it is exercised.
+ # `**_` swallows the `purpose` keyword `_send` requires — the gate that
+ # keeps this hub off the open-relay list, exercised in
+ # `test_mail_is_not_a_relay.py`. What this module is about is the body.
monkeypatch.setattr("meshbay_hub.mail._send",
lambda msg, **_: sent.append(msg) or True)
return sent
@pytest.mark.asyncio
-async def test_register_appends_the_recovery_key_to_the_email(
- client, _skip_email_verification):
+async def test_a_register_carrying_the_recovery_key_is_refused(
+ client, db_session, _skip_email_verification):
r = await client.post("/v1/users/register", json={
"username": "rk1_test", "email": "rk1@example.com",
"auth_key": _auth_key("a-long-enough-passphrase", "rk1_test"),
"recovery_key": RECOVERY,
})
- assert r.status_code in (200, 201), r.text
- assert len(_skip_email_verification) == 1
- body = _skip_email_verification[0].get_content()
- assert RECOVERY in body
- assert "recovery key" in body.lower()
+ assert r.status_code == 400, r.text
+ assert "recovery key" in r.json()["detail"]
+ assert _skip_email_verification == [], "nothing was mailed"
+ assert (await db_session.execute(
+ select(User).where(User.username == "rk1_test"))).scalar_one_or_none() is None
@pytest.mark.asyncio
-async def test_register_without_recovery_key_sends_only_the_code(
+async def test_a_resend_carrying_the_recovery_key_is_refused(
client, _skip_email_verification):
- r = await client.post("/v1/users/register", json={
- "username": "rk2_test", "email": "rk2@example.com",
- "auth_key": _auth_key("a-long-enough-passphrase", "rk2_test"),
- })
- assert r.status_code in (200, 201), r.text
- body = _skip_email_verification[0].get_content()
- assert "recovery key" not in body.lower()
- assert "verification code is" in body.lower()
+ # The resend door has no captcha: it was how a stranger who knew a pending
+ # username and address could have the hub mail a "recovery key" of theirs.
+ body = {"username": "rk2_test", "email": "rk2@example.com",
+ "auth_key": _auth_key("a-long-enough-passphrase", "rk2_test")}
+ assert (await client.post("/v1/users/register", json=body)).status_code == 201
+ r = await client.post("/v1/users/register", json={**body, "recovery_key": RECOVERY})
+ assert r.status_code == 400, r.text
+ for msg in _skip_email_verification:
+ assert RECOVERY not in msg.get_content()
@pytest.mark.asyncio
-async def test_the_recovery_key_is_not_persisted(
- client, db_session, _skip_email_verification):
- await client.post("/v1/users/register", json={
+async def test_the_verification_mail_carries_only_the_code(
+ client, _skip_email_verification):
+ r = await client.post("/v1/users/register", json={
"username": "rk3_test", "email": "rk3@example.com",
"auth_key": _auth_key("a-long-enough-passphrase", "rk3_test"),
- "recovery_key": RECOVERY,
})
- rows = (await db_session.execute(select(EmailVerification))).scalars().all()
- assert rows
- for row in rows:
- assert RECOVERY not in (row.code or "")
- assert RECOVERY not in (row.email_encrypted or "")
- user = (await db_session.execute(
- select(User).where(User.username == "rk3_test"))).scalar_one()
- assert RECOVERY not in repr(vars(user))
-
-
-def test_mail_body_with_and_without_the_key(monkeypatch):
- captured = []
- monkeypatch.setattr("meshbay_hub.mail._send",
- lambda msg, **_: captured.append(msg) or True)
+ assert r.status_code == 201, r.text
+ (msg,) = _skip_email_verification
+ body = msg.get_content()
+ assert "verification code is" in body.lower()
+ assert "recovery" not in body.lower()
- mail.send_verification_code("x@example.com", "123456",
- recovery_key="MY-RECOVERY-KEY")
- body = captured[-1].get_content()
- assert "123456" in body
- assert "MY-RECOVERY-KEY" in body
- assert "recovery key" in body.lower()
- mail.send_verification_code("x@example.com", "123456")
- body = captured[-1].get_content()
- assert "123456" in body
- assert "recovery key" not in body.lower()
+def test_the_mail_function_takes_no_recovery_key():
+ with pytest.raises(TypeError):
+ mail.send_verification_code("x@example.com", "123456", recovery_key=RECOVERY)
diff --git a/packages/meshbay-hub/tests/test_recovery_mailto.py b/packages/meshbay-hub/tests/test_recovery_mailto.py
new file mode 100644
index 0000000..401a69f
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_recovery_mailto.py
@@ -0,0 +1,70 @@
+"""
+"E-mail it to myself" on the recovery screen (docs/MESHBAY_DESIGN.md §3.6).
+
+The recovery key never reaches the hub; a `mailto:` link has the person's own
+mail application send it to their own address. This runs the page's
+`recoveryMailto` under Node, with the English strings, and reads the link back
+the way a mail application would.
+"""
+
+import json
+import shutil
+import subprocess
+from urllib.parse import parse_qs, unquote, urlsplit
+
+import pytest
+from spa_source import STATIC
+
+pytestmark = pytest.mark.skipif(shutil.which("node") is None, reason="no node")
+
+MNEMONIC = "ABCD EFGH JKLM NPQR STUV WXYZ 2345 6789 ABCD EFGH JKLM NPQR STUV"
+
+HARNESS = r"""
+const fs = require('fs');
+const [page, locale, email, user, key] = process.argv.slice(1);
+const src = fs.readFileSync(page, 'utf8');
+const start = src.indexOf('export function recoveryMailto(');
+if (start < 0) throw new Error('recoveryMailto not found');
+const end = src.indexOf('\n}\n', start);
+const fn = src.slice(start, end + 2).replace(/^export /, '');
+(async () => {
+ const strings = (await import(locale)).default;
+ const t = (k, params) => {
+ let s = strings[k];
+ if (s == null) throw new Error('missing string ' + k);
+ for (const [n, v] of Object.entries(params || {})) s = s.split(`{${n}}`).join(v);
+ return s;
+ };
+ const recoveryMailto = new Function('t', fn + '\nreturn recoveryMailto;')(t);
+ process.stdout.write(JSON.stringify(recoveryMailto(email, user, key)));
+})();
+"""
+
+
+def _link(email: str, user: str = "alice_tester") -> str:
+ out = subprocess.run(
+ ["node", "-e", HARNESS, str(STATIC / "auth-page.js"),
+ (STATIC / "locales" / "en.js").as_uri(), email, user, MNEMONIC],
+ capture_output=True, text=True, check=True)
+ return json.loads(out.stdout)
+
+
+def test_the_link_sends_the_key_to_the_person_and_nowhere_else():
+ link = _link("alice+mesh@example.org")
+ parts = urlsplit(link)
+ assert parts.scheme == "mailto"
+ assert unquote(parts.path) == "alice+mesh@example.org"
+ assert "@" in parts.path, "an encoded '@' is not decoded by every mail app"
+ query = parse_qs(parts.query)
+ assert set(query) == {"subject", "body"}, "no cc, no bcc, nothing else"
+ body = query["body"][0]
+ assert MNEMONIC in body and "alice_tester" in body
+ assert "\n\n" in body, "line breaks survive the encoding"
+
+
+def test_an_address_cannot_add_recipients_or_headers():
+ # An address is the person's own, but it is still text put into a URL.
+ link = _link("a@example.org?bcc=x@evil.example&body=")
+ query = parse_qs(urlsplit(link).query)
+ assert set(query) == {"subject", "body"}
+ assert MNEMONIC in query["body"][0]