// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "MatrixManager.h" #include #include "MatrixLoginUtils.h" #include "core/constructor/AppSettings.h" #include "core/security/SecretStore.h" #include "koutnet_matrix_debug.h" #include #include #include #include #include #include #include #include #include namespace { // Store entry for the Matrix access token. Flat, like every other name in the // KOutNet folder - see CryptoManager and AppSettings. QString tokenStoreKey(const QString &userId) { // one slot per account. A shared slot is how a sign-in as somebody else used // to hand the next session a token naming a different owner. return QStringLiteral("matrix_access_token_") + userId; } // the slot every install before per-account keys wrote to. Read for migration // and removed the first time anything clears or rewrites the session. const QString &legacyTokenStoreKey() { static const QString key = QStringLiteral("matrix_access_token"); return key; } // what the homeserver files this login under in the user's device list. QString deviceDisplayName() { return QStringLiteral("KOutNet"); } QString joinDetail(const QString &message, const QString &details) { return details.isEmpty() ? message : message + QLatin1Char(' ') + details; } } // namespace namespace koutnet { AppSettings *MatrixManager::settings() const { return m_settings; } MatrixManager::MatrixManager(AppSettings *settings, QObject *parent) : QObject(parent) , m_settings(settings) { m_loginTimeout.setSingleShot(true); m_loginTimeout.setInterval(kLoginTimeoutMs); connect(&m_loginTimeout, &QTimer::timeout, this, [this]() { if (m_state != State::Connecting) return; // with E2EE on, connected() comes only after libQuotient has unpickled // the Olm account, so a fresh login holding a token waits on the store, // not the network. Only for a fresh login: assumeIdentity() sets the token // before asking anyone, so a resume cannot be told apart this way. const bool serverAnswered = !m_resuming && m_connection && m_connection->isLoggedIn(); // the connection is deliberately left running. Aborting it here turned // one slow homeserver into a screenful of "stopped without ready network // reply", read for an hour as a network fault. The jobs finish or fail on // their own, and a late success is still accepted below. // // the pending credentials are not cleared either: the deferred lambdas in // login() gate on them, and erasing them made the late success unreachable. // Whichever lambda wakes last logs in the newest credentials. setState(State::Failed, serverAnswered ? i18nc("@info:status Matrix login stalled after the password was accepted", "The sign-in was accepted but the encryption keys could not be opened in time. " "Unlock the secret store if it is asking, and try again.") : i18nc("@info:status Matrix login failed", "The homeserver did not answer in time. Nothing was signed in; the attempt is still running and will report itself in the log.")); const QPointer attempt(m_connection); QTimer::singleShot(kLoginAbandonMs, this, [this, attempt]() { // only if this same attempt is still the current one and still has // not produced anything; a login that came good owns the slot now. if (m_connection == nullptr || m_connection != attempt || m_state != State::Failed) return; retireConnection(QStringLiteral("the login attempt was given up on after it stopped answering")); }); }); m_syncTimeout.setSingleShot(true); m_syncTimeout.setInterval(kSyncTimeoutMs); connect(&m_syncTimeout, &QTimer::timeout, this, &MatrixManager::onSyncDeadline); // the SSO browser flow ends with the homeserver sending the browser to // koutnet://sso?state=...&loginToken=...; registering here routes that click // into onSsoRedirect(). The state tells a genuine callback from a forged link. QDesktopServices::setUrlHandler(QStringLiteral("koutnet"), this, "onSsoRedirect"); } MatrixManager::~MatrixManager() = default; bool MatrixManager::loggedIn() const { return m_state == State::Syncing || m_state == State::Online || m_state == State::Reconnecting; } bool MatrixManager::busy() const { return m_state == State::Connecting; } bool MatrixManager::encryptionActive() const { return m_connection && m_connection->encryptionEnabled(); } QString MatrixManager::userId() const { return m_connection ? m_connection->userId() : QString(); } QString MatrixManager::homeserver() const { return m_connection ? m_connection->homeserver().toString() : QString(); } QString MatrixManager::statusText() const { switch (m_state) { case State::LoggedOut: return i18nc("@info:status Matrix connection state", "Not signed in"); case State::Connecting: return i18nc("@info:status Matrix connection state", "Signing in..."); case State::Syncing: return i18nc("@info:status Matrix connection state", "Syncing..."); case State::Online: return i18nc("@info:status Matrix connection state, %1 is a Matrix user id", "Signed in as %1", userId()); case State::Reconnecting: return m_lastError.isEmpty() ? i18nc("@info:status Matrix connection state", "Reconnecting...") : i18nc("@info:status Matrix connection state, %1 is what the homeserver or the network reported", "Reconnecting after: %1", m_lastError); case State::Failed: break; } return m_lastError.isEmpty() ? i18nc("@info:status Matrix connection state", "Sign-in failed") : m_lastError; } void MatrixManager::setState(State state, const QString &error) { if (m_state == state && m_lastError == error) return; // only the states that mean something went wrong are announced; the status // line carries the rest, and a notification per reconnect is noise. const bool announce = !error.isEmpty() && (state == State::Failed || state == State::Reconnecting); m_state = state; m_lastError = error; if (!error.isEmpty()) qCWarning(KOUTNET_LOG_MATRIX) << "matrix session:" << error; Q_EMIT stateChanged(); // after stateChanged() so that whatever reads the manager while showing the // message already agrees with it. if (announce) Q_EMIT sessionError(error); } Quotient::Connection *MatrixManager::makeConnection() { retireConnection(QStringLiteral("a new session is starting")); auto *c = new Quotient::Connection(this); // before anything else, and before any login: enableEncryption() refuses once // the connection holds a token, and says so only in a warning nobody reads. c->enableEncryption(true); // left alone deliberately: whether a new direct chat is created encrypted is // a decision this build does not make yet, since it does not create them. // without the cache every start is a full initial sync of every room. c->setCacheState(true); c->setLazyLoading(true); connect(c, &Quotient::Connection::connected, this, &MatrixManager::onConnected); // libQuotient turns encryption off when the key store cannot be set up. // The session carries on unencrypted, which is survivable but must not be // silent: everything downstream draws from encryptionActive(). connect(c, &Quotient::Connection::encryptionChanged, this, [this](bool enabled) { Q_EMIT encryptionActiveChanged(); if (enabled) return; // Reported rather than made a state: the session still works and the // state machine has nowhere honest to put "signed in but unencrypted". const QString message = i18nc("@info:status the Matrix session could not set up its encryption key store", "Encryption could not be started for this session, so encrypted rooms will stay unreadable. " "This usually means the secret store could not be opened."); qCWarning(KOUTNET_LOG_MATRIX) << "matrix session:" << message; Q_EMIT sessionError(message); }); // the account has no cross-signing keys - fresh, or reset. Until the master, // self-signing and user-signing keys exist, other devices send us no room keys. connect(c, &Quotient::Connection::crossSigningSetupRequired, this, [this]() { qCInfo(KOUTNET_LOG_MATRIX) << "cross-signing keys not found; setup required"; Q_EMIT crossSigningRequired(); }); connect(c, &Quotient::Connection::loginError, this, [this](const QString &message, const QString &details) { m_pendingUser.clear(); m_pendingPassword.clear(); m_loginTimeout.stop(); m_syncTimeout.stop(); const bool wasResume = m_resuming; m_resuming = false; const QString detail = joinDetail(message, details); retireConnection(QStringLiteral("the homeserver rejected the sign-in")); if (!wasResume) { setState(State::Failed, detail); return; } // the homeserver answered no, so the stored session is wrong. Kept, it // would be retried on every start and fail the same way in silence. clearStoredSession(); setState(State::Failed, i18nc("@info:status a stored Matrix session was refused, %1 is what the homeserver said", "The saved sign-in is no longer accepted (%1). Sign in again.", detail)); }); connect(c, &Quotient::Connection::resolveError, this, [this](const QString &error) { m_pendingUser.clear(); m_pendingPassword.clear(); m_loginTimeout.stop(); m_syncTimeout.stop(); m_resuming = false; retireConnection(QStringLiteral("the homeserver address could not be resolved")); setState(State::Failed, error); }); connect(c, &Quotient::Connection::syncDone, this, [this]() { m_syncTimeout.stop(); m_lastSyncError.clear(); if (m_resuming) { // the first completed sync is the only proof a resumed token is good // (see m_resuming), so the session is confirmed here, not on connected(). m_resuming = false; storeSession(); } setState(State::Online); }); connect(c, &Quotient::Connection::syncError, this, [this](const QString &message, const QString &details) { m_lastSyncError = joinDetail(message, details); qCWarning(KOUTNET_LOG_MATRIX) << "sync error" << m_lastSyncError; // not a failure by itself: libQuotient retries, and a dropped wifi must // not throw away a good token. The state moves; the deadline decides. if (m_state == State::Online || m_state == State::Reconnecting) setState(State::Reconnecting, m_lastSyncError); if (!m_syncTimeout.isActive()) armSyncDeadline(); }); connect(c, &Quotient::Connection::loggedOut, this, [this]() { // Reached when the homeserver ends the session on its own - a token // revoked from another device. Our own logout() detaches first. clearStoredSession(); retireConnection(QStringLiteral("the homeserver ended the session")); // left in Failed rather than moved on to LoggedOut: the two look the same // to the sign-in page except that Failed still carries the reason. setState(State::Failed, i18nc("@info:status", "The homeserver signed this device out.")); }); m_connection = c; Q_EMIT connectionChanged(); // the connection object is what encryptionActive() reads, so replacing or // dropping it moves that answer too. Q_EMIT encryptionActiveChanged(); return c; } void MatrixManager::retireConnection(const QString &why) { if (!m_connection) return; auto *c = m_connection; m_connection = nullptr; // Printed before the abort: stopping the connection makes libQuotient log // every job in flight as "stopped without ready network reply". qCInfo(KOUTNET_LOG_MATRIX).noquote() << QStringLiteral("closing the Matrix connection -") << why << QStringLiteral("- any 'stopped without ready network reply' below is this cleanup, not the homeserver"); c->disconnect(this); c->stopSync(); c->deleteLater(); Q_EMIT profileChanged(); Q_EMIT connectionChanged(); Q_EMIT encryptionActiveChanged(); } void MatrixManager::armSyncDeadline() { m_syncTimeout.start(); } void MatrixManager::onSyncDeadline() { if (m_state != State::Syncing && m_state != State::Reconnecting) return; const QString reason = m_lastSyncError.isEmpty() ? i18nc("@info:status Matrix sync gave up with nothing reported", "The homeserver stopped answering; no messages are arriving.") : i18nc("@info:status Matrix sync gave up, %1 is what libQuotient reported", "Syncing failed: %1", m_lastSyncError); retireConnection(QStringLiteral("no sync completed before the deadline")); // the stored session stays. A network that went away is not a token that was // revoked, and the next start should be allowed to try it. setState(State::Failed, reason); } bool MatrixManager::keyBackupAvailable() const { // the backup lives in account data, one event, and the lookup is cached; // an absent backup is an empty object, which accountDataJson() reports as "{}". return m_connection != nullptr && !m_connection->accountDataJson(QStringLiteral("m.megolm_backup.v1")).isEmpty(); } bool MatrixManager::isKeyBackupUnlocked() const { return m_connection != nullptr && m_keyBackupUnlocked; } void MatrixManager::unlockKeyBackup(const QString &recoveryKeyOrPassphrase) { auto *connection = m_connection; if (connection == nullptr) return; // A recovery key and a passphrase share one field. A key has a fixed shape // (twelve groups of four base58 chars), so the matching call is tried first // and the other falls back, which saves the deliberate miss most times. const bool tryAsKey = matrix::looksLikeRecoveryKey(recoveryKeyOrPassphrase); auto *handler = new Quotient::SSSSHandler(); handler->setConnection(connection); connect(handler, &Quotient::SSSSHandler::keyBackupUnlocked, this, [this, handler]() { m_keyBackupUnlocked = true; Q_EMIT keyBackupUnlocked(); connect(handler, &Quotient::SSSSHandler::finished, handler, &QObject::deleteLater); }); connect(handler, &Quotient::SSSSHandler::error, this, [this, handler, recoveryKeyOrPassphrase, tryAsKey]() { // one retry as the other interpretation of the field, then report. The // first tap is disconnected so the second error reaches only the report. disconnect(handler, &Quotient::SSSSHandler::error, this, nullptr); if (recoveryKeyOrPassphrase.isEmpty()) { Q_EMIT keyBackupFailed(i18nc("@info:status", "No recovery key or passphrase was given.")); handler->deleteLater(); return; } connect(handler, &Quotient::SSSSHandler::error, this, [this, handler]() { Q_EMIT keyBackupFailed(i18nc("@info:status", "That did not unlock the room key backup.")); handler->deleteLater(); }); if (tryAsKey) handler->unlockSSSSWithPassphrase(recoveryKeyOrPassphrase); else handler->unlockSSSSFromSecurityKey(recoveryKeyOrPassphrase); }); if (recoveryKeyOrPassphrase.isEmpty()) handler->unlockSSSSFromCrossSigning(); else if (tryAsKey) handler->unlockSSSSFromSecurityKey(recoveryKeyOrPassphrase); else handler->unlockSSSSWithPassphrase(recoveryKeyOrPassphrase); } void MatrixManager::login(const QString &homeserverUrl, const QString &userIdOrLocalpart, const QString &password) { if (userIdOrLocalpart.isEmpty() || password.isEmpty()) { setState(State::Failed, i18nc("@info:status Matrix login", "A user name and a password are needed.")); return; } m_resuming = false; m_lastSyncError.clear(); m_syncTimeout.stop(); auto *c = makeConnection(); setState(State::Connecting); m_loginTimeout.start(); // resolveServer handles the .well-known delegation that setHomeserver skips. // Given no server, the domain has to come out of the MXID, so a lone // homeserver is pasted back onto the user name first. const QString server = homeserverUrl.trimmed(); QString target = userIdOrLocalpart.trimmed(); if (!target.startsWith(QLatin1Char('@'))) target.prepend(QLatin1Char('@')); if (!target.contains(QLatin1Char(':')) && !server.isEmpty()) { QString host = server; host.remove(QStringLiteral("https://")); host.remove(QStringLiteral("http://")); while (host.endsWith(QLatin1Char('/'))) host.chop(1); target += QLatin1Char(':') + host; } if (!target.contains(QLatin1Char(':'))) { m_loginTimeout.stop(); retireConnection(QStringLiteral("no domain in the user id and no homeserver given")); setState(State::Failed, i18nc("@info:status Matrix login", "Give a homeserver, or write the user ID in full as @name:server.")); return; } // Delegation is followed when the user asked for it and when there is nothing // else: an empty homeserver leaves only the MXID's domain, which is exactly // what .well-known is for - see matrixFollowDelegation in the kcfg. const bool followDelegation = m_settings && m_settings->matrixFollowDelegation(); if (server.isEmpty() || followDelegation) { m_pendingUser = target; m_pendingPassword = password; connect( c, &Quotient::Connection::homeserverChanged, this, [this](const QUrl &) { if (!m_connection || m_pendingPassword.isEmpty()) return; const QString user = m_pendingUser; const QString pass = m_pendingPassword; m_pendingUser.clear(); m_pendingPassword.clear(); m_connection->loginWithPassword(user, pass, deviceDisplayName()); }, Qt::SingleShotConnection); c->resolveServer(target); return; } // an address typed by hand with delegation off is taken at its word. // matrix.org delegates to matrix-client.matrix.org, which some networks do // not carry while the plain domain answers. // // setHomeserver() plus a wait for the flows suppresses the lookup, and the // wait is load-bearing: with the flows not yet in, loginWithPassword() // resolves from the MXID and follows the record after all. QUrl base = QUrl::fromUserInput(server); if (base.scheme().isEmpty()) base.setScheme(QStringLiteral("https")); // Wait for the flows before logging in: loginWithPassword derives the server // from the MXID when they are not loaded, throwing away scheme and port. m_pendingUser = target; m_pendingPassword = password; // the first signal can contain an empty flow list. Wait for password auth. connect(c, &Quotient::Connection::loginFlowsChanged, this, [this, base]() { if (!m_connection || m_pendingPassword.isEmpty()) return; if (!m_connection->supportsPasswordAuth()) return; const QString user = m_pendingUser; const QString pass = m_pendingPassword; m_pendingUser.clear(); m_pendingPassword.clear(); m_connection->loginWithPassword(user, pass, deviceDisplayName()); Q_UNUSED(base); }); c->setHomeserver(base); } bool MatrixManager::resumeSession() { if (!m_settings) return false; const QString user = m_settings->matrixUserId(); const QString device = m_settings->matrixDeviceId(); const QString server = m_settings->matrixHomeserver(); if (user.isEmpty() || device.isEmpty()) return false; QString token; if ((!koutnet::SecretStore::read(tokenStoreKey(user), &token) || token.isEmpty()) && (!koutnet::SecretStore::read(legacyTokenStoreKey(), &token) || token.isEmpty())) { // the token is the session. Without it the recorded user id and device id // are litter that would make the interface claim a session that is gone. clearStoredSession(); setState(State::Failed, i18nc("@info:status a stored Matrix session could not be reopened", "The saved sign-in could not be read back from the secret store. Sign in again.")); return false; } m_resuming = true; m_lastSyncError.clear(); auto *c = makeConnection(); setState(State::Connecting); m_loginTimeout.start(); // A stored session never resolves anything: assumeIdentity() asks for no // login flow, so a valid base URL satisfies libQuotient and .well-known is // never reached. The address that worked last time is used again. if (!server.isEmpty()) { const QUrl base = QUrl::fromUserInput(server); if (base.isValid()) c->setHomeserver(base); } // Reaches connected() before the token has been shown to anybody. Everything // that treats the resume as unproven hangs off m_resuming. c->assumeIdentity(user, device, token); // A resumed token has never been shown to the homeserver, and a migrated one // may name another owner - the legacy store slot was shared. Ask whose token // this is before any sync: sending as the wrong account is worse. c->callApi().then(this, [this, c, user](const Quotient::GetTokenOwnerJob *job) { if (job->userId() == user || c != m_connection) return; qCWarning(KOUTNET_LOG_MATRIX) << "resumed token belongs to" << job->userId() << "but the configuration says" << user; retireConnection(QStringLiteral("the resumed session belongs to another account")); clearStoredSession(); setState(State::Failed, i18nc("@info:status %1 is the account the token belongs to, %2 the account the configuration expected", "The saved sign-in belongs to %1, not %2. Sign in again.", job->userId(), user)); }); return true; } QString MatrixManager::ssoLoginUrl(const QString &homeserverUrl) { QUrl base = QUrl::fromUserInput(homeserverUrl.trimmed()); if (base.scheme().isEmpty()) base.setScheme(QStringLiteral("https")); if (!base.isValid() || base.host().isEmpty()) return QString(); // the QML path calls this and then completeSsoLogin(), without // startSsoLogin(). The homeserver is kept with the URL for the token-only API. m_ssoHomeserver = base.toString(); // an unguessable state rides in the redirect; the homeserver echoes it back so // the loginToken can be tied to the attempt that started it. A koutnet://sso // callback from anywhere else carries no such state and is refused. m_ssoState = matrix::makeSsoState(); QUrl redirect(QStringLiteral("koutnet://sso")); QUrlQuery redirectQuery; redirectQuery.addQueryItem(QStringLiteral("state"), m_ssoState); redirect.setQuery(redirectQuery); // the redirect the homeserver is told to use; once SSO is done the browser // lands here with a loginToken we hand to loginWithToken(). return matrix::ssoRedirectUrl(base, redirect).toString(); } void MatrixManager::startSsoLogin(const QString &homeserverUrl) { const QString url = ssoLoginUrl(homeserverUrl); if (!url.isEmpty()) QDesktopServices::openUrl(QUrl(url)); } void MatrixManager::onSsoRedirect(const QUrl &url) { // A callback is worth a token only if it is the tail of an SSO attempt this // process started: the state comes back with it, and anything else is forged - // a web link, a script, another koutnet:// producer - trying to log this // session into an account its owner controls. A mismatch burns the state. if (m_ssoState.isEmpty()) { qCWarning(KOUTNET_LOG_MATRIX) << "an SSO callback arrived while no SSO attempt was pending - ignored"; return; } QString state; if (!matrix::ssoCallbackState(url, &state) || state != m_ssoState) { qCWarning(KOUTNET_LOG_MATRIX) << "an SSO callback carried the wrong state - refused"; m_ssoState.clear(); setState(State::Failed, i18nc("@info:status Matrix SSO login", "This sign-in link does not belong to a sign-in started from here. Start the sign-in again inside the app.")); return; } m_ssoState.clear(); // the homeserver appends loginToken to the redirect, in the query or the // fragment depending on the server, so try both. A fragment is raw query text, // and QUrlQuery would swallow the first key under a leading '?'. QString token = QUrlQuery(url).queryItemValue(QStringLiteral("loginToken")); if (token.isEmpty() && !url.fragment().isEmpty()) { QUrl fragment; fragment.setQuery(url.fragment()); token = QUrlQuery(fragment).queryItemValue(QStringLiteral("loginToken")); } if (!token.isEmpty()) loginWithToken(m_ssoHomeserver, token); } void MatrixManager::completeSsoLogin(const QString &token) { if (m_ssoHomeserver.isEmpty()) { setState(State::Failed, i18nc("@info:status Matrix SSO login", "Choose a homeserver before completing SSO sign-in.")); return; } // the flow was finished by hand; a callback that reaches the OS afterwards // must not be accepted as the same attempt a second time. m_ssoState.clear(); loginWithToken(m_ssoHomeserver, token); } void MatrixManager::loginWithToken(const QString &homeserverUrl, const QString &token) { if (token.isEmpty()) { setState(State::Failed, i18nc("@info:status Matrix SSO login", "A login token is needed to sign in.")); return; } m_resuming = false; m_lastSyncError.clear(); m_syncTimeout.stop(); auto *c = makeConnection(); setState(State::Connecting); m_loginTimeout.start(); // loginWithToken() cannot resolve a server, so the homeserver is set up front, // the way resumeSession() does for a stored access token. const QString server = homeserverUrl.trimmed(); if (!server.isEmpty()) { QUrl base = QUrl::fromUserInput(server); if (base.scheme().isEmpty()) base.setScheme(QStringLiteral("https")); c->setHomeserver(base); } c->loginWithToken(token, deviceDisplayName()); } QString MatrixManager::avatarUrl() const { if (!m_connection || !m_connection->user()) return {}; const QUrl url = m_connection->user()->avatarUrl(); return url.scheme() == QLatin1String("mxc") ? m_connection->makeMediaUrl(url).toString() : QString(); } QString MatrixManager::displayName() const { return m_connection && m_connection->user() ? m_connection->user()->displayname() : QString(); } void MatrixManager::setDisplayName(const QString &displayName) { if (!m_connection || !m_connection->user() || !loggedIn()) { Q_EMIT sessionError(i18nc("@info:status", "Sign in to a Matrix account to change the profile.")); return; } const QString trimmed = displayName.trimmed(); if (trimmed.isEmpty() || trimmed == this->displayName()) return; m_connection->user()->rename(trimmed); Q_EMIT profileChanged(); } void MatrixManager::setAvatar(const QString &localFilePath) { if (!m_connection || !m_connection->user() || !loggedIn()) { Q_EMIT sessionError(i18nc("@info:status", "Sign in to a Matrix account to change the avatar.")); return; } const QString path = localFilePath.startsWith(QStringLiteral("file://")) ? QUrl(localFilePath).toLocalFile() : localFilePath; if (path.isEmpty()) return; // Quotient uploads the file and sets the avatar URL on the account. m_connection->user()->setAvatar(path); } // A banner is not account data: Matrix has no profile field for a header // picture, and a state event would ask for room power a DM partner does not hold. // So the banner rides as a room message with KOutNet's own msgtype, sent to every // joined room; MatrixRoomBridge keeps it off the timeline. void MatrixManager::setBanner(const QString &localFilePath) { if (!m_connection || !loggedIn()) { Q_EMIT sessionError(i18nc("@info:status", "Sign in to a Matrix account to change the banner.")); return; } const QString path = localFilePath.startsWith(QStringLiteral("file://")) ? QUrl(localFilePath).toLocalFile() : localFilePath; if (path.isEmpty()) return; // One upload, many rooms: every room points at the same mxc://. No content // type is passed - an open device handed to uploadContent aborts the job, and // name-based sniffing yields the same type anyway. auto job = m_connection->uploadFile(path); connect(job.operator->(), &Quotient::BaseJob::success, this, [this, job]() { if (!m_connection) return; QJsonObject content; content.insert(QStringLiteral("msgtype"), QStringLiteral("im.koutnet.banner")); content.insert(QStringLiteral("body"), QStringLiteral("banner")); content.insert(QStringLiteral("url"), job->contentUri().toString()); for (Quotient::Room *room : m_connection->allRooms()) { if (room == nullptr || room->joinState() != Quotient::JoinState::Join) continue; room->postJson(QStringLiteral("m.room.message"), content); } }); } void MatrixManager::onConnected() { if (auto *user = m_connection->user()) { connect(user, &Quotient::User::defaultAvatarChanged, this, &MatrixManager::profileChanged, Qt::UniqueConnection); connect(user, &Quotient::User::defaultNameChanged, this, &MatrixManager::profileChanged, Qt::UniqueConnection); user->load(); auto *refresh = new QTimer(user); refresh->setInterval(60000); connect(refresh, &QTimer::timeout, user, &Quotient::User::load); refresh->start(); Q_EMIT profileChanged(); } m_loginTimeout.stop(); m_pendingUser.clear(); m_pendingPassword.clear(); if (!m_connection) return; // A resume has nothing new to write and nothing yet to confirm; its session // is stored again once a sync has proved the token still works. if (!m_resuming) storeSession(); // Reads whatever the last run cached, so the room list is on screen before // the first sync comes back. m_connection->loadState(); setState(State::Syncing); armSyncDeadline(); m_connection->syncLoop(); } void MatrixManager::storeSession() { if (!m_connection || !m_settings) return; const QString token = QString::fromUtf8(m_connection->accessToken()); if (!koutnet::SecretStore::write(tokenStoreKey(m_connection->userId()), token)) { // no fallback to the config file: the rest of the session is not written // either, so the next start asks again rather than finding half a session. Q_EMIT sessionNotPersisted(koutnet::SecretStore::lastError()); return; } m_settings->setMatrixUserId(m_connection->userId()); m_settings->setMatrixDeviceId(m_connection->deviceId()); m_settings->setMatrixHomeserver(m_connection->homeserver().toString()); m_settings->save(); // the pre-split slot, retired on the first successful write to the keyed one. koutnet::SecretStore::remove(legacyTokenStoreKey()); } void MatrixManager::clearStoredSession() { if (m_settings && !m_settings->matrixUserId().isEmpty()) koutnet::SecretStore::remove(tokenStoreKey(m_settings->matrixUserId())); koutnet::SecretStore::remove(legacyTokenStoreKey()); if (!m_settings) return; m_settings->setMatrixUserId(QString()); m_settings->setMatrixDeviceId(QString()); // the homeserver stays: it is not a secret and it is what the login form // should offer next time. m_settings->save(); } void MatrixManager::logout() { m_loginTimeout.stop(); m_syncTimeout.stop(); m_pendingUser.clear(); m_pendingPassword.clear(); m_resuming = false; m_lastSyncError.clear(); m_keyBackupUnlocked = false; // Local first, and whatever the homeserver does about it. Waiting for the // round trip left the button doing nothing against a server that never // answered: token and ids are gone before the network is asked. auto *c = m_connection; m_connection = nullptr; clearStoredSession(); setState(State::LoggedOut); Q_EMIT connectionChanged(); Q_EMIT encryptionActiveChanged(); if (!c) return; // Detached before it is asked anything: its signals steer the state above, // and a refused logout would otherwise put the interface back where it started. c->disconnect(this); // Politeness, so the token stops working on the homeserver too. Nothing // depends on the answer; the timer below covers a job that never finishes. c->logout(); const QPointer pending(c); QTimer::singleShot(kLogoutGraceMs, this, [pending]() { if (!pending) return; qCInfo(KOUTNET_LOG_MATRIX) << "the homeserver never acknowledged the sign-out; dropping the connection locally." << "The token may still be live server-side - revoke the KOutNet device from another client if that matters."; pending->stopSync(); pending->deleteLater(); }); } } // namespace koutnet