""" A new passphrase's floor, and the hub's proof of work โ€” both checked here. The hub never sees a passphrase (docs/MESHBAY_DESIGN.md ยง3.1), so the floor โ€” 12 characters and about 60 estimated bits โ€” can only be enforced by the client: `auth-page.js` `passwordBits`, the same estimate, so a passphrase the page refuses is refused here too. """ import hashlib import math import re MIN_LENGTH = 12 MIN_BITS = 60 _WEAK = re.compile(r"(password|motdepasse|azerty|qwerty|123456|meshbay)", re.I) def passphrase_bits(pw: str) -> int: if not pw: return 0 pool = 0 if re.search(r"[a-z]", pw): pool += 26 if re.search(r"[A-Z]", pw): pool += 26 if re.search(r"[0-9]", pw): pool += 10 if re.search(r"[^A-Za-z0-9]", pw): pool += 32 # JavaScript counts UTF-16 units; a character outside the BMP is two. length = len(pw.encode("utf-16-le")) // 2 bits = length * math.log2(pool or 1) if len(set(pw)) < length / 2: bits *= 0.6 if re.fullmatch(r"[0-9]+", pw): bits *= 0.5 if _WEAK.search(pw): bits *= 0.3 # Math.round: halves go up. return math.floor(bits + 0.5) def passphrase_problem(pw: str) -> str | None: """Why a new passphrase is refused, or None.""" if len(pw.encode("utf-16-le")) // 2 < MIN_LENGTH: return f"A passphrase has {MIN_LENGTH} characters at least." if passphrase_bits(pw) < MIN_BITS: return ("This passphrase is too easy to guess: make it longer, or mix in " "other kinds of characters.") return None def solve_captcha(challenge: dict) -> str | None: """ The answer to `GET /v1/users/captcha`: the number below `max_number` whose `` hashes to `challenge` (`captcha.js` `solve`), as the token the register and reset-request bodies carry. None if there is none. """ prefix, want = challenge["prefix"], bytes.fromhex(challenge["challenge"]) for n in range(int(challenge["max_number"])): if hashlib.sha256(f"{prefix}{n}".encode()).digest() == want: return f"{prefix}{n}.{challenge['signature']}" return None