// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "MatrixLoginUtils.h" #include #include #include #include namespace koutnet::matrix { QUrl ssoRedirectUrl(const QUrl &homeserver, const QUrl &redirectUrl) { // the homeserver is taken as given: only the path and the one query // parameter are ours, so a homeserver the user typed with a trailing slash // or a path of its own still lands on the redirect endpoint. QUrl url = homeserver; url.setPath(QStringLiteral("/_matrix/client/r0/login/sso/redirect")); QUrlQuery query; query.addQueryItem(QStringLiteral("redirectUrl"), redirectUrl.toString()); url.setQuery(query); return url; } QString makeSsoState() { // 32 bytes of system randomness, hex-encoded: long enough to be unguessable, // and the hex alphabet keeps it out of URL quoting entirely. QByteArray raw(32, Qt::Uninitialized); QRandomGenerator::system()->fillRange(reinterpret_cast(raw.data()), raw.size() / int(sizeof(quint32))); return QString::fromLatin1(raw.toHex()); } bool ssoCallbackState(const QUrl &url, QString *outState) { QString state = QUrlQuery(url).queryItemValue(QStringLiteral("state")); if (state.isEmpty() && !url.fragment().isEmpty()) { // A fragment is raw query text; handing it to QUrlQuery with a leading // '?' would swallow the first key, so let QUrl parse "?key=value" itself. QUrl fragment; fragment.setQuery(url.fragment()); state = QUrlQuery(fragment).queryItemValue(QStringLiteral("state")); } if (state.isEmpty()) return false; if (outState) *outState = state; return true; } bool looksLikeRecoveryKey(const QString &candidate) { if (candidate.isEmpty()) return false; // Twelve groups, four characters each, dashes between - no other shape is a // valid recovery key, so a passphrase that happens to contain a dash is not // mistaken for one. The alphabet is base58 without the four characters a // human confuses: 0, O, I and l. const QStringList groups = candidate.split(QLatin1Char('-'), Qt::SkipEmptyParts); if (groups.size() != 12) return false; static const QRegularExpression group(QStringLiteral("^[1-9A-HJ-NP-Za-km-z]{4}$")); for (const QString &g : groups) { if (!group.match(g).hasMatch()) return false; } return true; } }