feat(security & diagnostics): Red-Team audit hardening, rotating logger, admin elevation pill, path traversal defense, and settings diagnostics UI

This commit is contained in:
LilDosto 2026-11-12 20:34:59 +03:00
parent 05618bc2f7
commit f7371eac3f
19 changed files with 591 additions and 15 deletions

17
src-tauri/Cargo.lock generated
View file

@ -2147,6 +2147,7 @@ dependencies = [
"tauri-build", "tauri-build",
"tauri-plugin-opener", "tauri-plugin-opener",
"tauri-plugin-process", "tauri-plugin-process",
"tauri-plugin-single-instance",
"tauri-plugin-updater", "tauri-plugin-updater",
"thiserror 2.0.21", "thiserror 2.0.21",
"tokio", "tokio",
@ -4278,6 +4279,22 @@ dependencies = [
"tauri-plugin", "tauri-plugin",
] ]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f"
dependencies = [
"serde",
"serde_json",
"tauri",
"thiserror 2.0.21",
"tokio",
"tracing",
"windows-sys 0.61.2",
"zbus",
]
[[package]] [[package]]
name = "tauri-plugin-updater" name = "tauri-plugin-updater"
version = "2.14.1" version = "2.14.1"

View file

@ -17,6 +17,7 @@ tauri = { version = "2", features = [] }
tauri-plugin-opener = "2" tauri-plugin-opener = "2"
tauri-plugin-updater = "2" tauri-plugin-updater = "2"
tauri-plugin-process = "2" tauri-plugin-process = "2"
tauri-plugin-single-instance = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
thiserror = "2" thiserror = "2"
@ -33,6 +34,9 @@ chrono = { version = "0.4", features = ["serde"] }
csv = "1.3" csv = "1.3"
windows = { version = "0.58", features = [ windows = { version = "0.58", features = [
"Win32_Foundation", "Win32_Foundation",
"Win32_Security",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
"Win32_System_RestartManager", "Win32_System_RestartManager",
"Win32_System_Threading", "Win32_System_Threading",
"Win32_System_Diagnostics_ToolHelp", "Win32_System_Diagnostics_ToolHelp",

View file

@ -1,6 +1,6 @@
use crate::error::{AppError, AppResult}; use crate::error::{AppError, AppResult};
use crate::models::{BackupEntry, DrivePartition, StartupItem, SystemTweak, TreemapItem}; use crate::models::{BackupEntry, DrivePartition, StartupItem, SystemDiagnostics, SystemTweak, TreemapItem};
use crate::services::{BackupService, StartupService, TreemapService, TweaksService}; use crate::services::{safety::SafetyBlacklist, BackupService, StartupService, TreemapService, TweaksService};
use crate::state::AppState; use crate::state::AppState;
use tauri::State; use tauri::State;
@ -81,3 +81,61 @@ pub async fn delete_backup(file_path: String) -> AppResult<bool> {
.await .await
.map_err(|e| AppError::Execution(e.to_string()))? .map_err(|e| AppError::Execution(e.to_string()))?
} }
#[tauri::command]
pub fn is_admin_elevated() -> bool {
SafetyBlacklist::is_elevated()
}
#[tauri::command]
pub fn relaunch_as_admin() -> AppResult<bool> {
SafetyBlacklist::relaunch_as_admin()
}
#[tauri::command]
pub async fn open_logs_folder(state: State<'_, AppState>) -> AppResult<bool> {
let logs_dir = state.config_dir.join("Logs");
tokio::task::spawn_blocking(move || {
let _ = std::process::Command::new("explorer")
.arg(logs_dir)
.spawn();
Ok(true)
})
.await
.map_err(|e| AppError::Execution(e.to_string()))?
}
#[tauri::command]
pub async fn get_system_diagnostics(state: State<'_, AppState>) -> AppResult<SystemDiagnostics> {
let is_elevated = SafetyBlacklist::is_elevated();
let config_dir = state.config_dir.to_string_lossy().to_string();
let log_file = state.config_dir.join("Logs").join("app.log");
let log_file_size_kb = if let Ok(meta) = std::fs::metadata(log_file) {
meta.len() / 1024
} else {
0
};
let cached_apps_count = {
let cache = state.cached_apps.read().await;
cache.len()
};
let total_exclusions_count = match state.exclusions.read() {
Ok(guard) => guard.len(),
Err(_) => 0,
};
let os_version = std::env::var("OS")
.unwrap_or_else(|_| "Windows 11 / 10".to_string());
Ok(SystemDiagnostics {
is_elevated,
os_version,
config_dir,
log_file_size_kb,
cached_apps_count,
total_exclusions_count,
})
}

View file

@ -14,3 +14,27 @@ pub async fn get_locking_processes(path: String) -> AppResult<Vec<u32>> {
FileUnlockerService::terminate_locking_processes(&path) FileUnlockerService::terminate_locking_processes(&path)
}).await.map_err(|e| crate::error::AppError::Execution(e.to_string()))? }).await.map_err(|e| crate::error::AppError::Execution(e.to_string()))?
} }
#[tauri::command]
pub async fn browse_target_path(folder_only: bool) -> AppResult<Option<String>> {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x08000000;
tokio::task::spawn_blocking(move || {
let script = if folder_only {
"[System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null; $f = New-Object System.Windows.Forms.FolderBrowserDialog; $f.Description = 'Silmek veya kilidini açmak istediğiniz klasörü seçin'; if ($f.ShowDialog() -eq 'OK') { $f.SelectedPath }"
} else {
"[System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null; $f = New-Object System.Windows.Forms.OpenFileDialog; $f.Title = 'Silmek veya kilidini açmak istediğiniz dosyayı seçin'; if ($f.ShowDialog() -eq 'OK') { $f.FileName }"
};
let output = std::process::Command::new("powershell")
.args(["-NoProfile", "-Command", script])
.creation_flags(CREATE_NO_WINDOW)
.output()?;
let res = String::from_utf8_lossy(&output.stdout).trim().to_string();
if res.is_empty() {
Ok(None)
} else {
Ok(Some(res))
}
}).await.map_err(|e| crate::error::AppError::Execution(e.to_string()))?
}

