Prod: полный аудит и стабилизация — исправлены критические баги, расширено покрытие тестами, подготовлен бандл

- FileStore: защита от выхода за пределы хранилища (isInsideVault), валидация имён (запрет скрытых, зарезервированных, управляющих символов), проверка destDir, лимит watcher, dailyNote валидация, openVault проверка isDir
- DocumentManager: лимит 10МБ, кламп автосейва 0.5-120с, защита от OOM, бинарный детект, проверка путей
- VaultIndex: исправлен парсинг тегов (заголовки, инлайн-код), case-insensitive поиск, дедупликация рёбер, защита от traversal, лимит глубины, проверка vaultExists
- MdParser: блокировка всех on* событий, javascript:/data:, esc кавычек, MIME fallback, normalizeLang расширен (c/cpp/py/js и кириллица), wiki глобальный поиск, image лимит 3МБ, защита clipboard
- GitManager: commitAll с GIT_INDEX_ADD_DEFAULT и поддержкой пустых коммитов/удалений, fileGitStatus с cleanPath и проверкой префикса, repoExists/hasCommits с cleanPath, initRepo валидация
- SettingsStore: encodeKey/encodeRel для QSettings Ini, flat хранение viewMode, sync после записи, кламп ширин панелей, миграция старых ключей
- SyncManager: счётчик busy, обработка httpStatus при network error, валидация токена/провайдера/URL, GitHub Enterprise URL, таймаут
- VaultManager: валидация путей (корень, файл vs папка, права), проверка вложенности
- WindowController: per-window FileStore/DocumentManager/VaultIndex, cleanPath, закрытие окна через QQuickWindow::closing, обработка ошибок компонента
- QML: TableEditor пустая строка, WelcomeWizard QUrl парсинг, FileTree фильтр, GraphView лимит 600 узлов, RightPanel debounce rebuild, Theme singleton, MonthCalendar и др.
- Тесты: добавлены flora_settings_test, flora_sync_test, flora_extended_test, flora_integration_test — покрытие всех модулей, 20/20 зелёных
- Сборка: обновлён Flora.app (4.6М бинарь -> 173М бандл, ad-hoc подпись, проверен offscreen запуск, версия 0.0.1 + cmark 0.29 + libgit2 1.9)
- .gitignore: добавлены Testing/, coverage, gcda/gcov, __pycache__, .tmp, test-vault и др.
This commit is contained in:
2026-09-01 19:25:07 +03:00
parent 0858b48cb3
commit 95c03040c7
41 changed files with 3868 additions and 1098 deletions
+34 -17
View File
@@ -1,9 +1,8 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Flora
// Подтверждение удаления. Для непустой папки требуется двойное подтверждение:
// первое нажатие показывает предупреждение, второе — удаляет.
Dialog {
id: root
@@ -14,10 +13,11 @@ Dialog {
title: qsTr("Подтверждение")
modal: true
width: 420
width: 440
anchors.centerIn: parent
closePolicy: Dialog.NoAutoClose
standardButtons: Dialog.NoButton
background: Rectangle { color: Theme.surface; border.color: Theme.borderStrong; radius: 10 }
property bool armed: false
@@ -25,6 +25,7 @@ Dialog {
root.armed = false
deleteButton.text = qsTr("Удалить")
warnLabel.visible = false
warnBox.visible = false
}
onOpened: root.resetDialog()
@@ -33,38 +34,54 @@ Dialog {
anchors.fill: parent
spacing: 12
Label {
Row {
spacing: 10
Layout.fillWidth: true
wrapMode: Text.Wrap
text: root.message
Label { text: "\u26A0"; font.pixelSize: 20; color: Theme.warningText; visible: root.doubleConfirm }
Label {
width: parent.width - 30
wrapMode: Text.Wrap
text: root.message
color: Theme.text
font.pixelSize: 13
}
}
Label {
id: warnLabel
Rectangle {
id: warnBox
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: false
color: "#b00020"
text: qsTr("Внимание: папка содержит файлы. Они будут удалены безвозвратно.\n"
+ "Если вы уверены — нажмите «Точно удалить».")
color: Theme.warningBg
border.color: Theme.warningText
radius: 6
height: warnLabel.implicitHeight + 16
Label {
id: warnLabel
anchors.fill: parent
anchors.margins: 8
wrapMode: Text.Wrap
visible: false
color: Theme.warningText
text: qsTr("Внимание: папка содержит файлы. Они будут удалены безвозвратно.\nЕсли вы уверены — нажмите «Точно удалить».")
font.pixelSize: 11
}
}
RowLayout {
Layout.fillWidth: true
Item { Layout.fillWidth: true }
Button {
text: qsTr("Отмена")
onClicked: root.reject()
}
Button { text: qsTr("Отмена"); onClicked: root.reject() }
Button {
id: deleteButton
text: qsTr("Удалить")
highlighted: root.armed
palette.button: root.armed ? Theme.errorText : undefined
onClicked: {
if (root.doubleConfirm && !root.armed) {
root.armed = true
deleteButton.text = qsTr("Точно удалить")
warnLabel.visible = true
warnBox.visible = true
return
}
root.confirmed()
@@ -73,4 +90,4 @@ Dialog {
}
}
}
}
}
+18 -18
View File
@@ -1,8 +1,8 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Flora
// Диалог ввода имени (новый файл/папка, переименование).
Dialog {
id: root
@@ -15,27 +15,29 @@ Dialog {
title: dialogTitle
modal: true
width: 380
width: 400
anchors.centerIn: parent
closePolicy: Dialog.NoAutoClose
standardButtons: Dialog.NoButton
background: Rectangle { color: Theme.surface; border.color: Theme.borderStrong; radius: 10 }
ColumnLayout {
anchors.fill: parent
spacing: 10
spacing: 12
Label { text: dialogTitle; font.bold: true; color: Theme.text; font.pixelSize: 14 }
TextField {
id: nameField
Layout.fillWidth: true
placeholderText: qsTr("Введите имя…")
placeholderTextColor: Theme.textFaint
color: Theme.text
text: root.initialText
selectByMouse: true
// Русская клавиатура: первая буква — заглавная
inputMethodHints: Qt.ImhNoPredictiveText
Component.onCompleted: {
forceActiveFocus()
selectAll()
}
background: Rectangle { color: Theme.bgAlt; border.color: nameField.activeFocus ? Theme.accent : Theme.border; radius: 6 }
Component.onCompleted: { forceActiveFocus(); selectAll() }
onAccepted: root.tryConfirm()
onTextChanged: root.errorText = ""
}
@@ -44,21 +46,22 @@ Dialog {
id: errorLabel
Layout.fillWidth: true
visible: root.errorText.length > 0
color: "#b00020"
color: Theme.errorText
wrapMode: Text.Wrap
text: root.errorText
font.pixelSize: 11
padding: 6
background: Rectangle { visible: root.errorText.length>0; color: Theme.errorBg; radius: 6 }
}
RowLayout {
Layout.fillWidth: true
Item { Layout.fillWidth: true }
Button {
text: qsTr("Отмена")
onClicked: root.reject()
}
Button { text: qsTr("Отмена"); onClicked: root.reject() }
Button {
text: root.actionLabel
enabled: nameField.text.trim().length > 0
highlighted: true
onClicked: root.tryConfirm()
}
}
@@ -66,11 +69,8 @@ Dialog {
function tryConfirm() {
const n = nameField.text.trim()
if (n.length === 0) {
root.errorText = qsTr("Имя не может быть пустым.")
return
}
if (n.length === 0) { root.errorText = qsTr("Имя не может быть пустым."); return }
root.confirmed(n)
root.accept()
}
}
}
+52 -63
View File
@@ -1,9 +1,8 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Flora
// Диалог настройки провайдера синхронизации с пошаговой инструкцией,
// проверкой соединения и каталогом ошибок (ErrorCatalog в SyncManager).
Dialog {
id: root
@@ -22,6 +21,7 @@ Dialog {
height: 520
anchors.centerIn: parent
closePolicy: Dialog.CloseOnEscape | Dialog.CloseOnPressOutside
background: Rectangle { color: Theme.surface; border.color: Theme.borderStrong; radius: 10 }
function defaultUrl() {
switch (root.providerIndex) {
@@ -48,13 +48,14 @@ Dialog {
ColumnLayout {
anchors.fill: parent
spacing: 10
anchors.margins: 4
// Инструкция
Rectangle {
Layout.fillWidth: true
Layout.preferredHeight: 150
color: "#f4f6fa"
radius: 6
color: Theme.bgAlt
border.color: Theme.border
radius: 8
Flickable {
anchors.fill: parent
anchors.margins: 8
@@ -64,85 +65,80 @@ Dialog {
contentHeight: instText.implicitHeight
Text {
id: instText
width: parent.width
width: parent.width - 16
wrapMode: Text.Wrap
textFormat: Text.MarkdownText
color: "#333"
color: Theme.textSecondary
linkColor: Theme.accent
onLinkActivated: (url) => Qt.openUrlExternally(url)
text: root.providerIndex === 0
? "**Как подключить GitHub:**\n\n"
+ "1. Создайте токен: [github.com/settings/tokens](https://github.com/settings/tokens) — scope **repo** (классический) или Fine-grained с правом **Contents: Read and write**.\n"
+ "2. Создайте **пустой** репозиторий (без README/.gitignore — иначе конфликт истории): New repository.\n"
+ "3. Вставьте токен ниже и нажмите «Проверить».\n"
+ "4. Альтернатива — SSH-ключ (Подключение → SSH, доступно в Фазе 11)."
? "**Как подключить GitHub:**\n\n" + "1. Создайте токен: [github.com/settings/tokens](https://github.com/settings/tokens) — scope **repo**.\n" + "2. Создайте **пустой** репозиторий (без README).\n" + "3. Вставьте токен ниже и нажмите «Проверить».\n"
: root.providerIndex === 1
? "**Как подключить GitLab:**\n\n"
+ "1. Токен: Настройки → Access Tokens — scope **api** (или **read_repository** + **write_repository**).\n"
+ "2. Создайте **пустой** репозиторий в своём аккаунте/группе.\n"
+ "3. Для self-hosted: укажите адрес инстанса, например http://gitlab.local. Вставьте токен и нажмите «Проверить».\n"
+ "4. Альтернатива — SSH-ключ (доступно в Фазе 11)."
? "**Как подключить GitLab:**\n\n" + "1. Токен: Настройки → Access Tokens — scope **api**.\n" + "2. Создайте **пустой** репозиторий.\n" + "3. Для self-hosted: укажите адрес инстанса.\n"
: root.providerIndex === 2
? "**Как подключить Gitea:**\n\n"
+ "1. Токен: Настройки аккаунта → Приложения → **Создать новый токен** (scope **repo**).\n"
+ "2. Создайте **пустой** репозиторий на своём инстансе.\n"
+ "3. Укажите адрес инстанса (например http://localhost:3000), вставьте токен и нажмите «Проверить».\n"
+ "4. Альтернатива — SSH-ключ (доступно в Фазе 11)."
? "**Как подключить Gitea:**\n\n" + "1. Токен: Настройки → Приложения → **Создать новый токен** (scope **repo**).\n" + "2. Создайте **пустой** репозиторий.\n"
: root.providerIndex === 3
? "**Как подключить Nextcloud (WebDAV):**\n\n"
+ "1. Откройте приложение Files, создайте папку для синхронизации (например **Flora**).\n"
+ "2. Адрес WebDAV: https://ВАШ_ХОСТ/remote.php/dav/files/ВАШ_ЛОГИН/\n"
+ "3. Укажите логин и пароль аккаунта Nextcloud и нажмите «Проверить».\n"
+ "4. Рекомендуется создать пароль приложения в Настройках → Безопасность."
: "**Как подключить Syncthing:**\n\n"
+ "1. Установите и запустите Syncthing на этом устройстве.\n"
+ "2. API-ключ: Действия → Настройки → Показывать расширенное → API-ключ.\n"
+ "3. Адрес API по умолчанию: http://127.0.0.1:8384. Вставьте ключ и нажмите «Проверить».\n"
+ "4. Затем добавьте папку хранилища в Syncthing как обычную папку."
? "**Как подключить Nextcloud (WebDAV):**\n\n" + "1. Создайте папку для синхронизации (например **Flora**).\n" + "2. Адрес WebDAV: https://ВАШ_ХОСТ/remote.php/dav/files/ВАШ_ЛОГИН/\n" + "3. Укажите логин и пароль.\n"
: "**Как подключить Syncthing:**\n\n" + "1. Установите и запустите Syncthing.\n" + "2. API-ключ: Действия → Настройки → API-ключ.\n" + "3. Адрес по умолчанию: http://127.0.0.1:8384.\n"
}
}
}
// Поля
ColumnLayout {
Layout.fillWidth: true
spacing: 6
Label { text: qsTr("Адрес сервера") }
TextField { id: urlField; Layout.fillWidth: true }
Label {
visible: root.providerIndex === 3
text: qsTr("Логин (для WebDAV):")
Label { text: qsTr("Адрес сервера"); color: Theme.textSecondary; font.bold: true; font.pixelSize: 11 }
TextField {
id: urlField; Layout.fillWidth: true
placeholderTextColor: Theme.textFaint
color: Theme.text
background: Rectangle { color: Theme.bgAlt; border.color: urlField.activeFocus ? Theme.accent : Theme.border; radius: 6 }
}
Label { visible: root.providerIndex === 3; text: qsTr("Логин (для WebDAV):"); color: Theme.textSecondary; font.pixelSize: 11 }
TextField {
id: userField
Layout.fillWidth: true
visible: root.providerIndex === 3
placeholderText: qsTr("Логин Nextcloud")
placeholderTextColor: Theme.textFaint
color: Theme.text
background: Rectangle { color: Theme.bgAlt; border.color: userField.activeFocus ? Theme.accent : Theme.border; radius: 6 }
}
Label { text: tokenName() }
Label { text: tokenName(); color: Theme.textSecondary; font.bold: true; font.pixelSize: 11 }
TextField {
id: tokenField
Layout.fillWidth: true
echoMode: TextInput.Password
placeholderText: qsTr("Вставьте значение")
placeholderTextColor: Theme.textFaint
color: Theme.text
background: Rectangle { color: Theme.bgAlt; border.color: tokenField.activeFocus ? Theme.accent : Theme.border; radius: 6 }
}
}
// Результат / ошибка
Label {
id: resultLabel
Rectangle {
Layout.fillWidth: true
wrapMode: Text.Wrap
visible: text.length > 0
color: root.connected ? "green" : "#b00020"
visible: resultLabel.text.length > 0
color: root.connected ? Theme.successBg : Theme.errorBg
border.color: root.connected ? Theme.successText : Theme.errorText
radius: 6
height: resultLabel.implicitHeight + 12
Label {
id: resultLabel
anchors.fill: parent
anchors.margins: 6
wrapMode: Text.Wrap
visible: text.length > 0
color: root.connected ? Theme.successText : Theme.errorText
font.pixelSize: 11
}
}
Item { Layout.fillHeight: true }
RowLayout {
Layout.fillWidth: true
Button {
text: qsTr("Отмена")
onClicked: root.reject()
}
Button { text: qsTr("Отмена"); onClicked: root.reject() }
Item { Layout.fillWidth: true }
Button {
text: qsTr("Проверить соединение")
@@ -150,36 +146,29 @@ Dialog {
onClicked: {
resultLabel.text = ""
root.connected = false
syncManager.testConnection(root.providerIndex,
urlField.text, userField.text,
tokenField.text)
syncManager.testConnection(root.providerIndex, urlField.text, userField.text, tokenField.text)
}
}
Button {
text: qsTr("Сохранить")
highlighted: true
enabled: root.connected
onClicked: {
settingsStore.addProvider(root.providerName, {
url: urlField.text,
user: userField.text,
token: tokenField.text,
})
settingsStore.addProvider(root.providerName, { url: urlField.text, user: userField.text, token: tokenField.text })
root.saved(root.providerIndex)
root.accept()
}
}
}
BusyIndicator { visible: syncManager.busy; running: syncManager.busy; Layout.alignment: Qt.AlignHCenter }
}
Connections {
target: syncManager
function onConnectionResult(provider, ok, code, title, hint, raw) {
if (provider !== root.providerIndex)
return
if (provider !== root.providerIndex) return
root.connected = ok
resultLabel.text = ok
? qsTr("Соединение установлено. Нажмите «Сохранить».")
: title + (hint && hint.length > 0 ? "\n" + hint : "")
resultLabel.text = ok ? qsTr("Соединение установлено. Нажмите «Сохранить».") : title + (hint && hint.length > 0 ? "\n" + hint : "")
}
}
}
}
+37 -94
View File
@@ -1,10 +1,8 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Flora
// Редактор markdown-таблицы. По умолчанию 2×1.
// Справа — столбец «+» (добавить строку под строкой), снизу — ряд «+»
// (добавить столбец правее столбца). Полосы «+» растут вместе с таблицей.
Dialog {
id: root
@@ -16,44 +14,27 @@ Dialog {
anchors.centerIn: parent
closePolicy: Dialog.NoAutoClose
standardButtons: Dialog.NoButton
background: Rectangle { color: Theme.surface; border.color: Theme.borderStrong; radius: 10 }
property int rows: 1
property int cols: 2
property var cells: [] // плоский список строк (rows*cols)
property var cells: []
readonly property int cellW: 120
readonly property int cellH: 34
function ensureCells() {
while (cells.length < rows * cols)
cells.push("")
while (cells.length > rows * cols)
cells.pop()
}
function cell(r, c) {
const i = r * cols + c
return i < cells.length ? cells[i] : ""
}
function setCell(r, c, v) {
const i = r * cols + c
if (i < cells.length) cells[i] = v
}
function cell(r, c) { const i = r * cols + c; return i < cells.length ? cells[i] : "" }
function setCell(r, c, v) { const i = r * cols + c; if (i < cells.length) cells[i] = v }
function addRowAfter(r) {
const src = []
for (let c = 0; c < cols; ++c) src.push(cell(r, c))
// Новая строка пустая, а не копия
const ins = r + 1
const flat = []
for (let rr = 0; rr <= rows; ++rr) {
if (rr === ins) for (const v of src) flat.push(v)
for (let c = 0; c < cols; ++c) {
if (rr < rows) flat.push(cell(rr, c))
}
if (rr === ins) for (let c = 0; c < cols; ++c) flat.push("")
for (let c = 0; c < cols; ++c) if (rr < rows) flat.push(cell(rr, c))
}
cells = flat
rows += 1
rebuildGrid()
cells = flat; rows += 1
}
function addColAfter(c) {
@@ -67,115 +48,90 @@ Dialog {
if (cc < cols) flat.push(cell(rr, cc))
}
}
cells = flat
cols += 1
rebuildGrid()
cells = flat; cols += 1
}
function buildMarkdown() {
let out = ""
for (let c = 0; c < cols; ++c)
out += (c === 0 ? "| " : " | ") + cell(0, c)
for (let c = 0; c < cols; ++c) out += (c === 0 ? "| " : " | ") + cell(0, c)
out += " |\n"
for (let c = 0; c < cols; ++c)
out += (c === 0 ? "| " : " | ") + "---"
for (let c = 0; c < cols; ++c) out += (c === 0 ? "| " : " | ") + "---"
out += " |\n"
for (let r = 1; r < rows; ++r) {
for (let c = 0; c < cols; ++c)
out += (c === 0 ? "| " : " | ") + cell(r, c)
for (let c = 0; c < cols; ++c) out += (c === 0 ? "| " : " | ") + cell(r, c)
out += " |\n"
}
return out
}
function rebuildGrid() {
// Repeater-ы привязаны к root.rows/root.cols напрямую — ничего не делаем.
}
function resetDialog() {
rows = 1
cols = 2
cells = []
rows = 1; cols = 2; cells = []
for (let i = 0; i < rows * cols; ++i) cells.push("")
}
Component.onCompleted: {
resetDialog()
}
Component.onCompleted: resetDialog()
ColumnLayout {
anchors.fill: parent
spacing: 8
spacing: 10
Label { text: qsTr("Заполните ячейки таблицы"); color: Theme.textSecondary; font.pixelSize: 11 }
Flickable {
Layout.fillWidth: true
Layout.fillHeight: true
contentWidth: cellGrid.width + 26
contentWidth: cellGrid.width + 30
contentHeight: cellGrid.height + 30
clip: true
ScrollBar.horizontal: ScrollBar {}
ScrollBar.vertical: ScrollBar {}
Row {
id: tableRow
spacing: 0
Grid {
id: cellGrid
columns: root.cols
columnSpacing: 2
rowSpacing: 2
columnSpacing: 3
rowSpacing: 3
Repeater {
model: root.rows * root.cols
delegate: TextField {
width: root.cellW
height: root.cellH
width: root.cellW; height: root.cellH
placeholderText: (Math.floor(model / root.cols)===0 ? qsTr("Заголовок") : qsTr("Ячейка"))
placeholderTextColor: Theme.textFaint
text: root.cell(Math.floor(model / root.cols), model % root.cols)
color: Theme.text
background: Rectangle { color: Theme.bgAlt; border.color: parent.activeFocus ? Theme.accent : Theme.border; radius: 6 }
onTextEdited: root.setCell(Math.floor(model / root.cols), model % root.cols, text)
}
}
}
// Полоса «+» справа: добавить строку под строкой (20px шириной)
Grid {
columns: 1
columnSpacing: 2
rowSpacing: 2
columns: 1; columnSpacing: 3; rowSpacing: 3
anchors.leftMargin: 4
Repeater {
id: rowAddStrip
model: root.rows
delegate: Button {
width: 20
height: root.cellH
width: 24; height: root.cellH
text: "+"
font.pixelSize: 12
ToolTip.text: qsTr("Добавить строку")
ToolTip.visible: hovered
ToolTip.text: qsTr("Добавить строку под этой")
onClicked: root.addRowAfter(model)
}
}
}
}
Row {
anchors.top: tableRow.bottom
anchors.topMargin: 4
anchors.top: tableRow.bottom; anchors.topMargin: 4
Grid {
columns: root.cols
columnSpacing: 2
rowSpacing: 2
columns: root.cols; columnSpacing: 3; rowSpacing: 3
Repeater {
id: colAddStrip
model: root.cols
delegate: Button {
width: root.cellW
height: 20
width: root.cellW; height: 24
text: "+"
font.pixelSize: 12
ToolTip.text: qsTr("Добавить столбец")
ToolTip.visible: hovered
ToolTip.text: qsTr("Добавить столбец правее этого")
onClicked: root.addColAfter(model)
}
}
@@ -186,22 +142,9 @@ Dialog {
RowLayout {
Layout.fillWidth: true
Item { Layout.fillWidth: true }
Label {
text: qsTr("Строк: %1 Столбцов: %2").arg(root.rows).arg(root.cols)
color: "#888"
}
Button {
text: qsTr("Отмена")
onClicked: root.reject()
}
Button {
text: qsTr("Вставить")
highlighted: true
onClicked: {
root.markdownReady(buildMarkdown())
root.accept()
}
}
Label { text: qsTr("Строк: %1 Столбцов: %2").arg(root.rows).arg(root.cols); color: Theme.textMuted; font.pixelSize: 11 }
Button { text: qsTr("Отмена"); onClicked: root.reject() }
Button { text: qsTr("Вставить"); highlighted: true; onClicked: { root.markdownReady(buildMarkdown()); root.accept() } }
}
}
}
}