Files
shared/packages/python-backend/src/shared_backend/totp.py
T
Gabriel20xx da97fd4fb1
Lint / Lint (Node/Svelte) (push) Successful in 24s
Lint / Lint (Go) (push) Successful in 28s
Lint / Lint (Python) (push) Failing after 14s
Tests / Test (Node/Svelte) (push) Successful in 18s
Tests / Test (Go) (push) Successful in 25s
Tests / Test (Python) (push) Successful in 12s
feat(auth): implement TOTP setup and management
- Added TOTP support for two-factor authentication in the auth module.
- Introduced new types and interfaces for TOTP setup and token actions in the web UI.
- Created backend logic for generating and verifying TOTP secrets and tokens.
- Implemented user management features including role assignments and user CRUD operations.
- Enhanced UI components for managing users and TOTP settings.
- Added styles for optional labels and authentication reset links.
- Implemented reset code generation and validation for admin accounts.
2026-08-05 14:57:01 +02:00

76 lines
2.4 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:
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 ""