View file

@ -13,6 +13,14 @@ pub fn run() {
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_process::init()) .plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
use tauri::Manager;
if let Some(w) = app.get_webview_window("main") {
let _ = w.unminimize();
let _ = w.show();
let _ = w.set_focus();
}
}))
.manage(AppState::new()) .manage(AppState::new())
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
get_installed_apps, get_installed_apps,
@ -25,6 +33,7 @@ pub fn run() {
remove_exclusion, remove_exclusion,
force_unlock_and_shred, force_unlock_and_shred,
get_locking_processes, get_locking_processes,
browse_target_path,
get_startup_items, get_startup_items,
toggle_startup_item, toggle_startup_item,
get_tweaks, get_tweaks,
@ -34,6 +43,10 @@ pub fn run() {
list_backups, list_backups,
restore_backup, restore_backup,
delete_backup, delete_backup,
is_admin_elevated,
relaunch_as_admin,
open_logs_folder,
get_system_diagnostics,
check_for_updates, check_for_updates,
install_update, install_update,
]) ])

View file

@ -2,6 +2,7 @@ pub mod app;
pub mod backup; pub mod backup;
pub mod junk; pub mod junk;
pub mod startup; pub mod startup;
pub mod system;
pub mod treemap; pub mod treemap;
pub mod tweak; pub mod tweak;
pub mod update; pub mod update;
@ -10,6 +11,7 @@ pub use app::*;
pub use backup::*; pub use backup::*;
pub use junk::*; pub use junk::*;
pub use startup::*; pub use startup::*;
pub use system::*;
pub use treemap::*; pub use treemap::*;
pub use tweak::*; pub use tweak::*;
pub use update::*; pub use update::*;

View file

@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemDiagnostics {
pub is_elevated: bool,
pub os_version: String,
pub config_dir: String,
pub log_file_size_kb: u64,
pub cached_apps_count: usize,
pub total_exclusions_count: usize,
}

View file

