Files
shared/packages/python-backend/src/shared_backend/totp.py
T

75 lines
2.4 KiB
Python
Raw Normal View History

"""RFC 6238 TOTP helpers shared by Python auth services."""
from __future__ import annotations
import base64
import binascii
import hashlib
import hmac
import secrets
import struct
import time
from urllib.parse import quote, urlencode
TOTP_PERIOD_SECONDS = 30
TOTP_DIGITS = 6
TOTP_WINDOW = 1
def generate_totp_secret() -> str:
return base64.b32encode(secrets.token_bytes(20)).decode("ascii").rstrip("=")
def totp_provisioning_uri(issuer: str, account: str, secret: str) -> str:
normalized_issuer = str(issuer or "").strip()
normalized_account = str(account or "").strip()
label = f"{normalized_issuer}:{normalized_account}" if normalized_issuer else normalized_account
params = {
"secret": _normalize_secret(secret),
"algorithm": "SHA1",
"digits": str(TOTP_DIGITS),
"period": str(TOTP_PERIOD_SECONDS),
}
if normalized_issuer:
params["issuer"] = normalized_issuer
return f"otpauth://totp/{quote(label, safe='')}?{urlencode(params)}"
def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
normalized_secret = _normalize_secret(secret)
normalized_token = _normalize_token(token)
if not normalized_secret or len(normalized_token) != TOTP_DIGITS:
return False
try:
key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8))
except (ValueError, binascii.Error):
return False
if not key:
return False
period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS)
for offset in range(-TOTP_WINDOW, TOTP_WINDOW + 1):
counter = period + offset
if counter < 0:
continue
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
index = digest[-1] & 0x0F
value = (
((digest[index] & 0x7F) << 24)
| (digest[index + 1] << 16)
| (digest[index + 2] << 8)
| digest[index + 3]
)
candidate = f"{value % 1_000_000:06d}"
if hmac.compare_digest(candidate, normalized_token):
return True
return False
def _normalize_secret(value: str) -> str:
return str(value or "").strip().upper().replace(" ", "").rstrip("=")
def _normalize_token(value: str) -> str:
token = str(value or "").strip()
return token if len(token) == TOTP_DIGITS and token.isdigit() else ""