File size: 2,438 Bytes
0eec4dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Secrets, TOTP and QR helpers."""
import base64, hashlib, hmac, io, os, re, secrets, time

import pyotp
import qrcode
import qrcode.image.svg
from cryptography.fernet import Fernet

DATA_DIR = os.environ.get("HUB_SERVER_DATA", os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "server_data"))
ALLOWED_DOMAIN = os.environ.get("ALLOWED_DOMAIN", "indusface.com").lower().lstrip("@")
ISSUER = "Indusface Work Hub"


def app_secret():
    s = os.environ.get("APP_SECRET")
    if s:
        return s
    os.makedirs(DATA_DIR, exist_ok=True)
    p = os.path.join(DATA_DIR, ".secret")
    if not os.path.exists(p):  # dev convenience only; production must set APP_SECRET
        with open(p, "w") as f:
            f.write(secrets.token_urlsafe(48))
        os.chmod(p, 0o600)
    return open(p).read().strip()


def _fernet():
    return Fernet(base64.urlsafe_b64encode(hashlib.sha256(("totp|" + app_secret()).encode()).digest()))


def encrypt(s):
    return _fernet().encrypt(s.encode()).decode()


def decrypt(s):
    return _fernet().decrypt(s.encode()).decode()


def hash_token(t):
    return hashlib.sha256(t.encode()).hexdigest()


def new_device_token():
    return secrets.token_urlsafe(32)


def allowed_email(email):
    """Only real @<ALLOWED_DOMAIN> addresses; rejects guest (#EXT#) and look-alike domains."""
    e = (email or "").strip().lower()
    return bool(re.fullmatch(r"[a-z0-9][a-z0-9._%+\-']*@" + re.escape(ALLOWED_DOMAIN), e)) and "#ext#" not in e


def mask_email(e):
    u, _, d = e.partition("@")
    return (u[:1] + "***@" + d) if u else ""


def new_totp_secret():
    return pyotp.random_base32()


def totp_uri(secret, email):
    return pyotp.TOTP(secret).provisioning_uri(name=email, issuer_name=ISSUER)


def qr_data_uri(text):
    img = qrcode.make(text, image_factory=qrcode.image.svg.SvgPathImage, box_size=10)
    buf = io.BytesIO()
    img.save(buf)
    return "data:image/svg+xml;base64," + base64.b64encode(buf.getvalue()).decode()


def verify_totp(secret, code, last_step=0):
    """Return the accepted time-step (for replay protection) or None."""
    code = re.sub(r"\s+", "", code or "")
    if not re.fullmatch(r"\d{6}", code):
        return None
    t = pyotp.TOTP(secret)
    cur = int(time.time() // 30)
    for step in (cur, cur - 1, cur + 1):
        if step > last_step and hmac.compare_digest(t.generate_otp(step), code):
            return step
    return None