QtPass Developer documentation
QtPass test coverage
Current view: top level - src/totp.cpp (source / functions) Coverage Total Hit
Test: QtPass Lines: 98.4 % 187 184
Test Date: 2026-12-03 23:34:20 Functions: 100.0 % 19 19
Branches: 97.7 % 132 129

             Branch data     Line data    Source code
       1                 :             : // SPDX-FileCopyrightText: 2025 KeePassXC Team <team@keepassxc.org>
       2                 :             : // SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
       3                 :             : // SPDX-License-Identifier: GPL-3.0-or-later
       4                 :             : 
       5                 :             : /**
       6                 :             :  * @file
       7                 :             :  * @brief Implements Totp: otpauth URI parsing with its length cap and HOTP
       8                 :             :  * and unknown-algorithm refusal, RFC 4226 dynamic truncation, Steam encoding
       9                 :             :  * and URI round-tripping.
      10                 :             :  *
      11                 :             :  * @see totp.h
      12                 :             :  */
      13                 :             : 
      14                 :             : #include "totp.h"
      15                 :             : #include "base32.h"
      16                 :             : 
      17                 :             : #include <QCoreApplication>
      18                 :             : #include <QCryptographicHash>
      19                 :             : #include <QDateTime>
      20                 :             : #include <QLatin1Char>
      21                 :             : #include <QMessageAuthenticationCode>
      22                 :             : #include <QStringList>
      23                 :             : #include <QUrl>
      24                 :             : #include <QUrlQuery>
      25                 :             : #include <QtEndian>
      26                 :             : #include <QtGlobal>
      27                 :             : #include <string_view>
      28                 :             : 
      29                 :             : #include <algorithm>
      30                 :             : 
      31                 :             : namespace {
      32                 :             : 
      33                 :             : /// Steam Guard's alphabet: no A, E, I, L, O, S, U, Z, 0 or 1.
      34                 :             : constexpr std::string_view kSteamAlphabet = "23456789BCDFGHJKMNPQRTVWXY";
      35                 :             : /// Number of symbols in kSteamAlphabet.
      36                 :             : constexpr quint64 kSteamAlphabetSize = kSteamAlphabet.size();
      37                 :             : /// Shortest HMAC output the dynamic truncation below can read from (SHA-1).
      38                 :             : constexpr int kMinHmacSize = 20;
      39                 :             : 
      40                 :             : /**
      41                 :             :  * @brief Map an `algorithm` URI value onto a hash function.
      42                 :             :  *
      43                 :             :  * Surrounding whitespace, case, an `HMAC` prefix and `-`/`_` separators are
      44                 :             :  * ignored, so `SHA-256`,
      45                 :             :  * `HmacSHA256` and `HMAC-SHA-256` all name SHA-256. Anything else is not a
      46                 :             :  * hash function QtPass has: no result, rather than a SHA-1 code that looks
      47                 :             :  * right and an algorithm that toUri() would then leave out.
      48                 :             :  *
      49                 :             :  * @param name Value of the `algorithm` parameter.
      50                 :             :  * @return The matching algorithm, or std::nullopt for an unknown one.
      51                 :             :  */
      52                 :         103 : auto algorithmByName(const QString &name) -> std::optional<Totp::Algorithm> {
      53                 :         103 :   QString compact = name.trimmed().toUpper();
      54                 :         103 :   compact.remove(QLatin1Char('-'));
      55                 :         103 :   compact.remove(QLatin1Char('_'));
      56      [ +  +  + ]:         206 :   if (compact.startsWith(QStringLiteral("HMAC"))) {
      57                 :          15 :     compact.remove(0, 4);
      58                 :             :   }
      59         [ +  + ]:         103 :   if (compact == QStringLiteral("SHA1")) {
      60                 :          12 :     return Totp::Algorithm::Sha1;
      61                 :             :   }
      62         [ +  + ]:          91 :   if (compact == QStringLiteral("SHA256")) {
      63                 :          26 :     return Totp::Algorithm::Sha256;
      64                 :             :   }
      65         [ +  + ]:          65 :   if (compact == QStringLiteral("SHA512")) {
      66                 :          14 :     return Totp::Algorithm::Sha512;
      67                 :             :   }
      68                 :          51 :   return std::nullopt;
      69                 :             : }
      70                 :             : 
      71                 :             : /**
      72                 :             :  * @brief Canonical name for an algorithm, as written into an otpauth URI.
      73                 :             :  * @param algorithm Hash function.
      74                 :             :  * @return "SHA1", "SHA256" or "SHA512".
      75                 :             :  */
      76                 :           6 : auto algorithmName(Totp::Algorithm algorithm) -> QString {
      77      [ +  +  - ]:           6 :   switch (algorithm) {
      78                 :           3 :   case Totp::Algorithm::Sha512:
      79                 :           3 :     return QStringLiteral("SHA512");
      80                 :           3 :   case Totp::Algorithm::Sha256:
      81                 :           3 :     return QStringLiteral("SHA256");
      82                 :             :   case Totp::Algorithm::Sha1:
      83                 :             :     break;
      84                 :             :   }
      85                 :           0 :   return QStringLiteral("SHA1");
      86                 :             : }
      87                 :             : 
      88                 :             : /**
      89                 :             :  * @brief Map an algorithm onto the QtCore hash enumerator.
      90                 :             :  * @param algorithm Hash function.
      91                 :             :  * @return The QCryptographicHash equivalent.
      92                 :             :  */
      93                 :             : auto cryptoHash(Totp::Algorithm algorithm) -> QCryptographicHash::Algorithm {
      94                 :          53 :   switch (algorithm) {
      95                 :             :   case Totp::Algorithm::Sha512:
      96                 :             :     return QCryptographicHash::Sha512;
      97                 :           6 :   case Totp::Algorithm::Sha256:
      98                 :           6 :     return QCryptographicHash::Sha256;
      99                 :             :   case Totp::Algorithm::Sha1:
     100                 :             :     break;
     101                 :             :   }
     102                 :          41 :   return QCryptographicHash::Sha1;
     103                 :             : }
     104                 :             : 
     105                 :             : /// Percent-encode a URI label or issuer, keeping ':' and '@' readable.
     106                 :          54 : auto encodeLabel(const QString &value) -> QString {
     107                 :         108 :   return QString::fromLatin1(QUrl::toPercentEncoding(value, ":@"));
     108                 :             : }
     109                 :             : 
     110                 :             : /**
     111                 :             :  * @brief Read a positive integer query parameter.
     112                 :             :  * @param value Raw parameter text.
     113                 :             :  * @param fallback Returned when @p value is absent, non-numeric or zero.
     114                 :             :  * @return The parsed value, or @p fallback.
     115                 :             :  */
     116                 :         734 : auto parsePositiveUInt(const QString &value, uint fallback) -> uint {
     117                 :         734 :   bool ok = false;
     118                 :             :   const uint parsed = value.toUInt(&ok);
     119   [ +  +  +  + ]:         734 :   return (ok && parsed > 0) ? parsed : fallback;
     120                 :             : }
     121                 :             : 
     122                 :             : /// The decoded query items of an otpauth URI, in the order written.
     123                 :             : using QueryItems = QList<QPair<QString, QString>>;
     124                 :             : 
     125                 :             : /**
     126                 :             :  * @brief The value of a query parameter of an otpauth URI.
     127                 :             :  *
     128                 :             :  * Parameter names are matched without regard to case, as the list of
     129                 :             :  * names kept by unmodelledParams() is: read exactly, `Digits=8` was neither
     130                 :             :  * read nor kept, and toUri() wrote the defaults in its place. The first of a
     131                 :             :  * name wins, as QUrlQuery::queryItemValue() has it.
     132                 :             :  *
     133                 :             :  * @param items The URI's query items.
     134                 :             :  * @param name The parameter's name.
     135                 :             :  * @return Its value, or nothing when the URI has no such parameter.
     136                 :             :  */
     137                 :        2151 : auto firstParam(const QueryItems &items, QLatin1StringView name)
     138                 :             :     -> std::optional<QString> {
     139         [ +  + ]:        5429 :   for (const QPair<QString, QString> &item : items) {
     140         [ +  + ]:        4103 :     if (item.first.compare(name, Qt::CaseInsensitive) == 0) {
     141                 :             :       return item.second;
     142                 :             :     }
     143                 :             :   }
     144                 :        1326 :   return std::nullopt;
     145                 :             : }
     146                 :             : 
     147                 :             : /**
     148                 :             :  * @brief The query parameters of an otpauth URI that Totp does not model.
     149                 :             :  * @param items The URI's query items.
     150                 :             :  * @return Those items, as written, for toUri() to put back.
     151                 :             :  */
     152                 :         316 : auto unmodelledParams(const QueryItems &items) -> QueryItems {
     153                 :             :   // Anything we do not model is kept verbatim so toUri() can put it back;
     154                 :             :   // dropping it silently mutated URIs carrying e.g. `image=`.
     155                 :             :   static const QStringList known = {
     156                 :           6 :       QStringLiteral("secret"),    QStringLiteral("issuer"),
     157                 :           6 :       QStringLiteral("digits"),    QStringLiteral("period"),
     158                 :         358 :       QStringLiteral("algorithm"), QStringLiteral("encoder")};
     159                 :         316 :   QueryItems extra;
     160         [ +  + ]:        1036 :   for (const QPair<QString, QString> &item : items) {
     161         [ +  + ]:         720 :     if (!known.contains(item.first, Qt::CaseInsensitive)) {
     162                 :             :       extra.append(item);
     163                 :             :     }
     164                 :             :   }
     165                 :         316 :   return extra;
     166                 :             : }
     167                 :             : 
     168                 :             : /**
     169                 :             :  * @brief Read the settings an `otpauth://` URI carries.
     170                 :             :  * @param url The URI, already known to have the otpauth scheme.
     171                 :             :  * @param trimmed The text @p url was made from, for its fragment.
     172                 :             :  * @param settings Receives everything but the key.
     173                 :             :  * @param rawSecret Receives the `secret` parameter as written.
     174                 :             :  * @return Refusal::None, or why the URI cannot give a code.
     175                 :             :  */
     176                 :         419 : auto readOtpauthUri(const QUrl &url, const QString &trimmed,
     177                 :             :                     Totp::Settings &settings, QString &rawSecret)
     178                 :             :     -> Totp::Refusal {
     179                 :             :   // Counter-based HOTP cannot be generated from a clock; refuse rather than
     180                 :             :   // return a wrong code that looks right.
     181         [ +  + ]:         838 :   if (url.host().compare(QStringLiteral("totp"), Qt::CaseInsensitive) != 0) {
     182                 :         104 :     return url.host().compare(QStringLiteral("hotp"), Qt::CaseInsensitive) == 0
     183         [ +  + ]:          52 :                ? Totp::Refusal::Hotp
     184                 :             :                : Totp::Refusal::UnreadableUri;
     185                 :             :   }
     186                 :             : 
     187                 :         367 :   const QUrlQuery query(url);
     188                 :             :   // FullyDecoded, because toUri() percent-encodes these again: the default
     189                 :             :   // PrettyDecoded leaves escapes in place and the round trip double-encodes.
     190                 :         367 :   const QueryItems items = query.queryItems(QUrl::FullyDecoded);
     191                 :             :   const auto param = [&items](QLatin1StringView name) {
     192                 :        1050 :     return firstParam(items, name);
     193                 :             :   };
     194                 :         734 :   rawSecret = param(QLatin1StringView("secret")).value_or(QString());
     195                 :         734 :   settings.issuer = param(QLatin1StringView("issuer")).value_or(QString());
     196                 :             :   // Not part of the OTP configuration, but the user's text: kept as written,
     197                 :             :   // from the input itself (QUrl splits at the first '#' as well, but its
     198                 :             :   // view would re-encode '%' and '`' and decode escapes).
     199      [ +  +  + ]:         367 :   if (url.hasFragment()) {
     200                 :          34 :     settings.fragment = trimmed.mid(trimmed.indexOf(QLatin1Char('#')) + 1);
     201                 :             :   }
     202                 :             :   // The label is everything after the host, e.g. "/Example:alice".
     203                 :         367 :   settings.label = url.path();
     204      [ +  +  + ]:         367 :   if (settings.label.startsWith(QLatin1Char('/'))) {
     205                 :         364 :     settings.label.remove(0, 1);
     206                 :             :   }
     207                 :             :   // toUInt() returns 0 with no error signal for anything non-numeric, and the
     208                 :             :   // clamp below would turn that into digits=1 / step=1 — a one-character code
     209                 :             :   // rotating every second, which normalize() would then persist. Keep the RFC
     210                 :             :   // default unless the value really is a usable number.
     211                 :         367 :   settings.digits =
     212                 :         734 :       parsePositiveUInt(param(QLatin1StringView("digits")).value_or(QString()),
     213                 :             :                         Totp::DEFAULT_DIGITS);
     214                 :         367 :   settings.step =
     215                 :         734 :       parsePositiveUInt(param(QLatin1StringView("period")).value_or(QString()),
     216                 :             :                         Totp::DEFAULT_STEP);
     217                 :             :   // An empty value is the default, as an absent one is. An unknown hash
     218                 :             :   // function is refused, as HOTP is: its code cannot be made here.
     219                 :         367 :   if (const std::optional<QString> algorithm =
     220                 :         367 :           param(QLatin1StringView("algorithm"));
     221   [ +  +  +  +  :         585 :       algorithm.has_value() && !algorithm->trimmed().isEmpty()) {
                   +  + ]
     222                 :         103 :     const std::optional<Totp::Algorithm> known = algorithmByName(*algorithm);
     223         [ +  + ]:         103 :     if (!known.has_value()) {
     224                 :          51 :       return Totp::Refusal::UnknownAlgorithm;
     225                 :             :     }
     226                 :          52 :     settings.algorithm = *known;
     227                 :             :   }
     228                 :         632 :   if (param(QLatin1StringView("encoder"))
     229                 :         632 :           .value_or(QString())
     230                 :         632 :           .compare(QStringLiteral("steam"), Qt::CaseInsensitive) == 0) {
     231                 :           9 :     settings.encoder = Totp::Encoder::Steam;
     232                 :             :   }
     233                 :         316 :   settings.extraParams.append(unmodelledParams(items));
     234                 :         316 :   return Totp::Refusal::None;
     235                 :         367 : }
     236                 :             : 
     237                 :             : /**
     238                 :             :  * @brief Whether a text that is no otpauth URI is written as a base32
     239                 :             :  *        secret.
     240                 :             :  *
     241                 :             :  * Base32::sanitizeInput() drops what is not base32, so a URI of another
     242                 :             :  * scheme (a Google Authenticator export, otpauth-migration://...?data=...,
     243                 :             :  * steam://), zbarimg output with its "QR-Code:" prefix, or a secret with a
     244                 :             :  * remark in brackets would become a secret made of its leftover letters,
     245                 :             :  * with a confident, wrong code. Only what a secret is written with passes:
     246                 :             :  * letters, the digits sanitizeInput() reads (0, 1 and 8 as O, L and B),
     247                 :             :  * white space, "=" padding, and dashes, dots or underscores between groups
     248                 :             :  * (JBSW.Y3DP..., as some services show it), which it drops.
     249                 :             :  *
     250                 :             :  * @param text The trimmed text.
     251                 :             :  * @return true when every character may be part of a written secret.
     252                 :             :  */
     253                 :         337 : auto isWrittenAsSecret(const QString &text) -> bool {
     254         [ +  + ]:       13935 :   return std::all_of(text.cbegin(), text.cend(), [](QChar c) {
     255                 :             :     const char16_t u = c.unicode();
     256         [ +  + ]:       13887 :     return c.isSpace() || u == u'-' || u == u'=' || u == u'.' || u == u'_' ||
     257         [ +  + ]:       13935 :            (u >= u'A' && u <= u'Z') || (u >= u'a' && u <= u'z') ||
     258                 :       13935 :            (u >= u'0' && u <= u'8');
     259                 :         337 :   });
     260                 :             : }
     261                 :             : 
     262                 :             : } // namespace
     263                 :             : 
     264                 :         775 : auto Totp::parse(const QString &config, Refusal *why)
     265                 :             :     -> std::optional<Settings> {
     266                 :             :   const auto refuse = [why](Refusal reason) -> std::optional<Settings> {
     267   [ +  +  +  +  :         369 :     if (why != nullptr) {
          +  +  +  +  +  
                +  +  + ]
     268                 :         285 :       *why = reason;
     269                 :             :     }
     270                 :         369 :     return std::nullopt;
     271                 :             :   };
     272         [ +  + ]:         775 :   if (why != nullptr) {
     273                 :         469 :     *why = Refusal::None;
     274                 :             :   }
     275                 :             :   // Checked before anything else sees it (trimmed() copies it, QUrl and
     276                 :             :   // QUrlQuery would make a crafted URI of tens of MiB tens of millions of
     277                 :             :   // query items on the GUI thread); padding counts too.
     278         [ +  + ]:         775 :   if (config.size() > MAX_CONFIG_LENGTH) {
     279                 :             :     return refuse(Refusal::TooLong);
     280                 :             :   }
     281                 :             :   const QString trimmed = config.trimmed();
     282         [ +  + ]:         770 :   if (trimmed.isEmpty()) {
     283                 :             :     return refuse(Refusal::Empty);
     284                 :             :   }
     285                 :             : 
     286                 :         762 :   Settings settings;
     287                 :         762 :   QString rawSecret;
     288                 :             : 
     289                 :         762 :   const QUrl url(trimmed);
     290   [ +  +  +  +  :        2274 :   if (url.isValid() && url.scheme().compare(QStringLiteral("otpauth"),
          +  +  +  +  +  
                +  +  + ]
     291                 :             :                                             Qt::CaseInsensitive) == 0) {
     292                 :         419 :     const Refusal unread = readOtpauthUri(url, trimmed, settings, rawSecret);
     293         [ +  + ]:         419 :     if (unread != Refusal::None) {
     294                 :             :       return refuse(unread);
     295                 :             :     }
     296      [ +  +  + ]:         686 :   } else if (trimmed.startsWith(QStringLiteral("otpauth:"),
     297                 :             :                                 Qt::CaseInsensitive)) {
     298                 :             :     // Claims to be an otpauth URI but QUrl could not parse it. Falling through
     299                 :             :     // to the bare-secret branch would hand the whole string to
     300                 :             :     // Base32::sanitizeInput(), which strips the punctuation and leaves
     301                 :             :     // decodable base32 — producing a confidently wrong code. Refuse instead.
     302                 :             :     return refuse(Refusal::UnreadableUri);
     303                 :             :   } else {
     304                 :             :     // Not an otpauth URI: a bare base32 secret.
     305         [ +  + ]:         337 :     if (!isWrittenAsSecret(trimmed)) {
     306                 :             :       return refuse(Refusal::NotASecret);
     307                 :             :     }
     308                 :         205 :     rawSecret = trimmed;
     309                 :             :   }
     310                 :             : 
     311                 :         521 :   const QByteArray sanitized = Base32::sanitizeInput(rawSecret.toLatin1());
     312                 :        1042 :   settings.key = Base32::decode(sanitized);
     313         [ +  + ]:         521 :   if (settings.key.isEmpty()) {
     314                 :             :     return refuse(Refusal::NoSecret);
     315                 :             :   }
     316                 :           0 :   settings.base32Key = QString::fromLatin1(sanitized);
     317                 :             : 
     318         [ +  + ]:         406 :   if (settings.encoder == Encoder::Steam) {
     319                 :           9 :     settings.digits = STEAM_DIGITS;
     320                 :             :   }
     321                 :             :   // Clamp on every path: an out-of-range `digits` would otherwise overflow the
     322                 :             :   // modulus, and a zero `step` would divide by zero.
     323                 :         406 :   settings.digits = qBound(MIN_DIGITS, settings.digits, MAX_DIGITS);
     324                 :         406 :   settings.step = qBound(1U, settings.step, MAX_STEP);
     325                 :             : 
     326                 :             :   return settings;
     327                 :        1524 : }
     328                 :             : 
     329                 :         287 : auto Totp::describe(Refusal why) -> QString {
     330   [ +  +  +  +  :         287 :   switch (why) {
                +  +  + ]
     331                 :           1 :   case Refusal::TooLong:
     332                 :             :     //: OTP is a one-time password (a two-factor code).
     333                 :             :     return QCoreApplication::translate("Totp",
     334                 :           1 :                                        "The OTP configuration is too long.");
     335                 :           2 :   case Refusal::Hotp:
     336                 :             :     //: Keep HOTP and TOTP as written: they are the names of the two kinds.
     337                 :             :     return QCoreApplication::translate(
     338                 :             :         "Totp", "This is a counter-based (HOTP) configuration. QtPass makes "
     339                 :           2 :                 "time-based (TOTP) codes only.");
     340                 :          35 :   case Refusal::UnknownAlgorithm:
     341                 :             :     //: Keep otpauth://, SHA1, SHA256 and SHA512 as written.
     342                 :             :     return QCoreApplication::translate(
     343                 :             :         "Totp", "The algorithm in this otpauth:// link is not supported. "
     344                 :          35 :                 "QtPass supports SHA1, SHA256 and SHA512.");
     345                 :          36 :   case Refusal::UnreadableUri:
     346                 :             :     //: Keep otpauth:// as written: it is the name of the link format.
     347                 :             :     return QCoreApplication::translate("Totp",
     348                 :          36 :                                        "This otpauth:// link cannot be read.");
     349                 :         108 :   case Refusal::NotASecret:
     350                 :             :     //: Keep TOTP and otpauth://totp/ as written.
     351                 :             :     return QCoreApplication::translate(
     352                 :         108 :         "Totp", "This is not a TOTP secret or an otpauth://totp/ link.");
     353                 :         102 :   case Refusal::NoSecret:
     354                 :             :     //: The secret is the shared key of the one-time password; keep base32.
     355                 :             :     return QCoreApplication::translate(
     356                 :         102 :         "Totp", "The secret is missing or is not valid base32.");
     357                 :             :   case Refusal::None:
     358                 :             :   case Refusal::Empty:
     359                 :             :     break;
     360                 :             :   }
     361                 :           3 :   return {};
     362                 :             : }
     363                 :             : 
     364                 :         143 : auto Totp::isValid(const QString &config) -> bool {
     365                 :         143 :   return parse(config).has_value();
     366                 :             : }
     367                 :             : 
     368                 :          81 : auto Totp::counter(const Settings &settings, quint64 unixTime) -> quint64 {
     369                 :          81 :   return unixTime / settings.step;
     370                 :             : }
     371                 :             : 
     372                 :          28 : auto Totp::secondsRemaining(const Settings &settings, quint64 unixTime)
     373                 :             :     -> uint {
     374                 :          28 :   return settings.step - static_cast<uint>(unixTime % settings.step);
     375                 :             : }
     376                 :             : 
     377                 :          53 : auto Totp::generate(const Settings &settings, quint64 unixTime) -> QString {
     378                 :          53 :   const quint64 bigEndianCounter = qToBigEndian(counter(settings, unixTime));
     379                 :             :   const QByteArray message(reinterpret_cast<const char *>(&bigEndianCounter),
     380                 :          53 :                            sizeof(bigEndianCounter));
     381                 :             : 
     382                 :             :   const QByteArray hmac = QMessageAuthenticationCode::hash(
     383   [ +  +  +  +  :         100 :       message, settings.key, cryptoHash(settings.algorithm));
                   -  + ]
     384         [ -  + ]:          53 :   if (hmac.size() < kMinHmacSize) {
     385                 :           0 :     return {};
     386                 :             :   }
     387                 :             : 
     388                 :             :   // RFC 4226 dynamic truncation. QByteArray elements are signed char, so every
     389                 :             :   // byte is widened through quint8: without that, any byte >= 0x80
     390                 :             :   // sign-extends and corrupts the assembled 31-bit value.
     391                 :             :   const int offset =
     392                 :          53 :       static_cast<quint8>(hmac.at(hmac.size() - 1)) & 0x0F; // NOLINT
     393                 :             :   const quint32 binary =
     394                 :          53 :       (static_cast<quint32>(static_cast<quint8>(hmac.at(offset)) & 0x7F)
     395                 :          53 :        << 24) |
     396                 :          53 :       (static_cast<quint32>(static_cast<quint8>(hmac.at(offset + 1))) << 16) |
     397                 :          53 :       (static_cast<quint32>(static_cast<quint8>(hmac.at(offset + 2))) << 8) |
     398                 :          53 :       static_cast<quint32>(static_cast<quint8>(hmac.at(offset + 3)));
     399                 :             : 
     400         [ +  + ]:          53 :   if (settings.encoder == Encoder::Steam) {
     401                 :             :     // Steam emits the least significant symbol first.
     402                 :           3 :     quint64 value = binary;
     403                 :           3 :     QString code;
     404                 :           3 :     code.reserve(static_cast<int>(STEAM_DIGITS));
     405         [ +  + ]:          18 :     for (uint i = 0; i < STEAM_DIGITS; ++i) {
     406                 :          15 :       code.append(QLatin1Char(kSteamAlphabet[value % kSteamAlphabetSize]));
     407                 :          15 :       value /= kSteamAlphabetSize;
     408                 :             :     }
     409                 :             :     return code;
     410                 :             :   }
     411                 :             : 
     412                 :             :   // Integer exponentiation into a quint64: pow() into a quint32 (as KeePassXC
     413                 :             :   // did) overflows at ten digits.
     414                 :             :   quint64 modulus = 1;
     415         [ +  + ]:         394 :   for (uint i = 0; i < settings.digits; ++i) {
     416                 :         344 :     modulus *= 10;
     417                 :             :   }
     418                 :         100 :   return QString::number(binary % modulus)
     419                 :          50 :       .rightJustified(static_cast<int>(settings.digits), QLatin1Char('0'));
     420                 :             : }
     421                 :             : 
     422                 :           2 : auto Totp::generateNow(const Settings &settings) -> QString {
     423                 :           2 :   return generate(settings, currentUnixTime());
     424                 :             : }
     425                 :             : 
     426                 :          43 : auto Totp::toUri(const Settings &settings) -> QString {
     427                 :             :   const QString label =
     428         [ +  + ]:          43 :       settings.label.isEmpty() ? QStringLiteral("QtPass") : settings.label;
     429                 :             :   // The Key-Uri-Format spec says the secret's base32 padding is omitted, and
     430                 :             :   // third-party importers reject or truncate `secret=...======`.
     431                 :             :   // sanitizeInput() re-adds padding when reading, so this round-trips.
     432                 :             :   const QString secret =
     433                 :          86 :       QString::fromLatin1(Base32::removePadding(settings.base32Key.toLatin1()));
     434         [ +  + ]:          43 :   QString uri = QStringLiteral("otpauth://totp/%1?secret=%2")
     435                 :          86 :                     .arg(encodeLabel(label), secret);
     436         [ +  + ]:          43 :   if (!settings.issuer.isEmpty()) {
     437                 :          22 :     uri += QStringLiteral("&issuer=%1").arg(encodeLabel(settings.issuer));
     438                 :             :   }
     439         [ +  + ]:          43 :   if (settings.algorithm != Algorithm::Sha1) {
     440                 :             :     uri +=
     441                 :          12 :         QStringLiteral("&algorithm=%1").arg(algorithmName(settings.algorithm));
     442                 :             :   }
     443                 :          43 :   uri += QStringLiteral("&digits=%1&period=%2")
     444                 :          43 :              .arg(settings.digits)
     445                 :          43 :              .arg(settings.step);
     446         [ +  + ]:          43 :   if (settings.encoder == Encoder::Steam) {
     447                 :           2 :     uri += QStringLiteral("&encoder=steam");
     448                 :             :   }
     449                 :             :   // Re-emit anything the parser did not model, so canonicalising an existing
     450                 :             :   // URI does not quietly discard parameters other authenticators honour.
     451         [ +  + ]:          46 :   for (const QPair<QString, QString> &item : settings.extraParams) {
     452                 :           6 :     uri += QStringLiteral("&%1=%2").arg(
     453                 :           6 :         QString::fromLatin1(QUrl::toPercentEncoding(item.first)),
     454                 :           6 :         QString::fromLatin1(QUrl::toPercentEncoding(item.second)));
     455                 :             :   }
     456         [ +  + ]:          43 :   if (!settings.fragment.isEmpty()) {
     457                 :          12 :     uri += QLatin1Char('#') + settings.fragment;
     458                 :             :   }
     459                 :          43 :   return uri;
     460                 :             : }
     461                 :             : 
     462                 :          56 : auto Totp::normalize(const QString &config, const QString &label,
     463                 :             :                      const QString &issuer) -> QString {
     464                 :          56 :   const std::optional<Settings> settings = parse(config);
     465         [ +  + ]:          56 :   if (!settings.has_value()) {
     466                 :          18 :     return {};
     467                 :             :   }
     468                 :          38 :   Settings canonical = *settings;
     469         [ +  + ]:          38 :   if (canonical.label.isEmpty()) {
     470                 :          16 :     canonical.label = label;
     471                 :             :   }
     472         [ +  + ]:          38 :   if (canonical.issuer.isEmpty()) {
     473                 :          30 :     canonical.issuer = issuer;
     474                 :             :   }
     475                 :             :   // Percent-encoding and the added fields can take a value near the length
     476                 :             :   // cap past it; a URI parse() refuses would store an OTP that makes no code.
     477                 :          38 :   QString uri = toUri(canonical);
     478         [ +  + ]:          38 :   if (uri.size() > MAX_CONFIG_LENGTH) {
     479                 :           1 :     return {};
     480                 :             :   }
     481                 :             :   return uri;
     482                 :          38 : }
     483                 :             : 
     484                 :          21 : auto Totp::currentUnixTime() -> quint64 {
     485                 :          21 :   return static_cast<quint64>(QDateTime::currentSecsSinceEpoch());
     486                 :             : }
        

Generated by: LCOV version 2.0-1