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

82 lines
2.7 KiB
Python

"""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:
return verify_totp_step(secret, token, now) is not None
def verify_totp_step(secret: str, token: str, now: float | None = None) -> int | None:
normalized_secret = _normalize_secret(secret)
normalized_token = _normalize_token(token)
if not normalized_secret or len(normalized_token) != TOTP_DIGITS:
return None
try:
key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8))
except (ValueError, binascii.Error):
return None
if not key:
return None
period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS)
# Prefer the current step if a six-digit collision occurs in the window.
for offset in (0, -1, 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 counter
return None
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()
# str.isdigit() accepts other scripts' digits too, and hmac.compare_digest refuses those.
return token if len(token) == TOTP_DIGITS and token.isascii() and token.isdigit() else ""