File size: 2,914 Bytes
6b066c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""Accounts for StepWise: admin, parent and child logins.

Passwords are stored only as scrypt hashes. A login returns a signed token that the
browser keeps and sends as "Authorization: Bearer <token>". The token carries the
user id, an expiry and the user's token version; changing or resetting a password
bumps the version, which signs that user out everywhere.
"""
from __future__ import annotations

import base64
import hashlib
import hmac
import json
import os
import secrets
import time

TOKEN_DAYS = 60
_N, _R, _P = 2 ** 14, 8, 1


def _secret() -> bytes:
    s = os.environ.get("SESSION_SECRET")
    if s:
        return s.encode()
    # Stable across restarts without a new Space secret: derived from secrets the Space already has.
    seed = (os.environ.get("ACCESS_KEY", "") + "|" + os.environ.get("HF_TOKEN", "") + "|stepwise-session").encode()
    return hashlib.sha256(seed).digest()


SECRET = _secret()


def hash_password(pw: str) -> str:
    salt = secrets.token_bytes(16)
    h = hashlib.scrypt(pw.encode(), salt=salt, n=_N, r=_R, p=_P, dklen=32)
    return f"scrypt${_N}${_R}${_P}${salt.hex()}${h.hex()}"


def verify_password(pw: str, stored: str) -> bool:
    try:
        _, n, r, p, salt, h = stored.split("$")
        got = hashlib.scrypt(pw.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p), dklen=32)
        return hmac.compare_digest(got.hex(), h)
    except (ValueError, TypeError):
        return False


def _b64(b: bytes) -> str:
    return base64.urlsafe_b64encode(b).rstrip(b"=").decode()


def _unb64(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def make_token(uid: str, version: int) -> str:
    body = _b64(json.dumps({"u": uid, "v": version, "exp": int(time.time()) + TOKEN_DAYS * 86400}).encode())
    sig = _b64(hmac.new(SECRET, body.encode(), hashlib.sha256).digest())
    return f"{body}.{sig}"


def read_token(token: str) -> dict | None:
    try:
        body, sig = token.split(".")
        want = _b64(hmac.new(SECRET, body.encode(), hashlib.sha256).digest())
        if not hmac.compare_digest(sig, want):
            return None
        data = json.loads(_unb64(body))
        return data if data.get("exp", 0) > time.time() else None
    except (ValueError, TypeError, json.JSONDecodeError):
        return None


class LoginLimiter:
    """At most 8 wrong passwords per username in 15 minutes."""

    def __init__(self, limit: int = 8, window: int = 900) -> None:
        self.limit, self.window, self.fails = limit, window, {}

    def blocked(self, name: str) -> bool:
        t = time.time()
        self.fails[name] = [x for x in self.fails.get(name, []) if t - x < self.window]
        return len(self.fails[name]) >= self.limit

    def fail(self, name: str) -> None:
        self.fails.setdefault(name, []).append(time.time())

    def clear(self, name: str) -> None:
        self.fails.pop(name, None)