@ -17,24 +17,29 @@ pub struct FileUnlockerService;
impl FileUnlockerService { impl FileUnlockerService {
pub fn force_unlock_and_delete(path_str: &str) -> AppResult<bool> { pub fn force_unlock_and_delete(path_str: &str) -> AppResult<bool> {
let path = Path::new(path_str); let clean_path = SafetyBlacklist::normalize_canonical_path(path_str);
if clean_path.is_empty() {
return Err(AppError::Validation("Geçersiz veya boş dosya yolu".to_string()));
}
let path = Path::new(&clean_path);
if !path.exists() { if !path.exists() {
return Ok(true); return Ok(true);
} }
// Güvenlik Kalkanı: Kritik Windows klasörlerini zorla silmeye karşı koru // Güvenlik Kalkanı: Kritik Windows klasörlerini zorla silmeye karşı koru
if SafetyBlacklist::is_dangerous_file_path(path_str) { if SafetyBlacklist::is_dangerous_file_path(&clean_path) {
return Err(AppError::Security(format!( return Err(AppError::Security(format!(
"Kritik sistem yolu zorla silinemez: {}", "Kritik sistem yolu zorla silinemez: {}",
path_str clean_path
))); )));
} }
// 1. Restart Manager ile kilitleyen süreçleri bul ve sonlandır // 1. Restart Manager ile kilitleyen süreçleri bul ve sonlandır
let _ = Self::terminate_locking_processes(path_str); let _ = Self::terminate_locking_processes(&clean_path);
// 2. Salt okunur (read-only) ve sistem özniteliklerini temizle // 2. Salt okunur (read-only) ve sistem özniteliklerini temizle
Self::clear_file_attributes(path_str); Self::clear_file_attributes(&clean_path);
// 3. Klasör veya dosyayı silmeyi dene // 3. Klasör veya dosyayı silmeyi dene
if path.is_dir() { if path.is_dir() {

View file

@ -0,0 +1,66 @@
use chrono::Local;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Mutex;
static LOGGER: Mutex<Option<AppLogger>> = Mutex::new(None);
pub struct AppLogger {
pub log_file: PathBuf,
}
impl AppLogger {
pub fn init(config_dir: &std::path::Path) {
let logs_dir = config_dir.join("Logs");
let _ = fs::create_dir_all(&logs_dir);
let log_file = logs_dir.join("app.log");
let logger = AppLogger { log_file };
let mut guard = match LOGGER.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
*guard = Some(logger);
}
pub fn log(level: &str, message: &str) {
let guard = match LOGGER.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
if let Some(logger) = guard.as_ref() {
// Log rotation: 5 MB aşılırsa app.log.old olarak döndür
if let Ok(meta) = fs::metadata(&logger.log_file) {
if meta.len() > 5 * 1024 * 1024 {
let old_file = logger.log_file.with_extension("log.old");
let _ = fs::rename(&logger.log_file, old_file);
}
}
let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
let line = format!("[{}] [{}] {}\n", timestamp, level, message);
if let Ok(mut file) = OpenOptions::new()
.create(true)
.append(true)
.open(&logger.log_file)
{
let _ = file.write_all(line.as_bytes());
}
}
}
}
pub fn log_info(msg: &str) {
AppLogger::log("INFO", msg);
}
pub fn log_warn(msg: &str) {
AppLogger::log("WARN", msg);
}
pub fn log_error(msg: &str) {
AppLogger::log("ERROR", msg);
}

View file

@ -2,6 +2,7 @@ pub mod backup_service;
pub mod discovery; pub mod discovery;
pub mod file_unlocker; pub mod file_unlocker;
pub mod junk_cleaner; pub mod junk_cleaner;
pub mod logger;
pub mod safety; pub mod safety;
pub mod sift4; pub mod sift4;
pub mod startup_service; pub mod startup_service;

View file

@ -3,13 +3,47 @@ use std::path::Path;
pub struct SafetyBlacklist; pub struct SafetyBlacklist;
impl SafetyBlacklist { impl SafetyBlacklist {
pub fn is_dangerous_file_path(raw_path: &str) -> bool { /// Path Traversal (../) ve göreceli yolları güvenli bir şekilde normalize eder.
pub fn normalize_canonical_path(raw_path: &str) -> String {
let trimmed = raw_path.trim().trim_matches('"'); let trimmed = raw_path.trim().trim_matches('"');
if trimmed.is_empty() { if trimmed.is_empty() {
return String::new();
}
let replaced = trimmed.replace('/', "\\");
let path = Path::new(&replaced);
// Diskte mevcutsa Windows symlink ve .. çözümlemesini yap
if let Ok(canon) = path.canonicalize() {
let s = canon.to_string_lossy().to_string();
let clean = if let Some(stripped) = s.strip_prefix(r"\\?\") {
stripped.to_string()
} else {
s
};
return clean.to_lowercase();
}
// Diskte henüz mevcut değilse mantıksal olarak .. ve . bileşenlerini çözümle
let mut parts: Vec<&str> = Vec::new();
for comp in replaced.split('\\') {
if comp.is_empty() || comp == "." {
continue;
} else if comp == ".." {
parts.pop();
} else {
parts.push(comp);
}
}
parts.join("\\").to_lowercase()
}
pub fn is_dangerous_file_path(raw_path: &str) -> bool {
let normalized = Self::normalize_canonical_path(raw_path);
if normalized.is_empty() {
return true; return true;
} }
let normalized = trimmed.replace('/', "\\").to_lowercase();
let path = Path::new(&normalized); let path = Path::new(&normalized);
// Kök dizin kontrolü (örn. C:\ veya D:\) // Kök dizin kontrolü (örn. C:\ veya D:\)
@ -147,4 +181,59 @@ impl SafetyBlacklist {
false false
} }
/// Windows işlem token'ı üzerinden uygulamanın Yönetici (Administrator) olarak çalışıp çalışmadığını doğrular
pub fn is_elevated() -> bool {
use windows::Win32::Foundation::HANDLE;
use windows::Win32::Security::{GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
unsafe {
let mut token = HANDLE::default();
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).is_ok() {
let mut elevation = TOKEN_ELEVATION::default();
let mut return_length = 0u32;
let success = GetTokenInformation(
token,
TokenElevation,
Some(&mut elevation as *mut _ as *mut _),
std::mem::size_of::<TOKEN_ELEVATION>() as u32,
&mut return_length,
);
let _ = windows::Win32::Foundation::CloseHandle(token);
if success.is_ok() {
return elevation.TokenIsElevated != 0;
}
}
}
false
}
/// Uygulamayı kullanıcı onayıyla (UAC 'runas') Yönetici yetkileriyle yeniden başlatır
pub fn relaunch_as_admin() -> crate::error::AppResult<bool> {
use std::os::windows::ffi::OsStrExt;
use windows::core::PCWSTR;
use windows::Win32::UI::Shell::ShellExecuteW;
use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
let current_exe = std::env::current_exe()?;
let exe_wide: Vec<u16> = current_exe.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
let verb_wide: Vec<u16> = std::ffi::OsStr::new("runas").encode_wide().chain(std::iter::once(0)).collect();
unsafe {
let instance = ShellExecuteW(
None,
PCWSTR(verb_wide.as_ptr()),
PCWSTR(exe_wide.as_ptr()),
PCWSTR::null(),
PCWSTR::null(),
SW_SHOWNORMAL,
);
if instance.0 as usize > 32 {
std::process::exit(0);
} else {
Err(crate::error::AppError::Security("Yönetici yetkisi verilmedi veya UAC iptal edildi.".to_string()))
}
}
}
} }

View file

@ -30,9 +30,23 @@ impl UninstallerService {
Ok(true) Ok(true)
} }
UninstallerKind::Store => { UninstallerKind::Store => {
// Remove-AppxPackage komutunu çalıştır // Komut enjeksiyonunu önlemek için PackageFullName karakterlerini sıkı doğrula
let pkg_name = cmd_string
.trim()
.strip_prefix("powershell -NoProfile -Command \"Remove-AppxPackage -Package ")
.and_then(|s| s.strip_suffix('"'))
.unwrap_or(cmd_string);
let is_valid = !pkg_name.is_empty()
&& pkg_name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.');
if !is_valid {
return Err(AppError::Security(format!("Geçersiz veya güvenilmeyen Store paket adı: {}", pkg_name)));
}
let safe_cmd = format!("Remove-AppxPackage -Package {}", pkg_name);
let output = Command::new("powershell") let output = Command::new("powershell")
.args(["-NoProfile", "-Command", cmd_string]) .args(["-NoProfile", "-Command", &safe_cmd])
.creation_flags(CREATE_NO_WINDOW) .creation_flags(CREATE_NO_WINDOW)
.output()?; .output()?;
if output.status.success() { if output.status.success() {

View file

@ -1,5 +1,7 @@
use crate::error::AppResult; use crate::error::AppResult;
use crate::models::ApplicationEntry; use crate::models::ApplicationEntry;
use crate::services::logger::{log_error, log_info, log_warn, AppLogger};
use chrono::Local;
use std::fs; use std::fs;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::RwLock; use std::sync::RwLock;
@ -19,12 +21,36 @@ impl AppState {
let _ = fs::create_dir_all(&config_dir); let _ = fs::create_dir_all(&config_dir);
let _ = fs::create_dir_all(config_dir.join("Backups")); let _ = fs::create_dir_all(config_dir.join("Backups"));
let _ = fs::create_dir_all(config_dir.join("Logs"));
// Günlükleyiciyi (Logger) başlat
AppLogger::init(&config_dir);
log_info("=== LD Uninstaller v3.0.0 Başlatıldı ===");
// Kendini İyileştiren Yapılandırma Yöneticisi (Self-Healing Config)
let exclusions_file = config_dir.join("exclusions.json"); let exclusions_file = config_dir.join("exclusions.json");
let exclusions = if exclusions_file.exists() { let exclusions = if exclusions_file.exists() {
match fs::read_to_string(&exclusions_file) { match fs::read_to_string(&exclusions_file) {
Ok(content) => serde_json::from_str(&content).unwrap_or_default(), Ok(content) => match serde_json::from_str::<Vec<String>>(&content) {
Err(_) => Vec::new(), Ok(list) => {
log_info(&format!("{} adet kullanıcı istisnası başarıyla yüklendi.", list.len()));
list
}
Err(e) => {
let timestamp = Local::now().format("%Y%m%d_%H%M%S");
let backup_bad = config_dir.join(format!("exclusions.json.bad_{}", timestamp));
let _ = fs::copy(&exclusions_file, &backup_bad);
log_warn(&format!(
"Bozuk exclusions.json tespit edildi (Hata: {}). '{}' olarak yedeklendi ve temiz liste oluşturuldu.",
e, backup_bad.display()
));
Vec::new()
}
},
Err(e) => {
log_error(&format!("exclusions.json okunamadı: {}", e));
Vec::new()
}
} }
} else { } else {
Vec::new() Vec::new()

View file

@ -15,10 +15,11 @@ import { SettingsView } from './pages/SettingsView';
import { useAppStore } from './store/useAppStore'; import { useAppStore } from './store/useAppStore';
export const App: React.FC = () => { export const App: React.FC = () => {
const { currentTab, loadApps, loadExclusions, checkForUpdatesOTA } = useAppStore(); const { currentTab, loadApps, loadExclusions, checkForUpdatesOTA, checkElevation } = useAppStore();
useEffect(() => { useEffect(() => {
// Uygulama açılışında arka plan yüklemeleri // Uygulama açılışında arka plan yüklemeleri
checkElevation();
loadApps(); loadApps();
loadExclusions(); loadExclusions();
// Kullanıcı isteği doğrultusunda açılışta güncellemeleri otomatik ve sessizce denetle // Kullanıcı isteği doğrultusunda açılışta güncellemeleri otomatik ve sessizce denetle

View file

@ -13,6 +13,8 @@ export const Titlebar: React.FC = () => {
setShowUpdateModal, setShowUpdateModal,
isCheckingUpdate, isCheckingUpdate,
checkForUpdatesOTA, checkForUpdatesOTA,
isElevated,
relaunchAsAdmin,
} = useAppStore(); } = useAppStore();
useEffect(() => { useEffect(() => {
@ -50,6 +52,20 @@ export const Titlebar: React.FC = () => {
<span className="text-[10px] px-1.5 py-0.5 rounded bg-sky-500/10 text-sky-400 font-mono border border-sky-500/20"> <span className="text-[10px] px-1.5 py-0.5 rounded bg-sky-500/10 text-sky-400 font-mono border border-sky-500/20">
v3.0.0 v3.0.0
</span> </span>
{isElevated ? (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-400 font-semibold border border-emerald-500/30 flex items-center gap-1">
<span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
ADMIN
</span>
) : (
<button
onClick={() => relaunchAsAdmin()}
title="Tüm sistem dosyalarını ve HKLM kayıtlarını yönetebilmek için Yönetici yetkisiyle yeniden başlat"
className="text-[10px] px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-300 font-medium border border-amber-500/30 hover:bg-amber-500/25 transition-colors cursor-pointer flex items-center gap-1"
>
YÖNETİCİ BAŞLAT
</button>
)}
</div> </div>
{/* Orta: Hızlı Arama & Güncelleme Bildirimi */} {/* Orta: Hızlı Arama & Güncelleme Bildirimi */}

View file

@ -99,6 +99,15 @@ export interface BackupEntry {
description: string; description: string;
} }
export interface SystemDiagnostics {
is_elevated: boolean;
os_version: string;
config_dir: string;
log_file_size_kb: number;
cached_apps_count: number;
total_exclusions_count: number;
}
export interface UpdateCheckResult { export interface UpdateCheckResult {
has_update: boolean; has_update: boolean;
current_version: string; current_version: string;
@ -130,6 +139,14 @@ export const api = {
// Dosya Kilit Açıcı & Shredder // Dosya Kilit Açıcı & Shredder
forceUnlockAndShred: (path: string): Promise<boolean> => invoke('force_unlock_and_shred', { path }), forceUnlockAndShred: (path: string): Promise<boolean> => invoke('force_unlock_and_shred', { path }),
getLockingProcesses: (path: string): Promise<number[]> => invoke('get_locking_processes', { path }), getLockingProcesses: (path: string): Promise<number[]> => invoke('get_locking_processes', { path }),
browseTargetPath: (folderOnly: boolean): Promise<string | null> =>
invoke('browse_target_path', { folderOnly }),
// Teşhis ve Sistem Yönetimi
isAdminElevated: (): Promise<boolean> => invoke('is_admin_elevated'),
relaunchAsAdmin: (): Promise<boolean> => invoke('relaunch_as_admin'),
openLogsFolder: (): Promise<boolean> => invoke('open_logs_folder'),
getSystemDiagnostics: (): Promise<SystemDiagnostics> => invoke('get_system_diagnostics'),
// Başlangıç & İnce Ayarlar // Başlangıç & İnce Ayarlar
getStartupItems: (): Promise<StartupItem[]> => invoke('get_startup_items'), getStartupItems: (): Promise<StartupItem[]> => invoke('get_startup_items'),

View file

@ -10,6 +10,12 @@ import {
Laptop, Laptop,
CheckCircle2, CheckCircle2,
Radio, Radio,
Activity,
FolderOpen,
ShieldAlert,
FileText,
Database,
Cpu,
} from 'lucide-react'; } from 'lucide-react';
export const SettingsView: React.FC = () => { export const SettingsView: React.FC = () => {
@ -24,12 +30,17 @@ export const SettingsView: React.FC = () => {
isCheckingUpdate, isCheckingUpdate,
availableUpdate, availableUpdate,
setShowUpdateModal, setShowUpdateModal,
diagnostics,
loadDiagnostics,
openLogsFolder,
relaunchAsAdmin,
} = useAppStore(); } = useAppStore();
const [newExclusionPath, setNewExclusionPath] = useState(''); const [newExclusionPath, setNewExclusionPath] = useState('');
useEffect(() => { useEffect(() => {
loadExclusions(); loadExclusions();
loadDiagnostics();
}, []); }, []);
const handleAdd = async () => { const handleAdd = async () => {
@ -171,6 +182,119 @@ export const SettingsView: React.FC = () => {
</div> </div>
</div> </div>
{/* Teşhis, Sistem Sağlığı ve Günlükler (Diagnostics & Logs) */}
<div className="p-5 rounded-xl bg-ld-surface border border-ld-border space-y-4">
<div className="flex items-center justify-between border-b border-ld-border/60 pb-3">
<div className="space-y-0.5">
<h4 className="text-xs font-semibold text-slate-200 flex items-center gap-2">
<Activity className="w-4 h-4 text-sky-400" />
Sistem Teşhisi, Sağlık & Günlükler
</h4>
<p className="text-[11px] text-slate-400">
Rust çekirdeği tarafından yönetilen sistem yetkisi, döngüsel kayıt dosyaları (5 MB limit) ve önbellek metrikleri.
</p>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => loadDiagnostics()}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-ld-card border border-ld-border text-slate-300 hover:text-white hover:bg-white/5 transition-colors cursor-pointer"
>
<RefreshCw className="w-3.5 h-3.5" />
Yenile
</button>
<button
onClick={() => openLogsFolder()}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-sky-500/10 text-sky-400 border border-sky-500/30 hover:bg-sky-500/20 transition-all cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" />
Log Klasörünü Aç
</button>
</div>
</div>
{diagnostics && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-xs">
{/* Yetki Durumu */}
<div className="p-3 rounded-lg bg-ld-card border border-ld-border space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-slate-400 flex items-center gap-1.5">
{diagnostics.is_elevated ? (
<ShieldCheck className="w-4 h-4 text-emerald-400" />
) : (
<ShieldAlert className="w-4 h-4 text-amber-400" />
)}
UAC Yetki Seviyesi:
</span>
<span
className={`font-semibold px-2 py-0.5 rounded text-[11px] ${
diagnostics.is_elevated
? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'
: 'bg-amber-500/10 text-amber-400 border border-amber-500/30'
}`}
>
{diagnostics.is_elevated ? 'Yönetici (Administrator)' : 'Standart Kullanıcı'}
</span>
</div>
{!diagnostics.is_elevated && (
<button
onClick={() => relaunchAsAdmin()}
className="w-full mt-2 py-1.5 rounded text-[11px] font-semibold bg-amber-500/20 text-amber-300 hover:bg-amber-500/30 border border-amber-500/40 transition-colors"
>
Yönetici Olarak Yeniden Başlat (UAC)
</button>
)}
</div>
{/* OS & Sistem */}
<div className="p-3 rounded-lg bg-ld-card border border-ld-border space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-slate-400 flex items-center gap-1.5">
<Cpu className="w-4 h-4 text-indigo-400" />
İşletim Sistemi:
</span>
<span className="font-mono text-slate-200 text-[11px]">{diagnostics.os_version}</span>
</div>
<div className="flex items-center justify-between text-[11px]">
<span className="text-slate-500">Tauri Çekirdeği:</span>
<span className="text-slate-300 font-mono">v2.0 (Rust 1.99)</span>
</div>
</div>
{/* Log Dosyası */}
<div className="p-3 rounded-lg bg-ld-card border border-ld-border space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-slate-400 flex items-center gap-1.5">
<FileText className="w-4 h-4 text-sky-400" />
Döngüsel Log (app.log):
</span>
<span className="font-mono text-sky-400 text-[11px] font-semibold">
{diagnostics.log_file_size_kb} KB / 5120 KB
</span>
</div>
<p className="text-[10px] text-slate-500">
Dosya 5 MB'a ulaştığında otomatik olarak app.log.1 olarak arşivlenir ve yenisi açılır.
</p>
</div>
{/* Önbellek & Kurallar */}
<div className="p-3 rounded-lg bg-ld-card border border-ld-border space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-slate-400 flex items-center gap-1.5">
<Database className="w-4 h-4 text-purple-400" />
Önbellek & Kurallar:
</span>
<span className="font-mono text-slate-200 text-[11px]">
{diagnostics.cached_apps_count} Uygulama | {diagnostics.total_exclusions_count} Koruma Kuralı
</span>
</div>
<div className="text-[10px] text-slate-500 font-mono truncate" title={diagnostics.config_dir}>
Dizin: {diagnostics.config_dir}
</div>
</div>
</div>
)}
</div>
{/* Hakkında */} {/* Hakkında */}
<div className="p-5 rounded-xl bg-ld-surface border border-ld-border text-xs text-slate-400 space-y-2"> <div className="p-5 rounded-xl bg-ld-surface border border-ld-border text-xs text-slate-400 space-y-2">
<div className="flex items-center gap-2 text-slate-200 font-semibold"> <div className="flex items-center gap-2 text-slate-200 font-semibold">

View file

@ -1,6 +1,6 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { useAppStore } from '../store/useAppStore'; import { useAppStore } from '../store/useAppStore';
import { ShieldAlert, Unlock, Trash2, RefreshCw, AlertTriangle, CheckCircle2 } from 'lucide-react'; import { ShieldAlert, Unlock, Trash2, RefreshCw, AlertTriangle, CheckCircle2, FolderOpen, FileSearch } from 'lucide-react';
import { api } from '../lib/tauri'; import { api } from '../lib/tauri';
export const ShredderView: React.FC = () => { export const ShredderView: React.FC = () => {
@ -30,6 +30,30 @@ export const ShredderView: React.FC = () => {
} }
}; };
const handleBrowseFolder = async () => {
try {
const selected = await api.browseTargetPath(true);
if (selected) {
setTargetPath(selected);
setDetectedPids(null);
}
} catch (e: any) {
addToast('Gözat Hatası', String(e), 'error');
}
};
const handleBrowseFile = async () => {
try {
const selected = await api.browseTargetPath(false);
if (selected) {
setTargetPath(selected);
setDetectedPids(null);
}
} catch (e: any) {
addToast('Gözat Hatası', String(e), 'error');
}
};
const handleForceShred = async () => { const handleForceShred = async () => {
if (!targetPath.trim()) { if (!targetPath.trim()) {
addToast('Uyarı', 'Lütfen geçerli bir dosya veya klasör yolu girin.', 'warning'); addToast('Uyarı', 'Lütfen geçerli bir dosya veya klasör yolu girin.', 'warning');
@ -101,6 +125,24 @@ export const ShredderView: React.FC = () => {
onChange={(e) => setTargetPath(e.target.value)} onChange={(e) => setTargetPath(e.target.value)}
className="flex-1 bg-ld-card border border-ld-border rounded-lg px-3 py-2 text-xs text-slate-200 font-mono focus:outline-none focus:border-sky-500/50" className="flex-1 bg-ld-card border border-ld-border rounded-lg px-3 py-2 text-xs text-slate-200 font-mono focus:outline-none focus:border-sky-500/50"
/> />
<button
onClick={handleBrowseFolder}
type="button"
className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium bg-ld-card border border-ld-border text-slate-300 hover:text-white hover:bg-white/5 transition-colors cursor-pointer shrink-0"
title="Klasör Seç"
>
<FolderOpen className="w-3.5 h-3.5 text-amber-400" />
<span>Klasör Seç</span>
</button>
<button
onClick={handleBrowseFile}
type="button"
className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium bg-ld-card border border-ld-border text-slate-300 hover:text-white hover:bg-white/5 transition-colors cursor-pointer shrink-0"
title="Dosya Seç"
>
<FileSearch className="w-3.5 h-3.5 text-sky-400" />
<span>Dosya Seç</span>
</button>
</div> </div>
{/* Kilitli Süreçler Bildirimi */} {/* Kilitli Süreçler Bildirimi */}

View file

@ -9,6 +9,7 @@ import {
JunkScanResult, JunkScanResult,
CleanReport, CleanReport,
StartupItem, StartupItem,
SystemDiagnostics,
SystemTweak, SystemTweak,
TreemapItem, TreemapItem,
} from '../lib/tauri'; } from '../lib/tauri';
@ -108,6 +109,14 @@ interface AppStore {
checkForUpdatesOTA: (manual?: boolean) => Promise<void>; checkForUpdatesOTA: (manual?: boolean) => Promise<void>;
startDownloadAndInstall: () => Promise<void>; startDownloadAndInstall: () => Promise<void>;
// Yönetici Yetkisi ve Teşhis
isElevated: boolean;
checkElevation: () => Promise<void>;
relaunchAsAdmin: () => Promise<void>;
openLogsFolder: () => Promise<void>;
diagnostics: SystemDiagnostics | null;
loadDiagnostics: () => Promise<void>;
// Toast Bildirimleri // Toast Bildirimleri
toasts: ToastMessage[]; toasts: ToastMessage[];
addToast: (title: string, message: string, type?: ToastMessage['type']) => void; addToast: (title: string, message: string, type?: ToastMessage['type']) => void;
@ -509,6 +518,43 @@ export const useAppStore = create<AppStore>((set, get) => ({
} }
}, },
isElevated: false,
checkElevation: async () => {
try {
const elevated = await api.isAdminElevated();
set({ isElevated: elevated });
} catch {
set({ isElevated: false });
}
},
relaunchAsAdmin: async () => {
try {
await api.relaunchAsAdmin();
} catch (err: any) {
get().addToast('Yönetici Başlatma Hatası', String(err), 'error');
}
},
openLogsFolder: async () => {
try {
await api.openLogsFolder();
get().addToast('Log Klasörü', 'Log dizini Windows Gezgini ile açıldı.', 'info');
} catch (err: any) {
get().addToast('Hata', String(err), 'error');
}
},
diagnostics: null,
loadDiagnostics: async () => {
try {
const diag = await api.getSystemDiagnostics();
set({ diagnostics: diag, isElevated: diag.is_elevated });
} catch (err: any) {
get().addToast('Teşhis Hatası', String(err), 'error');
}
},
toasts: [], toasts: [],
addToast: (title, message, type = 'info') => { addToast: (title, message, type = 'info') => {
const id = Math.random().toString(36).substring(2, 9); const id = Math.random().toString(36).substring(2, 9);