// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "HistoryManager.h" #include "../security/CryptoManager.h" #include "../security/SecretStore.h" #include "koutnet_chat_debug.h" #include #include #include #include #include #include #include #include #include namespace { // how much of the readable part of a chat id survives into the file name. A // room alias can be longer than a file name is allowed to be, and the digest is // what carries the identity, so the readable part is free to be cut. constexpr int kMaxStemChars = 48; // Hex characters of SHA-256. Forty-eight bits is far past the point where a // collision is a realistic way to lose a conversation. constexpr int kDigestChars = 12; // every log written by this build opens with these bytes; a plain JSON array // does not, which is how load() tells a file an older build left on disk from // one this build wrote. The trailing byte is a format version - a change to // the on-disk layout bumps it so an older build cannot misread a newer file. constexpr char kHistoryFileMagic[] = "KNHST1"; constexpr qsizetype kHistoryFileMagicLen = sizeof(kHistoryFileMagic) - 1; // SecretStore entry holding the app's own at-rest key, base64 of 32 bytes. Not // derived from a passphrase and not a peer's session key: history must be // readable after every peer is gone and must not depend on a passphrase the // user would have to type on every start. constexpr char kHistoryKeyStoreName[] = "history_key"; } // namespace HistoryManager::HistoryManager(QObject *parent) : QObject(parent) { QDir dir = historyDir(); dir.mkpath(QStringLiteral(".")); // the logs are private; a directory the umask leaves world-readable would // defeat the seal. mkpath() honors the umask, so tighten it explicitly. QFile::setPermissions(historyDir().absolutePath(), QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner); ensureHistoryKey(); } void HistoryManager::setHistorySavingEnabled(bool enabled) { if (m_savingEnabled == enabled) return; m_savingEnabled = enabled; Q_EMIT historySavingEnabledChanged(); } void HistoryManager::setMaxMessagesPerChat(int count) { const int bounded = qBound(50, count, 10000); if (m_maxMessagesPerChat == bounded) return; m_maxMessagesPerChat = bounded; Q_EMIT maxMessagesPerChatChanged(); } QDir HistoryManager::historyDir() const { const QString base = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); return QDir(base + QStringLiteral("/history")); } QString HistoryManager::legacyStemFor(const QString &chatId) { static const QRegularExpression unsafe(QStringLiteral("[^\\w\\-]")); QString safe = chatId; safe.replace(unsafe, QStringLiteral("_")); return safe; } QString HistoryManager::stemFor(const QString &chatId) { const QString safe = legacyStemFor(chatId); // nothing was replaced and the name is short enough to be one: this id is // already unique among file names. Returning it untouched is what keeps // every log written before the digest existed readable. if (safe == chatId && safe.size() <= kMaxStemChars) return safe; const QString digest = QString::fromLatin1(QCryptographicHash::hash(chatId.toUtf8(), QCryptographicHash::Sha256).toHex().left(kDigestChars)); return safe.left(kMaxStemChars) + QLatin1Char('-') + digest; } QString HistoryManager::filePathFor(const QString &chatId) { const QDir dir = historyDir(); const QString path = dir.filePath(stemFor(chatId) + QStringLiteral(".json")); if (m_namesChecked.contains(chatId)) return path; m_namesChecked.insert(chatId); const QString legacy = dir.filePath(legacyStemFor(chatId) + QStringLiteral(".json")); // A log that has stopped reading back is indistinguishable from a lost one, // so the file moves with the scheme rather than being abandoned by it. Once // per chat per run, and never over a file that is already there - two ids // that used to share a name cannot both claim it. if (legacy != path && QFile::exists(legacy) && !QFile::exists(path)) { if (!QFile::rename(legacy, path)) qCWarning(KOUTNET_LOG_CHAT) << "could not move" << legacy << "to" << path; } return path; } QVariantList HistoryManager::load(const QString &chatId) { QVariantList result; QFile f(filePathFor(chatId)); if (f.exists() && f.open(QIODevice::ReadOnly)) { const QByteArray raw = f.readAll(); f.close(); if (raw.startsWith(kHistoryFileMagic)) { if (ensureHistoryKey()) { QByteArray body; const QByteArray sealed = raw.mid(kHistoryFileMagicLen); if (koutnet::CryptoManager::openAtRest(m_historyKey, sealed, &body)) { QJsonParseError err; const QJsonDocument doc = QJsonDocument::fromJson(body, &err); if (doc.isArray()) { result = doc.array().toVariantList(); } else { m_unreadable.insert(chatId); qCWarning(KOUTNET_LOG_CHAT) << "refusing to overwrite unreadable" << f.fileName() << err.errorString(); } } else { // Tampered, or a key the wallet no longer has: still the // user's log, so never write over it. m_unreadable.insert(chatId); qCWarning(KOUTNET_LOG_CHAT) << "refusing to overwrite a log that would not open" << f.fileName(); } } else { // no key and no store: the sealed file stays unreadable for // this run, and untouched - the banner says why. m_unreadable.insert(chatId); } } else { // A plain JSON array: a log an older build wrote in the clear. QJsonParseError err; const QJsonDocument doc = QJsonDocument::fromJson(raw, &err); if (doc.isArray()) { result = doc.array().toVariantList(); // Seal it now, so the disk stops carrying the conversation // readable. Reading and rewriting the same list cannot lose a // message even if the parse was lossy in both directions. if (ensureHistoryKey()) writeEncryptedTo(f.fileName(), result); } else if (!raw.trimmed().isEmpty()) { // still the user's log: never write over the file again m_unreadable.insert(chatId); qCWarning(KOUTNET_LOG_CHAT) << "refusing to overwrite unreadable" << f.fileName() << err.errorString(); } } } return result; } void HistoryManager::append(const QString &chatId, const QVariantMap &entry) { if (!m_savingEnabled) return; QVariantList msgs = load(chatId); msgs.append(entry); if (msgs.size() > m_maxMessagesPerChat) msgs = msgs.mid(msgs.size() - m_maxMessagesPerChat); writeChatFile(chatId, msgs); Q_EMIT historyAppended(chatId, entry); } void HistoryManager::replaceAll(const QString &chatId, const QVariantList &entries) { if (!m_savingEnabled) return; QVariantList msgs = entries; if (msgs.size() > m_maxMessagesPerChat) msgs = msgs.mid(msgs.size() - m_maxMessagesPerChat); // load() first, for a chat this process has not read yet: reading is what // discovers a file that will not parse, and writeChatFile() refuses those load(chatId); writeChatFile(chatId, msgs); } void HistoryManager::writeChatFile(const QString &chatId, const QVariantList &msgs) { if (m_unreadable.contains(chatId)) return; writeEncryptedTo(filePathFor(chatId), msgs); } void HistoryManager::writeEncryptedTo(const QString &path, const QVariantList &msgs) { if (!ensureHistoryKey()) return; // degraded store: never put a readable log on the disk // QSaveFile because a crash halfway through the old QFile write left the // chat truncated. The body may be large enough to matter, so it is sealed // first and written as one blob; the permissions are locked down before // commit() renames the temp file into place. QSaveFile f(path); if (!f.open(QIODevice::WriteOnly)) { qCWarning(KOUTNET_LOG_CHAT) << "failed to write" << path << f.errorString(); return; } f.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner); const QByteArray body = QJsonDocument(QJsonArray::fromVariantList(msgs)).toJson(QJsonDocument::Compact); f.write(kHistoryFileMagic, kHistoryFileMagicLen); f.write(koutnet::CryptoManager::sealAtRest(m_historyKey, body)); if (!f.commit()) qCWarning(KOUTNET_LOG_CHAT) << "commit failed" << path << f.errorString(); } bool HistoryManager::ensureHistoryKey() { if (m_historyKeyValid) return true; if (m_storeUnavailable) return false; // already reported; do not re-banner per message const bool before = historyEncryptionAvailable(); if (!koutnet::SecretStore::isAvailable()) { m_storeUnavailable = true; } else { QString stored; if (koutnet::SecretStore::read(QLatin1String(kHistoryKeyStoreName), &stored) && !stored.isEmpty()) { m_historyKey = QByteArray::fromBase64(stored.toLatin1()); // A wrong-length key cannot be sealed under and would fail every // open; regenerate rather than store a second copy by hand. if (m_historyKey.size() == koutnet::CryptoManager::kKeyLen) m_historyKeyValid = true; else m_historyKey.clear(); } if (m_historyKey.isEmpty()) { m_historyKey = koutnet::CryptoManager::generateAtRestKey(); if (koutnet::SecretStore::write(QLatin1String(kHistoryKeyStoreName), QString::fromLatin1(m_historyKey.toBase64()))) m_historyKeyValid = true; else { m_historyKey.clear(); m_storeUnavailable = true; } } } if (historyEncryptionAvailable() != before) { Q_EMIT historyEncryptionChanged(); if (!historyEncryptionAvailable()) Q_EMIT historyStoreUnavailable(koutnet::SecretStore::lastError()); } return historyEncryptionAvailable(); } void HistoryManager::migratePlaintextHistory() { if (m_migrationRan) return; m_migrationRan = true; if (!ensureHistoryKey()) return; const QDir dir = historyDir(); const QFileInfoList files = dir.entryInfoList({QStringLiteral("*")}, QDir::Files, QDir::Name); int sealed = 0; for (const QFileInfo &info : files) { const QString path = info.absoluteFilePath(); QFile f(path); if (!f.open(QIODevice::ReadOnly)) { qCWarning(KOUTNET_LOG_CHAT) << "could not read" << path << "during history migration"; continue; } const QByteArray raw = f.readAll(); f.close(); if (raw.startsWith(kHistoryFileMagic)) continue; // already sealed QJsonParseError err; const QJsonDocument doc = QJsonDocument::fromJson(raw, &err); if (err.error != QJsonParseError::NoError || !doc.isArray()) { // never overwrite a file this run cannot read back. qCWarning(KOUTNET_LOG_CHAT) << "leaving unparseable history file alone" << path << err.errorString(); continue; } writeEncryptedTo(path, doc.array().toVariantList()); ++sealed; } if (sealed > 0) qCInfo(KOUTNET_LOG_CHAT) << "sealed" << sealed << "plaintext history file(s)"; } QVariantList HistoryManager::loadCallLog() { return load(QStringLiteral("__call_log__")); } void HistoryManager::addCall(const QVariantMap &entry) { append(QStringLiteral("__call_log__"), entry); } QVariantList HistoryManager::loadChatIndex() { return load(QStringLiteral("__chat_index__")); } void HistoryManager::saveChatIndex(const QVariantList &entries) { replaceAll(QStringLiteral("__chat_index__"), entries); }