Functional Weave
Code in Rust

auth.totp@1.0.0

impl/python/totp_uri.py

1,548 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import Any

from .auth_totp_hotp_code import check_totp_settings, totp_secret_key  ← hotpCode, another function of this group · built into the same file, even by a slim install
from .auth_totp_types import TotpSettings
from .encoding_base32_base32_encode import base32_encode

_UNRESERVED = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"


def _percent_encode(text: str) -> str:
    # RFC 3986: everything but the unreserved characters, as UTF-8 bytes.
    out = []
    for b in text.encode("utf-8"):
        ch = chr(b)
        out.append(ch if ch in _UNRESERVED else "%%%02X" % b)
    return "".join(out)


def _check_label_part(value: Any, name: str) -> None:
    if not isinstance(value, str):
        raise TypeError("%s must be text" % name)
    if value == "":
        raise ValueError("%s must not be empty" % name)
    if ":" in value:
        raise ValueError("%s must not contain a colon" % name)


def totp_uri(issuer: str, account: str, secret: str, settings: TotpSettings) -> str:
    """The Key Uri Format authenticator apps scan from a QR code. The secret
    is written back in canonical form (upper case, unpadded)."""
    _check_label_part(issuer, "issuer")
    _check_label_part(account, "account")
    check_totp_settings(settings)
    canonical = base32_encode(totp_secret_key(secret), False)
    return "otpauth://totp/%s:%s?secret=%s&issuer=%s&algorithm=%s&digits=%d&period=%d" % (
        _percent_encode(issuer),
        _percent_encode(account),
        canonical,
        _percent_encode(issuer),
        settings.algorithm,
        settings.digits,
        settings.period,
    )