aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-cli/src/meshbay_cli/client/passphrase.py
blob: 071c708b15ded582f62c6d4cc63ce24828654b62 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
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
    `<prefix><number>` 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